function scoutscroll() {
  setTimeout(function() {
    $.scrollTo({top: 0, left: 0}, 800 );
  },500);
}
General = {
  linknames: ['today','howitworks','localbusiness','scoutfinds','local_scouts','about','contact','faq','mobile','policies'],
  reset_footer: function() {
    var browser=navigator.appName;
    var window_height = 0;
    if(browser!="Microsoft Internet Explorer"){    
      window_height = window.innerHeight;
    } else{
      window_height = document.documentElement.clientHeight;
    }
    var top = window_height - $('.footer').height();
    var min_height = 0;
    $('.container_16.content > div').each( function() {
      var that = $(this);
      min_height = Math.max(that.outerHeight() + that.offset().top, min_height);
    });
    top = Math.max(top,min_height);
    $('.footer').css('top',top);
    $('.footer').show();
  },
  reset_footer_synch: function(timeout, timeout2, timeout3){
    setTimeout(General.reset_footer, (timeout) ? timeout : 200);
    setTimeout(General.reset_footer, (timeout2) ? timeout2 : 800);
    setTimeout(General.reset_footer, (timeout3) ? timeout3 : 1500);
  },
  highlightlink: function(linkname){
    $.each(General.linknames, function(){
      if(this == linkname){
        $('.footer a[name='+this+']').css('color', '#FFFFFF');
        $('.'+this+'_header').addClass('set');
      }else{
        $('.footer a[name='+this+']').css('color', '#463724');
        $('.'+this+'_header').removeClass('set');
      }
    });
    if (linkname == 'past_deals') {
      $('.scoutfinds_header').addClass('set');
      $('.footer a[name=past_deals]').css('color', '#FFFFFF');
    }
  },
  setup_email: function(){
    $('.email_header a[name=sendbutton]').click(function(){
      General.send_email('.email_header');
    });
    $('input[fieldset=register][name=email]').keyup(function(e){
      if (e.keyCode==13) {
        General.send_email('.email_header');
      }
    });
    $('.email_sidebar a[name=sendbutton]').click(function(){
      General.send_email('.email_sidebar');
    });
    $('input[name=email]').focus(function() {
        if (this.value == 'enter email here') {
          this.value = '';
          $(this).removeClass('unset').addClass('set');
        }
    }).blur(function() {
        if (this.value == '') {
          this.value = 'enter email here';
          $(this).addClass('unset').removeClass('set');
        }
    });
  },
  validate: function(email_address) {
    if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email_address)){
      return true;
    }
    return false;
  },
  send_email: function(divclass) {
    var div = $(divclass);
    var elm = $('a[name=sendbutton]', div);
    if (elm.attr('disabled')!='true') {
      var user = {};
      $('input[fieldset=register]', div).each(function() {
        user[this.name] = this.value;
      });
      if (user.email=='GREAT SUCCESS!'){
        elm.attr('disabled','true');
        $('.sendbutton_pic', div).addClass('down');
      } else if (user.email == null || user.email=='enter email here' || user.email=='') {
        elm.attr('disabled','false');
      } else {
        if(General.validate(user.email)){
          WebServices.register_email(user);
          $('.emailinput', div).css('color', '#504f46');
          $('.sendbutton_pic', div).addClass('down');
          $('.emailinput', div).val("GREAT SUCCESS!");
          $('.emailinput', div).attr('disabled','true');
          $('.promise', div).show();
          $('.bad_email', div).hide();
          $('.non_success').hide();
          $('body').css('background-color', '#000000'); 
          $('.splash_success').show();
        } else{
          $('.emailinput', div).css('color', '#fa6e11');
          $('.promise', div).hide();
          $('.bad_email', div).show();
        }
      }
    }
  },
  setup_mobile_widget: function(){
    if (General.city.short_name == 'new-york') {
      $('.complex.mobile_widget').hide();
      $('.new_york.mobile_widget').show();
    } else {
      $('.complex.mobile_widget').show();
      $('.new_york.mobile_widget').hide();
    }
    WebServices.get_unexpired_deals(function(rows){    
      $('.mobile_widget .just_added').empty();
      $('.mobile_widget .simple_just_added').empty();
      var html = '';
      for (i=0; i<3 && i<rows.length;i++){
        var biz_name = (rows[i].biz_name.length > 14)? rows[i].biz_name.substr(0, 12)+'...': rows[i].biz_name;
        html += "<p>"+biz_name+"</p>";
      }
      $('.mobile_widget .simple_just_added').append(html);
      html = '<div style="text-decoration:underline">JUST ADDED</div>'+html;
      $('.mobile_widget .just_added').append(html);
      $('.mobile_widget .expiring').empty();
      html = '<div style="text-decoration:underline">EXPIRING</div>';
      rows.sort(function (a, b) {
        return a.expiration_utc-b.expiration_utc;
      });
      for (i=0; i<3 && i<rows.length;i++){
        var biz_name = (rows[i].biz_name.length > 14)? rows[i].biz_name.substr(0, 12)+'...': rows[i].biz_name;
        html += "<p>"+biz_name+"</p>";
      }
      $('.mobile_widget .expiring').append(html);
    });
  },
  check_phone_number: function(){
    var valid_number = true;
    if($('.phone_number1').val() == null || $('.phone_number1').val().length < 3){
      $('.phone_number1').css('border-color', '#ff0000');
      valid_number = false;
    } else{
      $('.phone_number1').css('border-color', '#BBBBBB');
    }
    if($('.phone_number2').val() == null || $('.phone_number2').val().length < 3){
      $('.phone_number2').css('border-color', '#ff0000');
      valid_number = false;
    } else{
      $('.phone_number2').css('border-color', '#BBBBBB');
    }
    if($('.phone_number3').val() == null || $('.phone_number3').val().length < 4){
      $('.phone_number3').css('border-color', '#ff0000');
      valid_number = false;
    } else{
      $('.phone_number3').css('border-color', '#BBBBBB');
    }
    return valid_number;
  },
  fill_title: function(){
    var title = Today.deal.percentage_off+' Off at '+Today.deal.biz_name;
    title = (title.length > 26)? title.substr(0,25)+'...': title;
    $('.popup_signup .deal_title').empty();
    $('.popup_signup .deal_title').append(title);

    var exp_date = '';
    if(Today.deal.expiration_utc){
      var mydate = new Date(Today.deal.expiration_utc);
      exp_date = mydate.toString('MM/dd/yyyy').toUpperCase();
    }
    $('.above_send').append("Expires: <b>"+exp_date+"</b>. Valid for one user per phone.");
    $('.below_email').empty();
    $('.below_email').append("<p>Print &amp; redeem.</p><p>Expires: <b>"+exp_date+"</b>. Valid for one user per email.</p>");
  },
  setup_popup: function(){
    var popupoptions = {
      expose: {color: '#333', loadSpeed: 200, opacity: 0.9 }, 
      onBeforeLoad: function(event) { 
        if ($('#popup_signup img').attr('src') !='/images/popup_signup.png') {
            $('#popup_signup img').attr('src', '/images/popup_signup.png');
        }
      }
    };
    $("a[name=get_it_free][rel]").overlay(popupoptions);
    $("a[name=get_it_free]").click(function(){
      $('.above_send').show();
      $('a[name=send_it]').show();
      $('.error.above_send_2').hide();
      $('.error.above_send_3').hide();

      $('.below_email').show();
      $('a[name=send_it_email]').show();
      $('.error.below_email_2').hide();
      $('.error.below_email_3').hide();
      
      $('.phone_number1').css('border-color', '#BBBBBB');
      $('.phone_number2').css('border-color', '#BBBBBB');
      $('.phone_number3').css('border-color', '#BBBBBB');
      $('.simple_email').css('border-color', '#BBBBBB');
      
      $('.popup_success').hide();
      $('.popup_signup').show();
      if(!Today.deal){
        var arguments = "length=1";
        WebServices.get_deals(arguments, function(rows){    
          Today.deal = rows[0];
          General.fill_title();
        });
      } else {
        General.fill_title();
      }
    });
    $('a[name=send_it]').click(function(){
      var valid_number = General.check_phone_number();
      if(valid_number){
        var phone = ""+$('.phone_number1').val()+$('.phone_number2').val()+$('.phone_number3').val();
        WebServices.send_sms_message(Today.deal.deal_id, phone, $('.carrier').val(), false, function(error_detail){
          if(error_detail){
            if(error_detail == 'duplicate ignoring'){
              $('.phone_number1').css('border-color', '#cd7d16');
              $('.phone_number2').css('border-color', '#cd7d16');
              $('.phone_number3').css('border-color', '#cd7d16');

              $('a[name=send_it]').hide();
              $('.above_send').hide();
              $('.error.above_send_3').hide();
              $('.error.above_send_2').show();
              $('a[name=resend_sms]').click(function(){
                var valid_number = General.check_phone_number();
                if(valid_number){
                  var phone = ""+$('.phone_number1').val()+$('.phone_number2').val()+$('.phone_number3').val();
                  WebServices.send_sms_message(Today.deal.deal_id, phone, $('.carrier').val(), true, function(error_detail){
                    var phone_pretty = ""+$('.phone_number1').val()+"-"+$('.phone_number2').val()+"-"+$('.phone_number3').val();
                    var via_msg = "You’ll get your goods via text at "+phone_pretty+" shortly.";
                    General.popup_deal_success(via_msg);
                  });
                }
              });
            } else if(error_detail == 'triplicate ignoring' || error_detail == "expired or non-existent deal"){
              var subject = encodeURIComponent("Deal Issues - " + Today.deal.deal_id + " - " + phone+"/"+$('.carrier').val());
              var mailto = "mailto:sweatervest@scoutmob.com?subject="+subject;
              $('.dealsupport.sms').attr('href', mailto);
              $('.phone_number1').css('border-color', '#cd7d16');
              $('.phone_number2').css('border-color', '#cd7d16');
              $('.phone_number3').css('border-color', '#cd7d16');

              $('a[name=send_it]').hide();
              $('.above_send').hide();
              $('.error.above_send_2').hide();
              $('.error.above_send_3').show();
            }
          } else {
            var phone_pretty = ""+$('.phone_number1').val()+"-"+$('.phone_number2').val()+"-"+$('.phone_number3').val();
            var via_msg = "You’ll get your goods via text at "+phone_pretty+" shortly.";
            General.popup_deal_success(via_msg);
          }
        });
      }
    });
    $('a[name=send_it_email]').click(function(){
      var email_address = $('.simple_email').val();
      if (email_address!=null && email_address!='enter email here' && email_address!='') {
        if(General.validate(email_address)){
          $('.simple_email').css('border-color', '#BBBBBB');
          WebServices.send_deal_email(Today.deal.deal_id, email_address, false, function(error_detail){
            if(error_detail){
              if(error_detail == 'duplicate ignoring'){
                $('.simple_email').css('border-color', '#cd7d16');
                
                $('a[name=send_it_email]').hide();
                $('.below_email').hide();
                $('.error.below_email_3').hide();
                $('.error.below_email_2').show();
                $('a[name=resend_email]').click(function(){
                  var email_address = $('.simple_email').val();
                  if (email_address!=null && email_address!='enter email here' && email_address!='') {
                    if(General.validate(email_address)){
                      $('.simple_email').css('border-color', '#BBBBBB');
                      WebServices.send_deal_email(Today.deal.deal_id, email_address, true, function(error_detail) { 
                        var via_msg = "You’ll get your goods via email at "+email_address+" shortly.";
                        General.popup_deal_success(via_msg);
                      }); 
                    } else {
                      $('.simple_email').css('border-color', '#ff0000');
                    }
                  }
                });
              } else if(error_detail == 'triplicate ignoring' || error_detail == "expired or non-existent deal"){
                var subject = encodeURIComponent("Deal Issues - " + Today.deal.deal_id + " - " + email_address);
                var mailto = "mailto:sweatervest@scoutmob.com?subject="+subject;
                $('.dealsupport.email').attr('href', mailto);
                $('.simple_email').css('border-color', '#cd7d16');
                
                $('a[name=send_it_email]').hide();
                $('.below_email').hide();
                $('.error.below_email_2').hide();
                $('.error.below_email_3').show();
              }
            } else {
              var via_msg = "You’ll get your goods via email at "+email_address+" shortly.";
              General.popup_deal_success(via_msg);
            }
          });
        } else {
          $('.simple_email').css('border-color', '#ff0000');
        }
      }
    });
    $('a[name=show_email]').click(function(){
      $('.popup_email').show();
    });
    $('.overlay div.close').click(function(){
      $('.popup_success').hide();
    });
  },
  popup_deal_success: function(via_message){
    $('#via_message').empty();
    $('#via_message').append(via_message);
    $('.popup_signup').hide();
    $('#popup_signup img').attr('src', '/images/popup_deal_on.png');
    $('.popup_success').show('normal');
  },
  deal_share_buttons: function(deal){
    var deal_title = deal.percentage_off+' Off at '+deal.biz_name;
    $('a[name=share_facebook]').click(function(){
      Facebook.postDeal(deal);
    });
    
     $('a[name=share_email]').attr('href', General.email_content(deal_title, General.city.root_url+'/deal'));

     var twit1 = "Get it now w/ Scoutmob: ";
     var twit2 = " " + General.city.root_url+"/deal";
     var size = 140-twit1.length-twit2.length;
     deal_title = (deal_title.length > size)? deal_title.substr(0,size-4)+'...': deal_title;
     var twitter = "http://twitter.com/home?status="+twit1+encodeURIComponent(deal_title)+twit2;
     $('a[name=share_twitter]').attr('href', twitter);
     $('.share_friends').show();
  },
  article_share_buttons: function(article){
    $('a[name=share_facebook]').click(function(){
      Facebook.postArticle(article);
    });
    
    $('a[name=share_email]').attr('href', General.email_content(article.title, General.city.root_url+'/scoutfinds/'+article.article_id));

    var twit1 = "From Scoutmob: ";
    var twit2 = " " + General.city.root_url+"/scoutfinds/"+article.article_id;
    var size = 140-twit1.length-twit2.length;
    var article_title = (article.title.length > size)? article.title.substr(0,size-4)+'...': article.title;
    var twitter = "http://twitter.com/home?status="+twit1+encodeURIComponent(article_title)+twit2;
    $('a[name=share_twitter]').attr('href', twitter);
    $('.share_friends').show();
  },
  email_content: function(title, link){
    var email = "mailto:?body=Hey there:%0A%0A";
    email += "Just dropping you a note that your thoughtful pal (aka ME) has my eye on "+encodeURIComponent(title)+". Pretty sweet, huh?%0A%0A";
    email += "Check out today's Scoutmob exclusive mobile deal + all kinds of curious local content at... %0A%0A";
    email += "http://www.scoutmob.com%0A%0A";
    email += "If you're interested in getting this kind of goodness every day, you can sign up for their free email and get a new daily deal every day.%0A%0A";
    email += "Soon enough, you too will be sharing your local wisdom with others.%0A%0AKeep Scouting.";
    return email;
  },
  setup_counter: function(){
    var deal = Today.deal;
    $('.counter').hide('normal',function(){
      var temp_date = new Date(deal.publication_utc);
      var today = new Date();
      var thisDay = today.getDay();
      if(deal.site_end_utc) {
        Counter.targetDate = new Date(deal.site_end_utc);
      } else {
        if(thisDay == 5 || thisDay == 6 || thisDay == 0){
          Counter.targetDate = temp_date.add(3).days();
        } else {
          Counter.targetDate = temp_date.add(1).days();
        }
      }
      Counter.update_counter();
      var exp_date = "";
      if(deal.expiration_utc){
        var mydate = new Date(deal.expiration_utc);
        exp_date = mydate.toString('MM/dd/yyyy').toUpperCase();
      }
      $('.expires .date').append(exp_date);
      $('.counter .percentage_off').empty();
      if(deal.percentage_off != null && deal.percentage_off.length > 3) {
        $('.counter .percentage_off').css('margin-left', '-71px');
      }
      $('.counter .percentage_off').append(deal.percentage_off);
      $('.counter .number_used').empty();
      $('.counter .number_used').append(deal.number_used);
      var number_left = deal.threshold - deal.number_used;
      if(number_left > 0){
        // deal_on = false;
        $('.threshold').empty();
        $('.threshold').append(number_left);
        $('.deal_on').hide();
        $('.deal_off').show();
      } else{
        // deal_on = true;
        $('.deal_off').hide();
        $('.deal_on').show();
      }
      $('.counter').show();
    });
  },
  setup_counter_widget: function(deal){
    if(!deal){
      var arguments = "length=1";
      WebServices.get_deals(arguments, function(rows){    
        Today.deal = rows[0];
        General.setup_counter();
        General.setup_popup();
      });
    } else{
      Today.deal = deal;
      General.setup_counter();
      General.setup_popup();
    }
  },
  setup_success:function() {
    var email_content = "mailto:?body="+encodeURIComponent("So I just signed up to get some sweet local deals courtesy of Scoutmob. They're free, they're mobile, and what's even better than all that, I picked up some sweet new dance moves just for signing up.%0A%0ACheck 'em out on http://scoutmob.com and get the daily email too.%0A%0A");

    var twitter_url = "http://twitter.com/home?status="+encodeURIComponent("Free local deals plus a dude who dances his pants off (after you sign up). Pretty sweet: http://www.scoutmob.com");

    var flashvars = {
        twitter_url:twitter_url,
        email_url: email_content,
        facebook_url:"javascript:Facebook.share",
        video_one_url:"/video/Scoutmob_success_part1.flv",
        video_two_url:"/video/Scoutmob_success_part2.flv",
        facebook_function:"Facebook.share"
    };
    var params = {allowScriptAccess: "always"};
    swfobject.embedSWF("/video/videoLoader.swf", "swf_id", "500", "330", "9.0.0", "", flashvars, params);
    
    $(".success_badge").click(function() {
      $('.splash_success').hide();
      $('body').css('background-color', '#fff'); 
      $('.non_success').show();
    });
  },
  setup: function(params) {
    $(window).resize(General.reset_footer);
    var pathname = window.location.pathname;
    var index = pathname.lastIndexOf("/");
    var link = pathname.slice(index+1);
    if(link == null || link.length == 0 || link==General.city.short_name){
      link = 'today';
    }
    if(link >= 0){
      pathname = pathname.substr(0,index);
      index = pathname.lastIndexOf("/");
      link = pathname.slice(index+1);
    }
    if(link == 'today'){
      $('.today_blurb').show();
    }else {
      $('.today_blurb').hide();
    }
    if(link == 'unsubscribe'){
      $('.email_header').hide();
      $('.social_buttons').hide();
    }else {
      $('.email_header').show();
    }
    if(link == 'deal'){
      link = 'today';
    }
    General.highlightlink(link);
    $.each(General.linknames, function(){
      $('a[name='+this+']').click(function(){
        window.location = General.citybaseUrl() +"/"+$(this).attr('name');
      });
    });
    $('a[name=unsubscribe]').click(function(){
      window.open(General.city.unsubscribe_url);
    });
    $('.add_friends a').click(function(){
      window.open(General.city.add_friends_url);
    });
    $('a[name=mobile_widget]').click(function(){
        window.location = General.citybaseUrl()+"/mobile";      
    });
    $('a[name=appstore]').click(function(){
      window.open("http://itunes.apple.com/app/scoutmob/id346700012?mt=8");
    });
    $('a[name=android_market]').click(function(){
      window.open("http://www.appbrain.com/app/com.scoutmob.ile");
    });
    General.setup_email();
    General.setup_mobile_widget();
    General.setup_success();
  },
  citybaseUrl:function() {
    return "/"+General.city.short_name;
  }
};

