// -----------------------------------------------------------------------------------
//
//  Configurationl
//
LightboxOptions = Object.extend( {

	ajaxOpened: false,
	contentOverlay: '',
	lightboxAjax : '',
	outerContentContainer : '',
	fileLoadingImage :loading_tcm,
	fileBottomNavCloseImage :fileBottomNavCloseImageUrl,
	overlayOpacity :0.8, // controls transparency of shadow overlay
	animate :true, // toggles resizing animations
	resizeSpeed :7, // controls the speed of the image resizing animations
	// (1=slowest and 10=fastest)
	borderSize :10, // if you adjust the padding in the CSS, you will need to
	// update this variable
	resizeDuration : 0.7,
	overlayDuration : 0.2, // shadow
	// When grouping images this is used to write: Image # of #.
	// Change it for non-english localization
	labelImage :"Image",
	labelOf :"of"
}, window.LightboxOptions || {});

// Defined local varaibles.
var countryCode = "GB";
var targetViewId = "";
var targetRev = "";
var loadTargetContent = false;
var action = "findAddress";


// -----------------------------------------------------------------------------------

var AjaxLightbox = Class.create();

AjaxLightbox.prototype = {
	imageArray : [],
	activeImage :undefined,

	// initialize()
	// Constructor runs on completion of the DOM loading. Calls updateImageList
	// and then
	// the function inserts html at the bottom of the page which is used to
	// display the shadow
	// overlay and the image container.
	//
	initialize : function() {

		this.updateAjaxList(); // Definately needed!

	},

	//
	// updateAjaxList()
	// Loops through anchor tags looking for 'lightbox' references and applies
	// onclick
	// events to appropriate links. You can rerun after dynamically adding
	// images w/ajax.
	//
	updateAjaxList : function() {

		this.updateAjaxList = Prototype.emptyFunction;

		document.observe('click', ( function(event) {
			var target = event.findElement('a[rel^=ajaxLightbox]')
					|| event.findElement('area[rel^=ajaxLightbox]');

			if (target) {

				if (target.id) {
					targetViewId = target.id;
					loadTargetContent = true;
					targetRev = target.rev;
				} else {
					targetViewId = "";
				}

				event.stop();
				this.start(target);
			}
		}).bind(this));
	},

	//
	// start()
	// Display overlay and lightbox. If image is part of a set, add siblings to
	// imageArray.
	//
	start : function(contentLink) {

		if($('contentLoading')) {
			$('contentLoading').show();
		}
		
			
		if(LightboxOptions.ajaxOpened == false) {
		
		
			if (LightboxOptions.resizeSpeed > 10)
				LightboxOptions.resizeSpeed = 10;
			if (LightboxOptions.resizeSpeed < 1)
				LightboxOptions.resizeSpeed = 1;
	
			// fade
			// in/out
			// duration
	
			// When Lightbox starts it will resize itself from 250 by 250 to the
			// current image dimension.
			// If animations are turned off, it will be hidden as to prevent a
			// flicker of a
			// white 250 by 250 box.
			var size = (LightboxOptions.animate ? 250 : 1) + 'px';
	
			var objBody = $$('body')[0];
	
			objBody.appendChild(Builder.node('div', {
				id :'contentOverlay'
			}));
	
			objBody.appendChild(Builder.node('div', {
				id :'lightboxAjax'
			}, [
	
			Builder.node('div', {
				id :'outerContentContainer'
			}, [ Builder.node('div', {
				style :'height:30px;'
			}, Builder.node('a', {
				style :'display:block;height:20px;width:400px:clear:right',
				id :'bottomNavContentClose',
				href :'#'
			}, Builder.node('img', {
				src :LightboxOptions.fileBottomNavCloseImage
			}))),
			// Builder.node('div',{style:'clear:both;height:1px'}),
					Builder.node('div', {
						id :'contentContainer'
					}, [
	
					Builder.node('div', {
						id :'contentPanel',
						style :'display:none'
					}), Builder.node('div', {
						id :'contentLoading'
					}, Builder.node('a', {
						id :'loadingLink',
						href :'#'
					}, Builder.node('img', {
						src :LightboxOptions.fileLoadingImage
					}))) ]) ]),
	
			]));
	
			$('contentOverlay').hide().observe('click', ( function() {
				this.end();
			}).bind(this));
			$('lightboxAjax').hide().observe('click', ( function(event) {
				if (event.element().id == 'lightbox')
					this.end();
			}).bind(this));
			$('outerContentContainer').setStyle( {
				width :size,
				height :size
			});
			$('loadingLink').observe('click', ( function(event) {
				event.stop();
				this.end();
			}).bind(this));
			$('bottomNavContentClose').observe('click', ( function(event) {
				event.stop();
				this.end();
				showElements();
			}).bind(this));
	
			var th = this;
			( function() {
				var ids = 'contentOverlay lightboxAjax outerContentContainer contentContainer contentPanel lightboxImage hoverNav contentLoading loadingLink ' + 'contentDataContainer imageData imageDetails caption numberDisplay bottomNav bottomNavContentClose';
				$w(ids).each( function(id) {
					th[id] = $(id);
				});
			}).defer();
			
			LightboxOptions.contentOverlay = $('contentOverlay');
			LightboxOptions.lightboxAjax = $('lightboxAjax');
			LightboxOptions.outerContentContainer = $('outerContentContainer');
			
			
			$$('object', 'embed').each( function(node) {
				node.style.visibility = 'hidden'
			});
	
			// stretch overlay to fill page and fade in
			var arrayPageSize = this.getPageSize();
			LightboxOptions.contentOverlay.setStyle( {
				width :arrayPageSize[0] + 'px',
				height :arrayPageSize[1] + 'px'
			});
			$('contentLoading').show();
			new Effect.Appear(LightboxOptions.contentOverlay, {
				duration :LightboxOptions.overlayDuration,
				from :0.0,
				to :LightboxOptions.overlayOpacity
			});
	
			// calculate top and left offset for the lightbox
			var arrayPageScroll = document.viewport.getScrollOffsets();
			var lightboxTop = arrayPageScroll[1]
					+ (document.viewport.getHeight() / 10);
			var lightboxLeft = arrayPageScroll[0];
			LightboxOptions.lightboxAjax.setStyle( {
				top :lightboxTop + 'px',
				left :lightboxLeft + 'px'
			}).show();

		}
		
		LightboxOptions.ajaxOpened = true;			
		this.changeContent(contentLink.rev);
		hideElements()

	},

	//
	// changeContent()
	// Hide most elements and preload image in preparation for resizing image
	// container.
	//
	changeContent : function(link) {

		this.activeImage = link; // update global var

		new Ajax.Updater($('contentPanel'), link, {
			method :'GET',
			evalScripts: true,
			onSuccess : function(transport) {

				this.contentLoading.hide();

			}.bind(this)

		});

		this.resizeImageContainer(600, 550, "open");

	},

	//
	// resizeImageContainer()
	//
	resizeImageContainer : function(imgWidth, imgHeight, state) {
		
		contentPanelHeight = imgHeight - 50;

		$("contentPanel").setStyle({'height': contentPanelHeight+'px'})	
		$("contentPanel").hide()
		
		// get current width and height
		var widthCurrent = LightboxOptions.outerContentContainer.getWidth();
		var heightCurrent = LightboxOptions.outerContentContainer.getHeight();

		// get new width and height
		var widthNew = (imgWidth + LightboxOptions.borderSize * 2);
		var heightNew = (imgHeight + LightboxOptions.borderSize * 2);
		// scalars based on change from old to new
		var xScale = (widthNew / widthCurrent) * 100;
		var yScale = (heightNew / heightCurrent) * 100;

		// calculate size difference between new and old image, and resize if
		// necessary
		var wDiff = widthCurrent - widthNew;
		var hDiff = heightCurrent - heightNew;

		new Effect.Scale(LightboxOptions.outerContentContainer, yScale, {
			scaleX :false,
			duration :LightboxOptions.resizeDuration,
			queue :'front'
		});
		new Effect.Scale(LightboxOptions.outerContentContainer, xScale, {
			scaleY :false,
			duration :LightboxOptions.resizeDuration,
			delay :LightboxOptions.resizeDuration,
			afterFinish : function() {
			
			if (state == "open") {
				
					$("contentPanel").show()
					$('contentLoading').hide();

					if( (targetViewId == 'findAddress' || targetViewId == 'changeAddress' || targetViewId == 'detailedAddress' ) && loadTargetContent){

						loadTargetContent = false;
					
						if($('countryOfResidence') != null) {
							countryCode = $('countryOfResidence').value;
						} else {
							countryCode = "GB";
						}
					
						if (countryCode == "GB") {
						
							ajaxGetGBCountry();
							hideMannualAddress();

						}else{
							ajaxGetCountryForDisplayChangeAddress();
						}
						
					}else if(targetViewId =="displayChangeAddress"){
						loadTargetContent = false;
						hideSearchAddress();
						ajaxGetCountryForDisplayChangeAddress();
						
					}else if( targetViewId == 'fundraiserEventInformationLookup' && loadTargetContent){
						loadTargetContent = false;
						displayFundraiserEventDescription();

					}
					
				}
			}
		});

	},

	//
	// end()
	//
	end : function() {
	
		$("contentPanel").scrollTop = 0;
		LightboxOptions.ajaxOpened = false;
		
		thisObject = this;
		
		thisObject.resizeImageContainer(250, 250);
		$$('select', 'object', 'embed').each( function(node) {
			node.style.visibility = 'visible'
		});	
		
		new Effect.Fade(LightboxOptions.lightboxAjax, {
			duration :LightboxOptions.overlayDuration,
			afterFinish : function() {
				$('lightboxAjax').remove();
			}
		});
		new Effect.Fade(LightboxOptions.contentOverlay, {
			duration :LightboxOptions.overlayDuration,
			afterFinish : function() {
				$('contentOverlay').remove();
			}
		});


	},

	//
	// getPageSize()
	//
	getPageSize : function() {

		var xScroll, yScroll;

		if (window.innerHeight && window.scrollMaxY) {
			xScroll = window.innerWidth + window.scrollMaxX;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight) { // all
			// but
			// Explorer
			// Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict,
			// Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}

		var windowWidth, windowHeight;

		if (self.innerHeight) { // all except Explorer
			if (document.documentElement.clientWidth) {
				windowWidth = document.documentElement.clientWidth;
			} else {
				windowWidth = self.innerWidth;
			}
			windowHeight = self.innerHeight;
		} else if (document.documentElement
				&& document.documentElement.clientHeight) { // Explorer 6 Strict
			// Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}

		// for small pages with total height less then height of the viewport
		if (yScroll < windowHeight) {
			pageHeight = windowHeight;
		} else {
			pageHeight = yScroll;
		}

		// for small pages with total width less then width of the viewport
		if (xScroll < windowWidth) {
			pageWidth = xScroll;
		} else {
			pageWidth = windowWidth;
		}

		return [ pageWidth, pageHeight ];
	}
}

document.observe('dom:loaded', function() {
	new AjaxLightbox();

	if($('buildingNameBoxDisplayId') != null){
		$('buildingNameBoxDisplayId').value = "false";
	}
});

/**
 * ajaxAddressSearchCall() This method used for ajax call while click of search
 * Button. on the light box.
 * 
 * Ajax request call parameter:
 * 
 * @param postCode
 * @param buildingNameOrNumber
 * 
 */
function ajaxAddressSearchCall() {
	$("contentPanel").show();

 
	var url = "ajaxAddressLookup.action";
	var postCode = $F('postCodeId');
	var buildingNameOrNumber = $F('buildingNameOrNumberId');
	
	if(validateAddress(postCode, buildingNameOrNumber)) {
	var params = 'postCode=' + postCode + '&buildingNameOrNumber='
			+ buildingNameOrNumber;

	new Ajax.Request(url, {
		method :'POST',
		asynchronous :true,
		parameters :params,
		onSuccess :searchAddressResult

	});
	}

	/**
	 * searchAddressResult() getting all the data from XML reponse and populate
	 * the select box.
	 * 
	 * @param transport
	 */
	function searchAddressResult(transport) {		
		
		var addressResultDiv = document.getElementById("addressResultDiv");
	
		// loop through list to clear previous search result. 
		while (addressResultDiv.childNodes.length >0){
	        addressResultDiv.removeChild(addressResultDiv.childNodes[0])
	    }
	
		var xml_doc = transport.responseXML.documentElement;
	
		if (xml_doc != null) {
			var errorMsg = xml_doc.getAttribute("message");
			var fieldName = xml_doc.getAttribute("fieldName");
			if (errorMsg != null && errorMsg != '') {
	
				$('postCodeError').innerHTML = "";
				$('buildingNameError').innerHTML = "";
	
				for (i = 0; i < xml_doc.childNodes[0].childNodes.length; i++) {
					fieldErrorMessage = xml_doc.childNodes[0].childNodes[i];
					fieldName = fieldErrorMessage.getAttribute("fieldName");
					msg = fieldErrorMessage.getAttribute("message");
	
					if (fieldName == "postcode") {
						$('buildingNameError').hide();
						$('postCodeError').innerHTML = msg;
						$('postCodeError').show();
						$('noDataSelected').hide();
					}
					if (fieldName == "buildingNameOrNumber") {
						$('postCodeError').hide();
						$('buildingNameError').innerHTML = msg;
						$('buildingNameError').show();
						$('noDataSelected').hide();
					}
					if (fieldName == "selectBox") {
						$('noDataSelected').show();
						$('noDataSelected').innerHTML = msg;
						$('buildingNameError').hide();
						$('postCodeError').hide();
						
					}
				}
	
			} else {
				for (i = 0; i < xml_doc.childNodes[0].childNodes.length; i++) {
	
					$('buildingNameError').hide();
					$('postCodeError').hide();
					$('noDataSelected').hide();
	
					var displayData = "";
					var populateAddressLine1 = xml_doc.childNodes[0].childNodes[i]
							.getAttribute("addressline1");
					var populateAddressLine2 = xml_doc.childNodes[0].childNodes[i]
							.getAttribute("addressline2");
					var populateCity = xml_doc.childNodes[0].childNodes[i]
							.getAttribute("city");
					var populateCounty = xml_doc.childNodes[0].childNodes[i]
							.getAttribute("county");
					var populatePostCode = xml_doc.childNodes[0].childNodes[i]
							.getAttribute("postcode");
	
					displayData = displayData + populateAddressLine1 + ",";
	
					if (populateAddressLine2 != null
							&& populateAddressLine2 != '') {
						displayData = displayData + populateAddressLine2 + ",";
					}
					displayData = displayData + populateCity + ",";
					displayData = displayData + populateCounty + ",";
	
					if (populatePostCode != null && populatePostCode != '') {
						displayData = displayData + populatePostCode;
					}
					addressResultDiv.options[i] = new Option(displayData);
	
				}
			}
			hideMannualAddress();
		}
	}

	$('contentLoading').hide();
  
}


/**
 * To get the selected country from country drop down. 
 */
function ajaxGetGBCountry() {	
	var url = "ajaxGetCountry.action";
	var country = "GB";
	var params = 'country=' + country;
	new Ajax.Request(url, {
			method :'POST',
			asynchronous :true,
			parameters :params,
			onSuccess :loadSelectedCountry
	});	
	
	function loadSelectedCountry(transport){
		var xml_doc = transport.responseXML.documentElement;
		var selectedCountry = xml_doc.getAttribute("selectedCountry");
		if (selectedCountry == "GB") {	
			if ($('nonMandatoryPostCode') != null)
			{
				$('nonMandatoryPostCode').hide();
			}
			if ($('nonukcountrylabel') != null)
			{
				$('nonukcountrylabel').hide();
			}
			
			
		}else{
			if ($('mandatoryPostCode') != null)
			{
				$('mandatoryPostCode').hide();
			}
			
			if ($('ukcountrylabel') != null)
			{
				$('ukcountrylabel').hide();
			}
			
		}
		ajaxLoadSearchAddress();
}
}
/**
 * To get the country form country drop down and hide the post code input box depend on country.
 *  
 */
function ajaxGetCountryForDisplayChangeAddress() {
	var url = "ajaxGetCountry.action";
	var country = "";
	
	//Get the postcode from the text field or span
	
	if($('countryOfResidence') != null) {
		country = $('countryOfResidence').value;
	} else {
		country = "GB";
	}
	
	var params = 'country=' + country;
	new Ajax.Request(url, {
			method :'POST',
			asynchronous :true,
			parameters :params,
			onSuccess :loadSelectedCountry
	});
	function loadSelectedCountry(transport){
		var xml_doc = transport.responseXML.documentElement;
		var selectedCountry = xml_doc.getAttribute("selectedCountry");
		if (selectedCountry == "GB") {			
			$('nonMandatoryPostCode').hide();
			$('nonukcountrylabel').hide();
		}else{
			$('mandatoryPostCode').hide();
			$('ukcountrylabel').hide();
		}
		loadManualAddress();
}
}

/**
 * ajaxLoadSearchAddress() This method used for ajax call while click of find
 * address link. This method load all the repective search data while light box
 * loads.
 * 
 * Ajax request call parameter:
 * 
 * @param postCode
 * @param buildingNameOrNumber
 * 
 */
function ajaxLoadSearchAddress() {

	$("contentPanel").show();
	hideMannualAddress();

	var url = "ajaxLoadAddress.action";
	var postCode = "";
	var country = "";
	var buildingNameOrNumber = "";
	
	//Get the postcode from the text field or span
	if($('countryOfResidence') != null) {
		country = $('countryOfResidence').value;
	}
	else{
		country = "GB";
	}
	
	if(targetViewId == 'findAddress' ) {
		if($('regPostCode') != null) {
			postCode = $F('regPostCode');
		}

		if($('regBuildingNmNo') != null) {
			buildingNameOrNumber = $F('regBuildingNmNo');
		}

	}

	if(postCode != "" || buildingNameOrNumber != "" ) {

		var params = 'postCode=' + postCode + '&buildingNameOrNumber='
				+ buildingNameOrNumber + '&country=' + country;

		new Ajax.Request(url, {
			method :'POST',
			asynchronous :true,
			parameters :params,
			onSuccess :loadserachAddress

		});

	} else {
		hideMannualAddress();
		$('contentLoading').hide();

	}
	

	/**
	 * loadserachAddress() get all the data from rtesponse as XMl and polulate
	 * in select box.
	 * 
	 * @param transport
	 */
	function loadserachAddress(transport) {

		if (document.getElementById("addressResultDiv") != null
				&& document.getElementById("addressResultDiv") != '') {
			var addressResultDiv = document.getElementById("addressResultDiv");
			var xml_doc = transport.responseXML.documentElement;

			for (i = 0; i < xml_doc.childNodes[0].childNodes.length; i++) {

				var displayData = "";
				var populateAddressLine1 = xml_doc.childNodes[0].childNodes[i]
						.getAttribute("addressline1");
				var populateAddressLine2 = xml_doc.childNodes[0].childNodes[i]
						.getAttribute("addressline2");
				var populateCity = xml_doc.childNodes[0].childNodes[i]
						.getAttribute("city");
				var populateCounty = xml_doc.childNodes[0].childNodes[i]
						.getAttribute("county");
				var populatePostCode = xml_doc.childNodes[0].childNodes[i]
						.getAttribute("postcode");

				displayData = displayData + populateAddressLine1 + ",";

				if (populateAddressLine2 != null && populateAddressLine2 != '') {
					displayData = displayData + populateAddressLine2 + ",";
				}
				displayData = displayData + populateCity + ",";
				displayData = displayData + populateCounty + ",";

				if (populatePostCode != null && populatePostCode != '') {
					displayData = displayData + populatePostCode;
				}
				addressResultDiv.options[i] = new Option(displayData);

				$('buildingNameOrNumberId').value = buildingNameOrNumber;
				$('postCodeId').value = postCode;
			}

			hideMannualAddress();

		}
	}
	$('contentLoading').hide();
}

/**
 * populateSeachAddress() This method used for ajax Call to polulate address in
 * search box..
 * 
 * Ajax request call parameter:
 * 
 * @param addressLine1
 * @param addressLine2
 * @param townOrCity
 * @param county
 * @param postCode
 * 
 * 
 */
 
 function hideDropdownItems(){
	 
	 $$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'hidden' });
	 
	 $$('#lightboxAjax select').each( function(node) {
		node.style.visibility = 'visible'
	  });
	 
 }
 
