/**
 * Masdings site JS.
 *
 * @author Doctor Net Limited
 * @copyright Copyright &copy; 2010, Doctor Net Limited
 * @package Masdings
 * @see http://www.doc-net.com
 */

// Global namespace
var Masdings = {};

/**
 *
 */
Masdings.menu = (function() {
   var initialise = function() {
      $('#main_menu LI').hover(function () {
         $('DIV.menu_container', this).fadeIn(250).fadeTo(250, 1);
      }, function () {
         $('DIV.menu_container', this).stop(); // cancel any active fadeIn FX
         $('DIV.menu_container', this).hide();
      });
   };

   Sprint.modules.add(initialise);
   return {};
}());

/**
 *
 */
Masdings.wmp_filtering = (function () {
   var arr_filter_groups = [],
   arr_filters_active = [],
   flt_price_filter_min = 0,
   flt_price_filter_max = 100,

   initialise = function () {
      detect_active_filters();
      if ($('#wmp_filter_price').size() > 0) {
         flt_price_filter_min = parseInt($('#wmp_filter_price_min').val(), 10);
         flt_price_filter_max = parseInt($('#wmp_filter_price_max').val(), 10);
         arr_staring_price_values = $('#wmp_filter_price_value').val().split(':');
         flt_price_filter_low = parseInt(arr_staring_price_values[0], 10);
         flt_price_filter_high = parseInt(arr_staring_price_values[1], 10);
         $('#wmp_filter_price').slider({
            animate: true,
            min: flt_price_filter_min,
            max: flt_price_filter_max,
            range: true,
            step: 5,
            values: [flt_price_filter_low, flt_price_filter_high],
            change: function (obj_event, obj_ui) {
               arr_values = obj_ui.values;
               $('#wmp_filter_price_low').html('&pound;' + Math.round(arr_values[0]) + '.00');
               $('#wmp_filter_price_high').html('&pound;' + Math.round(arr_values[1]) + '.00');
               $('#wmp_filter_price_value').val(arr_values[0] + ':' + arr_values[1]);
               Masdings.wmp_filtering.select_filter('ip', $('#wmp_filter_price_value').val());
               Masdings.wmp_filtering.refresh_results();
            },
            slide: function (obj_event, obj_ui) {
               arr_values = obj_ui.values;
               $('#wmp_filter_price_low').html('&pound;' + Math.round(arr_values[0]) + '.00');
               $('#wmp_filter_price_high').html('&pound;' + Math.round(arr_values[1]) + '.00');
            }
         });
      }
      replace_brand_links();
      replace_product_type_links();
   },
   detect_active_filters = function () {
      var obj_regex = new RegExp("[\\?&]filter=([^&#]*)");
      var arr_results = obj_regex.exec(window.location.search);
      var str_filter_active = '';
      if (arr_results !== null) {
         str_filter_active = arr_results[1];
      }
      if (str_filter_active.length > 0) {
         arr_filters = str_filter_active.split(',');
         var bol_done_ip = false;
         for (key in arr_filters) {
            if (key == 'ip' && bol_done_ip) {
               continue;
            }
            arr_filter_parts = arr_filters[key].split('-');
            Masdings.wmp_filtering.select_filter(arr_filter_parts[0], arr_filter_parts[1]);
            if (key == 'ip') {
               bol_done_ip = true;
            }
         }
      }
   },
   replace_brand_links = function() {
      replace_filtering_links('m');
   },
   replace_product_type_links = function() {
      replace_filtering_links('id');
   },
   replace_filtering_links = function(str_group_id) {
      $('#listing_drill_down_menu #filter_group_' + str_group_id + ' a').each(function(){
         var str_href = $(this).attr('href');

         var str_regexp = new RegExp('\\?filter=' + str_group_id + '-([0-9]+)');
         var arr_matches = str_regexp.exec(str_href);

         if(arr_matches && 2 == arr_matches.length) {
            var str_option = arr_matches[1];
            $(this).attr('href', '/#');
            $(this).click(function(){return filter_click(str_group_id, str_option)});
         }
      });
   },
   filter_click = function(str_group_id, str_option) {
      _select_filter(str_group_id, str_option);
      _refresh_results();
      return false;
   },
   _select_filter = function(str_group_id, str_option) {
      if(str_group_id == 'ip' || str_group_id == 'm' || str_group_id == 'id') {
         set_filter(str_group_id, str_option);
      } else {
         arr_filters_active.push([str_group_id, str_option]);
      }
   },
   _refresh_results = function() {
      var str_url = window.location.pathname;
      var str_filter = '';
      for (int_i = 0, int_n = arr_filters_active.length; int_i < int_n; int_i++) {
         if (arr_filters_active[int_i][0] != '') {
            str_filter += arr_filters_active[int_i][0] + '-' + arr_filters_active[int_i][1] + ',';
         }
      }
      window.location.href = str_url + '?filter=' + str_filter;
   },
   set_filter = function(str_group_id, str_option) {
      var bol_added = false;
      for (key in arr_filters_active) {
         if (arr_filters_active[key][0] == str_group_id) {
            arr_filters_active[key][1] = str_option;
            bol_added = true;
            break;
         }
      }
      if (!bol_added) {
         arr_filters_active.push([str_group_id, str_option]);
      }
   };

   Sprint.modules.add(initialise);

   var obj_public = {
      refresh_results: function () {
         _refresh_results();
      },
      select_filter: function(str_group_id, str_option) {
         _select_filter(str_group_id, str_option);
      }
   };
   return obj_public;
})();