Today = {
  deal: null,
  setup: function(params){
    var today = new Date();
    var thisDay = today.getDay();
    var article_type1  = "";
    var article_type2  = "";
    switch(thisDay){
      case 1:
        // $('.right_column .title_pic').addClass('weekday_digs');
        $('.content1 .header').addClass('today_out_school_night');
        $('.content2 .header').addClass('today_local_bites');
        article_type1 = Scoutfinds.article_types[9];
        article_type2 = Scoutfinds.article_types[8];
        break;
      case 2:
        // $('.right_column .title_pic').addClass('local_vantage');
        $('.content1 .header').addClass('today_you_says');
        $('.content2 .header').addClass('today_creative_eye');
        article_type1 = Scoutfinds.article_types[7];
        article_type2 = Scoutfinds.article_types[6];
        break;
      case 3:
        // $('.right_column .title_pic').addClass('you_seem_familiar');
        $('.content1 .header').addClass('today_recognize_this');
        $('.content2 .header').addClass('today_culture_hunter');
        article_type1 = Scoutfinds.article_types[5];
        article_type2 = Scoutfinds.article_types[4];
        break;
      case 4:
        // $('.right_column .title_pic').addClass('city_sampler');
        $('.content1 .header').addClass('today_local_mug');
        $('.content2 .header').addClass('today_were_diggin_it');
        article_type1 = Scoutfinds.article_types[3];
        article_type2 = Scoutfinds.article_types[2];
        break;
      case 5:
      default:
        // $('.right_column .title_pic').addClass('out_and_about');
        $('.content1 .header').addClass('today_weekend_finds');
        $('.content2 .header').addClass('today_caption_this');
        article_type1 = Scoutfinds.article_types[1];
        article_type2 = Scoutfinds.article_types[0];
        break;
    }
    Today.get_deal(params.deal_id);
    Today.get_scoutfinds(article_type1, article_type2);
    General.setup(params);
    General.reset_footer_synch();
    $('.right_column').show();
  },
  get_deal: function(deal_id){
    var arguments = "length=1";
    if (deal_id && deal_id != '' && deal_id != 'nil') {
      arguments = 'deal_id='+deal_id;
    }
    WebServices.get_deals(arguments, function(rows){
      Today.deal = rows[0];
      General.setup_counter_widget(Today.deal);
      General.deal_share_buttons(Today.deal);
    });
  },
  get_scoutfinds: function(article_type1, article_type2){
    var arguments = 'article_type_name='+article_type1+'&length=1';
    WebServices.get_articles(arguments, function(rows){
      if(rows != null && rows[0] != null){
        $('.content1 .picture').css('background', 'url('+rows[0].picture_today_url+') no-repeat');
        $('.content1 a[name=scoutfind]').attr('articleid', rows[0].article_id);
        $('.content1 .title').empty();
        $('.content1 .title').append(rows[0].title);
        $('.content1 .description').empty();
        $('.content1 .description').append(rows[0].short_description.substr(0,150)+'...  <a class="link" name="scoutfind" articleid="'+rows[0].article_id+'">{more}</a>');
      }
      $('.right_column a[name=scoutfind]').click(function(){
        window.location = General.citybaseUrl()+"/scoutfinds/"+$(this).attr('articleid');
      });
    });
    arguments = 'article_type_name='+article_type2+'&length=1';
    WebServices.get_articles(arguments, function(rows){
      if(rows != null && rows[0] != null){
        $('.content2 .picture').css('background', 'url('+rows[0].picture_today_url+') no-repeat');
        $('.content2 a[name=scoutfind]').attr('articleid', rows[0].article_id);
        $('.content2 .title').empty();
        $('.content2 .title').append(rows[0].title);
        $('.content2 .description').empty();
        $('.content2 .description').append(rows[0].short_description.substr(0,150)+'...  <a class="link" name="scoutfind" articleid="'+rows[0].article_id+'">{more}</a>');
      }
      $('.right_column a[name=scoutfind]').click(function(){
        window.location = General.citybaseUrl()+"/scoutfinds/"+$(this).attr('articleid');
      });
    });
  }
};
Deal = {
  setup: function(deal_id){
    General.setup();
    $('.deal .fine_print').show();
    Deal.get_deal(deal_id);
    $('.deal').show('normal', General.reset_footer_synch);
  },
  get_deal: function(deal_id){
    var arguments = "length=1";
    if (deal_id && deal_id != '' && deal_id != 'nil') {
      arguments = 'deal_id='+deal_id;
    }
    WebServices.get_deals(arguments, function(rows){
      Deal.single_deal_setup(rows[0]);
    });
  },
  single_deal_setup: function(deal){
    General.setup_counter_widget(deal);
    General.deal_share_buttons(deal);
  }
};