function populateSeachAddress() {
$$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' });


	var stringChangeAddress;

	var addressResultDiv;
	var addressData;
	var addressLine1;
	var addressLine2;
	var townOrCity;
	var county;
	var postCode;
	var params;
	
	if($F('addressResultDiv') != null){
		addressResultDiv = $F('addressResultDiv').toString();

		addressData = addressResultDiv.split(',');
        
		postCode = addressData[addressData.length - 1];
		
		addressLine1 = addressData[0];


		if (addressData.length - 4 > 0) {
			addressLine2 = addressData[addressData.length - 4];
		}
		else {
			addressLine2 = "";
		}

		if (addressData.length - 3 > 0) {
			townOrCity = addressData[addressData.length - 3];
		} 
		else {
			townOrCity = "";
		}
		 
		 if (addressData.length - 2 > 0) {
			county = addressData[addressData.length - 2];
		 }
		 else {
			 county = "";
		 }
		params = 'addressLine1=' + escape(addressLine1) + '&addressLine2='
				+ escape(addressLine2) + '&townOrCity=' + escape(townOrCity) + '&county='
				+ escape(county) + '&postCode=' + escape(postCode);
	}

	var url = "ajaxSearchPolulateAddress.action";

	new Ajax.Request(url, {
		method :'POST',
		asynchronous :true,
		parameters :params,
		onSuccess :populateAddress

	});
	/**
	 * populateAddress() This methods executes on click of next button on search
	 * lightbox.
	 * 
	 * @param transport
	 */
	function populateAddress(transport) {

		var xml_doc = transport.responseXML.documentElement;
		var errorMsg = xml_doc.getAttribute("message");
		var fieldName = xml_doc.getAttribute("fieldName");

		if (errorMsg != null && errorMsg != '') {
			$('buildingNameError').hide();
			$('postCodeError').hide();
			$('noDataSelected').show();
			$('noDataSelected').innerHTML = "Please select an address.";

		} else {
			$('noDataSelected').innerHTML = "";

			stringChangeAddress = "<a href='#' rev='/fundraiser-web/fundraiser/lookupAddresss.action' target='_blank' rel='ajaxLightbox' id='changeAddress' >Change address</a>";
			if($('postcodeerror') != null) {
				$('postcodeerror').hide();
			}
			if($('buildingnumbererror') != null) {
				$('buildingnumbererror').hide();
			}
			if($('postcodeerrorimg') != null) {
				$('postcodeerrorimg').hide();
			}
			if($('buildingnumbererrorimg') != null) {
				$('buildingnumbererrorimg').hide();
			}
			
			if($('addressLookupTextComponent') != null ){
				$('addressLookupTextComponent').remove();
			}
			
			if( $('addressLookupDiv')!=null && $("addressLookupDiv") != ''){
				$('addressLookupDiv').hide();
			}
			
			if( $('postcodeChange')!=null && $("postcodeChange") != ''){
				$('postcodeChange').hide();
			}
			
			if( $('displayIdForbuildingNameNumber')!=null && $("displayIdForbuildingNameNumber") != ''){
				$('displayIdForbuildingNameNumber').hide();
			}
			if( $('regBuildingNmNo')!=null && $("regBuildingNmNo") != ''){
				$('regBuildingNmNo').hide();
			}
			if( $('displayIdPostCode')!=null && $("displayIdPostCode") != ''){
				$('displayIdPostCode').hide();
			}
			if( $('regPostCode')!=null && $("regPostCode") != ''){
				$('regPostCode').hide();
			}
			
			if( $('findAddress')!=null && $("findAddress") != ''){
				$('findAddress').hide();
			}

			if( $('detailedAddress')!=null && $("detailedAddress") != ''){
				$('detailedAddress').hide();
			}
			
			if( $('changeAddress')!=null && $("changeAddress") != ''){
				$('changeAddress').hide();
			}

			if( $('adminBuildingnameOrNumber')!=null && $("adminBuildingnameOrNumber") != ''){
				$('adminBuildingnameOrNumber').show();
			}
			if( $('adminPostCode')!=null && $("adminPostCode") != ''){
				$('adminPostCode').show();	
			}

			if( $('displayAddressData')!=null && $("displayAddressData") != ''){
				$('displayAddressData').hide();	
			}

			if( $('detailCorrectYes')!=null && $("detailCorrectYes") != ''){
				$('detailCorrectYes').checked= false;	
			}

			if( $('detailCorrectNo')!=null && $("detailCorrectNo") != ''){
				$('detailCorrectNo').checked= false;	
			}
			
			var postCodeChangeAddress = postCode + "&nbsp;&nbsp;&nbsp; &nbsp;"
					+ stringChangeAddress;
			if($('displayAddressData') != null) {
				$('displayAddressData').remove();	
			}

			$('displayAddressLine1').innerHTML = addressLine1;
			$('displayAddressLine2').innerHTML = addressLine2;
			$('displayCity').innerHTML = townOrCity;
			$('displayCounty').innerHTML = county;
			$('displayPostCode').innerHTML = postCodeChangeAddress

			if($('addressChangedUsingLink') != null) {
				$("addressChangedUsingLink").value=true;
			}
			closeLightBox();
			showElements();
		}
		
	}
	
	if($('displayAddress') != null) {
		if($('postcodeerror') != null) {
			$('postcodeerror').hide();
		}
		if($('buildingnumbererror') != null) {
			$('buildingnumbererror').hide();
		}
		if($('postcodeerrorimg') != null) {
			$('postcodeerrorimg').hide();
		}
		if($('buildingnumbererrorimg') != null) {
			$('buildingnumbererrorimg').hide();
		}

		$('displayAddress').show();
	}
	if ($("displayAddressManual")!= null) {
		 $("displayAddressManual").show();
	}
	if ($("displayAddressSession")!= null) {
		 $("displayAddressSession").hide();
	}

}

