/* Copyright (c) 2008 Quicksilver Workshop Inc. 
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0 
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 */

/**
 * @fileoverview Demonstrates AuthSub and cross domain
 * writes using Blogger JavaScript client library and the Google AJAX Feed API.  
 *
 * NOTES: This demo uses the jQuery library to handle a lot of the JavaScript 
 * UI effects. The $(...) is a common jQuery object expression and the jQuery 
 * library must be included before using it.  For more information on jQuery, 
 * please refer to the jQuery homepage - http://jquery.com/
 *
 */

// global namespace for the demo
var gummi = {};

// The Blogger API feed URL that allows blog entry submission for the demo
gummi.BLOGGER_FEED_URL = 'http://www.blogger.com/feeds';

// The Blogger API feed URL that allows retrieval of blogs belonging to a user
gummi.BLOGGER_GETBLOGS_FEED = 
    'http://www.blogger.com/feeds/default/blogs';

gummi.bloggerService = null;

// CSS IDs
gummi.MAIN_DIV = '#main';
gummi.DISPLAY_DIV = '#display';
gummi.DISPLAY_DIV_POST_TITLE = '#title';
gummi.DISPLAY_DIV_POST_CONTENT = '#content';

//gummi.BLOG_IFRAME = '#bloggerIframe';
gummi.BLOGGER_LOGIN_BUTTON = '#bloggerLogin';
gummi.BLOGGER_RUN_BUTTON = '#bloggerRun';

gummi.FEED_ADDRESS_BOX = '#feedAddress';
gummi.FEED_ACCESS_BUTTON = '#feedAccess';
gummi.FEED_STEP_NEXT_BUTTON = '#feedStepNext';
gummi.FEED_STEP_PREV_BUTTON = '#feedStepPrev';
gummi.BLOG_SELECTOR = '#blogChooser';

// Button labels
gummi.BLOGGER_LOGIN_LABEL = 'Blogger Login';
gummi.BLOGGER_LOGOUT_LABEL = 'Blogger Logout';
gummi.FEED_ACCESS_LABEL = 'Access Feed';

// Load the Google data JavaScript client library
google.load("gdata", "1.x");
google.load("feeds", "1");
google.setOnLoadCallback(init);


/**
 * Global initalization, for GData services, UI and UI event handlers
 */   
function init() {  
  // do not do anything if it is a token redirect
  if (!isTokenRedirect()) {    
    initBlogger();
    initFeed();
    $(gummi.MAIN_DIV).css({display: 'block'});
  }
}

/**
 * Detect whether the current session is a token redirect
 * @return {Boolean} True/false to whether this is a redirect session
 */  