FAQ = {
  question_number: 30,
  setup: function(){
    General.setup();
    for(i=1; i<=FAQ.question_number; i++){
      $('#'+i).attr('clicked', 'false');
      $('#'+i).click(function(){
        if($(this).attr('clicked') == 'true'){
          $(this).attr('clicked', 'false');
          $('#'+this.id+' .faq_answers').slideUp('fast', General.reset_footer_synch);
        } else {
          $(this).attr('clicked', 'true');
          $('#'+this.id+' .faq_answers').slideDown('slow', General.reset_footer_synch);
        }
      });
    }
    General.reset_footer_synch();
  }
};

LocalBusiness = {
  classnames: ['our_deal','what_is_scoutmob','why_scoutmob','faq_local_business','schedule_deal'],
  show_class: function(classname){
    $.each(LocalBusiness.classnames, function(){
      if(this == classname){
        $('.'+this).show();
        $('.'+this+'_tab.select').show();
        $('.'+this+'_tab.unselect').hide();
      }else{
        $('.'+this).hide();
        $('.'+this+'_tab.select').hide();
        $('.'+this+'_tab.unselect').show();
      }
    });
    General.reset_footer_synch();
  },
  setup: function(){
    General.setup();

    LocalBusiness.show_class('our_deal');
    $('a[name=our_deal_tab]').click(function(){
      LocalBusiness.show_class('our_deal');
      scoutscroll();
    });
    $('a[name=what_is_scoutmob_tab]').click(function(){
      LocalBusiness.show_class('what_is_scoutmob');
      scoutscroll();
    });
    $('a[name=why_scoutmob_tab]').click(function(){
      LocalBusiness.show_class('why_scoutmob');
      scoutscroll();
    });
    $('a[name=faq_local_business_tab]').click(function(){
      LocalBusiness.show_class('faq_local_business');
      scoutscroll();
    });
    $('a[name=schedule_deal_tab]').click(function(){
      LocalBusiness.show_class('schedule_deal');
      scoutscroll();
    });
  }
};