function populateSearchCharity(charityIdLB) {
$$('select', 'object', 'embed').each(function(node){ node.style.visibility = 'visible' });
	
	//alert('charityname from light box ' + charityNameLB);
	//alert('charityname from search box ' + $('charityName').value);

    var elementId = "charity.name." + charityIdLB;
    var nameElement = document.getElementById(elementId);
    var charityNameLB = nameElement.innerHTML;
    var charityName;
	var params;
	//charityName= $F('charityName')
	//$F('charityName') = charityNameLB
	var element = $$('div.fur0070hiddenDiv');
	var element2 = $$('div.fur0080hiddenDiv');
	if($('S').checked){		
		$('charityName').value = charityNameLB;
		$('charityId').value = charityIdLB;
		$('selectedCharityName').value = charityNameLB;
		element2[0].hide();
		element[0].show();	
	}else {		
		$('addCharityName').value = charityNameLB;
		$('addCharityId').value = charityIdLB;
		element[0].hide();	
		element2[0].show();
		addSelectedCharity();
	}
	//
	closeLightBox();
	showElements();		
	/*	
	params = 'charityName=' + escape(charityName);
	
	var url = "ajaxSearchPopulateCharity.action";
	
	new Ajax.Request(url, {
		method :'POST',
		asynchronous :true,
		parameters :params,
		onSuccess :populateCharity
	});
	*/
	/**
	 * This methods executes on click of next button on search
	 * lightbox.
	 * 
	 * @param transport
	 */      
/*	function populateCharity(transport) {
		alert("in populate charity");
		var xml_doc = transport.responseXML.documentElement;
		var errorMsg = xml_doc.getAttribute("message");
		var fieldName = xml_doc.getAttribute("fieldName");

			alert("fieldName " + fieldName);
			alert("xml_doc " + xml_doc);
			if($('charitynameerror') != null) {
				$('charitynameerror').hide();
			}
			
			alert("setting charity name " + charityNameLB);
						
			$('charityName').value = charityNameLB;
			$('charityId').value = charityIdLB;
			$('selectedCharityName').value = charityNameLB;

			closeLightBox();
			showElements();		
		
	}
	*/
}

