var demo_vimeo_id = 7935833;
var demo = '<object width="600" height="331"><param value="true" name="allowfullscreen"/><param value="transparent" name="wmode"/><param value="always" name="allowscriptaccess"/><param value="http://vimeo.com/moogaloop.swf?clip_id='+demo_vimeo_id+'&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=0&amp;show_portrait=0&amp;color=&amp;fullscreen=1&amp;autoplay=0" name="movie"/><embed width="600" height="331" allowscriptaccess="always" allowfullscreen="true" wmode="transparent" type="application/x-shockwave-flash" src="http://vimeo.com/moogaloop.swf?clip_id='+demo_vimeo_id+'&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=0&amp;show_portrait=0&amp;color=&amp;fullscreen=1&amp;autoplay=0"/></object>';

var is_chrome = /chrome/.test( navigator.userAgent.toLowerCase() );

$(function(){
  
  $('a.cause_item').removeClass('cause_item_selected');
  
  var uhash = document.location.hash;
  if(uhash[0] == '#' && uhash[1] == '/'){
    var charity = uhash.substring(2);
    make_new_cause(charity);
    charities.add_charity_to_cookie(charity);
  }
  
  if(track)track.goal('install', 'start');
  
  $(window).bind('scroll', function(){
    $(window).unbind('scroll');
    track.goal('install', 'scroll');
  });
  
  $('#causes_custom').click(function(){
    $(this).hide();
    placeholder($('#causes_custom_name'));
    $('#causes_custom_form').css('display', 'inline');//.find('input:eq(0)').focus();
    $('#causes_custom_form').submit(function(){
      var charity = $('#causes_custom_name').val();
      if(charity == $('#causes_custom_name').attr('placeholder')) return false;
      make_new_cause(charity);
      charities.add_charity_to_cookie(charity);
      $('#causes_custom_name').val('')
      return false;
    })
  });
  
  $('#download_now').click(function(){
    $(window).scrollTo({top: 600}, {
      duration: 180,
      onAfter: function(){
        var left = 0, right = 20, steptime = 80;
        $('#causes_wrapper h1:eq(0)').delay(200).animate({
          marginLeft: right + 'px'
        }, steptime).animate({
          marginLeft: left + 'px'
        }, steptime).animate({
          marginLeft: right + 'px'
        }, steptime).animate({
          marginLeft: left + 'px'
        }, steptime).animate({
          marginLeft: right + 'px'
        }, steptime).animate({
          marginLeft: left + 'px'
        }, steptime)
      }
    });
  })
  
  $('#flash_holder_video').html(demo);
  
  installer.init();
  register_tracking();
  chooser.init();
  chooser.draw();
  
  $('#get_started').click(installer.show);  
  
  if(!$.browser.mozilla /*&& !is_chrome */){
    $('#alertbar').html('Browse For A Cause is currently only supported on FireFox. <a href="'+BASE_URL+'learn#technical">Learn More</a>');
    $("body").animate({marginTop: '30px'}, 100); 
  }
});

function register_tracking() {
  //Goals
  $('a.cause_item').bind('mouseover', function(){ $('a.cause_item').unbind('mouseover'); track.goal('install', 'mouseover_charity'); });
  $('a.cause_item').bind('mousedown', function(){ $('a.cause_item').unbind('mousedown'); track.goal('install', 'select_charity'); });
  $('a#get_started').bind('mouseover', function(){ $('a#get_started').unbind('mouseover'); track.goal('install', 'mouseover_continue'); });
  $('a#get_started').bind('mousedown', function(){ $('a#get_started').unbind('mousedown'); track.goal('install', 'continue'); });
  
  //Actions
  $('#flash_holder_video embed, #link_watch_demo').bind('mousedown', function(){
    $('#flash_holder_video embed, #link_watch_demo').unbind('mousedown');
    track.str('watch_video');
  });
}

function watch_demo() {
  $('#flash_holder_video').html(
    $('#flash_holder_video').html().split('autoplay=0').join('autoplay=1') //Re-inject the video embed into the DOM with the code that makes it autostart
  );
}

