/**
 * This script is supposed to hold all necessary helper functions for the 
 * My Account section of the Comubia Storefront.
 */ 
var myacc = (function(jQuery)
{
	return { // <== this curly bracket has
		// app initializations called from jQuery(document).ready at the end of the file
		init: function( root ) {
			/* 
			here go all the inits.  One part of it
			is attaching the onClick functions to the buttons and other elements
			*/
			if ( root == null )
			{
				root = 'body ';
			}
			else
			{
				root += ' ';
			}
			
			//####################################################
			//
			//      Credit Cards
			//
			//####################################################
			// set default credit card AND customer address
			jQuery( root + '.mainCol input[type=radio]:not( :checked )' ).change(function(){ app.submitForm( {triggeredObject: this, actionName: jQuery( this ).attr( 'value' ), actionValue : this.id } ); return false; });
			
			// delete existing credit card AND customer address from the LIST Window
			jQuery( root + '.mainCol a.delete-address').click(function(){ app.submitForm( {triggeredObject: this } ); return false; });
			
			// edit existing credit card
			jQuery( root + 'a.edit-cc').click(function(){ 
					var options = {triggeredObject: this, title: 'Add/Edit Credit Card', method: 'GET', callBack: function( options ) {myacc.init( options.popupId ); } };
					app.ajaxSubmitAndShow( options ); 
					return false; 
			});
			
			// add a new credit card
			jQuery( root + 'button.add-new-card').click(function(){ 
					var options = {triggeredObject: this, title: 'Add/Edit Credit Card', method: 'GET', callBack: function( options ) {myacc.init( options.popupId ); } };
					app.ajaxSubmitAndShow( options ); 
					return false; 
			});
			
			// delete existing credit card from the POPUP
			jQuery( root + '.edit-cc-holder a.delete-address').click(function(){ 
					var options = {triggeredObject: this, title: 'Add/Edit Credit Card' };
					app.ajaxSubmitAndShow( options ); return false; 
			});
			
			// save button in the popup for add/edit credit card
			jQuery( root + '.edit-cc-holder a.save').click(function(){ 
					var options = {triggeredObject: this, title: 'Add/Edit Credit Card', callBack: function( options ) {myacc.init( options.popupId ); } };
					app.ajaxSubmitAndShow( options ); 
					return false; 
			});
			
			//####################################################
			//
			//      Customer Addresses
			//
			//####################################################
			// set default Address (same as for the credit cards!)
			// delete address (same as for the credit cards!)
			
			// create new address from List window
	        $( root + '.account .create-new-address').click(function(){
					var options = {triggeredObject: this, title: 'Add Address', method: 'GET', callBack: function( options ) {myacc.init( options.popupId ); } };
					app.ajaxSubmitAndShow( options ); 
					return false; 
			});

			// edditing exiting card from main window
			jQuery( root + 'a.edit').click(function(){ 
					var options = {triggeredObject: this, title: 'Edit Address', method: 'GET', callBack: function( options ) {myacc.init( options.popupId ); } };
					app.ajaxSubmitAndShow( options ); 
					return false; 
			});
			
			// delete existing addresses from the POPUP
			jQuery( root + '.edit-holder a.delete-address').click(function(){ 
					var options = {triggeredObject: this, title: 'Edit Address' };
					app.ajaxSubmitAndShow( options ); return false; 
			});
			
			// save button in the popup for add/edit address
			jQuery( root + '.edit-holder a.save').click(function(){ 
					var options = {triggeredObject: this, title: 'Edit Address', callBack: function( options ) {myacc.init( options.popupId ); } };
					app.ajaxSubmitAndShow( options ); 
					return false; 
			});
			
			
			// Show the Edit Address fields when Greater Rewards is clicked
		    jQuery('#Id_dwfrm_profile_customer_enrollgreaterrewards').bind('change click keypress',function(){
		        $('#addressForm')[this.checked?'show':'hide']();
		    }).change();
		    		    
			// Show the password fields only when clicked
		    jQuery('#Id_dwfrm_profile_login_changepassword').bind('change click keypress',function(){
		        $('#changepassword')[this.checked?'show':'hide']();
		    }).change();
		    
		    //####################################################
			//
			//      Wish List
			//
			//####################################################
			// the button that opens the popup dialog to sen the wishlist as email
			// alert( root + '.wish-list button.email\n' + jQuery( root + '.wish-list button.email' ) + '\n' + jQuery( root + '.wish-list button.email' ).size() ); 
			jQuery( root + '.wish-list button.email').click(function(){ 
					var options = {triggeredObject: this, width: 400, title: 'Email this wish list', callBack: function( options ) {myacc.init( options.popupId ); } };
					app.ajaxSubmitAndShow( options ); 
					return false; 
			});
			
			// this is the button that actually submits the 
			jQuery( root + '#emailAddresses button.email').click(function(){ 
					var options = {
							triggeredObject: this, 
							width: 400, 
							title: 'Email this wish list', 
							callBack: function( options ) {myacc.init( options.popupId ); },
							beforeCloseCallBack: function( options ){
								// jQuery( options.result ).
								var temp = jQuery( options.result ).filter( '#SendEmailAsynchrone' ).find( 'input#SendStatus' );
								if ( temp.size() > 0 )
									jQuery( '#emailResult' ).html( temp.val() );
								
								temp = jQuery( options.result ).filter( '#SendEmailAsynchrone' ).find( 'button.sendAction' );
								if ( temp.size() > 0 )
								{
									ops = {
										triggeredObject: temp[0],
										callBack: function( myOps ){
											var temp = jQuery( myOps.result ).filter( '#SendEmailAsynchrone' ).find( 'input#SendStatus' );
											if ( temp.size() > 0 )
												jQuery( '#emailResult' ).html( temp.val() );
										}
									};
									app.ajaxSubmitAndShow( ops ); 
								}
							} 
					};
					app.ajaxSubmitAndShow( options ); 
					return false; 
			});
			
			// hide all but the first where the value is empty
			jQuery( root + 'div.WLemailAddress input[value=]' ).parents( root + 'div.WLemailAddress' ).filter( ':gt(0)' ).hide();
			
			// if a key was pressed check if if we need to show one more text field
			// do not check for empty cause the user might have deleted the text to start 
			// all over again.  Check in the onBlur method, that's better 
			jQuery( root + 'input.WLemailAddress').bind('keyup', function(){
				myacc.__handleWlEmailInputEvent( this, root );
			});
			
			jQuery( root + 'input.WLemailAddress').bind('change', function(){
				myacc.__handleWlEmailInputEvent( this, root );
			});
			
			// unfortunatelly, the paste event is a want-to-paste event.  At this stage,
			// we do not get the information what will be pasted and we have no post-paste
			// event.  But we can assume that the paste operation will be done in less 
			// than 1/5 sec.  Hence, set a time out that 
			//   A - ensures only one line was pasted
			//   B - does the stuff with showing the one empty address field 
			jQuery( root + 'input.WLemailAddress').bind('paste', function(){
				var htmlElem = this;
				
				setTimeout ( function(){
						if ( htmlElem.value.indexOf( '\n' ) > -1 )
							 htmlElem.value = htmlElem.value.substring( 0, htmlElem.value.indexOf( '\n' ) );
						myacc.__handleWlEmailInputEvent( htmlElem, root );
					},
					200 );
			});
			
			// remove maybe warnings when leaving an empty text field 
			jQuery( root + 'input.WLemailAddress').bind('blur', function(){
				if ( app.StringHelper.trim( this.value ) == '' )
				{
					// make sure that spaces and all that is removed!
					this.value = '';
					jqDiv = jQuery( jQuery( this ).parents( root + 'div.WLemailAddress:visible' ) );
					jqDiv.find( 'span.WLemailLabel' ).removeClass( 'warning' );
					jqDiv.find( 'span.errorcaption' ).html( '' );
				}
			});
			
			// When the user want's to leave a field that is empty, make sure 
			// that at that time there is only one empty field visible.
			// Also we need to remove all that might look like and error indicator.
			// This form might be rejected from the DW server and have error texts
			// showing.
			jQuery( root + 'input.WLemailAddress').bind('focus', function(){
				// find all currently visible fields with empty values
				var visDivs = jQuery( root + 'div.WLemailAddress input' ).filter( function(){ return this.value==''; } ).parents( root + 'div.WLemailAddress:visible' );
				if ( visDivs.length == 0 )
					return true;  // there are no empty fields
				if ( visDivs.length == 1 && this.value == '' )
					return true;  // editing the empty field
				
				var hideThisDiv = visDivs;
				
				
				// **** ODD **** //
				// this has to be noted in this way.  I had the
				// scenario where there were two visible and 
				// but the comparison would evaluate to false!?!?!
				// this forces the JS engine to convert everything into 
				// number objects and run the compariosn.  Now it seems
				// to be working nicely
				if (  1*visDivs.length > 1*1 )
				{
					// alert( "in 2" );
					
					// we have either two empty fields or the user did not click in
					// the las visible empty field
					// we did not click the only visible field
					var index = visDivs.index( jQuery( jQuery( this ).parents( root + 'div.WLemailAddress' ) ) );
					
					// we have three cases:
					// -1 : meaning the user has two empty fields and clicked on a not empty field
					// ==> hide the 1st one
					// 0 : user clicked on the first element
					// ==> hide the 2nd one
					// 1 : user clicked on the second element
					// ==> hide the 1st one
					index = (index == 0 ? 1 : 0 ); // hide the 1st or the 2nd
					
					// this is the one we need to move
					hideThisDiv = visDivs.get( index );
					
				}
				// at this point we have to assume that all the DIVs are under the 
				// same parent!
				// there seems to be a glitch.  I the object I want to append is already
				// in the last spot it moves one spot ahead!
				var divsParent = jQuery( hideThisDiv ).parent();
				
				var index = divsParent.children().index( hideThisDiv );
				if ( index + 1 != jQuery( hideThisDiv ).parent().children( ':visible' ).length )
				{
					// this is now the place where we shift the elements around.
					// That means, we also need to shift the label around  the desc and
					// error texts stay with the div.
					var saveLabel = jQuery( hideThisDiv ).find( 'span.WLemailLabel' ).html();
					var saveRequired = jQuery( hideThisDiv ).find( 'span.required' ).html();
					// change the label form this position
					index = jQuery( hideThisDiv ).parent().children().index( hideThisDiv )
					
					// now move the field to the end
					hideThisDiv = divsParent.append( hideThisDiv );
					
					// and roll up the text
					var allDivs = divsParent.children();
					for ( i = allDivs.length -1; i > index; i-- )
					{
						var x1 = jQuery( allDivs.get( i - 1 ) );
						var x2 = jQuery( allDivs.get( i ) );
						
						x2.find( 'span.WLemailLabel' ).html( x1.find( 'span.WLemailLabel' ).html() );
						x2.find( 'span.required' ).html( x1.find( 'span.required' ).html() );
					}
					hideThisDiv = jQuery( allDivs.get( index ) );
					hideThisDiv.find( 'span.WLemailLabel' ).html( saveLabel );
					hideThisDiv.find( 'span.required' ).html( saveRequired );
				}
				if ( visDivs.length > 1 )
					divsParent.children( ':last' ).hide();
				
				return true;
			});
			
			$('button.print').unbind();
        	$('button.print').click(function(e){
        	//e.preventDefault();
        	//e.stopPropagation();
        	window.print();
        	return false;
        	});
			
		},  // end of init
		
		// helper method for showing additional 
		__handleWlEmailInputEvent: function( triggerObject, root )
		{
			if ( app.StringHelper.trim( triggerObject.value ).length == '' )
			{
				// the user emptied the content of this line.
				// do nothing, treat it in the next focus event
			}
			else
			{
				// get all visible empty ones.  If there is none add one
				if ( jQuery( root + 'input.WLemailAddress' ).filter( function(){ return this.value==''; } ).parent( 'div.WLemailAddress:visible' ).length == 0 )
					jQuery( root + 'input.WLemailAddress' ).filter( function(){ return this.value==''; } ).parent( 'div.WLemailAddress:hidden:first' ).show();
				/*
				// get all inputs for email
				var inputs = jQuery( root + 'input.WLemailAddress' );
				// get index of the one that was changed
				var index = inputs.index( jQuery( triggerObject ) );
				// get all tailing siblings
				inputs = jQuery( root + 'input.WLemailAddress:gt(' + index + ')' );
				// find the first empty one and set it visible
				for ( i = 0; i < inputs.length; i++ )
				{
					if ( app.StringHelper.trim( inputs[i].value ).length == '' )
					{
						jQuery( inputs[i] ).parents( 'div.WLemailAddress' ).show();
						break;
					}
				}
				*/
			}
		}
	}
}
)(jQuery);

jQuery(document).ready(function(){
	
	myacc.init();
});
 