 if (!window.console) console = {log: function() {}};

var empty_option = '<option value="">Select country first</option>';

// object to hold text for clickable elements ie search box
var elementTxt = new Object();

$(document).ready(function(){
  
  /**
   * retail console links
   */
  $('.retailConsoleLink').dialog({
    autoOpen: false,
    modal: false 
  });
  
  /**
   * private url links
   */
  $('.privateAccessUrl').dialog({
   autoOpen: false,
   modal: false 
  });
  
  /**
   * discount code list
   */
  $('.discountCodeList').dialog({
   autoOpen: false,
   modal: false 
  });
  
  /**
   * empty attached element on focus,
   * repopulate on blur if empty
   */
  $('.emptyOnFocus').each(function(){
     
    elementTxt[$(this).attr('id')] = $(this).val();
     
  });
   
  $('.emptyOnFocus').focus(function(){
     
     // clear text if equal to original
     if($(this).val() == elementTxt[$(this).attr('id')])
     {
       $(this).val(' '); // IE8 doesn't like empty val...
       $(this).select(); // So I'm adding a space and selecting it, so they just keep typing!
     }
     
  });
   
  $('.emptyOnFocus').blur(function(){
	
    // repopulate with original text if empty (not search)
    if($(this).attr('id') != 'searchStr' && $(this).val() == '')
    {
      $(this).val(elementTxt[$(this).attr('id')]);
    }
     
  });
   
  /**
   * if search box submits on main seach page
   * then submit main form instead
   */
  $('form#searchBoxForm').submit(function(){
    
    if($('form#searchFilterForm').length > 0)
    {
      // set hidden search string field in main form
      $('#filterSearchStr').val($('#searchStr').val());
      
      // submit main form
      $('form#searchFilterForm').submit();
      
      // stop this form submitting
      return false;
    }
    else
    {
      return true;
    }
    
    
  });
  
  // setup date selector
  $('div.dateSelectorWrap select.dateSelector').change(function(){
    setDate(this);
  });
  
  // setup country selector
  $('.country_selector').change(function ()
  {
    // console.log($(this).attr('name'));

    // get id
    var id = $(this).attr('name');

    id = id.substr(0, id.length - 12);

    // console.log(id);

    getProvinces(id);
  });
  
  // get initial provinces
  $('.country_selector').trigger('change');
  
  /**
   * add colour picker
   */
  $('.colourPicker').addColorPicker({'colorBg':'yes', 'cursor':'pointer','autoClose':'yes','multiple':'yes'}); 
  
  /**
   * faq links
   */
  faqLinks();

  /**
   * sort admin check lists
   */
  sortAdminCheckList();
  
});

/*
  gets the list of provinces, or a text entry field
*/
function getProvinces(address_prefix)
{
  // console.log(address_prefix);
  
  if($('[name="'+address_prefix+'[country_id]"]').length == 1)
  {
    // disable submit
    $('input[type="submit"]').attr('disabled', 'disabled');
    
    // get country id
    var country_id = $('[name="'+address_prefix+'[country_id]"]').val();
    
    if(country_id != '')
    {
      // get prefix in id style
      var prefix_id_format = address_prefix.replace(/[\[\]]/g, '_');
      prefix_id_format = prefix_id_format.replace(/__/g, '_');

      var province_id_str = prefix_id_format + '_hidden_province_id';
      province_id_str = province_id_str.replace(/__/g, '_');

//      console.log(province_id);

      // get address id
      var province_id = $('#' + province_id_str).val();

      var other_province_id_str = prefix_id_format + '_hidden_other_province';
      other_province_id_str = other_province_id_str.replace(/__/g, '_');

      // get other province
      var other_province = $('#' + other_province_id_str).val();

      // check for labels
      if($('[name="'+address_prefix+'[country_id]"]').siblings('label').length == 0)
      {
        noLabels = 1;
      }
      else
      {
        noLabels = 0;
      }

      $.post(
        '/profile/getProvinceSelect',
        {
          'id': country_id,
          'province_id': province_id,
          'other_province': other_province,
          'prefix': address_prefix,
          'no_labels': noLabels
        },
        function(data){

          $('#'+prefix_id_format+'ProvinceWrap').html(data);
          
          // enable submit
          $('input[type="submit"]').removeAttr('disabled');

          // set input mask based on country
          setInputMask(country_id,prefix_id_format);
        },
        'html'
      );
    }
  }
}

/*
  for date selector, updates hidden date field on update
*/
function setDate(select_box)
{
  // get name of input field to update
  var name = $(select_box).attr('id').split('-')[0];
  
  // alert(name);
  
  // get full date
  var date = $('#' + name + '-year').val() + '-' + $('#' + name + '-month').val() + '-' + $('#' + name + '-day').val();
  
  // alert(date);
  
  // update hidden field
  $('#' + name).val(date);
}

/**
 * show faqu links in popup
 */
function faqLinks()
{
  if($('a.faqLink').length > 0)
  {
    // add hidden popup box
    $('body').append('<div id="faqPopup" style="display:none;"></div>');
    
    // add dialog functionality
    $('#faqPopup').dialog({
      modal: true,
      autoOpen: false
      });
    
    $('a.faqLink').click(function(){
      
      $.get(
        '/article/getFaqPopup',
        {id: $(this).attr('id').split('_')[1]},
        function(data)
        {
          $('#faqPopup').html(data);
          
          $('#faqPopup').dialog('option', 'title', $('#faqPopup').find('h2').text());
          
          $('#faqPopup').find('h2').remove();
          
          $('#faqPopup').dialog('open');
        },
        'html'
      );
      
    });
  }
}

/**
 * move all checked items to top; keep alpha. order
 */
function sortAdminCheckList()
{
  $('ul.sf_admin_checklist').each(function(){

    var checkedLis = $(this).find('li input:checked').parent().detach();

    $(this).prepend(checkedLis);

  });
}

/**
 * set pcode and telephone input masks
 */
function setInputMask(countryId,prefix_id_format)
{
  //$('input.phone').unmask();
  //$('input.pcode').unmask();

  var pcode = $('#' + prefix_id_format + '_pcode');
  var phone = $('#' + prefix_id_format + '_telephone');

  pcode.unmask();
  phone.unmask();

  switch(countryId)
  {
    case 'CA':
//      console.log('CA');
      phone.mask('999-999-9999');
      pcode.mask('*** ***');
      break;
    case 'GB':
//      console.log('GB');
      phone.mask('0999999999?9');
      pcode.mask('*****?**');
      break;
    case 'US':
//      console.log('default');
      phone.mask('999-999-9999');
      pcode.mask('99999');
      break;
  }
}