/**
 * loadManualAddress() This method load all the data to manual address light box .
 * 
 */
function loadManualAddress() {

	var insertAddressline1 = $('displayAddressLine1').innerHTML;
	var selectedCountry = $('displayAddressLine1').innerHTML;
	
	var countryCode ="";
	if($('countryOfResidence') != null) {
		countryCode = $('countryOfResidence').value;
	} else {
		countryCode = "GB";
	}
	
	if ($('insertAddressLine1') != null && $('insertAddressLine1') != '') {
		$('insertAddressLine1').value = insertAddressline1;
	}

	var insertAddressline2 = $('displayAddressLine2').innerHTML;
	if ($('insertAddressLine2') != null && $('insertAddressLine2') != '') {
		$('insertAddressLine2').value = insertAddressline2;
	}

	var insertCity = $('displayCity').innerHTML;
	if ($('insertTownOrCity') != null && $('insertTownOrCity') != '') {
		$('insertTownOrCity').value = insertCity;
	}

	var insertCounty = $('displayCounty').innerHTML;
	if ($('insertCounty') != null && $('insertCounty') != '') {
		$('insertCounty').value = insertCounty;
	}
	if ($('insertCounty') != null && $('insertCounty') != '') {
			if ($('insertCounty1') != null) {
			  $('insertCounty1').value = insertCounty;
			} 
	}

	var insertPostCode = $('displayPostCode').innerHTML;
	var postCodeData = insertPostCode.split('&nbsp;');
	if ($('insertPostCode') != null && $('insertPostCode') != '') {
		$('insertPostCode').value = postCodeData[0];
	}
	if (countryCode != "GB") {
	var insertPostCode1 = $('displayPostCode').innerHTML;
	var postCodeData1 = insertPostCode1.split('&nbsp;');
	if ($('insertPostCode1') != null && $('insertPostCode1') != '') {
		$('insertPostCode1').value = postCodeData1[0];
	}
	}
	hideSearchAddress();
}
/**
 * updateManualAddress() This method used for ajax Call to polulate address in
 * manual address box..
 * 
 * Ajax request call parameter:
 * 
 * @param addressLine1
 * @param addressLine2
 * @param townOrCity
 * @param county
 * @param postCode
 */

