/*

	REQUIRED SCRIPTS:
		Display.js
		nodeHandlers.js

	Example Call:
		<textarea name="" id="myAddress"><!--- address value ---></textarea>
		<script>	
			new inputAddress(
				flexible			= true,
				targetTextArea		= document.getElementById('myAddress'),
				addressParts		= "description,street,street2,city,state,zip,county,country",
				defaultState		=	"",
				defaultCountry		=	"United States of America"
			);
		</script>
	
	Example Return of Values( each address part is seperated by tab, and each address is seperated by a return ):
		`description	street	suite	city	state	zip	county	country
		description	street	suite	city	state	zip	county	country`

*/

inputAddressCloneCount = 0;
/* PROMARY object controller */
	inputAddress = function( flexible , targetTextArea , addressParts , defaultState , defaultCountry ){

		/* defaults */
			this.flexible			= true;
			this.targetTextArea		= true;
			this.addressParts		= "description,street,street2,city,state,zip,county,country";
			this.defaultState		= "";
			this.defaultCountry		= "United States of America";
		/* end */

		/* convert arguments into this properties */
			this.flexible			=	flexible;
			this.targetTextArea		=	targetTextArea;
			this.addressParts		=	addressParts;
			this.defaultState		=	defaultState;
			this.defaultCountry		=	defaultCountry;
		/* end */

		this.addressParts = this.addressParts.replace(/\s/g,'').toLowerCase();
	
		/* this clone handling */
			eval('inputAddressClone' + inputAddressCloneCount + ' = this');
			this.inputAddressCloneCount = inputAddressCloneCount;
		/* end */
	
		this.targetTextArea.style.position = 'absolute';
		this.targetTextArea.style.left = '-1000px';
	
		/* convert value into row array */
			valueArray = new Array();
			if( this.targetTextArea.value.search(/[^\s\r\t\n]/) >= 0 ){
				var valueArray = this.targetTextArea.value.split('\n');
			}
			/* make columns out of rows in array */
				for( var x=0; x < valueArray.length; ++x ){
					valueArray[x] = valueArray[x].split('\t');
				}
			/* end */
		/* end */
		
		var tempSpan = document.createElement('SPAN');
		var tempSpan = document.createElement('SPAN');
		tempSpan.innerHTML = '<span style="display:inline-block"><div style="display:table-cell"></div></span>';
		this.inputContainer = tempSpan.getElementsByTagName('DIV')[0];
	
		if( this.flexible ){
			var tempSpan = document.createElement('SPAN');
			tempSpan.innerHTML='<span style="display:inline-block"><div style="display:table-cell;white-space:nowrap"></div></span>';
			tempSpan.appendChild( this.inputContainer.parentNode );
			var tempHref = document.createElement('A');
			tempHref.className = 'plusBox';
			tempHref.style.verticalAlign = 'bottom';
			eval("tempHref.onclick = function(){ inputAddressClone"+this.inputAddressCloneCount+".createAddress();return false; }");
			tempHref.innerHTML = '+';
			tempHref.href='';
			tempSpan.appendChild( tempHref );
			this.targetTextArea.parentNode.insertBefore( tempSpan , this.targetTextArea );
		}else{
			this.targetTextArea.parentNode.insertBefore( this.inputContainer.parentNode , this.targetTextArea );
		}
	
		/* Handle Assigned Values & and call to generate address */
			this.totalInputs = 0;

			var address_types = ['description','street','street2','city','state','zip','county','country'];
			var variables = new Array();
			
			/* init values */
				for( var x=0; x < address_types.length; ++x ){
					variables[address_types[x]] = "";
				}
			/* end */

			if( valueArray.length ){
				for( var x=0; x < valueArray.length; ++x ){
					var targetValuesCount = 0;
					for( var add_type_loop=0; add_type_loop < address_types.length; ++add_type_loop ){
						var regX = "(^|,)" + address_types[add_type_loop] + "(,|$)";
						if(
							valueArray[x].length > targetValuesCount
						&&
							this.addressParts.search( regX ) >= 0
						){
							variables[address_types[add_type_loop]] = valueArray[x][targetValuesCount]
							/* massage string */
								variables[address_types[add_type_loop]] = variables[address_types[add_type_loop]].replace(/(^(\s|\n|\r|\n)+|(\s|\n|\r|\n)+$)/,'');
								variables[address_types[add_type_loop]] = variables[address_types[add_type_loop]].replace(/^_$/,'');
							/* end */
							++targetValuesCount;
						}
					}
	
					this.createAddress( variables.description , variables.street , variables.street2 , variables.city , variables.state , variables.zip , variables.county , variables.country );
				}
			}else{
				this.createAddress( variables.description , variables.street , variables.street2 , variables.city , variables.state , variables.zip , variables.county , variables.country );
			}
		/* end */
		
		/* put the target textArea inside the container for value sync'ing */
			this.inputContainer.appendChild( this.targetTextArea );
		/* end */
		
		++inputAddressCloneCount;
	}