/**
 *
 */
Masdings.quicksearch = (function() {
   var str_search_text_id = '#quick_search_text',
   str_form_id = '#quicksearch',

   str_default_search_text = '',

   bol_form_ok = false,

   initialise = function() {
      str_default_search_text = $(str_search_text_id).val();

      $(str_search_text_id).focus(search_focus);
      $(str_search_text_id).blur(search_blur);

      // The search form must go through the search method
      $('#quicksearch').submit(function(){
         return bol_form_ok;
      });

      $(str_search_text_id).keypress(input_keypress);
      $('#submit_search').click(search);
   },
   // ie doesnt bubble the enter press input button correctly, this is a work around
   input_keypress = function(obj_event) {
      if(obj_event.keyCode == 13) { //enter pressed
          $('#submit_search').trigger('click');
         return false;
      }
   },
   search = function() {
      var str_term = $(str_search_text_id).val();

      str_term = alltrim(str_term);

      if(str_term.length == 0) {
         alert('Please enter a search term and try again');
         return false;
      }

      var str_action = $(str_form_id).attr('action');
      str_action = str_action + '/' + encodeURI(str_term);

      $(str_form_id).attr('action', str_action);
      $(str_form_id).attr('method', 'post');

      bol_form_ok = true;

      return true;
   },
   search_focus = function () {
      if(str_default_search_text === this.value) {
         this.value = '';
      }
   },
   search_blur = function () {
      if(this.value == '') {
         this.value = str_default_search_text;
      }
   },
   alltrim = function(str) {
      return str.replace(/^\s+|\s+$/g, '');
   };

   Sprint.modules.add(initialise);
   return {};
}());

