/**
 * 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
 */
SprintX.overlay = (function () {
   // overlay id - hidden by default
   var str_overlay_div = '#sprintx_overlay',
   // id of 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(); }
   },
   // Initialise method
   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();
      obj_overlay.expose().load();
   },
   // Load content into Overlay
   load_content = function() {
      if ($(str_content_id).length) {
         $(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) {
         $('#overlay_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();
   };

   SprintX.modules.add(initialise);

   // Public Methods
   var obj_public = {
	   show: function(str_id) {
	      str_content_id = '#' + str_id;
	      render();
		},
		hide: function() {
		   close();
		},
		set_options: function(obj_options) {
         $.extend(obj_overlay_options, obj_options);
		}
   };
	return obj_public;
}());


/**
 * SprintX Modal Window
 */
SprintX.modal_window = (function () {
   var str_trigger_selector = 'a.modal_window', // anchor for overlay - auto overlay
   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);
      return false;
   };

   SprintX.modules.add(initialise);

   return {};
})();


/**
 * SprintX Newsletter Signup
 *
 */
SprintX.emc_single = (function () {
   //
   var str_url = '/ajax-newsletter/subscribe',
   str_widget_id = '#emc_signup_single',
   str_form_selector = str_widget_id + ' form',
   str_email_id  = '#emc_signup_single_email',
   str_submit_id  = '#emc_signup_single_submit',
   str_messaging_area_selector = str_widget_id + ' .messaging',
   //
   obj_error_codes = {
      'already_subscribed' : -11,
      'unknown' : -100
   },
   //
   str_emc_list_description = 'the SprintX Newsletter',
   //
   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%%.'
   },
   //
   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_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);
   },
   //
   replace_list_description = function(str_message) {
      return str_message.replace(/%%EMC_LIST_DESCRIPTION%%/gi, str_emc_list_description);
   },
   //
   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 = 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 = 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_form_messaging_enabled = function() {
      return $(str_messaging_area_selector).length;
   };

   //
   SprintX.modules.add(initialise);

   //
	var obj_public = {
	   //
	   set_error_codes: function(int_already_subscribed, int_unknown) {
	      obj_error_codes.already_subscribed = int_already_subscribed;
	      obj_error_codes.unknown = int_unknown;
		},
		//
		set_emc_list_description: function(str) {
         str_emc_list_description = str;
		},
		//
		set_messages: function(obj) {
         $.extend(obj_messages, obj);
		}
   };

	return obj_public;
}());




SprintX.emc_signup_multi = (function () {
   //
   var str_url = '/ajax-newsletter/subscribe',
   str_widget_id = '#emc_signup_multi',
   str_form_selector = str_widget_id + ' form',
   arr_hashes = [],
   arr_request_queue = [],
   arr_messages = [],
   str_messaging_area_selector = str_widget_id + ' .messaging',
   str_current_key = '',
   //
   obj_error_codes = {
      'already_subscribed' : -11,
      'unknown' : -100
   },
   //
   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%%.'
   },
   //
   initialise = function() {
      // Sanity check
      if($(str_widget_id).length === 0) {
         return;
      }

      arr_hashes['men'] = {hash:'asdljas', description: 'the SprintX Mens Newsletter'};
      arr_hashes['women'] = {hash:'awege', description: 'the SprintX Womens Newsletter'};

      // Look for list hash defintions in the form
      for(str_key in arr_hashes) {
         var str_selector = '#emc_signup_multi input[name="hash[' +  str_key + ']"]';
         if($(str_selector).length) {
            arr_hashes[str_key].hash = $(str_selector).val();
         }
      }

      $('#emc_signup_multi_submit').click(radio_submit);
      $('.emc_signup_multi_submit').click(input_submit);
   },
   //
   radio_submit = function() {
      var str_list_keys = $("#emc_signup_multi :radio[name=multi]:checked").val();
      if(str_list_keys == undefined) {
         // :todo: Error Message
      } else {
         queue_requests(str_list_keys);
         subscribe();
      }

      return false;
   },
   //
   input_submit = function() {
      var str_list_keys = $(this).attr('name');
      queue_requests(str_list_keys);
      subscribe();
      return false;
   },
   //
   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]);
         }
      }
   },
   //
   subscribe = function() {
      // wrong - gets called multiple times
      var str_email = $('#emc_signup_multi_email').val();
      // :todo: email validation

      str_current_key = arr_request_queue.pop();

      AjaxHandler.set_url(str_url);

      AjaxHandler.add_data('email', str_email);
      AjaxHandler.add_data('mailing_list_hash', arr_hashes[str_current_key].hash);
// :todo: add facilities for firstname and lastname
//      AjaxHandler.add_data('firstname', str_firstname);
//      AjaxHandler.add_data('lastname', str_lastname);

      AjaxHandler.dispatch(
         function (obj_response) { success(obj_response); },
         function (obj_response) { failure(obj_response); }
      );
      return false;
   },
   //
   success = function(obj_response) {
      var str_list_description = arr_hashes[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);

      if(arr_request_queue.length) {
         subscribe();
      } else {
         display_messages();
      }
   },
   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 = arr_hashes[str_current_key].description;
      var str_message = replace_list_description(str_message, str_list_description);
      var obj_message = {text: str_message, css_class: 'error'};
      arr_messages.push(obj_message);

      if(arr_request_queue.length) {
         subscribe();
      } else {
         display_messages();
      }
   },
   //
   replace_list_description = function(str_message, str_list_description) {
      return str_message.replace(/%%EMC_LIST_DESCRIPTION%%/gi, str_list_description);
   },
   //
   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>';
   		}

         $('#emc_signup_multi .messaging').empty();
         $('#emc_signup_multi .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_form_messaging_enabled = function() {
      return $(str_messaging_area_selector).length;
   };

   //
   SprintX.modules.add(initialise);

   //
	var obj_public = {
	   //
	   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: function(str_key, obj_details) {
		   if(arr_hashes[str_key] == undefined) {
		      arr_hashes[str_key] = obj_details;
		   } else {
            $.extend(arr_hashes[str_key], obj_details);
		   }
		}
   };

	return obj_public;
}());