/* end */

/* faciliate the creation of address inputs */
	inputAddress.prototype.createAddress = function( description , street , street2 , city , state , zip , county , country ){
		var newAddress = document.createElement('DIV');
		newAddress.style.padding='0px';
		newAddress.style.margin='0px';
		newAddress.innerHTML='<span style="display:inline-block"><div style="display:table-cell;margin:0px;padding:0px;"></div></span>';
		
		/* address description logic */
			if( this.addressParts.search( /(^|,)description(,|$)/ ) > -1 ){
				if( description ){
					var inputDescription = createDescriptionSelect( description );
				}else{
					var inputDescription = createDescriptionSelect();
				}
				inputDescription.name='null';
				inputDescription.className = 'addressInput';
				this.attachOnChangeRecorder( inputDescription );
				newAddress.getElementsByTagName('DIV')[0].appendChild( inputDescription );
			}
		/* end */

		/* address street logic */
			if( this.addressParts.search( /(^|,)street(,|$)/ ) > -1 ){
				var inputStreet = document.createElement('INPUT');
				inputStreet.name
				inputStreet.className = 'addressInput';
				if( street )inputStreet.value = street;
				if( typeof(OlOs) != 'undefined' && typeof(OlOs.inputs) != 'undefined' ){
					inputStreet.setAttribute('defaultIndicator','Street Address');
					OlOs.inputs.setDefaultValueHint( inputStreet , 'Street Address' );
				}
				this.attachOnChangeRecorder( inputStreet );
				inputStreet.size = 25;
				newAddress.getElementsByTagName('DIV')[0].appendChild( inputStreet );
			}
		/* end */
		
		/* address street2 logic */
			if( this.addressParts.search( /(^|,)street2(,|$)/ ) > -1 ){
				var inputStreet2 = document.createElement('INPUT');
				inputStreet2.name='addressInput';
				inputStreet2.className = 'addressInput';
				if( street2 )inputStreet2.value = street2;
				if( typeof(OlOs) != 'undefined' && typeof(OlOs.inputs) != 'undefined' ){
					inputStreet2.setAttribute('defaultIndicator','Address Suffix');
					OlOs.inputs.setDefaultValueHint( inputStreet2 , 'Address Suffix' );
				}
				this.attachOnChangeRecorder( inputStreet2 );
				inputStreet2.size = 15;
				newAddress.getElementsByTagName('DIV')[0].appendChild( inputStreet2 );
				newAddress.getElementsByTagName('DIV')[0].appendChild( document.createElement('BR') );
			}
		/* end */
		
		/* address city logic */
			if( this.addressParts.search( /(^|,)city(,|$)/ ) > -1 ){
				var inputCity = document.createElement('INPUT');
				inputCity.name='null';
				inputCity.className = 'addressInput';
				if( city )inputCity.value = city;
				if( typeof(OlOs) != 'undefined' && typeof(OlOs.inputs) != 'undefined' ){
					inputCity.setAttribute('defaultIndicator','City');
					OlOs.inputs.setDefaultValueHint( inputCity , 'City' );
				}
				this.attachOnChangeRecorder( inputCity );
				inputCity.size = 15;
				newAddress.getElementsByTagName('DIV')[0].appendChild( inputCity );
			}
		/* end */
	
		/* address state logic */
			if( this.addressParts.search( /(^|,)state(,|$)/ ) > -1 ){
				if( state ){
					var inputState = createStateSelect( state );
				}else{
					var inputState = createStateSelect( this.defaultState );
				}
				inputState.name = 'null';
				inputState.className='addressInput';
				this.attachOnChangeRecorder( inputState );
				newAddress.getElementsByTagName('DIV')[0].appendChild( inputState );
			}
		/* end */
		
		/* address zip logic */
			if( this.addressParts.search( /(^|,)zip(,|$)/ ) > -1 ){
				var inputZip = document.createElement('INPUT');
				inputZip.name='null';
				inputZip.className = 'addressInput';
				if( zip )inputZip.value = zip;
				if( typeof(OlOs) != 'undefined' && typeof(OlOs.inputs) != 'undefined' ){
					inputZip.setAttribute( 'defaultIndicator' , 'Zip' );
					OlOs.inputs.setDefaultValueHint( inputZip , 'Zip' );
				}
				this.attachOnChangeRecorder( inputZip );
				inputZip.size = 10;
				newAddress.getElementsByTagName('DIV')[0].appendChild( inputZip );
				/* Add line return if country or county found next */
					if( this.addressParts.search( /(^|,)county(,|$)/ ) > -1 || this.addressParts.search( /(^|,)country(,|$)/ ) > -1 ){
						newAddress.getElementsByTagName('DIV')[0].appendChild( document.createElement('BR') );
					}
			}
		/* end */
		
		/* address county logic */
			if( this.addressParts.search( /(^|,)county(,|$)/ ) > -1 ){
				var inputCounty = document.createElement('INPUT');
				inputCounty.name='null';
				inputCounty.className = 'addressInput';
				if( county )inputCounty.value = county;
				if( typeof(OlOs) != 'undefined' && typeof(OlOs.inputs) != 'undefined' ){
					inputCounty.setAttribute('defaultIndicator','County');
					OlOs.inputs.setDefaultValueHint( inputCounty , 'County' );
				}
				this.attachOnChangeRecorder( inputCounty );
				inputCounty.size = 15;
				newAddress.getElementsByTagName('DIV')[0].appendChild( inputCounty );
			}
		/* end */
	
		/* address country logic */
			if( this.addressParts.search( /(^|,)country(,|$)/ ) > -1 ){
				if( country ){
					var inputCountry = createCountrySelect( country );
				}else{
					var inputCountry = createCountrySelect( this.defaultCountry );
				}
				inputCountry.name='null';
				inputCountry.className = 'addressInput';
				this.attachOnChangeRecorder( inputCountry );
				newAddress.getElementsByTagName('DIV')[0].appendChild( inputCountry );
			}
		/* end */
	
		/* facilitate the functionality of flexible address's */
			if( this.flexible ){
				newAddress.getElementsByTagName('DIV')[0].style.paddingTop = '6px';
				newAddress.getElementsByTagName('DIV')[0].style.paddingBottom = '6px';
		
				var tempDiv = document.createElement('DIV');
				tempDiv.style.whiteSpace = 'nowrap';
				tempDiv.appendChild( newAddress.getElementsByTagName('SPAN')[0] );
				
				var tempSpan = document.createElement('SPAN');
				tempSpan.innerHTML = '<span style="display:inline-block"><div style="display:table-cell"></div></span>';
				tempSpan.getElementsByTagName('DIV')[0].innerHTML='<a href="" class="minusBox" onclick="if( confirm(\'Confirm Delete\') ){this.parentNode.parentNode.parentNode.innerHTML=\'\';return false;}">-</a>';
				tempSpan.getElementsByTagName('DIV')[0].innerHTML+='&nbsp;';
				tempDiv.appendChild( tempSpan.getElementsByTagName('SPAN')[0] );
				this.inputContainer.appendChild( tempDiv );
			}else{
				this.inputContainer.appendChild( newAddress.getElementsByTagName('SPAN')[0] );
			}
		/* end */
	
	
		++this.totalInputs;
	}