function make_new_cause(charity) {
  var desc = 'This is a charity you have specified. Money will be donated to this 501(c)(3) organization to support their non-profit';
  
  $('#causes_picker').prepend(
    '<li><a class="cause_item cause_custom" style="opacity:0"><div class="cause_item_inside"><div class="icon"><img src="' + BASE_URL + 'images/causes/default.png"/></div><div class="tick"></div><h4>' + charity + '</h4><p>' + desc + '</p><div class="cause_item_actions"><span class="support">Support Cause</span><span class="users"><!-- TBD: 12,300 Supporters --></span></div></div></a></li>'
  );
  
  $('a.cause_item:first').click(function(){chooser.item_pick(this)}).animate({opacity:1},350);
  
  var page = chooser.get_current_page();
  if(page != 1) chooser.show_page(1);
  chooser.item_pick($('a.cause_item:first').get(0));
}


var installer = {
  init: function(){
    $('#main').after('<div id="overlay"></div>');
    $('#overlay').after('<div id="install_helper"><h2>Finish in 3 Easy Steps!</h2><ol><li>1. Click&nbsp;&nbsp;<img style="vertical-align:middle" src="http://browseforacause.com/images/icon_ff_install_allow.png"/></li><li>2. Click Install Now</li><li>3. Restart Your Browser. You\'re Done!</li></ol><div id="install_arrow"></div><div id="install_close"</div></div>');
    $('#install_close').click(installer.close);
  },
  show: function(){
    setTimeout(function(){
      $('#overlay').css({height: $(document).height(), width: '100%', opacity: 0}).show().animate({opacity: .94}, 200);
      $(window).scrollTo({top: 0}, {duration: 180});
    }, 300);
    setTimeout(function(){
      $('#install_helper').css({opacity: 0, display:'block'}).animate({opacity: 1}, 300);
    }, 600);
    //return false;
  },
  close: function(){
    $('#install_helper').animate({opacity: 0}, 200, function(){
      $('#overlay').animate({opacity: 0}, 150, function(){$(this).hide()});
      $(this).hide();
    });
    return false;
  }
}

var charities = {
  cookie_name: 'charities',
  cookie_separator: '|*|',
  get_cookie: function(){
    var val = $.cookie(this.cookie_name);
    if(!val || val.length == 0) return [];
    return val.split(this.cookie_separator);
  },
  set_cookie: function(val){
    if(typeof val != "string") val = val.join(this.cookie_separator)
    $.cookie(this.cookie_name, val, {expires: 1000, path: '/', domain: 'browseforacause.com'});
  },
  add_charity_to_cookie: function(name){
    var val = this.get_cookie();
    if(val.indexOf(name) < 0) val.push(name);
    this.set_cookie(val);
  },
  update_page_from_cookie: function(){
    var list = this.get_cookie();
    var charities = [];
    $('a.cause_item').each(function(){ //Run through charities in page and sync with cookie list
      var charity = $(this).find('h4').text();
      charities.push(charity);
      if(list.indexOf(charity) >= 0) $(this).addClass('cause_item_selected');
      else $(this).removeClass('cause_item_selected');
    });
    $(list).each(function(i, charity){ //Run through cookie list and add any custom charities
      if(charity.length > 0 && charities.indexOf(charity) < 0) make_new_cause(charity);
    });
    chooser.update_get_started_label();
  },
  update_cookie_from_page: function(){
    var list = [];
    $('a.cause_item_selected').each(function(){
      list.push($(this).find('h4').text());
    });
    this.set_cookie(list);
  }
}

var chooser = {
  init: function(){
  
    $('a.cause_item').click(function(){chooser.item_pick(this)});
    
    $('#causes_pagination a').mousedown(function(){

      if($(this).hasClass('current')) return; //Already on paginated section
      
      $(this).parents('ul').find('a').removeClass('current');
      $(this).addClass('current');
      
      chooser.show_page(parseInt($(this).text()));

    }).click(function(){
      $(this).blur();
    });
    
    $('#causes_pagination a:first').addClass('current')
    
  },
  get_current_page: function(){
    return parseInt($('#causes_pagination a.current').text());
  },
  show_page: function(page){
    $('#causes_pagination a').removeClass('current');
    $('#causes_pagination a:eq(' + (page-1) + ')').addClass('current');
    $('#causes_picker').animate({ marginTop: (-232 * (page-1)) + 'px'}, 250);
  },
  item_pick: function(item){
    $(item).toggleClass('cause_item_selected');
    charities.update_cookie_from_page();
    this.update_get_started_label();
  },
  update_get_started_label: function(){
    var count = $('.cause_item_selected').length;
    if(count == 0) {
      $('#get_started span').html('Support These Charities');
    } else if(count == 1){
      $('#get_started span').html('Support This Charity');
    } else {
      $('#get_started span').html('Support These ' + count + ' Charities');
    }
  },
  draw: function(){
    charities.update_page_from_cookie();
  }
}