function updateManualAddress() {

	var stringChangeAddress;
	var addressLine1 = $('insertAddressLine1').value;
	var addressLine2 = $('insertAddressLine2').value;
	var townOrCity = $('insertTownOrCity').value;
	var county = $('insertCounty').value;
	var county1 = $('insertCounty1').value;
	var postCode = $('insertPostCode').value;
	var postCode1 = $('insertPostCode1').value;
	var country = $('insertCountry').value;
	if (countryCode != "GB") {
		postCode = postCode1;
		county = county1;
	}
	
	if(validateManualAddress(addressLine1, addressLine2, townOrCity, county, postCode, countryCode)) {
		
	var params = 'addressLine1=' + escape(addressLine1) + '&addressLine2='
			+ escape(addressLine2) + '&townOrCity=' + escape(townOrCity) + '&county='
			+ escape(county) + '&postCode=' + escape(postCode) + '&country=' + escape(country);

	var url = "ajaxManualPolulateAddress.action";

	new Ajax.Request(url, {
		method :'POST',
		asynchronous :true,
		parameters :params,
		onSuccess :populateManualAddress

	});
	
	}

	/**
	 * populateAddress() This methods executes on click of next button on manual
	 * search lightbox.
	 * 
	 * @param transport
	 */
	function populateManualAddress(transport) {

		var xml_doc = transport.responseXML.documentElement;
		if (transport.responseText !== undefined) {
			var errorMsg = xml_doc.getAttribute("message");
			if($('postcodeerror') != null) {
				$('postcodeerror').hide();
			}
			if($('buildingnumbererror') != null) {
				$('buildingnumbererror').hide();
			}
			if($('postcodeerrorimg') != null) {
				$('postcodeerrorimg').hide();
			}
			if($('buildingnumbererrorimg') != null) {
				$('buildingnumbererrorimg').hide();
			}
		if (errorMsg != null && errorMsg != '') {
				$('manualaddressLine1').innerHTML = "";
				$('manualaddressLine2').innerHTML = "";
				$('manualTownOrCity').innerHTML = "";
				$('manualCounty').innerHTML = "";
				$('manualPostCode').innerHTML = "";
			for ( i = 0 ; i < xml_doc.childNodes[0].childNodes.length; i++){					
				fieldErrorMessage = xml_doc.childNodes[0].childNodes[i];					
				fieldName = fieldErrorMessage.getAttribute("fieldName");
				msg = fieldErrorMessage.getAttribute("message");								

				if (fieldName == "addressline1") {
					$('manualaddressLine1').innerHTML = msg;
				} 
				if (fieldName == "addressline2") {						
					$('manualaddressLine2').innerHTML = msg;
				} 
				if (fieldName == "city") {						
					$('manualTownOrCity').innerHTML = msg;
				} 
				if (fieldName == "county") {					
					$('manualCounty').innerHTML = msg;
				} 
				if (fieldName == "postcode") {					
					$('manualPostCode').innerHTML = msg;
				}
			}

		} else {

				stringChangeAddress = "<a href='#' rev='/fundraiser-web/fundraiser/lookupAddresss.action' target='_blank' rel='ajaxLightbox' id='changeAddress'>Change address</a>";

				if ($('displayAddress') != null) {
					$('displayAddress').show();
					}

					if ($('displayAddressManual') != null)
					{
						if($('postcodeerror') != null) {
							$('postcodeerror').hide();
						}
						if($('buildingnumbererror') != null) {
							$('buildingnumbererror').hide();
						}
						if($('postcodeerrorimg') != null) {
							$('postcodeerrorimg').hide();
						}
						if($('buildingnumbererrorimg') != null) {
							$('buildingnumbererrorimg').hide();
						}
						$('displayAddressManual').show();
					}
				
				if($('addressLookupTextComponent') != null ){
					$('addressLookupTextComponent').remove();
				}
				
				if($('postcodeChange') != null ){
					$('postcodeChange').remove();
				}

				if($('displayAddressData') != null) {
					$('displayAddressData').remove();	
				}
				
				if( $('displayIdForbuildingNameNumber')!=null && $("displayIdForbuildingNameNumber") != ''){
					$('displayIdForbuildingNameNumber').hide();
				}
				if( $('regBuildingNmNo')!=null && $("regBuildingNmNo") != ''){
					$('regBuildingNmNo').hide();
				}
				if( $('displayIdPostCode')!=null && $("displayIdPostCode") != ''){
					$('displayIdPostCode').hide();
				}
				if( $('regPostCode')!=null && $("regPostCode") != ''){
					$('regPostCode').hide();
				}
				if( $('findAddress')!=null && $("findAddress") != ''){
					$('findAddress').hide();
				}
				if( $('detailedAddress')!=null && $("detailedAddress") != ''){
					$('detailedAddress').hide();
				}
				if( $('changeAddress')!=null && $("changeAddress") != ''){
					$('changeAddress').hide();
				}
				if( $('adminBuildingnameOrNumber')!=null && $("adminBuildingnameOrNumber") != ''){
					$('adminBuildingnameOrNumber').show();
				}
				if( $('adminPostCode')!=null && $("adminPostCode") != ''){
					$('adminPostCode').show();	
				}
                if( $('displayAddressData')!=null && $("displayAddressData") != ''){
				    $('displayAddressData').hide();	
			    }
				
				if( $('detailCorrectYes')!=null && $("detailCorrectYes") != ''){
					$('detailCorrectYes').checked= false;	
				}

				if( $('detailCorrectNo')!=null && $("detailCorrectNo") != ''){
					$('detailCorrectNo').checked= false;	
				}


				var postCodeChangeAddress = postCode
						+ "&nbsp;&nbsp;&nbsp; &nbsp;" + stringChangeAddress;

				$('displayAddressLine1').innerHTML = addressLine1;
				$('displayAddressLine2').innerHTML = addressLine2;
				$('displayCity').innerHTML = townOrCity;
				$('displayCounty').innerHTML = county;
				$('displayPostCode').innerHTML = postCodeChangeAddress


				if ($("displayAddressSession") != null) {
					 $("displayAddressSession").hide();
				}
				if($('addressChangedUsingLink') != null) {
					$("addressChangedUsingLink").value=true;
				}
				closeLightBox();
				showElements();

			}

		}
	}
}
function hideSearchAddress() {
	if ($("searchAddress") != null && $("searchAddress") != '') {
		//initialFlag = "N";
		$("searchAddress").hide();
	}
	if ($("mannualAddress") != null && $("mannualAddress") != '') {
		$("mannualAddress").show();
		if ($('insertAddressLine1') != null && $('insertAddressLine1') != '') {
			$('insertAddressLine1').focus();
		}
	}

}

