/**
 * SprintX site enhancement
 *
 * @author Alan Horrocks <ahorrocks@doc-net.com>
 * @author Jim Tunstall <jtunstall@doc-net.com>
 * @copyright Copyright &copy; 2009, Doctor Net Limited
 * @package SprintX Website
 */

// Global namespace
var SprintX = {};

// Module stack
SprintX.modules = (function () {
   // Queued modules
	var arr_modules = [];

	// Public methods
	return {
	   // Add module
		add: function (obj_module_initialise) {
			arr_modules[arr_modules.length] = obj_module_initialise;
		},

		// Run modules
		run: function () {
			for (var int_index in arr_modules) {
            arr_modules[int_index]();
         }
		}
	};
}());

/* SprintX WMP */
SprintX.wmp = (function () {
   var int_current_wmn,

   initialise = function () {},
   _highligh_active_wmn = function () {
      $('#wmn_' + int_current_wmn).addClass('wmn_active');
   };

   SprintX.modules.add(initialise);

   var obj_public = {
	   select_wmn: function(int_wmn_id) {
	      int_current_wmn = int_wmn_id;
	      _highligh_active_wmn();
		}
   };

	return obj_public;
})();

/**
 * SprintX Overlay
 *
 * Display content in a styled popup
 *
 * Usage:
 * 1. Ensure the html has the correct elements str_overlay_div and str_content_source (see *** for an example)
 * 2. In js call SprintX.overlay.show('foo') where 'str_content_source #foo_content' is to be shown in the popup
 *
 */
SprintX.overlay = (function () {
   // overlay id - hidden by default
   var str_overlay_div = '#sprintx_overlay',
   // parent id of overlay source
   str_content_source = '#overlay_source',
   // id of (selected) overlay content
   str_content_id = '',
   // jQueryTOOLS Overlay
   obj_overlay,
   obj_overlay_options = {
      color: '#999',
      loadSpeed: 'fast',
      closeSpeed: 'fast',
      onBeforeClose: function(){ on_before_close(); },
      onLoad: function(){ on_load(); }
   },
   // Construct
   initialise = function() {
      // Is the overlay div (skeleton html) in the page?
      if($(str_overlay_div).length) {
         obj_overlay = $(str_overlay_div).expose(obj_overlay_options);
         $(str_overlay_div + ' .close').click(close);
      }
   },
   //  jQueryTOOLS Overlay Event Handler
   on_load = function() {
      $(str_overlay_div).show();
   },
   // jQueryTOOLS Overlay Event Handler
   on_before_close = function () {
      unload_content();
      $(str_overlay_div).hide();
   },
   // Show Overlay
   render = function() {
      load_content();
      position_window();
      if (obj_overlay) {
         obj_overlay.expose().load();
      }
   },
   // Load content into Overlay
   load_content = function() {
      if ($(str_content_id).length) {
         $(str_overlay_div + ' .body .inner').empty();
         $(str_overlay_div + ' .body .inner').append($(str_content_id));
      } else {
         // Silently Fail - Show an empty overlay
      }
   },
   // Unload content from Overlay
   unload_content = function() {
      if($(str_content_id).length) {
         $(str_content_source).append($(str_content_id));
      } else {
         $(str_content_id).empty();
      }

      str_content_id = '';
   },
   // Position Overlay window in the center of the screen
   position_window = function() {
      var int_top = $(window).scrollTop() + (($(window).height() - $(str_overlay_div).outerHeight()) / 2);
      var int_left = $(window).scrollLeft() + (($(window).width() - $(str_overlay_div).outerWidth()) / 2);
      $(str_overlay_div).css('top', int_top).css('left', int_left);
   },
   // Close overlay
   close = function () {
      obj_overlay.expose().close();
   };

   // Go
   SprintX.modules.add(initialise);

   // Public Methods
   var obj_public = {
      // Show overlay
	   show: function(str_id) {
	      str_content_id = '#' + str_id;
	      render();
		},
		// Hide overlay
		hide: function() {
		   close();
		},
		// Resizes the window via animation
		resize: function(int_width, int_height, int_speed) {
         var int_chosen_speed = 750;
         if (int_speed && int_speed > 0) {
            int_chosen_speed = int_speed;
         }

         $('#sprintx_overlay').animate({
            height: (int_height + 40) + "px",
            width: (int_width + 20) + "px"
         }, int_chosen_speed, 'linear', function () {
            var int_top = $(window).scrollTop() + (($(window).height() - $(str_overlay_div).outerHeight()) / 2);
            var int_left = $(window).scrollLeft() + (($(window).width() - $(str_overlay_div).outerWidth()) / 2);
            $(str_overlay_div).animate({
               top: int_top,
               left: int_left
            }, int_chosen_speed);
         });
		},
		// Set overlay options
		set_options: function(obj_options) {
         $.extend(obj_overlay_options, obj_options);
		}
   };
	return obj_public;
}());

