// "use strict";
/*jslint browser: true, newcap: true, nomen: false, onevar: true, eqeqeq: true, bitwise: true, immed: true */
/*global jQuery: true, window: true */

(function ($, _) {

  var css_assets = [ "/assets/common.css", "/assets/anglo.css" ]

  // Google Analytics, async
  function setup_google_analytics () {
    if ('development' === _.environment) {
      return;
    }
    _._gaq = _._gaq || [];
    _._gaq.push(['_setAccount',     'UA-941020-3' ]);
    _._gaq.push(['_setDomainName',  'anglodance.co.uk' ]);
    _._gaq.push(['_trackPageview']);

    var ga = document.createElement('script'); 
    ga.type = 'text/javascript'; 
    ga.async = true;
    ga.src = ('https:' === document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga);
  }

  // Auto complete fields
  function setup_auto_completion (scope) {
    scope = $(scope || '.existing_client.simple');
    $('.client_text', scope).autocomplete({ 
      source: 
        function (request, response) {
          $.ajax({ 
            url: '/admin/clients.json?text_query=' + request.term,
            success: function (data) {
              response($.map(data, function (item) {
                return { 
                  'value': item.client.id, 
                  'label': item.client.name 
                };
              }));
            }
          });
        },
      select: 
        function(event, ui) { 
          $('.client_id', scope).val(ui.item.value);
          $(event.target)
            .val(ui.item.label)
            .closest('form')
            .submit();
          return false;
        },
      minLength: 2,
      delay: 400
    }).closest('form').find('.submission').hide();
  }
  
  // Replace links in submission area with buttons for consistent style
  function replace_form_links (scope) {
    $('.buttonisable', scope)
      .wrapInner('<span />')
      .addClass('buttonable')
      .filter('[type=submit]')
      .addClass('button_padding');
  }

  // Add hover / stripe effect
  function apply_graphics (scope) {
    // Auto hide/show if JS enabled
    $('.auto_hide', scope).hide();
    $('.auto_show', scope).show();
    // Zebra striping
    $('ul.striped > li:even, table.striped tbody > tr:even', scope).addClass('even').removeClass('odd last');
    $('ul.striped > li:odd,  table.striped tbody > tr:odd ', scope).addClass('odd').removeClass('even last');
    $('ul.striped > li:last, table.striped tbody > tr:last').addClass('last');
    // Hover styles
    $('ul.hoverable li, table.hoverable tbody > tr', scope).hover(
      function () { 
        $(this).addClass('hovering'); 
        $('.auto_hide', this).stop(true, true).fadeIn('fast');
      },
      function () { 
        $(this).removeClass('hovering'); 
        $('.auto_hide', this).stop(true, true).fadeOut('slow');
      });
  }
  
  // Binding of client to new notes
  function note_client_selection (scope) {
    var 
      zone      = $('.note_client', scope),
      selection = $('.selection',  zone);
    selection.change(function () {
      var
        active  = $('input:checked', selection).val(),
        items   = { 
          'new':      [ 'new', 'existing', 'none' ],
          'existing': [ 'existing', 'new', 'none' ],
          'none':     [ 'none', 'existing', 'new' ] },
        actions = [ 'show', 'hide', 'hide' ],
        area    = items[active];
      while(area.length) {
        $('.' + area.shift() + '_client', zone)[actions.shift()]();
      }
    }).trigger('change');
  }
  
  // AJAX call recent notes
  function show_recent_notes (scope) {
    $.get('/admin/notes/recent.html', function(result) {
      var 
        doc = $(result),
        notes = $('#note_list', doc);
      $('#notices', scope).html(notes.html());
    });
    _.setTimeout(show_recent_notes, 15000);
  }

  function set_up_map () {
    if (! _.google.maps) {
      return;
    }
    var 
      map_api   = _.google.maps,
      canvas    = $('.location_map'),
      address   = canvas.find('address').html(),
      position  = $('meta[name="geo.position"]').attr('content').split(','),
      location  = new map_api.LatLng(
        _.parseFloat(position[0]), 
        _.parseFloat(position[1])),
      settings = {
        zoom: 15,
        center: location,
        mapTypeId: map_api.MapTypeId.ROADMAP,
        mapTypeControl: false,
        navigationControlOptions: { style: map_api.NavigationControlStyle.SMALL } },
      map = new map_api.Map(canvas.addClass('mini_map').get(0), settings),
      marker = new map_api.Marker({
        position: location,
        map: map }),
      info = new map_api.InfoWindow({ content: address });
    info.open(map, marker);
    map_api.event.addListener(marker, 'click', function () {
      info.open(map, marker);
    });
  }
  
  function setup_time_table_view (scope) {
    var scope = $(scope || '#time_tables');
    $.get('/pages/timetables.html', function (page) {
      $('.info', scope).hide().html($('#content .classes', page).html());
    });
    $('.day_summary', scope).hide();
    $('.menu a', scope).click(function (event) {
      var 
        node = $(event.target).closest('a').attr('class'),
        mark_up = $('.info #' + node, scope).map(function (__, item) { 
          return $(item).html(); 
        }).get().join('');
      // _.console.log($('.info #' + node, scope));
      replace_form_links($('.day_summary', scope).hide().html(mark_up).fadeIn('slow'));
      return false;
    });
  }
  
  function apply_about_us_slider (scope) {
    var 
      about_markup,
      styles_markup,
      area = $('#about', scope),
      zone = $('#page_wrapper', scope),
      nav_link = $('li.about, .about_summary, p.about', scope);
    // Read page
    $.get('/pages/about.html', function (page) {
      about_markup = $('#content .about', page).html();
    });
    $.get('/pages/dance_styles.html', function (page) {
      styles_markup = $('#content .dance_styles', page).html();
    });
    // Toggle link for about
    nav_link.find('a').click(function () {
      if (nav_link.hasClass('selected')) {
        zone.animate({ 'margin-left': '260px' });
        nav_link.removeClass('selected');
      } else {
        area.html(about_markup);
        zone.animate({ 'margin-left': '610px' });
        nav_link.addClass('selected');
      }
      return false;
    });
    // Timetable 
    $('.style_info', scope).live('click', function (event) {
      var 
        link      = $(event.target).closest('a'),
        selector  = link.attr('href').replace(/.*?\#/, '#'),
        content   = $(styles_markup),
        selected  = $(selector, content).html();
      area.html(selected + '<a href="#" class="buttonable close_panel"><span>Close</span></a>');
      zone.animate({ 'margin-left': '610px' });
      return false;
    });
    // Close about info
    $('.close_panel', scope).live('click', function () {
      zone.animate({ 'margin-left': '260px' });
      return false;
    }); 
  }

  function apply_correct_dance_type_heights (scope) {
    $('.types .zone li', scope).wrapInner('span');
    $('.dance_styles .types .column', scope).each(function (__, item) {
      var parent_height = $(item).parents('.two_column_split').height();
      $(item).height(parent_height - 25); // Why 25? -> padding?
    });
  }
  
  function expanding_news (scope) {
    $('.news_item', scope)
      .find('.extra')
        .hide()
        .end()
      .find('.overview')
        .append('<p class="read_more"><a href="#" class="buttonisable">Read More</a></p>')
      .find('.read_more a')
        .click(function (event) {
          $(event.target)
            .hide('slow')
            .parents('.news_item')
            .find('.extra')
              .show('fast');
          return false;
        });
    // Expand if id found in the URL
    if (_.location.hash.length > 0) {
      $(_.location.hash, scope)
        .find('.extra').show().end()
        .find('.read_more').hide();
    }
  }

  function set_up_time_table_toggles (scope) {
    // Save markup into buffer
    var 
      criteria_ui         = $('.toggles', scope),
      time_table          = $('.event_list', scope),
      time_table_content  = time_table.html();

    // Look at criteria state, reset markup and then hide accordingly
    function toogle_time_table_classes () {
      // Reset content
      time_table.html(time_table_content);
      // Hide hidden bits
      if ($('.dance_type .included a', criteria_ui).length) {
        $('.dance_type .excluded a', criteria_ui).map(function (__, item) { 
          $('.' + item.id.replace('toggle_', ''), time_table).hide();
        });
      }
      // Show anything else (needed due to overlap dance types for some classes)
      $('.dance_type .included a', criteria_ui).map(function (__, item) { 
        $('.' + item.id.replace('toggle_', ''), time_table).show();
      });
      // Replace days with nothing in them
      $('.day', time_table).each(function (__, node) {
        if (! $('.days:visible', node).length) {
          $(node).hide();
        }
      });
      $('.invisible .details', time_table).hide();
      $('.age_group', time_table)
        .hide()
        .closest($('.age_group .active', criteria_ui).attr('href').replace('#', '.'))
        .show();
      $(_).trigger('refresh');
    }
    
    // Show details
    $('.invisible h3 a', time_table)
      .live('click', function (event) {
        $(event.target)
          .closest('.event')
          .removeClass('invisible')
          .addClass('expanded')
          .find('.details')
          .show('fast');
        return false;
      });

    // Hide details
    $('.expanded h3 a', time_table)
      .live('click', function (event) {
        $(event.target)
          .closest('.event')
          .removeClass('expanded')
          .addClass('invisible')
          .find('.details')
          .fadeOut();
        return false;
      });

    $('.dance_type a', criteria_ui).each(function (__, item) {
      $(item)
        .attr('id', $(item).attr('href').replace('#', 'toggle_'))
        .bind('click', function (event) {
          $(event.target)
            .closest('li')
            .toggleClass('excluded')
            .toggleClass('included');
          toogle_time_table_classes();
        });
    });
    
    $('.age_group a', criteria_ui).click(function (event) {
      var 
        items = $('.age_group', time_table),
        links = $('.age_group a', criteria_ui).removeClass('active'),
        group = $(event.target).addClass('active');
        toogle_time_table_classes();
    }).first().click();
    
    $('.dance_type a', criteria_ui).click();
  }
  
  function tool_tips (scope) {
    $('.field_with_errors', scope).each(function (__, node) {
      $('input, select, textarea', node).tooltip({ content: $('span.error', node).hide().html() });
    });
    $('.tooltip', scope).tooltip({ position: { my: 'center top', at: 'center bottom' } });
  }
  
  function event_attendance (scope) {
    var 
      list    = $('select#event_id', scope),
      states  = $('#event_state', scope);
    function toggle_state_dropdown () {
      if ('' === list.val()) {
        states.fadeOut();
      } else {
        states.fadeIn();
      }
    }
    list.change(toggle_state_dropdown);
    toggle_state_dropdown();
  }
  
  function sms_message_size (scope) {
    var 
      total = $('#credit_count',     scope),
      text  = $('#sms_message_text', scope),
      info  = $('#sms_message_size', scope);
    
    function check_size () {
      var 
        clients = $('.client_list li', scope).length,
        size    = text.val().length,
        sum     = (size >= 160) ? Math.ceil(size / 153) : 1,
        credits = sum * clients,
        msg     = (sum > 4) ? 'Too big to send' : 'Credit(s) for this message: ' + sum;
      info.html('Chars used: ' + size + '. ' + msg);
      total.html('Credits used: ' + credits)
    }
    text.live('keydown keyup change', check_size).trigger('change');
  }
  
  function apply_sorting (scope) {
    if (! $.fn.sortable) {
      return;
    }
    $.each([ 'dance_types', 'posts' ], function (index, item) {
      var items = $('#' + item, scope);
      items.sortable({
        axis:         'y', 
        dropOnEmpty:  false, 
        handle:       '.handle', 
        cursor:       'crosshair',
        items:        'tr',
        opacity:      0.4,
        scroll:       true,
        update: function() {
          $.ajax({
            type:     'post', 
            data:     items.sortable('serialize') + '&_method=put', 
            dataType: 'script', 
            url:      '/admin/' + item + '/sort',
            complete: function (request) {
              apply_striping_and_hovers();
              items.effect('highlight');
            }
          });
        }
      }).find('.handle').click(function (event) {
        alert('Drag to move!');
        return false;
      });
    });
  }
  
  function apply_fixed_menu () {
    function extend_menu () {
      $('#inner_page_wrapper').height([ 
        $(window).height(), 
        $('#content').height() 
      ].sort(function ( a, b ) {
        // God damn JS 'lexical' corting on number types
        return a - b;
      }).pop());
    }
    extend_menu();
    $(_).resize(extend_menu);
    _.setInterval(extend_menu, 500); // Bit of a hack
    $('body').addClass('fixed_menu');
  }
  
  function client_forms (scope) {
    $('.new_sms_group_client', scope).live('submit', function (event) {
      var 
        form = $(event.target).closest('form'),
        client = form.find('.client_id');
      if (! client.val().match(/\d+/)) {
        _.alert('Please enter a name of a client');
        return false;
      }
      return true;
    });
  }
  
  function rich_text_editors () {
    if (! _.CKEDITOR) {
      return;
    }
    // Global to all editor instances
    _.CKEDITOR.addStylesSet( 'default', [
      // Block Styles
      { name : 'Note',                element : 'p', attributes : { 'class' : 'note' } },
      { name : 'Heading 1',           element : 'h1' },
      { name : 'Heading 1 (Page)',    element : 'h1', attributes : { 'class' : 'page' } },
      { name : 'Heading 2',           element : 'h2' },
      { name : 'Heading 3',           element : 'h3' },
      { name : 'Heading 4',           element : 'h4' },
      { name : 'Heading 5',           element : 'h5' },
      { name : 'Heading 6',           element : 'h6' },
      { name : 'Normal / Paragraph',  element : 'p' },
      { name : 'Preformatted Text',   element : 'pre' },
      { name : 'Address',             element : 'address' },
      // Inline Styles
      { name : 'Highlight',           element : 'span', attributes : { 'class' : 'highlight' } }
    ]);

    $('.rich_text').each(function (__, item) {
      $(item).ckeditor({ 
        width: $(item).width(),
        height: $(item).height(),
        forcePasteAsPlainText: true,
        uiColor : '#eee',
        customConfig: '',
        contentsCss: css_assets,
        toolbar: [
          [ 'Source', '-', 'Preview' ],
          [ 'Cut', 'Copy', 'PasteText' ],
          [ 'Undo', 'Redo', '-', 'Find', 'Replace', '-', 'SelectAll', 'RemoveFormat' ],
          [ 'Styles' ],
          '/',
          [ 'Bold', 'Italic', 'Strike','-', 'Subscript', 'Superscript' ],
          [ 'NumberedList', 'BulletedList', 'Blockquote'],
          [ 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
          [ 'Link', 'Unlink' ],
          [ 'Anchor', 'SpecialChar'],
          [ 'Maximize', 'ShowBlocks', '-', 'About']
        ],
        on: {
          instanceReady: function (env) {
            var tag, writer = this.dataProcessor.writer;
            writer.indentationChars = '  ';
            writer.breakBeforeOpen  = false;
            writer.breakAfterOpen   = false;
            writer.breakBeforeClose = false;
            writer.breakAfterClose  = true;
            for (tag in writer._.rules) {
              // There are some annoying edge cases where internal textile 
              // doesn't take kindy to whitespace
              writer.setRules(tag, {
                breakBeforeOpen:   false,
                breakAfterOpen:    false,
                breakBeforeClose:  false
              });
            }
          }
        }
      });
    });
  }

  $(document).ready(function () { 
    $('.auto_hide').hide();
    $('.auto_show').show();
    expanding_news();
    replace_form_links();
    note_client_selection();
    setup_auto_completion();
    apply_graphics();
    apply_about_us_slider();
    apply_correct_dance_type_heights();
    set_up_time_table_toggles();
    tool_tips();
    sms_message_size();
    event_attendance();
    apply_sorting();
    apply_fixed_menu();
    rich_text_editors();
    client_forms();
    setup_google_analytics();
    if (_.location.href.match(/admin/)) {
      show_recent_notes();
    }
    if ($('.location_map').length && _.google) {
      set_up_map();
    }
    if ($('.home_page').length) {
      setup_time_table_view();
    }
    $('.open_in_new_window').live('click', function (event) {
      _.open($(event.target).attr('href'), 'new_window', 'width=800,height=600,toolbars=true,scrollbars=true');
      return false;
    });
  });
}(jQuery, window));