function hideMannualAddress() {
	if ($("searchAddress") != null && $("searchAddress") != '') {
		$("searchAddress").show();
		if ($('buildingNameOrNumberId') != null && $('buildingNameOrNumberId') != '') {
			$('buildingNameOrNumberId').focus();
		}
	}
	if ($("mannualAddress") != null && $("mannualAddress") != '') {
		$("mannualAddress").hide();
	}

}

function hide() {
	if ($("searchAddress") != null && $("searchAddress") != '') {
		$("searchAddress").hide();
	}
	if ($("mannualAddress") != null && $("mannualAddress") != '') {
		$("mannualAddress").hide();
	}

}

function closeLightBox() {

	AjaxLightbox.prototype.end();

}

function hideElements(){
	if($('cardType') != null) {
	  $('cardType').style.display = 'none';
	}
	if($('firstnameTitle') != null) {
	  $('firstnameTitle').style.display = 'none';
	}
	if($('countryResidence') != null) {
	  $('countryResidence').style.display = 'none';
	}
	if($('menu1') != null) {
		  $('menu1').style.display = 'none';
		}
		if($('menu2') != null) {
		  $('menu2').style.display = 'none';
		}
		if($('menu3') != null) {
		  $('menu3').style.display = 'none';
		}
		if($('menu4') != null) {
		  $('menu4').style.display = 'none';
		}
} 
function showElements(item){ 
	if($('cardType') != null) {
	  $('cardType').style.display = 'inline';   
	}
	if($('firstnameTitle') != null) {
	  $('firstnameTitle').style.display = 'inline';   
	}
	if($('countryResidence') != null) {
	  $('countryResidence').style.display = 'inline';   
	}
	if($('menu1') != null) {
	  $('menu1').style.display = 'inline';   
	}
	if($('menu2') != null) {
	  $('menu2').style.display = 'inline';   
	}
	if($('menu3') != null) {
	  $('menu3').style.display = 'inline';   
	}
	if($('menu4') != null) {
	  $('menu4').style.display = 'inline';   
	}
} 