/**
 * SprintX Modal Window
 *
 * Extension for SprintX overlay that links anchor tags to overlay content.
 *
 * Usage:
 *  <a href="#" id="foo" class="modal_window">foo</a> will display an overlay containing content from
 *  a div with id="foo_content"
 *  Adding a class resize will transition the overlay
 *
 */
SprintX.modal_window = (function () {
   // anchor for overlay - auto overlay
   var str_trigger_selector = 'a.modal_window',
   // Construct
   initialise = function () {
      $(str_trigger_selector).click(open);
   },
   // Overlay requested by link click
   open = function () {
      str_content_id = $(this).attr('id') + '_content';
      SprintX.overlay.show(str_content_id);

      if($(this).hasClass('resize')) {
         SprintX.overlay.resize(600, 200);
      }
      return false;
   };

   // Go
   SprintX.modules.add(initialise);

   return {};
})();

/**
 * SprintX Newsletter Signup - Single List
 *
 */
SprintX.emc_single = (function () {
   // Ajax Signup URL
   var str_url = '/ajax-newsletter/subscribe',
   // Widget ID
   str_widget_id = '#emc_signup_single',
   // Widget Form Element
   str_form_selector = str_widget_id + ' form',
   // ID of subscriber email
   str_email_id  = '#emc_signup_single_email',
   // ID of subscribe button
   str_submit_id  = '#emc_signup_single_submit',
   // In Widget messaging area
   str_messaging_area_selector = str_widget_id + ' .messaging',
   // Map of SprintEMC error codes
   obj_error_codes = {
      'already_subscribed' : -11,
      'unknown' : -100
   },
   // List description - Can be overridden for SprintX installations
   str_emc_list_description = 'the SprintX Newsletter',
   // Error messages - Can be overridden for SprintX installations
   obj_messages = {
      str_success_message: 'You have successfully been signed up to %%EMC_LIST_DESCRIPTION%%.',
      str_unknown_error_message: 'You could not be signed up to %%EMC_LIST_DESCRIPTION%% at this time.  Please try again.',
      str_already_subscribed_message: 'You are already signed up to %%EMC_LIST_DESCRIPTION%%.'
   },
   // Construct
   initialise = function() {
      // Sanity check
      if($(str_widget_id).length === 0) {
         return;
      }

      // Message setup
      set_list_description_in_messages();

      // Event Handlers
      $(str_submit_id).click(subscribe);
   },
   // Set list name in error messages
   set_list_description_in_messages = function() {
      obj_messages.str_success_message = replace_list_description(obj_messages.str_success_message );
      obj_messages.str_unknown_error_message = replace_list_description(obj_messages.str_unknown_error_message);
      obj_messages.str_already_subscribed_message = replace_list_description(obj_messages.str_already_subscribed_message);
   },
   // List text replacement
   replace_list_description = function(str_message) {
      return str_message.replace(/%%EMC_LIST_DESCRIPTION%%/gi, str_emc_list_description);
   },
   // Subscribe
   subscribe = function() {
      var str_email = $(str_email_id).val();
      // :todo: email validation

      AjaxHandler.set_url(str_url);
      AjaxHandler.process_form($(str_form_selector).get(0));

      AjaxHandler.dispatch(
         function (obj_response) { success(obj_response); },
         function (obj_response) { failure(obj_response); }
      );
      return false;
   },
   // Success handler
   success = function(obj_response) {
      if(is_form_messaging_enabled()) {
         $(str_messaging_area_selector).empty().html('<p>' + obj_messages.str_success_message + '</p>').show();
         $(str_form_selector).hide();
      } else {
         alert(obj_messages.str_success_message);
      }
   },
   // Failure handler
   failure = function(obj_response) {
      var str_code_field = 'code';

      var int_response_code = obj_error_codes.unknown;
      if($(str_code_field, obj_response).length) {
         int_response_code =  parseInt($(str_code_field, obj_response).text());
      }

      var str_message = obj_messages.str_unknown_error_message;
      if(int_response_code === obj_error_codes.already_subscribed) {
         str_message = obj_messages.str_already_subscribed_message;
      }

      if(is_form_messaging_enabled()) {
         $(str_messaging_area_selector).empty().html('<p class="error">' + str_message + '</p>').show();
      } else {
         alert(str_message);
      }
   },
   // Is in form message enabled ?
   is_form_messaging_enabled = function() {
      return $(str_messaging_area_selector).length;
   };

   // Go
   SprintX.modules.add(initialise);

   // Public methods
	var obj_public = {
	   // Set custom EMC codes
	   set_error_codes: function(int_already_subscribed, int_unknown) {
	      obj_error_codes.already_subscribed = int_already_subscribed;
	      obj_error_codes.unknown = int_unknown;
		},
		// Set list description
		set_emc_list_description: function(str) {
         str_emc_list_description = str;
		},
		// Set messages
		set_messages: function(obj) {
         $.extend(obj_messages, obj);
		}
   };

	return obj_public;
}());