Scoutfinds = {
  past_deals_count: 10,
  articles_count: 10,
  article_types: ['Caption This','Weekend Finds',"We're Digging It",'Local Mug','Culture Hunter','Recognize This','Creative Eye','What Say You','Local Bites','Out On a School Night'],
  linknames: ['weekly_list','past_deals','caption_this','weekend_finds','were_digging','local_mug','culture_hunter','recognize_this','creative_eye','what_say_you','local_bites','out_on_school'],
  // article_types: ['Seen','Under the Radar','Mix It Up','Word On the Street','Local Mug','Recognize This','Creative Eye','What Say You','Out On a School Night',"We're Digging It"],
  // linknames: ['weekly_list','past_deals','seen','under_the_radar','mix_it_up','word_on_street','local_mug','recognize_this','creative_eye','what_say_you','out_on_school','were_digging'],
  days: ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],
  articles: [],
  past_deals: [],
  content_divs: ['.weekly_list','.general_scoutfinds','.past_deals','.single_article'],
  highlightlink: function(linkname){
    linkname = (!linkname) ? 'weekly_list' : linkname;
    $.each(Scoutfinds.linknames, function(){
      if(this == linkname){
        if(linkname == 'past_deals') {
          General.highlightlink(linkname);
        }
        $('a[name='+this+'] div').addClass('set');
        $('[fieldset='+this+']').show();
      }else{
        $('a[name='+this+'] div').removeClass('set');
        $('[fieldset='+this+']').hide();
      }
    });
  },
  hide_other_content: function(div){
    for(i=0;i<this.content_divs.length; i++){
      if(this.content_divs[i] != div){
        $(this.content_divs[i]).hide();
      }
    }
    if(div != '.single_article'){
      $('.share_friends').hide();
    }
  },
  build_weekly_list: function(){
    Scoutfinds.hide_other_content(Scoutfinds.content_divs[0]);
    $('.weekly_list').hide('normal', function(){
      var today = new Date();
      var thisDay = today.getDay();
      var startIndex = Scoutfinds.linknames.length-thisDay * 2;
      if(startIndex == 0 || startIndex == 12){
        startIndex = 2;
      }
      var rowIndex = 0;
      var html = "";
      var arguments = "length=10";
      var arr = null;
      var article = null;
      WebServices.get_articles(arguments, function(rows){
        Scoutfinds.articles = rows;
        for(i=startIndex; i<Scoutfinds.linknames.length && rowIndex < rows.length; i++){
          arr = $.grep(Scoutfinds.articles, function (element) { return element.article_type == Scoutfinds.article_types[i-2]; });
          if(arr != null && arr.length > 0){
            article = arr[0];          
            html += '<div class="'+Scoutfinds.linknames[i]+'">';
            html += Scoutfinds.create_weekly_item(article, true);
            html += '</div>';
          }
        }
      
        for(i=2; i<startIndex; i++){
          arr = $.grep(Scoutfinds.articles, function (element) { return element.article_type == Scoutfinds.article_types[i-2]; });
          if(arr != null && arr.length > 0){
            article = arr[0];          
            html += '<div class="'+Scoutfinds.linknames[i]+'">';
            html += Scoutfinds.create_weekly_item(article, true);
            html += '</div>';
          }
        }
        $('.weekly_list .content').empty();
        $('.weekly_list .content').append(html);
        $('.weekly_list').show('normal', General.reset_footer_synch);
        $('.scoutfinds a[name=scoutfind]').click(function(){
          window.location = General.citybaseUrl()+"/scoutfinds/"+$(this).attr('articleid');
        });
      });
    });
  },
  create_weekly_item: function(article, with_header){
    var pub_date = "";
    if(article.publication_utc){
      var mydate = new Date(article.publication_utc);
      pub_date = mydate.toString('MMM dd').toUpperCase();
    }
    var html =  '';
    if(with_header){
      html +=   '<div class="header"></div>';
    }
    html +=     '<div class="date">'+pub_date+'</div>';
    html +=     '<a class="link" name="scoutfind" articleid="'+article.article_id+'"><img class="picture" src="'+article.picture_scoutfind_url+'"></a>';
    html +=     '<div class="title"><a class="link" name="scoutfind" articleid="'+article.article_id+'">'+article.title+'</a></div>';
    html +=     '<div class="description">'+article.short_description+'... <a class="link" name="scoutfind" articleid="'+article.article_id+'"> {more} </a></div>';
    return html;
  },
  page_scoutfinds: function(startindex){
    var firstrow = true;
    var html = "";
    var end = startindex+Scoutfinds.articles_count;
    for(i=startindex;i<Scoutfinds.articles.length && i<end; i++){
      var scoutfind = Scoutfinds.articles[i];
      if(firstrow && startindex == 0){
        firstrow = false;
        html += '<div class="article first">';
        html += Scoutfinds.create_weekly_item(scoutfind, false);
        html += '</div>';
      }else{
        html += '<div class="sf_horizontal_line sf_sprite"></div>';
        html += Scoutfinds.create_weekly_item(scoutfind, false);
      }
    }
    if(Scoutfinds.articles.length-startindex > Scoutfinds.articles_count){
      html += '<div class="show_more">';
      html += '  <div class="sf_horizontal_line sf_sprite"></div>';
      html += '  <a class="link" name="more" startindex="'+end+'">Show More Scoutfinds</a>';
      html += '</div>';
    } else {
      html += '<div class="sf_horizontal_line sf_sprite"></div>';
    }
    $('.general_scoutfinds .content').append(html);
    $('.general_scoutfinds a[name=more]').click(function(){
      $('.show_more').empty();
      Scoutfinds.page_scoutfinds(parseInt($(this).attr('startindex')));
      General.reset_footer_synch();
    });
    $('.scoutfinds a[name=scoutfind]').click(function(){
      window.location = General.citybaseUrl()+"/scoutfinds/"+$(this).attr('articleid');
    });
  },
  build_general_scoutfinds: function(linkname){
    Scoutfinds.hide_other_content(Scoutfinds.content_divs[1]);
    $('.general_scoutfinds').hide('normal', function(){
      $('.general_scoutfinds .header_pic').addClass('sf_header_'+linkname);
      var linkname_index = 0;
      for (i=0;i<Scoutfinds.linknames.length;i++){
        if(linkname == Scoutfinds.linknames[i]){
          linkname_index = i;
        }
      }
      var article_type = Scoutfinds.article_types[linkname_index-2];
      var arguments = 'article_type_name='+article_type;
      WebServices.get_articles(arguments, function(rows){
        Scoutfinds.articles = rows;
        $('.general_scoutfinds .content').empty();
        Scoutfinds.page_scoutfinds(0);
        $('.general_scoutfinds').show('normal', General.reset_footer_synch);
      });
    });
  },
  page_past_deals: function(startindex){
    var html = '';
    var end = startindex+Scoutfinds.past_deals_count;
    for(i=startindex;i<Scoutfinds.past_deals.length && i<end; i++){
      var scoutfind = Scoutfinds.past_deals[i];
      var pub_date = "";
      if(scoutfind.publication_utc){
        var mydate = new Date(scoutfind.publication_utc);
        pub_date = mydate.toString('MMM dd, yyyy').toUpperCase();
      }
      html += '<div class="past_deal">';
      html += '  <div class="sf_horizontal_line sf_sprite"></div>';
      html += '  <div class="date">  Featured: '+pub_date+'</div>';
      html += '  <div class="claimed"> Claimed: '+scoutfind.number_used+'</div>';
      html += '  <a class="link" name="sf_deal" dealid="'+scoutfind.deal_id+'"><img class="picture" src="'+scoutfind.picture_url+'"></a>';
      var title = scoutfind.percentage_off+' Off '+scoutfind.biz_name;
      title = (title.length > 33) ? title.substr(0,31)+'...' : title;
      html += '  <div class="title"><a class="link" name="sf_deal" dealid="'+scoutfind.deal_id+'">'+title+'</a></div>';
      html += '  <div class="description">'+scoutfind.short_write_up.substr(0,100)+'... <a class="link" name="sf_deal" dealid="'+scoutfind.deal_id+'"> {more} </a></div>';
      html += '</div>';
    }
    if(Scoutfinds.past_deals.length-startindex > Scoutfinds.past_deals_count){
      html += '<div class="show_more">';
      html += '  <div class="sf_horizontal_line sf_sprite"></div>';
      html += '  <a class="link" name="more" startindex="'+end+'">Show More Deals</a>';
      html += '</div>';
    } else {
      html += '<div class="sf_horizontal_line sf_sprite"></div>';
    }
    $('.past_deals .content').append(html);
    $('.past_deals a[name=more]').click(function(){
      $('.show_more').empty();
      Scoutfinds.page_past_deals(parseInt($(this).attr('startindex')));
      General.reset_footer_synch();
    });
    $('.scoutfinds a[name=sf_deal]').click(function(){
      var dealid = $(this).attr('dealid');
      window.location.hash = "#past_deals/"+$(this).attr('dealid');
    });
  },
  single_past_deal: function(deal){
    var pub_date = "";
    if(deal.publication_utc){
      var mydate = new Date(deal.publication_utc);
      pub_date = mydate.toString('MMM dd, yyyy').toUpperCase();
    }
    var exp_date = "";
    if(deal.expiration_utc){
      var mydate = new Date(deal.expiration_utc);
      exp_date = mydate.toString('MM/dd/yyyy').toUpperCase();
    }
    var html = '<div class="past_deal single">';
    html    += '  <div class="deal_sidebar"> \
                    <div class="address_info"> \
                    <div class="biz_name">'+deal.biz_name+'</div> \
                    <div class="neighborhood">'+deal.neighborhood.toUpperCase()+'</div> \
                    <div class="address">'+deal.address1+'</div> \
                    <div class="city_state">'+deal.address2+'</div> \
                    <div class="bizlinks"> \
                      <a class="link" name="website" href="'+deal.biz_website+'" target="_blank">web site</a>  |   \
                      <a class="link" name="map" href="'+deal.maps_url+'" target="_blank">map</a> \
                    </div> \
                  </div> \
                  <div class="fine_print"> \
                    <div class="skinny">THE SKINNY</div> \
                    <div class="expiration">Expires: '+exp_date+'</div> \
                    <div class="details">'+deal.fine_print+'</div> \
                  </div> \
                </div>';
    html    += '  <div class="past_deal_tag pages_sprite"></div>';
    html    += '  <div class="sf_horizontal_line sf_sprite"></div>';
    html    += '  <div class="date"> Featured: '+pub_date+'</div>';
    html    += '  <div class="claimed"> Claimed: '+deal.number_used+'</div>';
    html    += '  <img class="picture" src="'+deal.picture_url+'">';
    html    += '  <div class="title">'+deal.percentage_off+' Off '+deal.biz_name+'</div>';
    html    += '  <div class="description">'+deal.write_up+'</div>';
    html    += '</div>';

    $('.past_deals .content').hide('normal', function(){
      $('.past_deals .content').empty();
      $('.past_deals .content').append(html);
      scoutscroll();
      $('.past_deals .content').show('normal', General.reset_footer_synch);
    });
  },
  build_past_deals: function(){
    Scoutfinds.hide_other_content(Scoutfinds.content_divs[2]);
    
    $('.past_deals').hide('normal', function(){
      WebServices.get_deals_html('', function(html){
        $('.past_deals .content').html(html);
        $('.past_deal:lt('+(Scoutfinds.past_deals_count+1)+')').show();
        if ($('.past_deal:hidden').length > 0) {
          $('.show_more.deals').show(); //show more
        }
        $('.past_deals a[name=more]').click(function(){
          var total = $('.past_deal').length;
          var unshown = $('.past_deal:hidden').length;
          var shown = $('.past_deal:visible').length;
          var newshown = shown + Scoutfinds.past_deals_count;
          $('.past_deal:lt('+(newshown+1)+')').show();
          if (newshown < total) {
            $('.show_more.deals').show();
          } else {
            $('.show_more.deals').hide();
          }
          General.reset_footer_synch();
        });
        $('.past_deals').show('normal',General.reset_footer_synch);
        $('.scoutfinds a[name=sf_deal]').click(function(){
          var href = $(this).attr("href");
          var hash = href.substr(href.indexOf("#")+1);
          Scoutfinds.determine_scoutfind(hash);
        });
      });
    });
  },
  setup_single_article: function(article){
    Scoutfinds.hide_other_content(Scoutfinds.content_divs[3]);
    var div = $('.single_article');
    if(article.publication_utc){
      var mydate = new Date(article.publication_utc);
      pub_date = mydate.toString('MMM dd').toUpperCase();
    }

    var html = '<div class="article" article_type="'+article.article_type+'">';
    html    += '  <div class="sf_horizontal_line sf_sprite"></div>';
    html    += '  <div class="date">'+pub_date+'</div>';
    var picture_url = article.picture_scoutfind_url;
    if(article.article_type == 'Caption This'){
      picture_url = article.picture_seen_url;
    }
    html    += '  <img class="picture" src="'+picture_url+'">';
    html    += '  <p style="padding-bottom:5px;"></p>';
    html    += '  <span class="title">'+article.title+'</span>';
    html    += '  <p class="article_description">'+article.description+'</p>';
    html    += '</div';

    $(div).hide('normal', function(){
      $('.content', div).empty();
      $('.content', div).append(html);
      General.article_share_buttons(article);
      $(div).show('normal', General.reset_footer_synch);
    });
  },
  determine_scoutfind: function(hash){
    var vals = decodeURIComponent(hash).split("/");
    var id = null;
    var link = hash;
    if(vals.length > 1){
      id = vals[vals.length-1];
      link = vals[0];
    }
    if(link > 0){
      id = link;
      link = 'weekly_list';
    }
    if(id) {
      if(link == 'past_deals') {
        var arguments = 'deal_id='+id;
        WebServices.get_deals(arguments, function(rows){
          Scoutfinds.hide_other_content(Scoutfinds.content_divs[2]);
          Scoutfinds.single_past_deal(rows[0]);
          $('.past_deals').show('normal', General.reset_footer_synch);
        });
      }else{
        arguments = "article_id="+id;
        WebServices.get_articles(arguments, function(rows){
          var article = rows[0];
          Scoutfinds.setup_single_article(article);
        });
      }
    }else{    
      if(link == 'weekly_list' || link == null){
        Scoutfinds.build_weekly_list();
      }else if(link == 'past_deals'){
        Scoutfinds.build_past_deals();
      }else{
        Scoutfinds.build_general_scoutfinds(link);
      }
    }
    Scoutfinds.highlightlink(link);
    scoutscroll();
  },
  setup: function(article_id){
    General.setup();
    General.setup_email();
    $('.email_header').hide();
    General.highlightlink('scoutfinds');
    General.setup_counter_widget(null);
    var index = window.location.hash.lastIndexOf("#");
    if(index <  0){
      if(article_id != null && article_id > 0){
        this.determine_scoutfind(article_id);
      } else {
        this.determine_scoutfind('weekly_list');
      }
    }
  }
};

