/*global jQuery: true */
// ## Cambria
// ## CambriaUSA
//
// `global.js` handles most of the base functionality in the Cambria USA marketing pages.
// 
// ---------------------------------------------        
//
// Wraps the script in an anonymous function to reduce script collision    
;(function($, global){

  // Safe console logging
  ;(function () {
    var fns = 'log count info warn error'.split(' '),
        console = window.console || (window.console = {})
        noop = function () {},
        i = 0
    for (; i < fns.length; i++)  console[fns[i]] || (console[fns[i]] = noop)
  })()

  // ### Global  

  // Global object to store things in.
  global.CAMBRIA = global.CAMBRIA || {};

  // Client side storage wrapper
  var localStore = (function() {
		try {
		  return 'localStorage' in global && global['localStorage'] !== null;
		} catch(e) {
		  return false;
		}
	}());

	CAMBRIA.set = (function() {
		if (localStore) {
			return function(key, val) {
				localStorage[key] = val;
			};
		}
		return function(key, val) {
			$.cookie(key, val, {path: '/'});
		};
	}());

	CAMBRIA.get = (function() {
		if (localStore) {
			return function(key) {
				return localStorage[key];
			};
		}
		return function(key) {
			return $.cookie(key);
		};
	}());

  // Return the data for the given tile from the CAMBRIA.tiles json written by the server
  CAMBRIA.tileData = function tileData (name) {
    var tile, tiles = CAMBRIA.tiles
    if (!tiles)  throw "CAMBRIA.tiles was not set, can't get data for tile named: " + name
    if (!(tile = tiles[name]))  throw "CAMBRIA.tiles didnt have a tile named: " + name
    return tile    
  }

  // `placeholders` contains the call for select inputs to apply placeholder replacement too.
  var cambria = {
    placeholders: function() { return $('.container input'); }
  };

  // ### Collapsible Containers
  
  function enableCollapsibleContainers() {
    var col_root, sections, sections_content, section_titles;

    col_root = $('.collapsible');
    sections = $('.collapsible .section');
    sections_content = sections.find('.section-content');
    section_titles = sections.find('.open');

    sections_content.css({display: 'none'});

    section_titles.toggle(
      function(event) {
        var current = $(event.currentTarget);
        current.next('.section-content').show();
        current.parent().addClass('expanded');
      }, 
      function(event) {
        var current = $(event.currentTarget);
        current.next('.section-content').hide();
        current.parent().removeClass('expanded');
      }
    );
  }

  // ### Placeholder support
  //
  // Not using the native placeholder as it has styling issues in chrome.
  // http://blog.ajcw.com/2011/02/styling-the-html5-placeholder/
  //
  // This breaks `required` field validation on forms, peek inside
  // `loan-shared-utils.js` for a custom validation fn to handle this
  //
  function enableInputPlaceholders() {

    //if (!('placeholder' in document.createElement('input'))) {
      $('input[placeholder]').each(function() {
          $(this).bind({
              setPlaceHolder: function(e, empty) {
                  var str = empty ? '' : $(this).attr('placeholder')
                  $(this).val(str);
              },
              click: function(e) {
                  if ($(this).val() == $(this).attr('placeholder')) {
                      $(this).trigger('setPlaceHolder', [true]);
                  }
              },
              focus: function(e) {
                  if ($(this).val() == $(this).attr('placeholder')) {
                      $(this).trigger('setPlaceHolder', [true]);
                  }
              },
              blur: function(e) {
                  if ($(this).val() == '') {
                      $(this).trigger('setPlaceHolder');
                  }
              }
          });

          if ($(this).val() == '') {
              $(this).trigger('setPlaceHolder');
          }
      });
    //}
  }

  function toggleBySelection() {
    var toggles;
    toggles = $('.radio-select .radio-set');

    // Be default the non trade professional should be hidden
    $('.toggle-yes').hide();

    toggles.change(function(event) {
      var current;
      current = event.target.value;

      if (current === 'no' || current === 'No') {
        $('.toggle-non').show();
        $('.toggle-yes').hide();
      } else {
        $('.toggle-non').hide();
        $('.toggle-yes').show();
      }
    });
  }

  function enableCharacterCounting() {
    var inputs;
    inputs = $('.enable-count');

    inputs.each( countCharacters );
    inputs.bind('keyup focus', countCharacters );

    function countCharacters() {
      var updater, max, current_val;
      updater = $(this).next('.count');
      max = $(this).data('max');
      current_val = $(this).val().length;

      updater.text(current_val + ' / ' + max  );
      
      if (current_val > max) {
        updater.css({ 'color': 'red', 'font-weight': 'bold' });
        $(this).css({ 'border-color': 'red'});
      } else {
        updater.css({ 'color': '#818181', 'font-weight': 'normal' });
        $(this).css({ 'border-color': '#e1e1e1'});
      }
    }
   
  }
  
  // ### Document.ready / Initialization
  
  $(document).ready(function(){
  
  	// issue browser
	$('.issues .section a').click(function(){
		var issue = $(this).attr("href");
		$('.issues .digital-issue .issue.active').fadeOut(function(){	
			$(this).removeClass('active');	
			$('.issues .digital-issue .issue.'+issue).addClass('active').fadeIn();
		});
	});

    // Check to see if the uniform library is included and based on that restyle the inputs
    if ($.fn.uniform) { $('input:checkbox, input:radio, input:file, select').uniform(); }

    // Enable collapsible functions 
    if ($('.collapsible').length) { enableCollapsibleContainers(); }

    // Add in placeholder on input support - DISABLED DUE TO POOR CSS SUPPORT
    enableInputPlaceholders();
    
    // Clearfix for Mortgage Contact thumbnails
    $("ul.team li:nth-child(4n+1)").addClass("clear");
    
    // Adding height to Mortgage team list items for IE7 and lower 
    if (jQuery.browser.msie && jQuery.browser.version < "8") {
      $("ul.team li").addClass("taller");
    }
    
    // Table zebra stripes
    $("table tr:nth-child(even)").addClass("even");

    if ($('.contact').length > 0) {

      	$(".renovationdate").datepicker({
          showOn: "button",  
          buttonImage: "../images/ico_calendar.jpg",
          buttonText: "Select a date",
          showButtonPanel: true,
          closeText: "Close",
          buttonImageOnly: true,
          onClose: function(dateText, inst) { $(this).attr("disabled", false); },
          beforeShow: function(input, inst) { $(this).attr("disabled", true); }
			});   

      toggleBySelection();
    }

    enableCharacterCounting();
  });
}(jQuery, this));

