app = {};

app.init = function(){

  var self = this;


  ignore_regex = new RegExp(/(header|footer|nav)/);
  $.ajax({
    url: '/png_fix_selectors.json',
    type: 'GET',
    dataType: 'json',
    beforeSend:function(){},
    success: function(selector){
      $(document).pngFix({ignore_regex: ignore_regex, selector: selector.join(', ')});
    },
    error: function(){}
  });

  // $('div#logo').click(function(){
  //     window.location = '/';
  //   });


  // Pull the contact forms out of the DOM so IDs are unique
  this.contact_form = $('div#contact_container').html();
  $('div#contact_container').remove();
  this.insight_trial = $('div#insight_trial_container').html();
  $('div#insight_trial_container').remove();

  $('a.contact').click(function(){
    // google track of contact form view
    app.track_subpage('contact');

    $.overalls(self.contact_form, {blank: true});
    $('img#loader').hide();
    $('div#contact_form form.form_for_contact').find('input:submit').attr({disabled: false});
    $('div#contact_form form.form_for_contact').find("#lead_message").keyup(function(e){
      $('span#chars_left').html(140-$(this).val().length)
      if($(this).val().length >=140){
        if(e.keyCode >= 48 ){
          $(this).val($(this).val().slice(0,140))
          $('span#chars_left').html(140-$(this).val().length)
          return false;
        }
      }
    });
    return false;
  });

  $('a.show_login_menu').click(function(){
    $('ul.login_menu').toggle()
    return false;
  });


  $('div#contact_form form.form_for_contact').live('submit', function(){
    var $form = $(this);
    var data = $form.serialize();
    $.ajax({
          url: $form.attr('action'),
          type: 'POST',
          data: data,
          dataType: 'html',
          beforeSend:function(){
            $('img#loader').show();
            $form.find('input:submit').attr({disabled: true});
          },
          success: function(html){
            $form.parents('div#contact_form').replaceWith(html);
          },
          error: function(){
            $('img#loader').hide();
            $form.find('input:submit').attr({disabled: false});
            $form.append("<span class='icon ui-icon ui-icon-alert'/>Contact info was not sent. <br/> Looks like we're having a problem on our end <br/> Feel free to email us <a href='mailto:info@collectiveintellect.com'>info@collectiveintellect.com")
          }
        });
    return false;
  });

  // Bind clicks to .insight_trial to load #insight_trial_form into Overalls
  $('a.insight_trial').live('click', function(){
    $.overalls(self.insight_trial, {blank: true});
    $('img#insight_trial_loader').hide();
    $('div#insight_trial_form form').find('input:submit').attr({disabled: false});
    return false;
  });

  $('div#insight_trial_form form').live('submit', function(){
    var $form = $(this);
    var data = $form.serialize();
    $.ajax({
      url: $form.attr('action'),
      type: 'POST',
      data: data,
      dataType: 'html',
      beforeSend:function(){
        log('before send')
        $('img#insight_trial_loader').show();
        $form.find('input:submit').attr({disabled: true});
      },
      success: function(html){
        log('html')
        log('success')
        $form.parents('div#insight_trial_form').replaceWith(html);
      },
      error: function(){
        log('error!')
        $('img#insight_trial_loader').hide();
        $form.find('input:submit').attr({disabled: false});
        $form.append("<span class='icon ui-icon ui-icon-alert'/>Trial info was not sent. <br/> Looks like we're having a problem on our end <br/> Feel free to email us <a href='mailto:info@collectiveintellect.com'>info@collectiveintellect.com")
      }
    })
    return false;
  });

  // show or hide the multilingual warning when the checkbox is checked.
  $('#lead_needs_multilingual, #trial_needs_multilingual').live('change', function() {
    if($(this).is(':checked')) {
      $('.multilingual_warning').stop().fadeIn();
    }
    else {
      $('.multilingual_warning').stop().fadeOut();
    }
  });

  $('a.cancel').live('click', function() {
    $.overalls.close();
    return false;
  });

  $('a.define').click(function(){
    id = $(this).attr('href');
    $.overalls($(id).html());
    Cufon('div#overalls-overlay h2');
    return false;
  });

  $('div.content_type.socialsite').click(function(){
    window.open('http://www.facebook.com/pages/Collective-Intellect/143449332335329');
    return false;
  });

  $('div.content_type.microblog').click(function(){
    window.open('http://www.twitter.com/collectual');
    return false;
  });

  if( window.location.hash == "#contact"){
    $('a.contact').click();
  }else if ( window.location.hash == "#free_trial"){
    $('a.insight_trial').click();
  }

};