function displayFundraiserEventDescription() {

	var url = "informationDescrption.action";
	var targetURLParams = ""
	var eventId = "";
	
	if(targetRev != null && targetRev != ''){
		targetURLParams = targetRev.split("eventId=");
	}
	//In the targetURLParams, split variable and get the eventId
	if(targetURLParams != null){
		eventId = targetURLParams[1];
	}
	if(eventId != '') {

		var params = 'eventId=' + eventId;

		new Ajax.Request(url, {
			method :'POST',
			asynchronous :true,
			parameters :params,
			onSuccess :displayDescription

		});
	}

	
	function displayDescription(transport) {

		var xml_doc = transport.responseXML.documentElement;
		var message = xml_doc.getAttribute("description");
		$('displayDescription').innerHTML = message ;
		
	}
	
}

function validateAddress(postCode, buildingNameOrNumber) {
	 var validationPass = true;

	 

	 if(buildingNameOrNumber !=null && buildingNameOrNumber != '') {
	       if(containsInvalidChars(buildingNameOrNumber)) {
	            $('buildingNameError').show();
	            $('buildingNameError').innerHTML = "Invalid characters entered.";
	            validationPass = false;
	        }else {
	            $('buildingNameError').innerHTML = "";
	            $('postCodeError').innerHTML = "";
	        }
	        
	    }else {
	            $('buildingNameError').innerHTML = "";
	            $('postCodeError').innerHTML = "";
	    }  

	 

	 if(postCode != null && postCode != '') {
	        if(containsInvalidChars(postCode)) {
	            $('postCodeError').show();
	            $('postCodeError').innerHTML = "Invalid characters entered.";
	            validationPass = false;
	        }else {
	            $('postCodeError').innerHTML = "";
	        }
	 }else {
	         $('postCodeError').innerHTML = "Please enter valid postcode.";
	}
	 
	 return validationPass;
	}

