// Copyright 2007, Google Inc.
//
// Redistribution and use in source and binary forms, with or without 
// modification, are permitted provided that the following conditions are met:
//
//  1. Redistributions of source code must retain the above copyright notice, 
//     this list of conditions and the following disclaimer.
//  2. Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//  3. Neither the name of Google Inc. nor the names of its contributors may be
//     used to endorse or promote products derived from this software without
//     specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF 
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

// Change this to set the name of the managed resource store to create.
// You use the name with the createManagedStore, and removeManagedStore,
// and openManagedStore APIs. It isn't visible to the user.
var STORE_NAME = "my_offline_docset2";

// Change this to set the URL of tha manifest file, which describe which
// URLs to capture. It can be relative to the current page, or an
// absolute URL.
var MANIFEST_FILENAME = "manifest2.json";

var localServer;
var store;

// Called onload to initialize local server and store variables
function init() {
  if (!window.google || !google.gears) {
    textOut("NOTE:  You must install Google Gears first.");
  } else {


    try {
    localServer = google.gears.factory.create("beta.localserver","1.0");

    textOut("Yeay, Google Gears is already installed.");
      db = google.gears.factory.create('beta.database', '1.0');

      if (db) {
        db.open('database-demo');
        db.execute('create table if not exists Demo2' +
                   ' (Phrase varchar(255),  Timestamp int, StoryUrl varchar(255))');

        success = true;
        // Initialize the UI at startup.


   
      }
	  

      displayRecentPhrases();
    } catch (ex) {
      setError('Could not create database: ' + ex.message);
	  return;
    }
  }

  // Enable or disable UI elements

  var inputs = document.getElementsByTagName('input');
  for (var i = 0, el; el = inputs[i]; i++) {
    el.disabled = !success;


  }

}









// Create the managed resource store
function createStore() {
/*  if (!window.google || !google.gears) {
    alert("You must install Google Gears first.");
    return;
  }
*/
    store = localServer.createManagedStore(STORE_NAME);
  store.manifestUrl = MANIFEST_FILENAME;
  store.checkForUpdate();

  var timerId = window.setInterval(function() {
    // When the currentVersion property has a value, all of the resources
    // listed in the manifest file for that version are captured. There is
    // an open bug to surface this state change as an event.
    if (store.currentVersion) {
      window.clearInterval(timerId);
      textOut("The documents are now available offline.\n" + 
              "With your browser offline, load the document at " +
              "its normal online URL to see the locally stored " +
			        "version. The version stored is: " + 
              store.currentVersion);
    } else if (store.updateStatus == 3) {
      textOut("Error: " + store.lastErrorMessage);
    }
  }, 500); 
  
  
}







// Remove the managed resource store.
function removeStore() {
  /*
  if (!window.google || !google.gears) {
    alert("You must install Google Gears first.");
    return;
  }
*/
  try {
    var localServer = google.gears.factory.create('beta.localserver', '1.0');
  } catch (ex) {
    setError('Could not create local server: ' + ex.message);
    return;
  }

  localServer.removeManagedStore(STORE_NAME);
  textOut("Done. The local store has been removed." +
          "You will now see online versions of the documents.");
}







// Utility function to output some status text.
function textOut(s) {
 var elm = document.getElementById("textOut");
  while (elm.firstChild) {
    elm.removeChild(elm.firstChild);
  } 
  elm.appendChild(document.createTextNode(s));

}


function handleSubmit() {

/*	
 if (!google.gears.factory || !db) {
    return;
  }
*/

   var w = document.form1.endpoints.selectedIndex;
   var elm = document.form1.endpoints.options[w].value;

  var phrase = elm;
  var currTime = new Date().getTime();

  $('#spinner').show();	

 // Insert the new item.
  // The Gears database automatically escapes/unescapes inserted values.
//  db.execute('insert into Demo values (?, ?)', [phrase, currTime]);

  // Update the UI.
  elm.value = '';
  

    var uri = 'my-proxy.php';
    var params = {
        endPoint : phrase,
        type : 'json',
        count : 20
    };

    $.getJSON(uri, params, function(json) {


		if ((json.stories.length > 0)) {
				for (i in json.stories) {
				   // $('#stories').append('<li><a href="' + json.stories[i].href + '">' + json.stories[i].title + '</a></li>');
				   db.execute('insert into Demo2 values (?, ?, ?)', [json.stories[i].title,  currTime, json.stories[i].href]);
				}

			   displayRecentPhrases();
					 $('#spinner').hide();
			}
    });

}


	function displayRecentPhrases() {

	  // We re-throw Gears exceptions to make them play nice with certain tools.
	  // This will be unnecessary in a future version of Gears.
	  try {

		// Get the 3 most recent entries. Delete any others.
		var rs = db.execute('select * from Demo2 order by Timestamp DESC  ');
		var index = 0;
		$('#status').empty();
		while (rs.isValidRow()) {
		
		
		 $('#status').append('<li><a href="' + rs.field(2) + '">' + rs.field(0) + '</a></li>');

		  ++index;
		  rs.next();
		}
		rs.close();
		$('#status').hide();
		$('#status').show('slow');


		//showResults()

	  } catch (e) {
		throw new Error(e.message);
	  }

		
	}

function emptyDB(){

  try {

    // Get the 3 most recent entries. Delete any others.
    var rs = db.execute('select * from Demo2 order by Timestamp DESC');
    var index = 0;
    while (rs.isValidRow()) {

       // recentPhrases[index] = rs.field(0);

      db.execute('delete from Demo2 where Timestamp=?', [rs.field(1)]);

      ++index;
      rs.next();
    }
    rs.close();
	displayRecentPhrases()

  } catch (e) {
    throw new Error(e.message);
  }


}

function jsonFlickrApi(rsp){

	if (rsp.stat != "ok"){

		// something broke!
		return;
	}

	for (var i=0; i<rsp.blogs.blog.length; i++){

		var blog = rsp.blogs.blog[i];

		var div = document.createElement('div');
		var txt = document.createTextNode(blog.name);

		div.appendChild(txt);
		document.body.appendChild(div);
	}
}