app.subnav = function(requested_page){
  // path and this_page used for google analytics below in _gaq.push(...)
  var path = window.location.pathname;
  path = path.substr(1,path.length).split('/');
  var this_page = path[0];

  //see if we have a subpage in the url, redirect if needed, otherwise pass through
  var subpage = $.bbq.getState('page')
  if(subpage){
    log(subpage);
    switch(subpage){
      case 'management':
      case 'board':
        subpage = "people";
      break;
      case 'listen':
        subpage = 'tools';
      break;
      // default :
      //   subpage = app.default_subpage();
    };
    log(subpage)
  }

  // handles people putting in old urls - requested page gets set in the home controller
  // we pass it in to this function on the about/product view and show the right subpage
  if(requested_page){
    log(requested_page)
    switch (requested_page) {
      //people
      case 'management_team':
      case 'board_of_directors':
        subpage = "people";
      break;
      // tools
      case "self_service":
      case "full_service":
      case "syndicated":
      case "topic_definition":
      case 'insight':
        subpage = 'tools';
      break;
      //approach
      case 'our_analytics':
      case 'our_approach':
        subpage = 'approach';
      break;
      default:
        subpage = app.default_subpage();
    };
  }


  if(subpage){
    log('subpage ready:', subpage)
    $.bbq.pushState({page: subpage});
  }


  $(window).bind( 'hashchange', function( event ) {
    var subpage = app.subpage();
    $('div.subpage:visible').hide();
    $('div#'+subpage).show();
    $('ul.subnav li').removeClass('active');
    $('li.'+subpage).addClass('active');
    Cufon.refresh('ul.subnav');
  });
  var subpage = app.subpage();
  $('div#'+subpage).show();
  $('li.'+subpage).addClass('active');
  Cufon('ul.subnav');
  app.track_subpage(subpage);
  $.bbq.pushState({page: subpage});

  $('ul.subnav li a, a.subnav').click( function(){
    var id = $(this).attr('href');
    $('div.subpage:visible').hide();
    $('div'+id).show();
    $('ul.subnav li').removeClass('active');
    $('li'+id.replace('#','.')).addClass('active');
    Cufon.refresh('ul.subnav');
    app.track_subpage( id );
    $.bbq.pushState({page: id.replace('#','')});
    return false;
  });

};

app.default_subpage = function(){
    return window.location.pathname.match('about') ? 'approach' : 'insight';
};

app.track_subpage = function(subpage){
  var path = window.location.pathname;
  path = path.substr(1,path.length).split('/');
  subpage = subpage.replace('#','');
  log('/'+path[0]+'/'+subpage);
  _gaq.push(['_trackPageview', '/'+path[0]+'/'+subpage]);
}

app.subpage = function(){
    var subpage = $.bbq.getState('page')  || app.default_subpage();
  return subpage;
};

app.customer_benefits = function(){
  if(!$.browser.msie){
    Cufon('div.benefit');
  }
  $('div.benefits').fadeIn('slow');
  $('div.slider').easySlider({
    continuous: true,
    prevId:     'slider_go_left',
    prevText:     '',
    nextId:     'slider_go_right',
    nextText:     ''
  });
  $('div.slider').find('.slider_control').fadeIn('slow');

  $('div.logo_slider').easySlider({
    pause:     8000,
    speed: 1600,
    auto:true,
    continuous: true,
    numeric: true
  });

};

app.init_screencasts = function(){
    flowplayer("insight_video",  {src: "/screencasts/flowplayer-3.2.2.swf", wmode: 'transparent'}, {clip:{autoPlay: false, autoBuffering: true}, onLoad: function() {this.setVolume(15);}});
    flowplayer("listen_video",   {src: "/screencasts/flowplayer-3.2.2.swf", wmode: 'transparent'}, {clip:{autoPlay: false, autoBuffering: true}, onLoad: function() {this.setVolume(15);}});
    flowplayer("semantic_video", {src: "/screencasts/flowplayer-3.2.2.swf", wmode: 'transparent'}, {clip:{autoPlay: false, autoBuffering: true}, onLoad: function() {this.setVolume(15);}});
};

function log(){
  if(window.console) {
    console.log.apply(console, arguments);
  }
}

