(function() {  

var KEYS={BACKSPACE:8,TAB:9,RETURN:13,ESC:27,SPACE:32,PAGE_UP:33,PAGE_DOWN:34,LEFT:37,UP:38,RIGHT:39,DOWN:40,DELETE:46,COMMA:188};

window.G = (function(){
  return {
    regExes: {
      email: /^([a-zA-Z0-9-_.]+@[a-zA-Z0-9-\.]+\.[a-zA-Z]{1,7})$/
    }, // regExes

    validateEmail: function(val) {
      return G.regExes.email.test(val);
    }, // validateEmail

    // G.QS
    QS: {
      parseQS: function() {
        G.QS.items = {};
        var qs = location.search.substr(1).split('&');
        for(var i=0; i<qs.length; i++) {
          pair = qs[i].split('=');
          G.QS.items[pair[0]] = pair[1];
        }
      },
      get: function(k) {
        if(typeof G.QS.items=='undefined') {
          G.QS.parseQS();
        }
        return G.QS.items[k];
      }
    }, // QS

    // G.log
    log: function(text) {
      var str = [];
      for(var i=0, len=arguments.length; i<len; i++) {
        str.push(arguments[i]);
      }
      if(typeof console!=='undefined') {
        console.log(str);
      }
    }, // log

    // G.error
    error: function() {
      var str = [];
      for(var i=0, len=arguments.length; i<len; i++) {
        str.push(arguments[i]);
      }
      if(typeof console!=='undefined') {
        console.error(str);
      }
    } // error
  };
})();

var project = {
  
  handlers: {
    toggleNode: function(e, args) {
      // args: { node: NODE, target: NODE }
      $(args.target).toggleClass('hide');
      // JSK: i want to remove "open" and replace it with the more semantically "toggled" "on"
      $(args.node)
        .toggleClass('open')
        .toggleClass('on')
        .blur();
      // Y.fire('wb:display:' + args.target.getAttribute('id'));
    }, // toggleNode

    toggleClass: function(e, args) {
      if(args.node.getAttribute('data-clear')=='true') {
        args.$target[0].className = args.node.getAttribute('data-class');
      }
      else {
        args.$target.toggleClass(args.node.getAttribute('data-class'));
      }
      
    }, // toggleClass

    changeText: function(e, args) {
      $(args.node).text(args.node.getAttribute('data-text'));
    }, // rotateCarousel

    alert: function(e, args) {
      alert(args.node.getAttribute('data-message'));
    } // alert

  }, // handlers
  
  addTracking: function() {
    var extra = new Date().getTime().toString();
    $.ajax({
      url: '/p293wgiacsdg' + extra,
      type: 'GET',
      dataType: 'json',
      success: function(data) {
        project.tracking = data.tracking;
        var $links = $('a');
        $.each(project.tracking, function(k, codes) {
          for(var i=0, cLen=codes.length, code, track, $elem; i<cLen; i++) {
            code = codes[i];
            track = [k, code[1]];
            $links.filter('[title="' + code[0] + '"]').each(function() {
              if(this.hasAttribute('data-extra')) {
                track.push(this.getAttribute('data-extra'));
              }
              $(this).attr('data-track', track.join(':'));
            });
          }
        });
        // var pt = ;
        // var page = document.getElementsByTagName('body')[0].id;
        $('[data-track]').live('click', function() {
          try {
            var dataTrack = document.getElementsByTagName('body')[0].id + ':' + this.getAttribute('data-track');
            _gat._getTracker('UA-26811494-1')._trackEvent(undefined, undefined, dataTrack);
          }
          catch(err) {
            _gat._getTracker('UA-26811494-1')._trackEvent('Error', 'Tracking', 'Unable to track event');
          }
          return true;
        });
      }, // success
      error: function(err) {
        console.log(err);
      } // error
    });
  }, // addTracking
  
  doClickActions: function(e) {
    var node = this;
    var actions = [],
        data = {},
        toggles = [],
        target = null,
        targetParent = null;
    if(node.tagName.toLowerCase()=='a' && !node.getAttribute('data-return')) {
      e.preventDefault();
    }
    if(node.getAttribute('data-c-actions')) {
      actions = node.getAttribute('data-c-actions').split(' ');  
    }
  
    try {
      if(node.tagName.toLowerCase()=='a') {
        var hash = node.hash;
        if(!!hash) {
          target = $(hash);
          targetParent = $(target).parent();
        }
        else {
          target = node.href;
        }
      }
      else if(node.getAttribute('data-target')) {
        target = $('#' + node.getAttribute('data-target'));
      }
    }
    catch(e) {
      //
    }
    for(var i=0, aLen=actions.length, action; i<aLen; i++) {
      action = actions[i];
      if(typeof project.handlers[action]!=='undefined') {
        project.handlers[action]( e, {
          node: node,
          title: node.getAttribute('data-title') ? node.getAttribute('data-title') : null,
          href: node.getAttribute('href') ? node.getAttribute('href').split('#')[0] : null,
          $target: target,
          $targetParent: targetParent,
          $data: typeof data[action]!=='undefined' ? data[action] : data
        });
      }
    }
  }, // doClickActions

  _init: function() {
    $('[data-c-actions]').live('click', project.doClickActions);
    project.addTracking();
  } // _init

}; // project

project._init();
window.project = project;
})();
