/**
 * @author Touchnote
 *  - requires jQuery +1.3 + low Pro for jQuery
 *  - This is a behavior for popup address form
 */		
var AddressPopup = $.klass({

	// construct this behavior
	initialize: function(opts) {
		// set any openers
		this.openers = $(opts.opener);
		
		this.is_open = false; 					// status
		this.addressForm = $('#addressForm');
		behavior = this;

		// register the JQ UI dialog for the image preview
		// this id should really be :first-child		
		opts = { 
			width: 560,
			height: 355,
			bgiframe: true,
			autoOpen: false,
			closeOnEscape: true,
			hide: 'slide',
			show: 'slide',
			resizable: false,
			modal: true
		};

		this.addressForm.dialog(opts);
		
		$('#addressLines').hover(function (){
			$(this).addClass('editing');
		}, function (){
			$(this).removeClass('editing');
		});	
		
		$('#PersonalizedProductMessage').focus(function (){
			$(this).addClass('editing');
			$(this).removeClass('notediting');
		}).blur(function (){
			$(this).addClass('notediting');
			$(this).removeClass('editing');
		});

		
		$('#PersonalizedProductMessage').keydown(function(event){
		
			// set timeout give the event an oppertunity to complete and updat the message
			setTimeout("behavior.validateMessageLineLength($('#PersonalizedProductMessage'))", 20);// Any browser issues slow this down	
		});

		// the dialog is prepopulated but the card back needs to be updated
		// this is most probably a server-side validation issue
		if(typeof opts.revalidate == 'boolean' && opts.revalidate){
			validateAddressForm();
		}

	},
	
	validateMessageLineLength: function (elem){
			var maxLines = 16;
			messageLines = $(elem).val().split('\n');
			if(messageLines.length > maxLines){
				$('#messageValidationError').text('Sorry, but you can only fit 16 lines of message on the postcard. Please delete a few lines.');
			}else{
				$('#messageValidationError').empty();
			}
	},

	onclick: $.delegate({
			'#addressLines': function (){this.openAddressForm();}
	}),

	openAddressForm: function() {
		$('.ui-widget-overlay').fadeIn();
		this.addressForm.dialog('open');
		this.is_open = true;
		return false; 
	},
	


	closeAddressForm: function() {
		$('.ui-widget-overlay').fadeOut();
		this.addressForm.dialog('close');
		this.is_open = false; 
		return false; 
	}

});