/**
 * SprintX Newsletter Signup - Multiple Lists
 *
 */
SprintX.emc_signup_multi = (function () {
   // Ajax Signup URL
   var str_url = '/ajax-newsletter/subscribe',
   // Widget ID
   str_widget_id = '#emc_signup_multi',
   // Widget Form Element
   str_form_selector = str_widget_id + ' form',
   // ID of subscriber email
   str_email_id  = '',
   // ID of subscriber firstname
   str_firstname_id = '',
   // ID of subscriber lastname
   str_lastname_id = '',
   // ID of submit button (radio)
   str_radio_submit_id  = '#emc_signup_multi_submit',
   // Class of submit buttons (input)
   str_input_submit_class  = '.emc_signup_multi_submit',
   // List definitions.  List hash and list description (for messaging). The key here is important as it corresponds to the form controls.
   obj_lists = {
      men: {hash:'sprintx_demo_mens', description: 'the SprintX Mens Newsletter'},
      women: {hash:'sprintx_demo_womens', description: 'the SprintX Womens Newsletter'}
   },
   // Requests Queue.
   arr_request_queue = [],
   // User messages
   arr_messages = [],
   // Class of messaging area
   str_messaging_area_selector = str_widget_id + ' .messaging',
   // Key of list being currently dealt with (subscribed to)
   str_current_key = '',
   // Map of SprintEMC error codes
   obj_error_codes = {
      'already_subscribed' : -11,
      'unknown' : -100
   },
   // Error messages
   obj_messages = {
      str_success_message: 'You have successfully been signed up to %%EMC_LIST_DESCRIPTION%%.',
      str_unknown_error_message: 'You could not be signed up to %%EMC_LIST_DESCRIPTION%% at this time.  Please try again.',
      str_already_subscribed_message: 'You are already signed up to %%EMC_LIST_DESCRIPTION%%.'
   },
   // Subscriber details. Email is mandatory, others optional
   obj_subscriber = {
      str_email: '',
      str_firstname: '',
      str_lastname: ''
   },
   // Construct
   initialise = function() {
      // Sanity check
      if($(str_widget_id).length === 0) {
         return;
      }

      // If there are hash definitions in the form use them. These have the highest priority.
      for(str_key in obj_lists) {
         var str_selector = str_widget_id + ' input[name="hash[' +  str_key + ']"]';
         if($(str_selector).length) {
            obj_lists[str_key].hash = $(str_selector).val();
         }
      }

      // Event Handlers
      $(str_radio_submit_id).click(radio_submit);
      $(str_input_submit_class).click(input_submit);
   },
   // Handle list radio control subscribe request
   radio_submit = function() {
      var str_list_keys = $(str_widget_id + ' :radio[name=multi]:checked').val();
      if(str_list_keys == undefined) {
         // :todo: Error Message
      } else {
         queue_requests(str_list_keys);
         set_subscriber();
         subscribe();
      }

      return false;
   },
   // Handle list input control subscribe request
   input_submit = function() {
      var str_list_keys = $(this).attr('name');
      queue_requests(str_list_keys);
      set_subscriber();
      subscribe();
      return false;
   },
   // Setup request queue
   queue_requests = function(str_list_keys) {
      arr_request_queue = [];

      var str_delimiter = '-';
      if(str_list_keys.indexOf(str_delimiter) == -1) {
         arr_request_queue.push(str_list_keys);
      } else {
         var arr_list_keys = str_list_keys.split(str_delimiter);
         for(int_index in arr_list_keys) {
            arr_request_queue.push(arr_list_keys[int_index]);
         }
      }
   },
   // Set subscriber details
   set_subscriber = function() {
      obj_subscriber.str_email = $('#emc_signup_multi_email').val();
      // :todo: email validation

      if($('#emc_signup_multi_firstname').length) {
         obj_subscriber.str_firstname = $('#emc_signup_multi_firstname').val();
      }

      if($('#emc_signup_multi_lastname').length) {
         obj_subscriber.str_lastname = $('#emc_signup_multi_lastname').val();
      }
   },
   // Subscribe to list
   subscribe = function() {
      str_current_key = arr_request_queue.pop();

      AjaxHandler.set_url(str_url);

      // Personal Details
      AjaxHandler.add_data('email', obj_subscriber.str_email);

      if(obj_subscriber.str_firstname != '') {
         AjaxHandler.add_data('firstname', obj_subscriber.str_firstname);
      }

      if(obj_subscriber.str_lastname != '') {
         AjaxHandler.add_data('lastname', obj_subscriber.str_lastname);
      }

      AjaxHandler.add_data('mailing_list_hash', obj_lists[str_current_key].hash);

      AjaxHandler.dispatch(
         function (obj_response) { success(obj_response); },
         function (obj_response) { failure(obj_response); }
      );
      return false;
   },
   // Success response handler
   success = function(obj_response) {
      var str_list_description = obj_lists[str_current_key].description;
      var str_message = replace_list_description(obj_messages.str_success_message, str_list_description);
      var obj_message = {text: str_message, css_class: 'success'};
      arr_messages.push(obj_message);

      // More requests?
      if(arr_request_queue.length) {
         subscribe();
      } else {
         display_messages();
      }
   },
   // Failure response handler
   failure = function(obj_response) {
      var str_code_field = 'code';

      var int_response_code = obj_error_codes.unknown;
      if($(str_code_field, obj_response).length) {
         int_response_code =  parseInt($(str_code_field, obj_response).text());
      }

      var str_message = obj_messages.str_unknown_error_message;
      if(int_response_code === obj_error_codes.already_subscribed) {
         str_message = obj_messages.str_already_subscribed_message;
      }

      var str_list_description = obj_lists[str_current_key].description;
      str_message = replace_list_description(str_message, str_list_description);
      var obj_message = {text: str_message, css_class: 'error'};
      arr_messages.push(obj_message);

      // More requests?
      if(arr_request_queue.length) {
         subscribe();
      } else {
         display_messages();
      }
   },
   // Allow a custom list name to be used.
   replace_list_description = function(str_message, str_list_description) {
      return str_message.replace(/%%EMC_LIST_DESCRIPTION%%/gi, str_list_description);
   },
   // Display message to user
   display_messages = function() {
      if(is_form_messaging_enabled()) {
         var str_lis = '';
         while(arr_messages.length){
            var obj_message = arr_messages.pop();
            str_lis += '<li class="' + obj_message.css_class + '">' + obj_message.text + '</li>';
         }

         $(str_widget_id + ' .messaging').empty();
         $(str_widget_id + ' .messaging').html('<ul>' + str_lis + '</ul>');
      } else {
         var str_message = '';
         while(arr_messages.length){
            str_message += arr_messages.pop().text + "\n";
         }
         alert(str_message);
      }
   },
   // Is there facility for embedding messages in this widget?
   is_form_messaging_enabled = function() {
      return $(str_messaging_area_selector).length;
   };

   // Go
   SprintX.modules.add(initialise);

   // Public Methods
	var obj_public = {
	   // Set error message codes
	   set_error_codes: function(int_already_subscribed, int_unknown) {
	      obj_error_codes.already_subscribed = int_already_subscribed;
	      obj_error_codes.unknown = int_unknown;
		},
		// Set List details. Allow customisation (hash and description) of default lists, or addition of new ones.
		set_list_details: function(str_key, obj_details) {
		   if(obj_lists[str_key] == undefined) {
		      obj_lists[str_key] = obj_details;
		   } else {
            $.extend(obj_lists[str_key], obj_details);
		   }
		}
   };

	return obj_public;
}());

// Checkout - Payment Page - Enable Add Delivery Address Popup
SprintX.checkout = SprintX.checkout ? SprintX.checkout : {};
SprintX.checkout.add_delivery_address  = (function () {
   var initialise = function () {
      if($('#add_delivery_address').length == 0) {
         return;
      };

      $('#add_delivery_address').click(function(){
         SprintX.overlay.show('add_delivery_address_content');
         return false;
      });

      $('#update_delivery_address_form').bind('valid_add_delivery_address_request', function() {
         AjaxHandler.reset();

         AjaxHandler.process_form($('#update_delivery_address_form'));
         AjaxHandler.set_url('/ajax-my-account/add-delivery-address');
         AjaxHandler.dispatch(function(obj_response) {
            window.location.reload();
            return false;
         });
       });
   };

   SprintX.modules.add(initialise);

   var obj_public = {};

	return obj_public;
})();

// JQuery DOM ready
$(document).ready(function() {
   // Run modules
   SprintX.modules.run();
});