/* Masdings Newsletter Subscription */
Masdings.newsletter = (function () {
   var str_mailing_list_hash = '#str_mailing_list_hash',
   str_mens_hash_value = '1a2,p',
   str_womens_hash_value = '5b2,p',
   arr_request_queue = [], // Requests queue
   initialise = function () {},
   _attach_handlers = function() {
      $('#btn_newsletter_men_real').click(submit_men);
      $('#btn_newsletter_women_real').click(submit_women);
      $('#btn_newsletter_both_real').click(submit_both);
   };
   submit_men = function() {
      arr_request_queue.push(str_mens_hash_value);
      send();
   },
   submit_women = function() {
      arr_request_queue.push(str_womens_hash_value);
      send();
   },
   submit_both = function() {
      arr_request_queue.push(str_mens_hash_value);
      arr_request_queue.push(str_womens_hash_value);
      send();
   },
   success = function(obj_response) {
      $('#overlay #form_newsletter_signup_real').hide();
      $('#overlay #newsletter_signup_content').append('<p>Thank you for signing up.  You\'ll hear from us soon.</p>');
      $('#overlay #newsletter_signup_content p').addClass('success');
   },
   failure = function(obj_response) {
      var str_error_message = $('message', obj_response).text();
      $('#form_newsletter_signup_real p').text(str_error_message + ' Please try again.');
      $('#form_newsletter_signup_real p').addClass('error_message');
   },
   send = function(str_field) {
      var_str_hash = arr_request_queue.pop();
      $('#str_mailing_list_hash_real').val(var_str_hash);

      AjaxHandler.reset('/ajax-newsletter/subscribe');
      AjaxHandler.process_form($('#form_newsletter_signup_real'));
      AjaxHandler.dispatch(function (obj_response) {
         // More requests?
         if(arr_request_queue.length) {
            send();
         } else {
            success(obj_response);
         }
      }, function (obj_response) {
         arr_request_queue = [];
         failure(obj_response);
      });
   };

   Sprint.modules.add(initialise);

   var obj_public = {
      attach_handlers: function () {
         _attach_handlers();
         return false;
      }
   }
   return obj_public;
}());

/* Masdings Styled Modal Pop-Up */
Masdings.modal_window = (function () {
   var obj_expose_overlay,
   str_overlay_div = '#overlay',
   str_content_id = '',
   str_trigger_selector = 'a.masdings_modal_window',
   hide = function () {
      $(str_overlay_div).hide();
   },
   obj_expose = {
      color: '#999',
      loadSpeed: 'fast',
      closeSpeed: 'fast',
      onBeforeClose: hide
   },
   initialise = function() {
      obj_expose_overlay = $(str_overlay_div).expose(obj_expose);
      $(str_trigger_selector).each(function () {
         var str_id = $(this).attr('id');

         $(this).click(function () {
            render($(this));
         });
      });
      $(str_overlay_div + ' .close img').click(close);
      $(str_overlay_div +' .close span').click(close);
   },
   render = function(obj_this) {
      if (str_content_id.length == 0) {
         str_content_id = obj_this.attr('id') + '_content';
      }
      $(str_overlay_div + ' .header .inner').empty();
      $(str_overlay_div + ' .body .inner').empty();
      if ($('#' + str_content_id).size() > 0) {
         obj_container_clone = $('#' + str_content_id).clone();
         // Need to update all DOM id's to be unique (we simply suffix with '_real' for now)
         $('*', obj_container_clone).each(function () {
            if ($(this).attr('id').length > 0) {
               $(this).attr('id', $(this).attr('id') + '_real');
            }
         })
         obj_container_clone.prependTo(str_overlay_div + ' .body .inner');
         $(str_overlay_div + ' .body .inner').children().each(function() {
            $(this).show();
         });
      }
      $(str_overlay_div + ' .body .inner > div > h3:first').appendTo(str_overlay_div + ' .header .inner');
      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);
      obj_expose_overlay.expose().load();
      $(str_overlay_div).show();
      str_content_id = '';

      str_function = obj_this.attr('href').substr(1);

      if(str_function) {
         eval('Masdings.' + str_function + '()');
      }

      return false;
   },
   close = function () {
      obj_expose_overlay.expose().close();
   };

   Sprint.modules.add(initialise);

   var obj_public = {
      show: function(str_new_content_id) {
         str_content_id = str_new_content_id;
         render();
      },
      hide: function() {
         close();
      }
   };
   return obj_public;
}());

/* Masdings carousel */
Masdings.carousel = (function () {
   var doop,  
   initialise = function() {
	  var obj_carousel_div = $('#home_carousel');
	  
	  if(obj_carousel_div.length > 0){
             $('.slides',obj_carousel_div).after('<div id="nav">').cycle({ 
		    fx:     'fade', 
		    speed:  'slow', 
		    timeout: 5000, 
		    pager:  '#nav',
		    slideExpr:	'.slide'
		});
          }
   };

   Sprint.modules.add(initialise);

   return {};
}());