Counter = {
  hours:{first:-1,second:-1},
  minutes:{first:-1,second:-1},
  seconds:{first:-1,second:-1},
  timer :1000,
  fadespeed: 1000,
  calc_countdown: function() {
    if (Counter.targetDate) {
      var now_utc = new Date().getTime();
      var target_utc = Counter.targetDate.getTime();
      // var now_utc = Date.UTC(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours(), now.getMinutes(), now.getSeconds(), now.getMilliseconds());
      var timediff = target_utc-now_utc;
      timediff = timediff > 0 ? timediff : 0;

      // var weeks = Math.floor(timediff / (1000 * 60 * 60 * 24 * 7));
      // timediff -= weeks * (1000 * 60 * 60 * 24 * 7);

      var days = Math.floor(timediff / (1000 * 60 * 60 * 24)); 
      timediff -= days * (1000 * 60 * 60 * 24);

      var hours = Math.floor(timediff / (1000 * 60 * 60)); 
      timediff -= hours * (1000 * 60 * 60);
      var totalhours = days*24 + hours;
      
      var mins = Math.floor(timediff / (1000 * 60)); 
      timediff -= mins * (1000 * 60);

      var secs = Math.floor(timediff / 1000); 
      timediff -= secs * 1000;

      return {hours:totalhours,minutes:mins,seconds:secs};
    }
  },
  update_helper:function(currentvalue, units, fadespeed) {
    var first = Math.floor(currentvalue / 10);
    if (Counter[units].first != first) {
      Counter[units].first = first;
      $('.'+units+'.first').fadeOut(fadespeed, function(){
        $('.'+units+'.first').attr('class',units+' first digit_'+first);
        $('.'+units+'.first').fadeIn(fadespeed);
      });
    }
    var second = currentvalue % 10;
    if (Counter[units].second != second) {
      Counter[units].second = second;
      $('.'+units+'.second').fadeOut(fadespeed, function(){
        $('.'+units+'.second').attr('class',units+' second digit_'+second);
        $('.'+units+'.second').fadeIn(fadespeed);
      });
    }
  },
  update_counter :function(){
    var caltime = Counter.calc_countdown();
    Counter.update_helper(caltime.seconds,'seconds',0);
    var munged_hours = (caltime.hours > 99 ) ? caltime.hours % 100 : caltime.hours;
    Counter.update_helper(munged_hours,'hours',Counter.fadespeed);
    Counter.update_helper(caltime.minutes,'minutes',Counter.fadespeed);
    window.setTimeout(function() {
      Counter.update_counter();
    },Counter.timer);        
  }
};

