jQuery(function(){
  jQuery('a.boost_button').click(function(e){
    e.preventDefault();
    jQuery.getScript(this.href);
    $(this).find('.boost_center .boost_number').text(function(i,c){
      if(c.indexOf('k')==-1){
        return parseInt(c,10)+1;
      }else{
        return c;
      }
    });
    jQuery(this).addClass('boosted').unbind('click').click(function(e){e.preventDefault();});
  });

  $('a.blog-link, a.blog-img-link').bind('click', function(e) {
    jQuery.get('/blog/'+$(this).data("id")+'/'+$(this).data("pathname")+'/send_to_blog', 'json');
  });
  
  //jQuery('#submit_a_blog').submitBlog();
  jQuery('.submit_ajax').submitWithAjax(function(data){});
  
  jQuery('.generate_favorite_html').submitWithAjaxCallback(
    function(data){
      jQuery('#badge_code').val(data['code']);
      if(data['errors']){
        jQuery.each(data['errors'],function(i,error){jQuery('#favorite_errors').append(jQuery("<div>").text(error))});
      }else{
        jQuery('#favorite_errors').html("");
      }
      jQuery('#favorite_title').val(data['favorite_title']);
      jQuery('#favorite_url').val(data['favorite_url']);
    }
  );
  
  jQuery('.badge_option').click(function(e){
    jQuery('#blogger_form').hide();$('#badge_code').val('');$('#badge_preview_loading').show();
    var a={};jQuery.each(jQuery('#badge_form').serializeArray(), function(e){ a[this.name]=this.value });
    var wid=200;switch(a.size){case"large":wid=250;break;case"small":wid=150;break};
    jQuery.ajax({
      dataType: 'jsonp',
      data: jQuery('#badge_form').serialize(),
      url: "http://tools.blognation.com/bn/tools/widget/code",
      success: function(data){
        jQuery('#badge_code').val(data.code);jQuery('#blogger_data').text(data.code);jQuery('#badge_preview_loading').hide();
        if(a.count=="noscript"){jQuery('#blogger_form').hide();}else{jQuery('#blogger_form').show();}
        if(a.size=="text"){
          jQuery("#badge_preview").hide();
          jQuery("li.badge_count").hide().find("input").removeAttr("checked");
          jQuery("li.text_count").show().find("input").attr("checked", "checked");
        }else{
          jQuery("#badge_preview").show();
          jQuery('#badge_frame #badge_top')
            .css('width',wid+'px')
            .css('height',(wid*.64)+'px')
            .css('background-image','url("/themes/directory/badges/'+data.img_base.replace(/http:\/\/|www\.|\.org|\.net|\.com/gi,'')+'/'+a.size+'-top'+(a.count=='true' ? '-boost' : (a.count=='rank' ? '-rank' : ''))+'.png")');
          if(a.link=="text"){
            jQuery('#badge_frame #badge_bottom').text(data.img_base.replace(/http:\/\/|www\./gi,''));
          }else{
            jQuery('#badge_frame #badge_bottom')
              .css('width',wid+'px')
              .css('height',(wid*.16)+'px')
              .css('background-image','url("/themes/directory/badges/'+data.img_base.replace(/http:\/\/|www\.|\.org|\.net|\.com/gi,'')+'/'+a.size+'-bottom.png")');
          }
          var bc = jQuery("li.badge_count");
          bc.show();
          if($(".badge_count input:checked").size()==0){
            jQuery(bc.find("input")[0]).attr("checked", "checked");
          }
          jQuery("li.text_count").hide().find("input").removeAttr("checked");
        }
      }
    });
  });

  jQuery(".twitter_feed").each(function(){
    var $this = jQuery(this);
    var twitterHandle = $this.data("handle");
    if(twitterHandle){
      (function(tweetContainer){
        jQuery.ajax({
          dataType: 'jsonp',
          url: "http://twitter.com/statuses/user_timeline/"+twitterHandle+".json",
          success: function(data){
            var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
            var $ul = jQuery("<ul />");
            for(var i=0; i<4; i++){
              var message = data[i];
              if(message){
                var date = new Date(message.created_at);
                var h = date.getHours();var m = date.getMinutes();
                var strDate = "";
                if(tweetContainer.data("simple-date")){
                  strDate = months[date.getMonth()]+" "+date.getDate()+", "+date.getFullYear();
                }else{
                  strDate = months[date.getMonth()]+" "+date.getDate()+", "+date.getFullYear()+" at "+(h > 12 ? h-12 : h)+":"+(m.toString().length > 1 ? m : "0"+m)+" "+(h > 12 ? "PM" : "AM");
                }
                
                // 1) add web links, 2) add @ links, 3) add # searches
                var parsedMsg = message.text.replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig,"<a href='$1' target='_blank'>$1</a>").replace(/(^|\s)@(\w+)/g, "$1<a href=\"http://www.twitter.com/$2\" target='_blank'>@$2</a>").replace(/(^|\s)#(\w+)/g, "$1<a href=\"http://search.twitter.com/search?q=%23$2\" target='_blank'>#$2</a>");
                var $li = jQuery("<li />");
                var $msg = jQuery("<div class='tweet_message'>"+parsedMsg+"</div>");
                var $date = jQuery("<div class='tweet_date'>"+strDate+"</div>");
                if(tweetContainer.data("simple-date")){
                  $li.append($date).append($msg);
                }else{
                  $li.append($msg).append($date);
                }
                $ul.append($li);
              }
            }
            tweetContainer.find(".tweets").html("").append($ul);
          }
        });
      })($this);
    }
  }); 

  jQuery(".rss_feed").each(function(){
    var $this = jQuery(this);
    var rssFeed = $this.data("feed");
    if(rssFeed){
      (function(rssContainer){
        jQuery.ajax({
          dataType: 'json',
          url: rssFeed,
          error: function(xhr, textStatus, errorThrown){rssContainer.find(".rss").html("Could not load the RSS feed.");},
          success: function(data){
            var $ul = jQuery("<ul />");
            for(var i=0; i<6; i++){
              var message = data[i]
              if(message){
                var $li = jQuery("<li />");
                var $post = jQuery("<div />").addClass("rss_item");
                var $title = jQuery("<a href='"+message.link+"' class='title' target='_blank'>"+message.title+"</a>");
                var $date = jQuery("<div class='date'>"+message.date+"</div>");
                $post.append($date).append($title);
                $li.append($post);
                $ul.append($li);
              }
            }
            rssContainer.find(".rss").html("").append($ul);
          }
        });
      })($this);
    }
  }); 
  
  jQuery('#category_select').bind('setCategories', function(e,site,def_val){
    $cs=jQuery(this);
    $cs.html('');
    if(site != ""){
      $cs.append('<option value="">Select a category</option>');
      jQuery.each(jQuery.parseJSON($('#category_select').attr('data-categories'))[site], function(i,v){
        is_sel=false;
        if(def_val==v[1]){is_sel=true;}
        $cs.append('<option '+(is_sel ? 'selected=true' : '')+' value="'+v[1]+'">'+v[0]+'</option>');
      });
    }else{
      $cs.append('<option value="">Choose a site first</option>');
    }
  });

  jQuery('#site_select').bind('setGroup', function(e,category){
    var $this = jQuery(this);
    if(!jQuery('#site_select').data("options")){
      jQuery('#site_select').data("options", jQuery('#site_select').clone());
    }

    if(category=="All"){
      $this.html("");
      $this.append($this.data("options").children().clone());
    }else{
      $this.html("");
      $this.append("<option value=''>Select a site</option>");
      $this.append($this.data("options").find("optgroup[label='"+category+"']").clone());
    }

  })

  jQuery('#directory_category_select').change(function() {
    jQuery('#site_select').trigger('setGroup', [jQuery(this).val()]);
  });

  jQuery('#site_select').change(function() {
    jQuery('#category_select').trigger('setCategories', [jQuery(this).val(), null]);
  });

  jQuery('#site_select').trigger('setGroup', [jQuery('#directory_category_select').val()]);
  jQuery('#category_select').trigger('setCategories', [jQuery('#site_select').val(), jQuery.parseJSON(jQuery('#category_select').attr('data-preselect'))]);

});