/* end */

inputAddress.prototype.attachOnChangeRecorder = function( targetInput ){
	var action = function(e){
		var target = OlOs.events.getEventTarget(e);
		syncAddressValues( target.parentNode.parentNode.parentNode.parentNode );
	}
	if( targetInput.attachEvent ){
		targetInput.attachEvent( 'onchange' , action );
	}else if( targetInput.addEventListener ){
		targetInput.addEventListener( 'change' , action , false );
	}
	if( targetInput.attachEvent ){
		targetInput.attachEvent( 'onblur' , action );
	}else if( targetInput.addEventListener ){
		targetInput.addEventListener( 'blur' , action , false );
	}
	if( targetInput.attachEvent ){
		targetInput.attachEvent( 'onkeyup' , action );
	}else if( targetInput.addEventListener ){
		targetInput.addEventListener( 'keyup' , action , false );
	}
}

/* Constant Functions */
	syncAddressValues = function( container ){
		var newValue	= "";
		var valueReview = "";

		if( typeof(OlOs) == 'undefined' || typeof(OlOs.node) == 'undefined' ){
			alert('Missing OlOs.node functions');
			return false;
		}

		/* address container loop */
			for( var x=0; x < container.childNodes.length; ++x ){
				if(
					container.childNodes.item(x).nodeType == 1
				&&
					(
						container.childNodes.item(x).getElementsByTagName('INPUT').length
					||
						container.childNodes.item(x).getElementsByTagName('SELECT').length
					)
				){
					var inputValueArray = OlOs.node.getElementsByClassName( container.childNodes.item(x) , 'addressInput' );
					
					if( x > 0 )newValue+='\n';

					/* individual address cell input loop */
						for( var y=0; y < inputValueArray.length; ++y ){
							valueReview="";
							if(
								inputValueArray[y].nodeName == 'INPUT'
							&&
								inputValueArray[y].getAttribute("defaultIndicator") != inputValueArray[y].value
							){
								valueReview= inputValueArray[y].value;
							}else if( inputValueArray[y].nodeName == 'SELECT' ){
								if( inputValueArray[y].options.length ){
									valueReview= inputValueArray[y].options[inputValueArray[y].options.selectedIndex].value;
								}else{
									valueReview = "";
								}
							}
							
							if( !valueReview.length )valueReview="_";
							
							newValue+= valueReview + '\t';
						}
					/* end */
				}
			}
		/* end */
		newValue = newValue.replace( /^[\n\r\s]+|[\n\r\s]+$/g , '' );		// trim the value
		newValue.replace( /(\n\n|\r\r)/g , '\n' );							// remove duplicate line returns
		container.getElementsByTagName('TEXTAREA')[0].value = newValue;
		
		//alert(newValue);
	}

	createStateSelect = function( selected ){
		var stateList = "AK,AL,AR,AZ,CA,Can,CO,CT,DC,DE,FL,GA,HI,IA,ID,IL,IN,KS,KY,LA,MA,MD,ME,MI,MN,MO,MS,MT,NC,ND,NE,NH,NJ,NM,NV,NY,OH,OK,OR,PA,PR,RI,SC,SD,TN,TX,UT,VA,VT,WA,WI,WV,WY";
		var stateArray = stateList.split(',');
		var stateInput = document.createElement('SELECT');
		for( var x=0; x < stateArray.length; ++x ){
			stateInput.options[stateInput.options.length] = new Option( stateArray[x] , stateArray[x] );
			if( selected && stateArray[x] == selected )stateInput.options[stateInput.options.length-1].selected = true;
		}
		return stateInput;
	}

	createCountrySelect = function( selectedValue ){
		var countryList="Afghanistan,Albania,Algeria,American Samoa,Andorra,Angola,Anguilla,Antarctica,Antigua and Barbuda,Argentina,Armenia,Aruba,Australia,Austria,Azerbaijan,Bahamas, The,Bahrain,Bangladesh,Barbados,Belarus,Belgium,Belize,Benin,Bermuda,Bhutan,Bolivia,Bosnia and Herzegovina,Botswana,Brazil,Brunei,Bulgaria,Burkina Faso,Burma (Myanmar),Burundi,Cambodia,Cameroon,Canada,Cape Verde,Cayman Islands,Central African Republic,Chad,Chile,China,Christmas Island,Cocos (Keeling) Islands,Colombia,Congo, Democratic Republic of the,Congo. Republic of the,Cook Islands,Costa Rica,Cote d'Ivoire,Croatia,Cuba,Cyprus,Czech Republic,Denmark,Djibouti,Dominica,Dominican Republic,Ecuador,Egypt,El Salvador,Equatorial Guinea,Eritrea,Estonia,Ethiopia,Faroe Islands,Fiji,Finland,France,French Guiana,French Polynesia,Gabon,Gambia, The,Gaza Strip,Georgia,Germany,Ghana,Gibraltar,Greece,Grenada,Guam,Guatemala,Guernsey,Guinea,Guyana,Haiti,Honduras,Hong Kong,Hungary,Iceland,India,Indonesia,Iran,Iraq,Ireland,Israel,Italy,Jamaica,Japan";
		countryList+= ",Jersey,Jordan,Kazakhstan,Kenya,Kiribati,Kuwait,Kyrgyzstan,Laos,Latvia,Lebanon,Lesotho,Liberia,Libya,Liechtenstein,Lithuania,Luxembourg,Macedonia,Madagascar,Malawi,Malaysia,Maldives,Mali,Malta,Marshall Islands,Mauritania,Mauritius,Mexico,Moldova,Monaco,Mongolia,Montenegro,Morocco,Mozambique,Namibia,Nepal,Netherland Antilles,Netherlands,New Zealand,Nicaragua,Niger,Nigeria,Norfolk Island,North Korea,Norway,Oman,Pakistan,Panama,Papua New Guinea,Paraguay,Peru,Philippines,Poland,Portugal,Puerto Rico,Qatar,Romania,Russia,Saint Helena,Saint Kitts and Nevis,Saint Lucia,Saint Vincent and the Grenadines,Saudi Arabia,Senegal,Serbia,Sierra Leone,Singapore,Slovakia,Slovenia,Solomon Islands,Somalia,South Africa,South Korea,Spain,Sri Lanka,Sudan,Suriname,Swaziland,Sweden,Switzerland,Syria,Taiwan,Tajikistan,Tanzania,Thailand,Togo,Tonga,Trinidad and Tobago,Tunisia,Turkey,Turkmenistan,Turks and Caicos Islands,Tuvalu,Uganda,Ukraine,United Arab Emirates,United Kingdom,United States of America,Uruguay,Uzbekistan,Vanuatu,Venezuela,Vietnam,Wallis and Futuna,West Bank,Yemen,Zambia,Zimbabwe";
		if( !selectedValue )selectedValue = "United States of America";
		var countryArray = countryList.split(',');
		var countryInput = document.createElement('SELECT');
		countryInput.style.fontSize = '11px';
		for( var x=0; x < countryArray.length; ++x ){
			countryInput.options[countryInput.options.length] = new Option( countryArray[x] , countryArray[x] );
			if( selectedValue && countryArray[x] == selectedValue ){
				countryInput.options[countryInput.options.length-1].selected = true;
			}
		}
		return countryInput;
	}

	createDescriptionSelect = function( selectedValue ){
		var descriptionList="Primary Residence,Contact Address,Business Address";
		var descriptionArray = descriptionList.split(',');
		var descriptionInput = document.createElement('SELECT');

		if( selectedValue == '_' ){ selectedValue=""; }

		descriptionInput.style.display = 'block';
		descriptionInput.options[descriptionInput.options.length] = new Option( 'Address Title' , '' );
		descriptionInput.options[descriptionInput.options.length-1].style.color = '#777777';
		descriptionInput.style.fontSize = '11px';
		for( var x=0; x < descriptionArray.length; ++x ){
			descriptionInput.options[descriptionInput.options.length] = new Option( descriptionArray[x] , descriptionArray[x] );
			/* assign selected value */
				if(
					selectedValue
				&&
					descriptionArray[x] == selectedValue
				){
					descriptionInput.options[descriptionInput.options.length-1].selected = true;
				}
			/* end */
		}
		if( selectedValue && !descriptionInput.selectedIndex ){
			descriptionInput.options[descriptionInput.options.length] = new Option( selectedValue , selectedValue );
			descriptionInput.options[descriptionInput.options.length-1].selected = true;
		}
		descriptionInput.options[descriptionInput.options.length] = new Option( 'Create Title' , 'Create Title' );
		descriptionInput.options[descriptionInput.options.length-1].style.color = 'red';
		descriptionInput.onchange = function(){
			if(
				this.options[this.selectedIndex].value == 'Create Title'
			&&
				(
					result=prompt('Enter New Address Title:','')
				)
			){
				this.options[this.options.length]=new Option(result,result);
				this.options[this.options.length-1].selected=true;
			}
		};
		return descriptionInput;
	}
/* end */