/**
 * @author Dale Larsen
 * Copyright 2009 getTechy.com
 */
var techBlog = {
   blogId: '662512279704956112',
   loadLimit: 8,
   disqusIdName: 'gettechy',
   defaultFeed: 'http://thingstechy.blogspot.com/feeds/posts/default',
   load: function($container, feedUrl, pid, byDate, byTag){
      var lib = techBlog;
      if (!feedUrl) feedUrl = lib.defaultFeed;
      if ($container && feedUrl) {
         //$container.html('Loading content...');
         /**
          * TODO: fix bug. IE can't load the blog list when we are requesting just one post.
          */
         $.ajax({
            url: feedUrl,
            type: 'get',
            dataType: 'jsonp',
            data: {
               alt: 'json-in-script'
            },
            success: function(data){
               var feed = data.feed;
               var entries = feed.entry;
               var loadOnePost = false;
               if (pid) {
                  pid = pid.split('#')[0];
                  loadOnePost = true;
               }
               if (entries.length) {
                  var matchesFound = false;
                  var matchedDateFound = false;
                  if (byDate) {
                     for (var i = 0; i < entries.length; i++) {
                        var thisPostDate = parseBloggerDate(entries[i].published.$t);
                        if (thisPostDate == byDate) {
                           matchedDateFound = true;
                           break;
                        }
                     }
                  }
                  if (!matchedDateFound && byDate) {
                     //$container.html('There are no articles posted this day. Please try another date.');
                     $('#dialogMsgTxt').html('There are no articles posted for ' + byDate + '. Please try another date.');
                     $("#dialog-message").dialog({
                        modal: true,
                        buttons: {
                           Ok: function(){
                              $(this).dialog("close");
                           }
                        }
                     });
                  } else {
                  
                     $container.empty();
                     var numInjected = 0;
                     for (var i = 0; i < entries.length; i++) {
                        var thisPostId = parseBloggerPostId(entries[i].id.$t);
                        var thisPostDate = parseBloggerDate(entries[i].published.$t);
                        var thisPostTags = lib.getTags(entries[i].category);
                        var postHasTag = lib.testPostTags(thisPostTags, byTag);
                        if (loadOnePost && !byDate && !byTag && thisPostId == pid) {
                           lib.injectPost($container, feedUrl, thisPostId, entries[i].title.$t, entries[i].content.$t, thisPostDate, thisPostTags, true);
                           numInjected++;
                           break;
                        } else if (!byDate && !byTag && !loadOnePost) {
                           lib.injectPost($container, feedUrl, thisPostId, entries[i].title.$t, entries[i].content.$t, thisPostDate, thisPostTags, false);
                           numInjected++;
                        } else if (byDate && !byTag && thisPostDate == byDate) {
                           lib.injectPost($container, feedUrl, thisPostId, entries[i].title.$t, entries[i].content.$t, thisPostDate, thisPostTags, false);
                           numInjected++;
                           matchesFound = true;
                        } else if (byTag && postHasTag) {
                           lib.injectPost($container, feedUrl, thisPostId, entries[i].title.$t, entries[i].content.$t, thisPostDate, thisPostTags, false);
                           numInjected++;
                           matchesFound = true;
                        } else if (!matchesFound && i == entries.length - 1) {
                           $container.html('The page you are requesting doesn\'t exist.');
                        }
                        if (numInjected > lib.loadLimit) break;
                     }
                  }
               } else {
                  $container.html('No entries to load');
               }
               var TagsHtml = '';
               for (var i = 0; i < lib.usedTags.length; i++) {
                  TagsHtml += '<div class="tagsListItem">' + lib.usedTags[i] + '</div>';
               }
               $('#blogTagsList').html(TagsHtml);
            }
         });
         return $container;
      }
   },
   usedTags: [],
   testPostTags: function(postTags, matchTag){
      var hasTag = false;
      var postTags = postTags.split(',');
      for (var i = 0; i < postTags.length; i++) {
         if (postTags[i] == matchTag) {
            hasTag = true;
            break;
         }
      }
      
      return hasTag;
   },
   getTags: function(tagObj){
      var returnTags = '';
      for (var i = 0; i < tagObj.length; i++) {
         var addDelim = (i == tagObj.length - 1) ? '' : ',';
         techBlog.usedTags.pushNoDup(tagObj[i].term);
         returnTags += tagObj[i].term + addDelim;
      }
      techBlog.usedTags.sort(sortAtoB);
      return returnTags;
   },
   injectPost: function($container, feedUrl, thisPostId, title, content, date, tags, showOnePost){
      var lib = techBlog;
      if (title && content && date) {
         var $thisPost = $('<div></div>').attr('id', 'blogPost-' + thisPostId).addClass('bloggerPostWr');
         var thisPostUrl = location.href;
         thisPostUrl = thisPostUrl.replace(/\#disqus_thread/, '');
         thisPostUrl += (thisPostUrl.match('pid')) ? '' : (thisPostUrl.match(/\?/) ? '&' : '?') + 'pid=' + thisPostId;
         var enc_thisPostUrl = encodeURIComponent(thisPostUrl);
         var postHtml = '';
         /** TODO:
          * when its just one post, load its comments too, if not, show how many comments there are.
          */
         postHtml += '<div id="postTitle-' + thisPostId + '" class="bloggerPostTitle">' + title + '</div>';
         postHtml += '<div class="bloggerPostDate"><div class="bloggerPostDateTxt">' + date;
         /**
          *# comments not returning right from disqus. Removing number display til it works right.
          if (!showOnePost) {
          var disqus_shortname = lib.disqusIdName; // required: replace example with your forum shortname
          //DON'T EDIT BELOW THIS LINE
          (function(){
          var s = document.createElement('script');
          s.async = true;
          s.type = 'text/javascript';
          s.src = 'http://' + disqus_shortname + '.disqus.com/count.js';
          (document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s);
          }());
          
          postHtml += '<div class="bloggerCommentCount"><a href="' + thisPostUrl + '#disqus_thread"># Comments</a></div>';
          }
          */
         postHtml += '</div>';
         postHtml += '<div class="socialSharingBox">';
         postHtml += '<a class="socialMediaIcon" target="_blank" href="http://www.delicious.com/save?v=5&noui&jump=close&url=' + enc_thisPostUrl + '&title=' + title + ': GetTechy.com" title="Bookmark on del.icio.us"><img src="/img/dl_icon.png"/></a>';
         postHtml += '<a class="socialMediaIcon" target="_blank" href="http://www.facebook.com/sharer.php?u=' + enc_thisPostUrl + '"  title="Share this on Facebook"><img src="/img/fb_icon.png"/></a></li>';
         postHtml += '<a class="socialMediaIcon" target="_blank" href="http://www.stumbleupon.com/submit?url=' + enc_thisPostUrl + '" title="Stumble This Page"><img src="/img/su_icon.png"/></a>';
         postHtml += '<a class="socialMediaIcon" target="_blank" href="http://twitter.com/home?status=' + title + ': GetTechy.com - ' + enc_thisPostUrl + '" title="Tweet This Page"><img src="/img/tw_icon.png"/></a></div>';
         postHtml += '</div>';
         postHtml += '<div class="bloggerPostContent">' + content + '</div>';
         postHtml += '<div class="bloggerPostFooter">';
         
         if (showOnePost) {
         
            document.title = 'GetTechy - ' + title;
            
            postHtml += '<div id="disqus_thread" class="disqusComments"></div>';
            
            /* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
            var disqus_shortname = lib.disqusIdName; // required: replace example with your forum shortname
            // The following are highly recommended additional parameters. Remove the slashes in front to use.
            var disqus_identifier = disqus_shortname + 'PostId_' + thisPostId;
            var disqus_url = thisPostUrl;
            
            /* * * DON'T EDIT BELOW THIS LINE * * */
            (function(){
               var dsq = document.createElement('script');
               dsq.type = 'text/javascript';
               dsq.async = true;
               dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js';
               (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
            })();
         } else {
            postHtml += '<a href="' + thisPostUrl + '" class="bloggerPostSeeComments">Add/Read Comments...</a>';
         }
         
         postHtml += '</div>';
         
         $thisPost.html(postHtml);
         $container.append($thisPost);
         $('#postTitle-' + thisPostId).click(function(){
            //$container.loadTechBlog(feedUrl, thisPostId);
            location.href = thisPostUrl;
         });
      }
   },
   postComment: function(postTitle, commentText){
      /*** using disqus ***/
   }
}
jQuery.fn.loadTechBlog = function(feedUrl, pid, byTag){
   if (pid) byTag = false;
   techBlog.load($(this), feedUrl, pid, false, byTag);
}
$(function(){
   $('div.tagsListItem').live('click', function(){
      location.href = 'http://gettechy.com/?tag=' + $(this).text();
      //techBlog.load($mainContent, false, false, false, $(this).text());//faster ajax method but doesn't change the url :(
   
   });
   $('#postDatePicker').datepicker({
      altFormat: 'mm-dd-yy',
      onSelect: function(dateText, inst){
         var formattedDate = parseDatePickerDate(dateText);
         techBlog.load($mainContent, false, false, formattedDate);
      }
   });
   
});

