// -----------------------------------------------------------------------------------
//
//  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 == "detailedAddressForNonUKCountry") {
	                               				ajaxGetCountryForDisplayChangeAddress();
						    } else if (targetViewId == "displayChangeAddress") {
								loadTargetContent = false;
								hideSearchAddress();
								ajaxGetCountryForDisplayChangeAddress();
							} else if (targetViewId == 'fundraiserEventInformationLookup'
									&& loadTargetContent) {
								loadTargetContent = false;
								displayFundraiserEventDescription();
							}else if( targetViewId == 'fundraiserThankYouMessagePreviewBtn' && loadTargetContent){
								loadTargetContent = false;
								thankyouMessageText();
							} else if(targetViewId == 'donorThankYouMessagePreviewBtn' && loadTargetContent) {
								loadTargetContent = false;
								donorthankyouMessageText();
							}else if (targetViewId == 'eventInformationLookup'
									&& loadTargetContent) {
								loadTargetContent = false;
								eventInformationLookup();
							}
						
						} 
					}
				});

	},

	//
	// end()
	//
	end : function() {
	
		LightboxOptions.ajaxOpened = false;
		thisObject = this;

		new Effect.Fade(LightboxOptions.lightboxAjax, {
			duration :LightboxOptions.overlayDuration,
			afterFinish : function() {
				$('lightboxAjax').remove();
			}
		});
		new Effect.Fade(LightboxOptions.contentOverlay, {
			duration :LightboxOptions.overlayDuration,
			afterFinish : function() {
				$('contentOverlay').remove();
			}
		});
		thisObject.resizeImageContainer(250, 250);
		$$('select', 'object', 'embed').each( function(node) {
			node.style.visibility = 'visible'
		});
		
		

	},

	//
	// 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();
});

/**
 * 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=' + escape(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" && $('nonMandatoryPostCode') != null) {			
			$('nonMandatoryPostCode').hide();
		}else if($('mandatoryPostCode') != null){
			$('mandatoryPostCode').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') != null) {			
		   $('nonMandatoryPostCode').hide();
		}else if($('mandatoryPostCode')!= null){			
			$('mandatoryPostCode').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 buildingNameOrNumber = "";
	if($('countryOfResidence') != null) {
		country = $('countryOfResidence').value;
	}
	else{
		country = "GB";
	}

	// Get the postcode from the text field or span

	if (targetViewId == 'findAddress') {
		if ($('regPostCode') != null) {
			postCode = $F('regPostCode');
		}

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

	} else if (targetViewId == 'changeAddress') {

		if ($('displayAddressDataPostCode') != null) {
			displayPostCodeHTML = $('displayAddressDataPostCode').innerHTML;
			postCode = displayPostCodeHTML.split("&nbsp;")[0];
		} else if ($('displayPostCode') != null) {
			displayPostCodeHTML = $('displayPostCode').innerHTML;
			postCode = displayPostCodeHTML.split("&nbsp;")[0];
		}
	}

	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 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();
			$('adminBuildingnameOrNumber').hide();
			$('adminPostCode').hide();
			$('noDataSelected').innerHTML = "Please select an address.";

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

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

			if ($('addressLookupTextComponent') != null) {
				$('addressLookupTextComponent').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($('displayLookUpAddress') != null
				    && $("displayLookUpAddress") != '') {
		       $('displayLookUpAddress').remove();
	        }

			if($('displayPostcodeAndHouseNO') != null
					&& $("displayPostcodeAndHouseNO") != '') {
		       $('displayPostcodeAndHouseNO').hide();
	        }
			
			if ($('validatePostcodeAndHouseName') != null) {		
				$('validatePostcodeAndHouseName').value = false;
			}

			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
	
			//TODO
			if($('addressLinkForUk')!=null) {
			 $('addressLinkForUk').hide();
			}
			 if($('addressLinkForOthers')!=null) {
			 $('addressLinkForOthers').hide();
			 }
		 
			 if($('addressLinkForUkOnClick')!=null) {
				 $('addressLinkForUkOnClick').hide();
			 }
			 if($('addressLinkForOthersOnClick')!=null){
				 $('addressLinkForOthersOnClick').hide();
			 }
			 if($('addressChangedUsingLink') != null) {
					$("addressChangedUsingLink").value=true;
				}
							
			closeLightBox();	
			showElements();
					
		}

	}
	
	if ($('displayAddress') != null) {
		if($('postcodeerror') != null) {
			$('postcodeerror').hide();
		}
		if($('postcodeerrorimg') != null) {
			$('postcodeerrorimg').hide();
		}
		if($('postcodeErrorMessage') != null) {
			$('postcodeErrorMessage').hide();
		}
		if($('postcodeErrorImage') != null) {
			$('postcodeErrorImage').hide();
		}
		if($('buildingNoErrorMessage') != null) {
			$('buildingNoErrorMessage').hide();
		}
		if($('buildingNoErrorImg') != null) {
			$('buildingNoErrorImg').hide();
		}
		if($('buildingErrorMessage') != null) {
			$('buildingErrorMessage').hide();
		}
		if($('buildingErrorImage') != null) {
			$('buildingErrorImage').hide();
		}
		$('displayAddress').show();
	}

}

/**
 * loadManualAddress() This method load all the data to manual address light box .
 * 
 */