function bage_preview(data) {
  var a={};jQuery.each(jQuery('#badge_form').serializeArray(), function(e){ a[this.name]=this.value });
  
}

jQuery.fn.submitWithAjax = function(success) {
  this.unbind('submit', false);
  this.submit(function() {
    jQuery.post(this.action, jQuery(this).serialize(), function(data){success(data);}, "script");
    return false;
  })

  return this;
};

jQuery.fn.submitWithAjaxCallback = function(success) {
  this.unbind('submit', false);
  this.submit(function() {
    jQuery.post(this.action, jQuery(this).serialize(), function(data){success(data);}, "json");
    return false;
  })

  return this;
};


jQuery.fn.submitBlog = function() {
  this.unbind('submit', false);
  this.submit(function() {
    var $submit_form = jQuery(this)
    $submit_form.find('.submit_error').remove();
    var $overlay = jQuery($submit_form.find('#submitting_blog'));
    $overlay.css('height', $submit_form.outerHeight()).css('width', $submit_form.outerWidth()).show();
    jQuery.post(this.action, $submit_form.serialize(), 
    function(data){
      //console.log(data.saved);
      $overlay.hide();
      if (data.saved) {
        $submit_form.prepend("<div id='submit_thanks'><h2>THANKS</h3><p>"+data.text+"</p></div>")
        $submit_form.find("#submit_information").hide();
      } else {
        if (data.error != 'none') {
          jQuery(data.error).each(function(i){
            $submit_form.find('input#'+this.toString().toLowerCase()).before("<span class='submit_error'>"+this.toString()+" Error*</span>");
          });
          $submit_form.find('input.submit_button').before("<div class='submit_error'>"+data.text+"</div>");
        }
      }
    }, 'json');
    return false;
  });
  return this;
};