function isTokenRedirect() {
  var status = false;
  var url = location.href;
  var matchArr = url.match(/#2/);
  
  if (matchArr != null) {
    status = true;
  }

  return status;
}

/**
 * Initialize blogger service and it's UI features
 */
function initBlogger() {
  gummi.bloggerService = 
      new google.gdata.blogger.BloggerService('QuicksilverWorkshop-gUMMI-1');

  // Set up event handling for blogger login/logout buttons
  $(gummi.BLOGGER_LOGIN_BUTTON).click(function() {
    if ($(gummi.BLOGGER_LOGIN_BUTTON).attr('value') == 
        gummi.BLOGGER_LOGIN_LABEL) {
      bloggerToken = 
          google.accounts.user.login(gummi.BLOGGER_FEED_URL);

    } else {

      if (hasBloggerToken()) {          
        $(gummi.BLOG_SELECTOR).hide();   
        $(gummi.BLOG_SELECTOR).empty();    
        google.accounts.user.logout();
        $(gummi.BLOGGER_LOGIN_BUTTON).
            attr({value: gummi.BLOGGER_LOGIN_LABEL});
        setIsBloggable();
      }            
    }
  });
  
  // Set up event handling for "blog" button 
  $(gummi.BLOGGER_RUN_BUTTON).click(function() {
    postBlogEntry();
  });  
  
  // Set up event handling for blog chooser
  $(gummi.BLOG_SELECTOR).change(function() {
    displayBlog();
  });

  // Initialize look & feel based on login status
  if (hasBloggerToken()) {
    
    $(gummi.BLOGGER_LOGIN_BUTTON).
        attr({value: gummi.BLOGGER_LOGOUT_LABEL});
    setIsBloggable();
    loadBlogList();
  } else {
    $(gummi.BLOGGER_LOGIN_BUTTON).
        attr({value: gummi.BLOGGER_LOGIN_LABEL});
    setIsBloggable();
    $(gummi.BLOG_SELECTOR).hide(); 
  }  
}

/**
 * Establish Stumble Upon Feed  connection
 */
 function setFeed(){
	 var feedUrl = $(gummi.FEED_ADDRESS_BOX).attr('value'); 
	 var feed = new google.feeds.Feed(feedUrl);
	 feed.setNumEntries(10);
	 $(gummi.FEED_STEP_NEXT_BUTTON).get(0).disabled = false;
	 $(gummi.FEED_STEP_PREV_BUTTON).get(0).disabled = false;	 
	 return feed;
 } 
 
 
function getFeed() {
	var html = [];
	var title = "";
	var content = "";
	currentStep = 0;
	feed = setFeed();	
		feed.load(function(result) {
			if (!result.error) {
				for (var i = 0; i < 1/*result.feed.entries.length*/; i++) {
					var entry = result.feed.entries[i];
					
					html.push('<div id=title>' + entry["title"] + '</div>');          
					html.push('<div id=content>' + entry["content"] + '</div>');          
				}
			}
			printToDisplay(html.join('<br>'));
			});	
}

function stepThruFeedNext() {
	html = [];
		feed.load(function(result) {
			if (!result.error) {
				
				lastStep = result.feed.entries.length;
				if(currentStep < lastStep - 1){
					currentStep = currentStep + 1;
					var entry = result.feed.entries[currentStep];
					
					html.push('<div id=title>' + entry["title"] + '</div>');          
					html.push('<div id=content>' + entry["content"] + '</div>');
					printToDisplay(html.join('<br>'));
				}
			}
			});	
}

function stepThruFeedPrev() {
	html = [];
		feed.load(function(result) {
			if (!result.error) {
				
				lastStep = result.feed.entries.length;
				if(currentStep > 0){
					currentStep = currentStep - 1;
					var entry = result.feed.entries[currentStep];
					
					html.push('<div id=title>' + entry["title"] + '</div>');          
					html.push('<div id=content>' + entry["content"] + '</div>');
					printToDisplay(html.join('<br>'));
				}
			}
			});	
}

/**
 * Initialize Stumble Upon feed accessor and it's UI features
 */
 function initFeed() {
  var currentStep = 0;
  
  $(gummi.FEED_ADDRESS_BOX).attr({value: "http://www.stumbleupon.com/syndicate.php?stumbler=360130&comments=1"});
	 
  $(gummi.FEED_ACCESS_BUTTON).click(function() {
    getFeed();
  }); 
  
  $(gummi.FEED_STEP_NEXT_BUTTON).click(function() {
    stepThruFeedNext();
  });  
  
  $(gummi.FEED_STEP_PREV_BUTTON).click(function() {
    stepThruFeedPrev();
  });  
  
  $(gummi.FEED_STEP_NEXT_BUTTON).get(0).disabled = true;
  $(gummi.FEED_STEP_PREV_BUTTON).get(0).disabled = true;
  
  //set up editable display
  $(gummi.DISPLAY_DIV).click(function() {
    
    var displayContent = $(gummi.DISPLAY_DIV).html();
    if ($.trim(displayContent).length > 0){
      
      displayContent = displayContent.replace(/<br>/g, '\n');

      var cols = 62;
      var rows = (displayContent.length / cols) * 3;    
 

      editBoxHtml = [
          '<textarea name=cond_des id=cond_des cols=',
          cols,
          ' rows=',
          rows,
          '>',
          displayContent,
          '</textarea>'
          ].join('');

      var editBox = $(editBoxHtml);

      editBox.blur(function() {

        var editContent = $(this).val();

        $(editBox).unbind('blur');
        $(editBox).remove();                

        editContent = editContent.replace(/\n/g, '<br>');      

        $(gummi.DISPLAY_DIV).html(editContent);
        $(gummi.DISPLAY_DIV).show();
      });       

      $(gummi.DISPLAY_DIV).after(editBox);
          
      $(this).hide();
      
      editBox.focus();    

    }
  });
}

/**
 * Check if there is a blogger AuthSub token for the current session
 * @return {Boolean} True/false to indicate if there is a blogger AuthSub token
 */  
function hasBloggerToken() {
  var success = true;

  if (google.accounts.user.checkLogin(gummi.BLOGGER_FEED_URL) == '') {
    success = false;
  }

  return success;
}

/**
 * Check the following condition before submitting an entry to Blogger
 *  1) content is not empty
 *  2) the user has a blog
 * @return {Boolean} True/false to indicate if a blog entry submission can 
 *     take place
 */  
function isBloggable() {
  var status = true;
  
  // check if the post entry is empty or two
  if ($.trim($(gummi.DISPLAY_DIV).html()).length == 0) {
    alert('you have nothing to blog');
    status = false;
  }  

  // check if there is a blog to blog to
  if ($(gummi.BLOG_SELECTOR).get(0).options
      [$(gummi.BLOG_SELECTOR).get(0).selectedIndex].value.length == 0) {
    alert('you don\'t have a blog');
    status = false;
  }

  return status;
}

/**
 * Submit the content on event display as a blog entry to Blogger
 */  
function postBlogEntry() {

  if (hasBloggerToken()) {
    if (isBloggable()) {
      insertBlogEntry();
    }
  }
}

/**
 * Submit the content on display panel as a blog entry to Blogger
 */
function insertBlogEntry() {

  var postUrl = $(gummi.BLOG_SELECTOR).get(0).options[$(gummi.BLOG_SELECTOR).get(0).selectedIndex].value;
  var authorName = null;

  var blogTitle = $(gummi.DISPLAY_DIV_POST_TITLE).html();
  var blogContent = $(gummi.DISPLAY_DIV_POST_CONTENT).html();
  /*
  var newEntry = new google.gdata.blogger.BlogPostEntry(
      {
          authors: [{name: '', email: ''}],
          title: {type: 'text', text: blogTitle},
          content: {type: 'text', text: blogContent}
      }
  );*/
  
  var newEntry = new google.gdata.blogger.BlogPostEntry({
    title: {
      type: 'text',
      text: blogTitle
    },
    content: {
      type: 'text',
      text: blogContent
    },
    categories: [
      {scheme: 'http://www.blogger.com/atom/ns#', term: 'Label1'},
      {scheme: 'http://www.blogger.com/atom/ns#', term: 'Label2'}
    ]
  });  
  
  postsFeedRoot.feed.insertEntry(newEntry,
      function() {
        PRINT('Blog post inserted:');
        PRINT('"<b>' + newEntry.getTitle().getText() + '</b>"');
      },
      handleError
  );  
  /*
  gummi.bloggerService.getBlogPostFeed(
      postUrl,
      function(root) {      
        root.feed.insertEntry(newEntry, displayBlog, handleError);
      },
      handleError
  );*/
}

function displayBlog(){handleError}

/**
 * load all the blogs of user into the blogger chooser menu
 */
function loadBlogList() {

  var query = 
      new google.gdata.blogger.BlogQuery(gummi.BLOGGER_GETBLOGS_FEED);

  gummi.bloggerService.getBlogFeed(
      query,
      function(root) {

        var entries = root.feed.getEntries();

        for(var i = 0, entry; entry = entries[i]; i++) {

          var postUrl = entry.getEntryPostLink().getHref();
          var blogUrl = entry.getHtmlLink().getHref();
          var blogTitle = entry.getTitle().getText();
          
          var optionItem = [
              '<option value=',
              postUrl,
              '>',
              blogUrl,
              '</option>'
              ].join('');

          $(gummi.BLOG_SELECTOR).append(optionItem);          
        }
        
        if (entries.length > 0) {
          $(gummi.BLOG_SELECTOR).get(0).selectedIndex = 0;
          $(gummi.BLOG_SELECTOR).trigger('change');
        }

        $(gummi.BLOG_SELECTOR).show();
      },
      handleError
  );    
}

/**
 * Enable a button to be clickable
 * @param {String} id is the CSS id of a button
 */
function enableButton(id) {
  $(id).get(0).disabled = false;
}

/**
 * Disable a button to be clickable
 * @param {String} id is the CSS id of a button
 */
function disableButton(id) {
  $(id).get(0).disabled = true;
}

/**
 * Enable or disable the "Blog >>>" button 
 * @param {Boolean} enable represent true/false whether the blogger 
 *     button is disabled
 */
function setIsBloggable() {
  // initialize the button value display based on token status
  if (hasBloggerToken()) {    
    $(gummi.BLOGGER_RUN_BUTTON).get(0).disabled = false;
  } else {
    $(gummi.BLOGGER_RUN_BUTTON).get(0).disabled = true;
  }
}

/**
 * Print the data on the display panel
 * @param {String} data is a string of content to be displayed
 */
function printToDisplay(data) {
  $(gummi.DISPLAY_DIV).html(data);
  $(gummi.DISPLAY_DIV).css({display: 'block'});
}

/**
 * Print the error message on the display panel
 * @param {Object} e is the error Object
 */
function errorToDisplay(e) {
  $(gummi.DISPLAY_DIV).html(e.cause ? e.cause.statusText : e.message);
}

/**
 * Error handler for JavaScript GData API calls, it is used as a callback
 * @param {Object} e is the error Object
 */
function handleError(e) {
  errorToDisplay(e);
}

/**
 * Set the start date and end date for the date chooser menu.
 * If there is a cookie, the date range will be set to the cookie data.
 * Otherwise the range will be set to be today's date
 */
function cookieGetDate() {
  
  if (!readCookie('startdate')) {
    var today = new Date();
    setStartDate(today);
    setEndDate(today);
  } else {
    setStartDate(new Date(parseInt(readCookie('startdate'))));
    eraseCookie('startdate');
    if (readCookie('enddate')) {
      setEndDate(new Date(parseInt(readCookie('enddate'))));
      eraseCookie('enddate');
    } 
  }
}

/**
 * Set the current date range as a cookie
 */
function cookieSetDate() {
  var start = getStartDate();
  var end = getEndDate();
  
  createCookie('startdate', start.getTime(), 1);
  createCookie('enddate', end.getTime(), 1);
}

/**
 * Create a JavaScript cookie
 * @param {String} name is the name of the cookie
 * @param {String} value is the value of the cookie
 * @param {Number} number is the numbers of days the 
 *     cookie will be expired from today
 */
function createCookie(name,value,days) {

  if (days) {
    var date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    var expires = '; expires=' + date.toGMTString();
  } else {
    var expires = '';
  }
  document.cookie = name + '=' + value+expires + '; path=/';
}

/**
 * Read the value of a JavaScript cookie
 * @param {String} name is the name of the cookie
 * @return {String} value of the cookie that matches the given name
 */
function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length; i++) {
    var c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1, c.length);
    }
    if (c.indexOf(nameEQ) == 0) { 
      return c.substring(nameEQ.length, c.length);
    }
  }
  return null;
}

/**
 * Set a cookie to be expired
 * @param {String} name is the name of the cookie
 */
function eraseCookie(name) {
  createCookie(name,"",-1);
}
