var PostcodeSearch = Class.create(
    {
        postcode: null,
        selectBox: null,
    
        initialize: function(postcodeId, searchButtonId, selectBoxId)
        {
            this.postcode    = $(postcodeId);
            this.selectBox   = $(selectBoxId);
			this.parentForm	 = this.postcode.up('form');
            
            Event.observe($(searchButtonId), 'click', this.getAddressList.bindAsEventListener(this));
			Event.observe($(postcodeId), 'keydown', this.catchReturn.bindAsEventListener(this));
			
        },
        
        catchReturn: function(e)
        {
			
			if( e.keyCode == Event.KEY_RETURN ){
				this.getAddressList();
				Event.stop(e);
			}
			
        },

		getAddressList: function()
        {
        	//hide list of addresses if already showing
        	$('qas').hide();
        	resetAddressForm();

        	//get user input and trim
        	var postcodeInput = $('postal_code').value;
        	postcodeInput = trim(postcodeInput) ;
        	if( postcodeInput.length < 2 ){
        		alert('Please enter the full postcode');
        		return false;
        	}
        	activateDeactivateLookupButton(false);
//        	activateDeactivateLoadingAnim(true);
            var self = this;
            var uri  = '/customer/qas/postal_code/' + encodeURIComponent(this.postcode.value) + '/';

            new Ajax.Request(uri,
                {
                    method:'get',
                    onSuccess: function(transport)
                    {
            			activateDeactivateLookupButton(true);
                        self.populateSelect(transport.headerJSON);
						activateDeactivateAddressList(true)
                    },
                    onFailure: function()
                    {
                        alert('Sorry, your postcode cannot be found. Please enter your address manually.')
                        activateDeactivateLookupButton(true);
                    }
                }
            );
        },
        
        getAddress: function(event)
        {//alert('AAA');
        	var self = this;
        	activateDeactivateLookupButton(false);
        	activateDeactivateAddressList(false);
        	$('qas').hide();
        	this.selectBox.add;
        	
        	var moniker = Event.element(event).value;
            var uri  = '/customer/qas/moniker/' + encodeURIComponent(moniker) + '/';
            
            new Ajax.Request(uri,
                 {
                     method:'get',
                     onSuccess: function(transport)
                     {
            			activateDeactivateLookupButton(true);
            			//this.selectBox.up().hide();
            			self.populateFieldsFromJson(transport.headerJSON)
						
                     },
                     onFailure: function()
                     {
                         alert('Sorry, your postcode cannot be be found.  Please enter your address manually.')
                         activateDeactivateLookupButton(true);
                     }
                 }
             );
        },
                
        populateFieldsFromJson: function(address)
        {
		
        	//Called after 2nd successful SOAP call (pointless?) 
        	$('line_1').value 	= address['line_1'];
        	$('line_2').value 	= address['line_2'];
        	$('city').value 	= address['city'];
        	$('region').value 	= address['region'];
        	$('postal_code').value = address['postcode'];
			//$('line_1').value 	= address['line_1'];
        },
        
		/*
		        populateFieldsFromString: function(event)
        {
        	//Called without 2nd SOAP call, uses summary string
        	$('qas').hide();
        	resetAddressForm();
        	var option        = Event.element(event);
            var address       = option.innerHTML.unescapeHTML();
            var addressParts  = address.split(',');
            
            //Trim all alements
            for ( var i in addressParts ){
            	if( typeof(addressParts[i]) == 'string' ){
            		addressParts[i] = trim( addressParts[i] );
            	}
            }
            
            //Get formatted postcode and remove from array
            $('postal_code').value = addressParts[addressParts.length-1];
            addressParts.pop();
            
            //Assign address elemnts to lines where available... chop array on CITY element
            // (the only element in CAPS) and use all before as Address lines, value after as region 
            
            //find city index (only field in CAPS)
            var cityIndex=0;
            for(cityIndex=0; cityIndex<=addressParts.length ; cityIndex++){
            	if( isUpperCase(addressParts[cityIndex]) ){
            		break;
            	}
            }
            //SET ADDRESS LINES  or hide (ignoring address 3 if present)
            var addressLines = addressParts.slice(0,cityIndex);
            
            otherLines = addressParts.slice(cityIndex);            
            
            $('line_1').value = addressLines[0];
            if( addressLines.length > 1 ){
            	$('line_2').value 	= addressParts[1];
            } else {
            	//$('line_2').up().previous().hide(); // Removed these as line2 field must be present
            	//$('line_2').up().hide();
            }
            
            //SET CITY LINE            
            $('city').value = otherLines[0];
            //SET REGION LINE or hide
            if(otherLines.length > 1){
            	$('region').value = otherLines[1];
            } else {
            	//$('region').up().previous().hide(); // Removed these as region field must be present
            	//$('region').up().hide();
            }
        },
		*/
		
		
		
        populateFieldsFromString: function(event)
        {
		
        	//Called without 2nd SOAP call, uses summary string
        	$('qas').hide();
        	resetAddressForm();
			
        	var selList        = Event.element(event);
			
			
			
			
			//alert(select.selectedIndex)
			//alert(option);
			
			//alert($('qas').selectedIndex);
			
			//alert(selList.options.item(selList.selectedIndex).value)
			//alert(selOption.innerHTML.unescapeHTML());
			
			//var options = selOption.getElementsByTagName('option');
			//options = $A(options);


			//alert(options[0].value);
			var address       = $('addresses').options.item($('addresses').selectedIndex).text;
			
			//var address       = option.innerHTML.unescapeHTML();
            //alert(address);
			
			var addressParts  = address.split(',');
            
            //Trim all alements
            for ( var i in addressParts ){
            	if( typeof(addressParts[i]) == 'string' ){
            		addressParts[i] = trim( addressParts[i] );
            	}
            }
            
            //Get formatted postcode and remove from array
            $('postal_code').value = addressParts[addressParts.length-1];
            addressParts.pop();
            
            //Assign address elemnts to lines where available... chop array on CITY element
            // (the only element in CAPS) and use all before as Address lines, value after as region 
            
            //find city index (only field in CAPS)
            var cityIndex=0;
            for(cityIndex=0; cityIndex<=addressParts.length ; cityIndex++){
            	if( isUpperCase(addressParts[cityIndex]) ){
            		break;
            	}
            }
            //SET ADDRESS LINES  or hide (ignoring address 3 if present)
            var addressLines = addressParts.slice(0,cityIndex);
            
            otherLines = addressParts.slice(cityIndex);            
            
            $('line_1').value = addressLines[0];
            if( addressLines.length > 1 ){
            	$('line_2').value 	= addressParts[1];
            } else {
            	//$('line_2').up().previous().hide(); // Removed these as line2 field must be present
            	//$('line_2').up().hide();
            }
            
            //SET CITY LINE            
            $('city').value = otherLines[0];
            //SET REGION LINE or hide
            if(otherLines.length > 1){
            	$('region').value = otherLines[1];
            } else {
            	//$('region').up().previous().hide(); // Removed these as region field must be present
            	//$('region').up().hide();
            }
        },
        
        populateSelect: function(addresses)
        {
            var selectBox = this.selectBox;
            var self      = this;
            
            selectBox.length = 0;
            
            //Set size of addresses box  max 15 rows
            if(addresses.length > 10){
            	$('addresses').setAttribute('size', '15');
            }else{
            	$('addresses').setAttribute('size', ''+addresses.length);
            }
            
            /*
            addresses.MESSAGE.ADDRESS.each(function(address)
                {
                    var option = new Element('option', { value: address }).update(address);
                    
                    selectBox.options.add(option);
                    
                    Event.observe(option, 'dblclick', self.populateFields.bindAsEventListener(this));
                }
            */
            
            if(addresses.length < 1){
            	alert('Your postcode cannot be found.  Please enter your address manually.')
            	return false
            }

            
        	addresses.each(function(address)
	            {
        			/*
	var addressString = address[0];
	                var option = new Element('option', { value: address[1] }).update(addressString);
	                selectBox.options.add(option);
	                //NO NEED FOR SECOND SOAP CALL HERE
	                //Event.observe(option, 'dblclick', self.getAddress.bindAsEventListener(self));
	                Event.observe(option, 'dblclick', self.populateFieldsFromString.bindAsEventListener(this));
        			*/

	            	var addressString = address[0];

	                var myOpt = new Option(addressString, address[1])
	                
	                selectBox.options.add(myOpt);

	                
	                //NO NEED FOR SECOND SOAP CALL HERE
	                //Event.observe(option, 'dblclick', self.getAddress.bindAsEventListener(self));
	                
	            }
            );
            //Event.observe(selectBox, 'dblclick', self.populateFieldsFromString.bindAsEventListener(this));
			
			Event.observe(selectBox, 'dblclick', self.getAddress.bindAsEventListener(this));
            //this.selectBox.up().show();
            
        	$('qas').show();
        }
    }
);