/*
//
SprintX.emc_single_signup = (function () {
   var obj_error_codes = {
      'already_subscribed' : -11,
      'unknown' : -100
   },
   initialise = function() {
      if($('#frm_emc_signup_single').length === 0) {
         return;
      }

      $('#emc_signup_single_submit').click(subscribe);
   },
   subscribe = function() {
      var str_email = $('#emc_signup_single_email').val();
      SprintX.emc_api.set_email(str_email);
      SprintX.emc_api.subscribe(
         SprintX.emc_single_signup.success,
         SprintX.emc_single_signup.failure
      );

      return false;
   };

   SprintX.modules.add(initialise);

	var obj_public = {
	   success: function() {
         alert('You have successfully been signed up to the SprintX Newsletter.');
	   },
	   failure: function() {
         alert('You could not signed up to the SprintX Newsletter at this time.  Please try again.');
	   }
	};
	return obj_public;
}());

//
SprintX.emc_api = (function () {
   var _obj_error_codes = {
      'already_subscribed' : -11,
      'unknown' : -100
   },
   str_firstname = '',
   str_lastname = '',
   str_email = '',
   str_hash = '',
   str_url = '/ajax-newsletter/subscribe',
   initialise = function() {
   },
   dispatch = function(success_callback, failure_callback) {
      AjaxHandler.set_url(str_url);
      AjaxHandler.add_data('email', str_email);
      AjaxHandler.add_data('mailing_list_hash', str_hash);
      AjaxHandler.add_data('firstname', str_firstname);
      AjaxHandler.add_data('lastname', str_lastname);

      AjaxHandler.dispatch(
         function (obj_xml_response) { emc_response(obj_xml_response, success_callback); },
         function (obj_xml_response) { emc_response(obj_xml_response, failure_callback); }
      );
   },
   emc_response = function(obj_xml_response, fnc_callback) {
      fnc_callback(obj_xml_response);
   };

   SprintX.modules.add(initialise);

	var obj_public = {
	   set_all: function() {},
	   set_firstname: function(str) {
         str_firstname = str;
	   },
	   set_lastname: function(str) {
         str_lastname = str;
	   },
	   set_email: function(str) {
         str_email = str;
	   },
	   set_hash: function(str) {
         str_hash = str;
	   },
	   obj_error_codes: function() {
	      return _obj_error_codes;
	   },
	   subscribe: function(success_callback, failure_callback) {
	      dispatch(success_callback, failure_callback);
	   }
	};

	return obj_public;
}());
*/

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