function loadManualAddress() {   
	
	var selectedCountry = $('displayAddressLine1').innerHTML;
	var insertAddressline1;
	var insertAddressline2;
	var insertCity;
	var insertCounty;
	var insertPostCode;

	var countryCode ="";
	
	if($('countryOfResidence') != null) {
		countryCode = $('countryOfResidence').value;
	} else {
		countryCode = "GB";
	}

	if ($('displayAddressLine1') != null ) {
		insertAddressline1 = $('displayAddressLine1').innerHTML;
	}

	if ($('displayAddressLine2') != null ) {
		insertAddressline2 = $('displayAddressLine2').innerHTML;
	}

	if ($('displayCity') != null ) {
		insertCity = $('displayCity').innerHTML;
	}

	if ($('displayCounty') != null ) {
		insertCounty = $('displayCounty').innerHTML;
	}

	if ($('displayPostCode') != null ) {
		insertPostCode = $('displayPostCode').innerHTML;
	}

	if ($('displayedAddressLine1') != null ) {
		
		insertAddressline1 = $('displayedAddressLine1').innerHTML;
	}

	if ($('displayedAddressLine2') != null ) {
		insertAddressline2 = $('displayedAddressLine2').innerHTML;
	}

	if ($('displayedCity') != null ) {
		insertCity = $('displayedCity').innerHTML;
	}

	if ($('displayedCounty') != null ) {
		insertCounty = $('displayedCounty').innerHTML;
	}

	if ($('displayedPostCode') != null ) {
		insertPostCode = $('displayedPostCode').innerHTML;
	}
   
	if ($('insertAddressLine1') != null && $('insertAddressLine1') != '') {			
		$('insertAddressLine1').value = insertAddressline1.trim();
			
	}	 
	
	if ($('insertAddressLine2') != null && $('insertAddressLine2') != '') {		
		$('insertAddressLine2').value = insertAddressline2.trim();
	}
	
	if ($('insertTownOrCity') != null && $('insertTownOrCity') != '') {		
		$('insertTownOrCity').value = insertCity.trim();
	}

	 
	if ($('insertCounty') != null && $('insertCounty') != '') {		
		$('insertCounty').value = insertCounty.trim();
	}	 
	
	var postCodeData = insertPostCode.trim().split('&nbsp;');
	if ($('insertPostCode') != null && $('insertPostCode') != '') {
		$('insertPostCode').value = postCodeData[0];
	}
	if (countryCode != "GB") {			
		if ($('insertPostCode1') != null && $('insertPostCode1') != '') {
			$('insertPostCode1').value = postCodeData[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 postCode = $('insertPostCode').value;
	var postCode1;
	if($('insertPostCode1') != null) {
	  postCode1 = $('insertPostCode1').value;
	}
	
	if (countryCode != "GB") {
		postCode = postCode1;
	}
	
	if(validateManualAddress(addressLine1, addressLine2, townOrCity, county, postCode)) {

        var params = 'addressLine1=' + escape(addressLine1) + '&addressLine2='
                + escape(addressLine2) + '&townOrCity=' + escape(townOrCity)
                + '&county=' + escape(county) + '&postCode=' + escape(postCode);
        
        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($('postcodeerrorimg') != null) {
				$('postcodeerrorimg').hide();
			}
			if($('postcodeErrorMessage') != null) {
				$('postcodeErrorMessage').hide();
			}
			if($('postcodeErrorImage') != null) {
				$('postcodeErrorImage').hide();
			}
			if($('buildingErrorMessage') != null) {
				$('buildingErrorMessage').hide();
			}
			if($('buildingNoErrorImg') != null) {
				$('buildingNoErrorImg').hide();
			}
			if($('buildingNoErrorMessage') != null) {
				$('buildingNoErrorMessage').hide();
			}
			if($('buildingErrorImage') != null) {
				$('buildingErrorImage').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='/charity-web/charity/lookupAddresss.action' target='_blank' rel='ajaxLightbox' id='changeAddress'>Change address</a>";

				$('displayAddress').show();

				if ($('addressLookupTextComponent') != null) {
					$('addressLookupTextComponent').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($('displayLookUpAddress') != null
					    && $("displayLookUpAddress") != '') {
		           $('displayLookUpAddress').remove();
	            }

				if($('displayPostcodeAndHouseNO') != null
					    && $("displayPostcodeAndHouseNO") != '') {
		           $('displayPostcodeAndHouseNO').hide();
	            }
				
				if ($('validatePostcodeAndHouseName') != null) {		
					$('validatePostcodeAndHouseName').value = false;
				}

				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($('addressLinkForUk')!=null) {
					 $('addressLinkForUk').hide();
					}
					 if($('addressLinkForOthers')!=null) {
					 $('addressLinkForOthers').hide();
					 }
				 
					 if($('addressLinkForUkOnClick')!=null) {
						 $('addressLinkForUkOnClick').hide();
					 }
					 if($('addressLinkForOthersOnClick')!=null){
						 $('addressLinkForOthersOnClick').hide();
					 }
					 if($('addressChangedUsingLink') != null) {
							$("addressChangedUsingLink").value=true;
						}

				closeLightBox();
				showElements();

			}

		}
	}	
}


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) {
var validationPass = true;
var countryOfResidenceVar = "GB";
if($('countryOfResidence') != null && $('countryOfResidence') != '') {
	countryOfResidenceVar = $('countryOfResidence').value;
} 

	 if(addressLine1Para != null) {
        if(containsInvalidCharsForManualAddress(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(containsInvalidCharsForManualAddress(addressLine2Para)) {
            $('manualaddressLine2').innerHTML = "Invalid characters entered.";
            validationPass = false;
        }else {
            $('manualaddressLine2').innerHTML = "";
        }
     }

	
    if(townOrCityPara != null) {
        if(containsInvalidCharsForManualAddress(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(containsInvalidCharsForManualAddress(countyPara)) {
            $('manualCounty').innerHTML = "Invalid characters entered.";
            validationPass = false;
        }else if(countyPara == '') {
            $('manualCounty').innerHTML = "Address details missing.";
            validationPass = false;
        }else {
            $('manualCounty').innerHTML = "";
        }
	}

    if(postCodePara != null) {
        if(containsInvalidChars(postCodePara)) {
            $('manualPostCode').innerHTML = "Invalid characters entered.";
            validationPass = false;
        }else if(postCodePara == '') {
			if(countryOfResidenceVar == 'GB') {
				$('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;
}

function containsInvalidCharsForManualAddress(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;
}

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 ($('Title') != null) {
		$('Title').style.display = 'none';
	}
	if ($('cardType') != null) {
		$('cardType').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 ($('Title') != null) {
		$('Title').style.display = 'inline';
	}
	if ($('cardType') != null) {
		$('cardType').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";
	// split the targetRev to get the parameter string (
	var targetURLParams = ""
	var eventId = "";

	if (targetRev != null && targetRev != '') {
		targetURLParams = targetRev.split("?");
	}
	// In the targetURLParams, split variable and get the eventId
	if (targetURLParams != null) {
		eventId = targetURLParams[1].split("=")[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 eventInformationLookup() {

	var url = "informationDescrption.action";
	// split the targetRev to get the paameter string (
	var targetURLParams = ""
	var eventId = "";

	if (targetRev != null && targetRev != '') {
		targetURLParams = targetRev.split("?");
	}
	// In the targetURLParams, split variable and get the eventId
	if (targetURLParams != null) {
		eventId = targetURLParams[1].split("=")[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 thankyouMessageText() {// 1

	var url = "thankyouMessagePreview.action";

	var thankyouText = $F('thankyouText');

	thankyouText = escape(thankyouText);
	while (thankyouText.indexOf("%0A") != -1)
	{
		thankyouText = thankyouText.replace(/%0A/,"<br>");
	}
	
	var params = 'thankyouText=' + thankyouText;
	
	new Ajax.Request(url, {// 5
				method :'POST',
				asynchronous :true,
				parameters :params,
				onSuccess :thankyouMessageData

			});

	function thankyouMessageData(transport) {// 1

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

	}
}

function donorthankyouMessageText() {// 1

	var url = "donorthankdyouMessagePreview.action";

	var thankyouText1 = $F('thankyouText1');
	
	thankyouText1 = escape(thankyouText1);
	while (thankyouText1.indexOf("%0A") != -1)
	{
		thankyouText1 = thankyouText1.replace(/%0A/,"<br>");
	}
	
	var params = 'thankyouText1=' + thankyouText1;

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

			});

	function thankyouMessageData(transport) {// 1

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

	}
}

String.prototype.trim = function(){
if(this != null) {
  return( this.replace(new RegExp("^([\\s]+)|([\\s]+)$", "gm"), "") );
}
}