Facebook = {
  API_KEY: '3bcd08d8babb54a04f5b9b32e636b11a',
  setup: function(){
    FB.init({
      appId  : Facebook.API_KEY,
      status : true, // check login status
      cookie : true, // enable cookies to allow the server to access the session
      xfbml  : true  // parse XFBML
    });
  },
  postDeal: function(deal){
    Facebook.setup();
    var deal_title = deal.percentage_off+' Off at '+deal.biz_name;
    FB.ui({
      method: 'stream.publish',
      attachment: {
        name: 'Get it now w/ Scoutmob: '+deal_title,
        href: General.city.root_url+'/deal',
        description: (deal.short_write_up.substr(0,250)+'...'),
        media: [{ 
          type: "image", 
          src: 'http://'+window.location.host+deal.picture_url, 
          href: General.city.root_url+'/deal'
        }]
      },
      action_links: [{ 
        text: 'Become a Fan', 
        href: General.city.facebook_url
      }]
    });
  },
  postArticle: function(article){
    Facebook.setup();
    FB.ui({
      method: 'stream.publish',
      attachment: {
        name: 'From Scoutmob: '+article.title,
        href: General.city.root_url+"/scoutfinds/"+article.article_id,
        description: article.short_description+'...',
        media: [{ 
          type: "image", 
          src: 'http://'+window.location.host+article.picture_scoutfind_url,
          href: General.city.root_url+"/scoutfinds/"+article.article_id
        }]
      },
      action_links: [{ 
        text: 'Become a Fan', 
        href: General.city.facebook_url
      }]
    });
  },
  share: function(){
    Facebook.setup();
    FB.ui({
      method: 'stream.publish',
      attachment: {
        name: 'Join the Mob!',
        href: 'http://www.scoutmob.com',
        description: "Free local deals plus a dude who dances his pants off (after you sign up). Pretty sweet: http://www.scoutmob.com"
      }
    });
  }
};