function validateManualAddress(addressLine1Para, addressLine2Para, townOrCityPara, countyPara, postCodePara, countryCodePara) {
	var validationPass = true;
	 
	     if(addressLine1Para != null) {
	        if(containsInvalidChars(addressLine1Para)) {
	            $('manualaddressLine1').innerHTML = "Invalid characters entered.";
	            validationPass = false;
	        }else if(addressLine1Para == '') {
	            $('manualaddressLine1').innerHTML = "Address details missing.";
	            validationPass = false;
	        }else {
	            $('manualaddressLine1').innerHTML = "";

	        }
	     }

	     if(addressLine2Para != null || addressLine2Para != '') {
	        if(containsInvalidChars(addressLine2Para)) {
	            $('manualaddressLine2').innerHTML = "Invalid characters entered.";
	            validationPass = false;
	        }else {
	            $('manualaddressLine2').innerHTML = "";
	        }
	     }

	    if(townOrCityPara != null) {
	        if(containsInvalidChars(townOrCityPara)) {
	            $('manualTownOrCity').innerHTML = "Invalid characters entered.";
	            validationPass = false;
	        }else if(townOrCityPara == '') {
	            $('manualTownOrCity').innerHTML = "Address details missing.";
	            validationPass = false;
	        }else {
	            $('manualTownOrCity').innerHTML = "";
	        }
	 }

	    if(countyPara != null) {
			if(countryCodePara == "GB"){
				if(containsInvalidChars(countyPara)) {
					$('manualCounty').innerHTML = "Invalid characters entered.";
					validationPass = false;
				}else if(countyPara == '') {
					$('manualCounty').innerHTML = "Address details missing.";
					validationPass = false;
				}else {
					$('manualCounty').innerHTML = "";
				}
			}else{
				if(containsInvalidChars(countyPara)) {
					$('manualCounty1').innerHTML = "Invalid characters entered.";
					validationPass = false;
				}else if(countyPara == '') {
					$('manualCounty1').innerHTML = "Address details missing.";
					validationPass = false;
				}else {
					$('manualCounty1').innerHTML = "";
				}

			}

	 }
	    if(postCodePara != null) {
			if(countryCodePara == "GB"){
				if(containsInvalidChars(postCodePara)) {
					$('manualPostCode').innerHTML = "Invalid characters entered.";
					validationPass = false;
				}else if(postCodePara == '') {
					$('manualPostCode').innerHTML = "Address details missing.";
					validationPass = false;
				}else {
					$('manualPostCode').innerHTML = "";
				}
			}
	    }
	 
	 return validationPass;
	}

function containsInvalidChars(string) {
	 
	 if (!string)return false;	 

	 var iChars = "|<>[]{}#€^~";

	 for ( var i = 0; i < string.length; i++) {
	  if (iChars.indexOf(string.charAt(i)) != -1)
	   return true;
	 }
	 return false;
	}