function activateDeactivateLookupButton(activate){
	if( activate == true ){
		$('postcode_lookup').removeAttribute('disabled'); 
		$('postcode_lookup').innerHTML = 'Look-Up Address';
    	$('postcode_lookup').className = '';
	} else {
		$('postcode_lookup').innerHTML = 'Searching...';
    	$('postcode_lookup').className = 'inactive';
    	$('postcode_lookup').addAttribute = 'disabled';
    	$('postcode_lookup').setAttribute('disabled', 'disabled');
	}
}

function activateDeactivateAddressList(activate){
	if( activate == true ){
		$('addresses').removeAttribute('disabled'); 
    	$('addresses').className = '';
	} else {
    	$('addresses').className = 'inactive';
    	$('addresses').addAttribute = 'disabled';
    	$('addresses').setAttribute('disabled', 'disabled');
	}
}

function activateDeactivateLoadingAnim(activate){
	
	if(activate){
		
		var anim = new Element('img', { 'src': '/assets/images/ajax-loading.gif', href: '/foo.html' });
		pc.insert( {'after' : anim} );
	} else {
		
	}
}

function resetAddressForm(){
	$('line_1').value 	= '';
	$('line_2').value 	= '';
	$('line_2').up().show();
	$('line_2').up().previous().show();
	$('city').value 	= '';
	$('region').value 	= '';
	$('region').up().show();
	$('region').up().previous().show();
}

function isUpperCase(myString) {
	return (myString == myString.toUpperCase());
}

function trim(myString) {
	return myString.replace(/^\s+|\s+$/g,"");
}
