<commit_before>(function(root, factory){

	if(typeof define === 'function' && define.amd) {
		define([], factory);
	} else if (typeof module === 'object' && module.exports) {
		module.exports = factory(;
	} else {
		root.chainit = factory();
	}

})(this, function(b) {

	var chain = function() {
		this.queue = [];
		this.result = [];
		this.temp_result;
	};

	chain.prototype.serial = function() {
		if(!checkargs(arguments)) {
			return [];
		}

		var queue = Array.prototype.slice.call(arguments);
		queue.shift()();

		return this;
	};

	chain.prototype.parallel = function() {

	};

	chain.prototype.getResult = function() {
		return this.result;
	};

	function checkargs(arg) {
		var valid = true;
		if(arg.length == 0) {
			valid = false
		}
		return valid;
	}

	function handler() {

	};

	handler.prototype.done = function() {
		var func = queue.shift();

		if(func) {
			temp_result = func(this, temp_result);
		}

		queue.length == 0 && result.push(temp_result);
	}

	return chain;

})<commit_msg>remove unused argument b<commit_after>(function(root, factory){

	if(typeof define === 'function' && define.amd) {
		define([], factory);
	} else if (typeof module === 'object' && module.exports) {
		module.exports = factory(;
	} else {
		root.chainit = factory();
	}

})(this, function() {

	var chain = function() {
		this.queue = [];
		this.result = [];
		this.temp_result;
	};

	chain.prototype.serial = function() {
		if(!checkargs(arguments)) {
			return [];
		}

		var queue = Array.prototype.slice.call(arguments);
		queue.shift()();

		return this;
	};

	chain.prototype.parallel = function() {

	};

	chain.prototype.getResult = function() {
		return this.result;
	};

	function checkargs(arg) {
		var valid = true;
		if(arg.length == 0) {
			valid = false
		}
		return valid;
	}

	function handler() {

	};

	handler.prototype.done = function() {
		var func = queue.shift();

		if(func) {
			temp_result = func(this, temp_result);
		}

		queue.length == 0 && result.push(temp_result);
	}

	return chain;

})
<|endoftext|>


<commit_before>/*
  Search-functions
*/

//Singleton application instance.
//Put search related methods into
//here (refactor).
app = new function Application() {
  var hymnBook = null
  var curHymnBook = "";
  var searchMethods = new Array()

  //Adds a search method. Associates the given
  //regular expression with the given HymnBook method.
  function addSearchMethod(regex, funcname) {
    searchMethods.push({"regex":regex, "func":funcname})
  }

  //Adds a search result to the page
  function addSearchResult(element)
  {
    // Insert what we are searching for "Search results for: 'XXX'"
    var test = document.getElementById(element.id + "_searchquery");

    if (test)
      test.innerHTML = "\"" + document.hymnform.searchquery.value + "\"";

    processSearchResults()
  }

  //Changes melody
  this.changeMelody = function(id) {
    var melodyId = document.getElementById(id + "_melodySelector").value;
    var downloadLink = document.getElementById(id + "_downloadMelody");

    // Change download link
    downloadLink.href = "hymns/midi/" + melodyId + ".mid";

    // Change list with links to hymns with the same melody
    app.updateListOfHymnsWithSameMelody(id);
  }

  this.clearSearchResults = function()
  {
    var searchResults = document.getElementById("searchresults");
    if (searchResults)
      while (searchResults.childNodes.length > 0)
        removeElement(searchResults.childNodes[0].id);

    processSearchResults();
  }

  /*
    Initializes the app.
  */
  this.init = function() {
    // Add an event-listener to Audio-tag in search result to reset playback when it has ended.
    var audio = document.getElementById("audioplayer");

    if (audio) {
      addEvent(audio, "ended", function() {
        resetPlaybackTime(audio.id);
      });
    }

    //Add search methods (order is significant!)
    addSearchMethod(/^[123456789]\d*$/, "searchByNumber")
    addSearchMethod(/^category:/, "searchByCategory")
    addSearchMethod(/^author:/, "searchByAuthor")
    addSearchMethod(/^\d+:+\d+$/, "searchVerse")
    //Global handler (must be added last!)
    addSearchMethod(/.+/, "searchByContent")
  }()

  /*
    Returns the audio extension (e.g. "ogg")
    to use.
  */
  function getAudioExtension() {
    var oracle = document.createElement("audio");
    if(oracle.canPlayType && !!oracle.canPlayType('audio/ogg; codecs="vorbis"'))
      return "ogg";
    else
      return "mp3";
  }

  /*
    Plays/pauses a melody. The ID if the hymn
    to be played is given as the first parameter.
  */
  this.playPauseMelody = function(id) {
    var audio = document.getElementById("audioplayer"),
        melodyId = document.getElementById(id + "_melodySelector").value,
        ext = getAudioExtension(),
        melodyPath = "hymns/" + ext + "/" + melodyId + "." + ext;

    if (supportsAudio() && audio.src !== melodyPath)
    {
        audio.pause()
        audio.src= melodyPath
        audio.load()
    }

    if(audio.paused)
      audio.play();
    else
      audio.pause();
  }

  //Presents the given data to the user
  this.presentSearchResult = function(data)
  {
    if(data)
    {
      var searchResults = document.getElementById("searchresults")
      if(window.ActiveXObject)
      {
        data  = stringToElement(data.substr(data.indexOf("?>") + 2))
        searchResults.innerHTML = data.innerHTML + searchResults.innerHTML
        addSearchResult(data.firstChild)
      }
      else
      {
        searchResults.insertBefore(data, searchResults.childNodes[0])
        addSearchResult(searchResults.childNodes[0])
      }
    }

    jsI18n.processPage()
    showElement("searchresults_p", true)
    showElement("searchresults", true)
  }

  function processSearchResults()
  {
    var searchResults = document.getElementById("searchresults");

    if (searchResults.childNodes.length > 1)
      for (var i = 1; i < searchResults.childNodes.length; i++)
        showElement(searchResults.childNodes[i].id + "_hymnDiv", false);

    if (searchResults.childNodes.length > 5)
    {
      var temp = searchResults.childNodes[searchResults.childNodes.length - 1]; // Must use this method instead of searchResults.lastChild to make it work in IE
      removeElement(temp.id);
    }

    if (searchResults.childNodes.length == 0)
    {
      showElement("searchresults_p", false)
      showElement("searchresults", false)
    }
  }

  //Removes the search result with the given id
  this.removeSearchResult = function(id)
  {
    if (id)
    {
      removeElement(id);

      processSearchResults()
    }
  }

  //Searches for a hymn
  //If the optional argument is given,
  //that text will be used as the search text.
  this.searchHymn = function(searchtext) {
    document.getElementById('searchtips').style.display='none'

    if(searchtext != null)
      document.hymnform.searchquery.value = searchtext

    var query = document.hymnform.searchquery.value
    var hbname = document.hymnform.hymnbook.value
    //TODO: Select hymnbook
    if (hbname)
    {
      if (curHymnBook !== hbname)
      {
        showElement("loadingImage", true);
        hymnBook  = new HymnBook("xml/hymnbooks/" + hbname + ".xml");
        showElement("loadingImage", false);

        curHymnBook = hbname;
      }
    }

    if (hymnBook)
    {
      //Call search method
      for(var i = 0; i < searchMethods.length; i++)
      {
        var sm = searchMethods[i]
        if(query.match(sm["regex"]))
        {
          hymnBook[sm["func"]].apply(this, [query])
          break;
        }
      }
    }

    //Focus on query
    document.hymnform.searchquery.focus()
    document.hymnform.searchquery.select()
  }

  this.showSearchTips = function() {
    document.getElementById('searchtips').style.display='block'
  }

  // Shows all the hymns with the same melody as the hymn with the given ID
  this.showHymnsWithMelody = function(id)
  {
    var showHymnsList = document.getElementById(id + "_showHymnsSameMelody");

    app.updateListOfHymnsWithSameMelody(id);
    showElement(id + "_hymnsWithSameMelodyList", true);

    var anchorParent = showHymnsList.parentNode;
    anchorParent.removeChild(showHymnsList);
  }

  // Updates list of hymns with same melody as the hymn with the given ID
  this.updateListOfHymnsWithSameMelody = function(id)
  {
    var hymnList = document.getElementById(id + "_hymnsWithSameMelodyList");
    var hymnNumbers = document.getElementById(id + "_melodySelector").value.split("_");

    hymnList.innerHTML = "";

    var length, currentHymn;
    for (var i = 0, length = hymnNumbers.length; i < length; i++)
    {
      currentHymn = hymnNumbers[i].match(/\d+/);

      var tempA = document.createElement("a");
        tempA.href = "javascript: app.searchHymn('" + new Number(currentHymn) + "')";
        tempA.innerHTML = new Number(currentHymn);

      var tempLi = document.createElement("li");
        tempLi.appendChild(tempA);

      hymnList.appendChild(tempLi);
    }
  }
}

//Helper for converting a XML Node (lists)
//into an XML document.
function NodeToXMLConverter()
{
  //Converts a node list into xml
  this.nodeListToXML = function(list, parentnode) {
    var xmlstr = "<" + parentnode + ">"

    for(var i = 0; i < list.length; i++)
      xmlstr += nodeToString(list[i])

    return stringToXML(xmlstr + "</" + parentnode + ">")
  }

  function nodeToString(node) {
    if(window.ActiveXObject)
      return node.xml
    else
      return new XMLSerializer().serializeToString(node)
  }

  this.nodeToXML  = function(node) {
    return stringToXML(nodeToString(node))
  }

  function stringToXML(str) {
    if(window.ActiveXObject)
    {
      var xml = new ActiveXObject("Microsoft.XMLDOM")
      xml.async = false
      xml.loadXML(str)
      return xml
    }
    else
      return new DOMParser().parseFromString(str, "text/xml")
  }
}

/*
  **IE-specific!**
  Creates a "generic" element and sets it's innerHTML property to str

  Hack?
*/
function stringToElement(str)
{
  var temp  = document.createElement("div");
  temp.innerHTML  = str;

  return temp;
}

/*
  Helper for searching through a document with XSLT.
*/
function XPathHelper(xml)
{
  var xmlDoc = xml
  //Returns all instances matched by the given xpath expression.
  this.evaluate = function(xpath, result) {
    if (xmlDoc != null)
    {
      if (window.ActiveXObject) //IE
      {
        xmlDoc.setProperty("SelectionLanguage", "XPath");
        return xmlDoc.selectNodes(xpath);
      }
      else
        return xmlDoc.evaluate(xpath, xmlDoc, null, XPathResult.ANY_TYPE, result);
    }
    return null;
  }

  //Returns all instances found by the given xpath expression as an array.
  this.findAll = function (xpath, result) {
    var results = this.evaluate(xpath, result)
    if(window.ActiveXObject && results)
      return results
    else if(!window.ActiveXObject)
    {
      var nodes = []
      var node;
      while(node = results.iterateNext())
        nodes.push(node)
      return nodes
    }
    else
      return []
  }

  //Returns the first instance matched by the given xpath expression.
  this.findFirst = function(xpath, result) {
    var results = this.evaluate(xpath, result)
    if (window.ActiveXObject && results && results.length > 0)
        return results[0]
    else if(!window.ActiveXObject)
      return results.iterateNext()
    else
      return null
  }
}

/*
  Helper for processing XML
  with an XSLT stylesheet.
*/
function XSLTHelper(xslt)
{
  var xsltDoc = xslt;

  this.process = function(xml)
  {
    if(window.ActiveXObject) //IE
    {
      xml.setProperty("SelectionLanguage", "XPath")
      return xml.transformNode(xsltDoc)
    }
    else if(document.implementation && document.implementation.createDocument)
    {
      var xsltProcessor = new XSLTProcessor();
      xsltProcessor.importStylesheet(xsltDoc);
      return xsltProcessor.transformToFragment(xml, document);
    }
    else //Not supported
    {
      return null;
    }
  }
}

function HymnBook(fname)
{
  var xmlDoc      = loadXMLDoc(fname, false);
  var lastResults = null;

  //Returns XML for all hymns in the hymn book
  this.allHymns = function() {
    return new XPathHelper(xmlDoc).evaluate("hymns/hymn");
  }

  //Processes the given XML node with the named stylesheet
  function processWithXSL(node, xslt) {
    var xml = null
    if(node.length != undefined)
      xml = new NodeToXMLConverter().nodeListToXML(node, "hymns")
    else
      xml = new NodeToXMLConverter().nodeToXML(node);

    var processor = new XSLTHelper(loadXMLDoc(xslt, false));
    return processor.process(xml);
  }

  //Searches hymn by author
  this.searchByAuthor = function(str) {
    var author = str.replace(/author:\s*/gi, "")
    if (xmlDoc != null)
    {
      var xpath = "/hymns/hymn[authors/author[contains(name, '" + author + "')]]"
      var hymns = new XPathHelper(xmlDoc).findAll(xpath)
      if(hymns.length > 0)
        app.presentSearchResult(processWithXSL(hymns, "xml/hymns.xsl"))
      else
        app.showSearchTips()
    }
  }

  //Searches hymn by category
  this.searchByCategory = function(str) {
    var category = str.replace(/category:\s*/gi, "")
    if (xmlDoc != null)
    {
      var xpath = "/hymns/hymn[contains(category, '" + category + "')]";
      var hymns = new XPathHelper(xmlDoc).findAll(xpath);
      if(hymns.length > 0)
        app.presentSearchResult(processWithXSL(hymns, "xml/hymns.xsl"))
      else
        app.showSearchTips()
    }
  }

  //Searches a hymn by verse content.
  //Uses javascript for the search.
  this.searchByContent = function(str) {
    var hymns = []
    var regex = new RegExp(searchEscape(str), "i")
    var all = new XPathHelper(xmlDoc).findAll('//hymn')
    for(var i = 0; i < all.length; i++)
    {
      // Search in title first
      var titles = all[i].getElementsByTagName("title")
      var title = (window.ActiveXObject) ? titles[0].text : titles[0].textContent
      if(title.match(regex))
        hymns.push(all[i])
      else { //Search in verses if necessary
        var verses = all[i].getElementsByTagName("verse")
        for(var v = 0; v < verses.length; v++)
        {
          var content = (window.ActiveXObject) ? verses[v].text : verses[v].textContent
          if(content.match(regex))
          {
            hymns.push(all[i])
            break
          }
        }
      }
    }
    if(hymns.length > 0)
      app.presentSearchResult(processWithXSL(hymns, "xml/hymns.xsl"))
    else
      app.showSearchTips()
  }

  //Searches a hymn by number
  this.searchByNumber = function(num) {
    if (xmlDoc != null)
    {
      var xpath = "/hymns/hymn[number=" + num + "]";
      var hymn = new XPathHelper(xmlDoc).findFirst(xpath);
      if(hymn)
        app.presentSearchResult(processWithXSL(hymn, "xml/hymn.xsl"))
      else
        app.showSearchTips()
    }
  }

  //Escapes a string to make it suitable as a hymn search regex.
  //Inserts word boundaries, allows wildcards (only as suffix)
  //and "and" functionality by using commas.
  function searchEscape(str) {
    return RegExp.escape(str).replace("\\,", ".*").replace("\\*", "\\w*").replace(/(\w+)(\\w\*)*/, "\\b$1$2\\b")
  }

  //Searches for a particular verse in a hymn
  this.searchVerse = function(str) {
    alert("Searching for verse " + str)
  }
}
<commit_msg>Stop playback if search results are cleared<commit_after>/*
  Search-functions
*/

//Singleton application instance.
//Put search related methods into
//here (refactor).
app = new function Application() {
  var hymnBook = null
  var curHymnBook = "";
  var searchMethods = new Array()

  //Adds a search method. Associates the given
  //regular expression with the given HymnBook method.
  function addSearchMethod(regex, funcname) {
    searchMethods.push({"regex":regex, "func":funcname})
  }

  //Adds a search result to the page
  function addSearchResult(element)
  {
    // Insert what we are searching for "Search results for: 'XXX'"
    var test = document.getElementById(element.id + "_searchquery");

    if (test)
      test.innerHTML = "\"" + document.hymnform.searchquery.value + "\"";

    processSearchResults()
  }

  //Changes melody
  this.changeMelody = function(id) {
    var melodyId = document.getElementById(id + "_melodySelector").value;
    var downloadLink = document.getElementById(id + "_downloadMelody");

    // Change download link
    downloadLink.href = "hymns/midi/" + melodyId + ".mid";

    // Change list with links to hymns with the same melody
    app.updateListOfHymnsWithSameMelody(id);
  }

  this.clearSearchResults = function()
  {
    var searchResults = document.getElementById("searchresults"),
        audio = document.getElementById("audioplayer");

    if (searchResults)
    {
      while (searchResults.childNodes.length > 0)
        removeElement(searchResults.childNodes[0].id);

      audio.pause();
    }

    processSearchResults();
  }

  /*
    Initializes the app.
  */
  this.init = function() {
    // Add an event-listener to Audio-tag in search result to reset playback when it has ended.
    var audio = document.getElementById("audioplayer");

    if (audio) {
      addEvent(audio, "ended", function() {
        resetPlaybackTime(audio.id);
      });
    }

    //Add search methods (order is significant!)
    addSearchMethod(/^[123456789]\d*$/, "searchByNumber")
    addSearchMethod(/^category:/, "searchByCategory")
    addSearchMethod(/^author:/, "searchByAuthor")
    addSearchMethod(/^\d+:+\d+$/, "searchVerse")
    //Global handler (must be added last!)
    addSearchMethod(/.+/, "searchByContent")
  }()

  /*
    Returns the audio extension (e.g. "ogg")
    to use.
  */
  function getAudioExtension() {
    var oracle = document.createElement("audio");
    if(oracle.canPlayType && !!oracle.canPlayType('audio/ogg; codecs="vorbis"'))
      return "ogg";
    else
      return "mp3";
  }

  /*
    Plays/pauses a melody. The ID if the hymn
    to be played is given as the first parameter.
  */
  this.playPauseMelody = function(id) {
    var audio = document.getElementById("audioplayer"),
        melodyId = document.getElementById(id + "_melodySelector").value,
        ext = getAudioExtension(),
        melodyPath = "hymns/" + ext + "/" + melodyId + "." + ext;

    if (supportsAudio() && audio.src !== melodyPath)
    {
        audio.pause()
        audio.src= melodyPath
        audio.load()
    }

    if(audio.paused)
      audio.play();
    else
      audio.pause();
  }

  //Presents the given data to the user
  this.presentSearchResult = function(data)
  {
    if(data)
    {
      var searchResults = document.getElementById("searchresults")
      if(window.ActiveXObject)
      {
        data  = stringToElement(data.substr(data.indexOf("?>") + 2))
        searchResults.innerHTML = data.innerHTML + searchResults.innerHTML
        addSearchResult(data.firstChild)
      }
      else
      {
        searchResults.insertBefore(data, searchResults.childNodes[0])
        addSearchResult(searchResults.childNodes[0])
      }
    }

    jsI18n.processPage()
    showElement("searchresults_p", true)
    showElement("searchresults", true)
  }

  function processSearchResults()
  {
    var searchResults = document.getElementById("searchresults");

    if (searchResults.childNodes.length > 1)
      for (var i = 1; i < searchResults.childNodes.length; i++)
        showElement(searchResults.childNodes[i].id + "_hymnDiv", false);

    if (searchResults.childNodes.length > 5)
    {
      var temp = searchResults.childNodes[searchResults.childNodes.length - 1]; // Must use this method instead of searchResults.lastChild to make it work in IE
      removeElement(temp.id);
    }

    if (searchResults.childNodes.length == 0)
    {
      showElement("searchresults_p", false)
      showElement("searchresults", false)
    }
  }

  //Removes the search result with the given id
  this.removeSearchResult = function(id)
  {
    if (id)
    {
      removeElement(id);

      processSearchResults()
    }
  }

  //Searches for a hymn
  //If the optional argument is given,
  //that text will be used as the search text.
  this.searchHymn = function(searchtext) {
    document.getElementById('searchtips').style.display='none'

    if(searchtext != null)
      document.hymnform.searchquery.value = searchtext

    var query = document.hymnform.searchquery.value
    var hbname = document.hymnform.hymnbook.value
    //TODO: Select hymnbook
    if (hbname)
    {
      if (curHymnBook !== hbname)
      {
        showElement("loadingImage", true);
        hymnBook  = new HymnBook("xml/hymnbooks/" + hbname + ".xml");
        showElement("loadingImage", false);

        curHymnBook = hbname;
      }
    }

    if (hymnBook)
    {
      //Call search method
      for(var i = 0; i < searchMethods.length; i++)
      {
        var sm = searchMethods[i]
        if(query.match(sm["regex"]))
        {
          hymnBook[sm["func"]].apply(this, [query])
          break;
        }
      }
    }

    //Focus on query
    document.hymnform.searchquery.focus()
    document.hymnform.searchquery.select()
  }

  this.showSearchTips = function() {
    document.getElementById('searchtips').style.display='block'
  }

  // Shows all the hymns with the same melody as the hymn with the given ID
  this.showHymnsWithMelody = function(id)
  {
    var showHymnsList = document.getElementById(id + "_showHymnsSameMelody");

    app.updateListOfHymnsWithSameMelody(id);
    showElement(id + "_hymnsWithSameMelodyList", true);

    var anchorParent = showHymnsList.parentNode;
    anchorParent.removeChild(showHymnsList);
  }

  // Updates list of hymns with same melody as the hymn with the given ID
  this.updateListOfHymnsWithSameMelody = function(id)
  {
    var hymnList = document.getElementById(id + "_hymnsWithSameMelodyList");
    var hymnNumbers = document.getElementById(id + "_melodySelector").value.split("_");

    hymnList.innerHTML = "";

    var length, currentHymn;
    for (var i = 0, length = hymnNumbers.length; i < length; i++)
    {
      currentHymn = hymnNumbers[i].match(/\d+/);

      var tempA = document.createElement("a");
        tempA.href = "javascript: app.searchHymn('" + new Number(currentHymn) + "')";
        tempA.innerHTML = new Number(currentHymn);

      var tempLi = document.createElement("li");
        tempLi.appendChild(tempA);

      hymnList.appendChild(tempLi);
    }
  }
}

//Helper for converting a XML Node (lists)
//into an XML document.
function NodeToXMLConverter()
{
  //Converts a node list into xml
  this.nodeListToXML = function(list, parentnode) {
    var xmlstr = "<" + parentnode + ">"

    for(var i = 0; i < list.length; i++)
      xmlstr += nodeToString(list[i])

    return stringToXML(xmlstr + "</" + parentnode + ">")
  }

  function nodeToString(node) {
    if(window.ActiveXObject)
      return node.xml
    else
      return new XMLSerializer().serializeToString(node)
  }

  this.nodeToXML  = function(node) {
    return stringToXML(nodeToString(node))
  }

  function stringToXML(str) {
    if(window.ActiveXObject)
    {
      var xml = new ActiveXObject("Microsoft.XMLDOM")
      xml.async = false
      xml.loadXML(str)
      return xml
    }
    else
      return new DOMParser().parseFromString(str, "text/xml")
  }
}

/*
  **IE-specific!**
  Creates a "generic" element and sets it's innerHTML property to str

  Hack?
*/
function stringToElement(str)
{
  var temp  = document.createElement("div");
  temp.innerHTML  = str;

  return temp;
}

/*
  Helper for searching through a document with XSLT.
*/
function XPathHelper(xml)
{
  var xmlDoc = xml
  //Returns all instances matched by the given xpath expression.
  this.evaluate = function(xpath, result) {
    if (xmlDoc != null)
    {
      if (window.ActiveXObject) //IE
      {
        xmlDoc.setProperty("SelectionLanguage", "XPath");
        return xmlDoc.selectNodes(xpath);
      }
      else
        return xmlDoc.evaluate(xpath, xmlDoc, null, XPathResult.ANY_TYPE, result);
    }
    return null;
  }

  //Returns all instances found by the given xpath expression as an array.
  this.findAll = function (xpath, result) {
    var results = this.evaluate(xpath, result)
    if(window.ActiveXObject && results)
      return results
    else if(!window.ActiveXObject)
    {
      var nodes = []
      var node;
      while(node = results.iterateNext())
        nodes.push(node)
      return nodes
    }
    else
      return []
  }

  //Returns the first instance matched by the given xpath expression.
  this.findFirst = function(xpath, result) {
    var results = this.evaluate(xpath, result)
    if (window.ActiveXObject && results && results.length > 0)
        return results[0]
    else if(!window.ActiveXObject)
      return results.iterateNext()
    else
      return null
  }
}

/*
  Helper for processing XML
  with an XSLT stylesheet.
*/
function XSLTHelper(xslt)
{
  var xsltDoc = xslt;

  this.process = function(xml)
  {
    if(window.ActiveXObject) //IE
    {
      xml.setProperty("SelectionLanguage", "XPath")
      return xml.transformNode(xsltDoc)
    }
    else if(document.implementation && document.implementation.createDocument)
    {
      var xsltProcessor = new XSLTProcessor();
      xsltProcessor.importStylesheet(xsltDoc);
      return xsltProcessor.transformToFragment(xml, document);
    }
    else //Not supported
    {
      return null;
    }
  }
}

function HymnBook(fname)
{
  var xmlDoc      = loadXMLDoc(fname, false);
  var lastResults = null;

  //Returns XML for all hymns in the hymn book
  this.allHymns = function() {
    return new XPathHelper(xmlDoc).evaluate("hymns/hymn");
  }

  //Processes the given XML node with the named stylesheet
  function processWithXSL(node, xslt) {
    var xml = null
    if(node.length != undefined)
      xml = new NodeToXMLConverter().nodeListToXML(node, "hymns")
    else
      xml = new NodeToXMLConverter().nodeToXML(node);

    var processor = new XSLTHelper(loadXMLDoc(xslt, false));
    return processor.process(xml);
  }

  //Searches hymn by author
  this.searchByAuthor = function(str) {
    var author = str.replace(/author:\s*/gi, "")
    if (xmlDoc != null)
    {
      var xpath = "/hymns/hymn[authors/author[contains(name, '" + author + "')]]"
      var hymns = new XPathHelper(xmlDoc).findAll(xpath)
      if(hymns.length > 0)
        app.presentSearchResult(processWithXSL(hymns, "xml/hymns.xsl"))
      else
        app.showSearchTips()
    }
  }

  //Searches hymn by category
  this.searchByCategory = function(str) {
    var category = str.replace(/category:\s*/gi, "")
    if (xmlDoc != null)
    {
      var xpath = "/hymns/hymn[contains(category, '" + category + "')]";
      var hymns = new XPathHelper(xmlDoc).findAll(xpath);
      if(hymns.length > 0)
        app.presentSearchResult(processWithXSL(hymns, "xml/hymns.xsl"))
      else
        app.showSearchTips()
    }
  }

  //Searches a hymn by verse content.
  //Uses javascript for the search.
  this.searchByContent = function(str) {
    var hymns = []
    var regex = new RegExp(searchEscape(str), "i")
    var all = new XPathHelper(xmlDoc).findAll('//hymn')
    for(var i = 0; i < all.length; i++)
    {
      // Search in title first
      var titles = all[i].getElementsByTagName("title")
      var title = (window.ActiveXObject) ? titles[0].text : titles[0].textContent
      if(title.match(regex))
        hymns.push(all[i])
      else { //Search in verses if necessary
        var verses = all[i].getElementsByTagName("verse")
        for(var v = 0; v < verses.length; v++)
        {
          var content = (window.ActiveXObject) ? verses[v].text : verses[v].textContent
          if(content.match(regex))
          {
            hymns.push(all[i])
            break
          }
        }
      }
    }
    if(hymns.length > 0)
      app.presentSearchResult(processWithXSL(hymns, "xml/hymns.xsl"))
    else
      app.showSearchTips()
  }

  //Searches a hymn by number
  this.searchByNumber = function(num) {
    if (xmlDoc != null)
    {
      var xpath = "/hymns/hymn[number=" + num + "]";
      var hymn = new XPathHelper(xmlDoc).findFirst(xpath);
      if(hymn)
        app.presentSearchResult(processWithXSL(hymn, "xml/hymn.xsl"))
      else
        app.showSearchTips()
    }
  }

  //Escapes a string to make it suitable as a hymn search regex.
  //Inserts word boundaries, allows wildcards (only as suffix)
  //and "and" functionality by using commas.
  function searchEscape(str) {
    return RegExp.escape(str).replace("\\,", ".*").replace("\\*", "\\w*").replace(/(\w+)(\\w\*)*/, "\\b$1$2\\b")
  }

  //Searches for a particular verse in a hymn
  this.searchVerse = function(str) {
    alert("Searching for verse " + str)
  }
}
<|endoftext|>


<commit_before>(function() {
  function displaySearchResults(results, store) {
    var searchResults = document.getElementById('search-results');

    if (results.length) { // Are there any results?
      var appendString = '';

      for (var i = 0; i < results.length; i++) {  // Iterate over the results
        var item = store[results[i].ref];
        appendString += '

' + item.title + '
';
        //appendString += '
' + item.content.substring(0, 150) + '...

';
      }

      searchResults.innerHTML = appendString;
    } else {
      searchResults.innerHTML = '
No results found
';
    }
  }

  function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split('&');

    for (var i = 0; i < vars.length; i++) {
      var pair = vars[i].split('=');

      if (pair[0] === variable) {
        return decodeURIComponent(pair[1].replace(/\+/g, '%20'));
      }
    }
  }

  var searchTerm = getQueryVariable('query');

  if (searchTerm) {
    document.getElementById('search-box').setAttribute("value", searchTerm);

    // Initalize lunr with the fields it will be searching on. I've given title
    // a boost of 10 to indicate matches on this field are more important.
    var idx = lunr(function () {
      this.field('id');
      this.field('title', { boost: 10 });
      this.field('author');
      this.field('category');
      this.field('content');
    });

    for (var key in window.store) { // Add the data to lunr
      idx.add({
        'id': key,
        'title': window.store[key].title,
        'author': window.store[key].author,
        'category': window.store[key].category,
        'content': window.store[key].content
      });

      var results = idx.search(searchTerm); // Get lunr to perform a search
      displaySearchResults(results, window.store); // We'll write this in the next section
    }
  }
})();
<commit_msg>Updated search.js<commit_after>(function() {
  function displaySearchResults(results, store) {
    var searchResults = document.getElementById('search-results');

    if (results.length) { // Are there any results?
      var appendString = '';

      for (var i = 0; i < results.length; i++) {  // Iterate over the results
        var item = store[results[i].ref];
        appendString += '

' + item.title + '

';
        //appendString += '
' + item.content.substring(0, 150) + '...

';
      }

      searchResults.innerHTML = appendString;
    } else {
      searchResults.innerHTML = '
No results found
';
    }
  }

  function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split('&');

    for (var i = 0; i < vars.length; i++) {
      var pair = vars[i].split('=');

      if (pair[0] === variable) {
        return decodeURIComponent(pair[1].replace(/\+/g, '%20'));
      }
    }
  }

  var searchTerm = getQueryVariable('query');

  if (searchTerm) {
    document.getElementById('search-box').setAttribute("value", searchTerm);

    // Initalize lunr with the fields it will be searching on. I've given title
    // a boost of 10 to indicate matches on this field are more important.
    var idx = lunr(function () {
      this.field('id');
      this.field('title', { boost: 10 });
      this.field('author');
      this.field('category');
      this.field('content');
    });

    for (var key in window.store) { // Add the data to lunr
      idx.add({
        'id': key,
        'title': window.store[key].title,
        'author': window.store[key].author,
        'category': window.store[key].category,
        'content': window.store[key].content
      });

      var results = idx.search(searchTerm); // Get lunr to perform a search
      displaySearchResults(results, window.store); // We'll write this in the next section
    }
  }
})();
<|endoftext|>


<commit_before>/*
 Copyright 2017 Credential Engine and other contributing parties.

 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.
*/

var repo;

EcRepository.caching = true;
EcRepository.cachingSearch = false;

var frameworkId = "";

var servers = ["https://dev.cassproject.org/api/"];
var repo;

if (queryParams.server != null)
    servers = [queryParams.server];

var webSocketBackoff = 100;

openWebSocket = function (r) {
    // Instead of /ws/custom, will be /ws in next release.
    var connection = new WebSocket(r.selectedServer.replace(/http/, "ws").replace(/api\//, "ws/custom"));

    connection.onopen = function () {
        console.log("WebSocket open.");
    };

    connection.onerror = function (error) {
        console.log(error);
    };

    //Re-establish connection on close.
    connection.onclose = function (evt) {
        console.log(evt);
        webSocketBackoff *= 2;
        setTimeout(function () {
            openWebSocket(r);
        }, webSocketBackoff);
    };

    connection.onmessage = function (e) {
        console.log('Server: ' + e.data);
        EcRepository.get(e.data, function (wut) {
            delete EcRepository.cache[wut.id];
            delete EcRepository.cache[wut.shortId()];
            if (new EcFramework().isA(wut.getFullType()))
                if (framework != null)
                    if (framework.id == wut.id) {
                        framework = new EcFramework();
                        framework.copyFrom(wut);
                        populateFramework();
                    }

            if (new EcCompetency().isA(wut.getFullType())) {
                var com = new EcCompetency();
                com.copyFrom(wut);
                refreshCompetency(com);
                if (selectedCompetency != null)
                    if (selectedCompetency.id == wut.id) {
                        selectedCompetency = com;
                        refreshSidebar();
                    }
            }
            if (new EcLevel().isA(wut.getFullType())) {
                var com = new EcLevel();
                com.copyFrom(wut);
                refreshCompetency(com);
                if (selectedCompetency != null)
                    if (selectedCompetency.id == wut.id) {
                        selectedCompetency = com;
                        refreshSidebar();
                    }
            }

        }, error);
    };

}

function cappend(event) {
    if (event.data.message == "selected") {
        console.log("I got " + event.data.selected.length + " selected items from the iframe");
        console.log(event.data.selected);
        appendCompetencies(event.data.selected, true);
        backPage();
    } else if (event.data.message == "back")
        backPage();
}

for (var i = 0; i < servers.length; i++) {
    var r = new EcRepository();
    r.selectedServer = servers[i];
    r.autoDetectRepository();
    servers[i] = r;
    repo = r;

    window.addEventListener('message', cappend, false);

    openWebSocket(r);
}
$("iframe").attr("src", "index.html?select=Add&view=true&origin=" + window.location.origin + "&server=" +
    r.selectedServer);

loadIdentity = function (callback) {
    if (queryParams.user == "self") {
        EcIdentityManager.readIdentities();
        EcIdentityManager.readContacts();
        if (EcIdentityManager.ids.length == 0) {
            loading("Generating identity...");
            EcPpk.generateKeyAsync(
                function (p1) {
                    identity = new EcIdentity();
                    identity.ppk = p1;
                    identity.displayName = "You";
                    EcIdentityManager.onIdentityChanged = EcIdentityManager.saveIdentities;
                    EcIdentityManager.addIdentity(identity);
                    callback();
                }
            );
        } else
            callback();
    } else if (queryParams.user == "wait") {
        var fun = function (evt) {
            var data = evt.data;
            if (data != null)
                data = JSON.parse(data);
            if (data.action == "identity") {
                identity = new EcIdentity();
                identity.ppk = EcPpk.fromPem(data.identity);
                identity.displayName = "You";
                EcIdentityManager.addIdentity(identity);
                callback();
            }
        };
        if (window.addEventListener) {
            window.addEventListener("message", fun, false);
        } else {
            window.attachEvent("onmessage", fun);
        }
    } else
        callback();
}
<commit_msg>Alternate WS endpoint (for weird non-reverse proxy stuff)<commit_after>/*
 Copyright 2017 Credential Engine and other contributing parties.

 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.
*/

var repo;

EcRepository.caching = true;
EcRepository.cachingSearch = false;

var frameworkId = "";

var servers = ["https://dev.cassproject.org/api/"];
var repo;

if (queryParams.server != null)
    servers = [queryParams.server];

var webSocketBackoff = 100;
var webSocketConnection = false;

openWebSocket = function (r) {
    var connection;
    // Instead of /ws/custom, will be /ws in next release.
    if (queryParams.webSocketOverride == null || queryParams.webSocketOverride === undefined)
        connection = new WebSocket(r.selectedServer.replace(/http/, "ws").replace(/api\//, "ws/custom"));
    else
        connection = new WebSocket(queryParams.webSocketOverride);

    connection.onopen = function () {
        console.log("WebSocket open.");
        webSocketConnection = true;
    };

    connection.onerror = function (error) {
        console.log(error);
    };

    //Re-establish connection on close.
    connection.onclose = function (evt) {
        console.log(evt);
        webSocketBackoff *= 2;
        webSocketConnection = false;
        setTimeout(function () {
            openWebSocket(r);
        }, webSocketBackoff);
    };

    connection.onmessage = function (e) {
        console.log('Server: ' + e.data);
        EcRepository.get(e.data, function (wut) {
            delete EcRepository.cache[wut.id];
            delete EcRepository.cache[wut.shortId()];
            if (new EcFramework().isA(wut.getFullType()))
                if (framework != null)
                    if (framework.id == wut.id) {
                        framework = new EcFramework();
                        framework.copyFrom(wut);
                        populateFramework();
                    }

            if (new EcCompetency().isA(wut.getFullType())) {
                var com = new EcCompetency();
                com.copyFrom(wut);
                refreshCompetency(com);
                if (selectedCompetency != null)
                    if (selectedCompetency.id == wut.id) {
                        selectedCompetency = com;
                        refreshSidebar();
                    }
            }
            if (new EcLevel().isA(wut.getFullType())) {
                var com = new EcLevel();
                com.copyFrom(wut);
                refreshCompetency(com);
                if (selectedCompetency != null)
                    if (selectedCompetency.id == wut.id) {
                        selectedCompetency = com;
                        refreshSidebar();
                    }
            }

        }, error);
    };

}

function cappend(event) {
    if (event.data.message == "selected") {
        console.log("I got " + event.data.selected.length + " selected items from the iframe");
        console.log(event.data.selected);
        appendCompetencies(event.data.selected, true);
        backPage();
    } else if (event.data.message == "back")
        backPage();
}

for (var i = 0; i < servers.length; i++) {
    var r = new EcRepository();
    r.selectedServer = servers[i];
    r.autoDetectRepository();
    servers[i] = r;
    repo = r;

    window.addEventListener('message', cappend, false);

    openWebSocket(r);
}
$("iframe").attr("src", "index.html?select=Add&view=true&origin=" + window.location.origin + "&server=" +
    r.selectedServer);

loadIdentity = function (callback) {
    if (queryParams.user == "self") {
        EcIdentityManager.readIdentities();
        EcIdentityManager.readContacts();
        if (EcIdentityManager.ids.length == 0) {
            loading("Generating identity...");
            EcPpk.generateKeyAsync(
                function (p1) {
                    identity = new EcIdentity();
                    identity.ppk = p1;
                    identity.displayName = "You";
                    EcIdentityManager.onIdentityChanged = EcIdentityManager.saveIdentities;
                    EcIdentityManager.addIdentity(identity);
                    callback();
                }
            );
        } else
            callback();
    } else if (queryParams.user == "wait") {
        var fun = function (evt) {
            var data = evt.data;
            if (data != null)
                data = JSON.parse(data);
            if (data.action == "identity") {
                identity = new EcIdentity();
                identity.ppk = EcPpk.fromPem(data.identity);
                identity.displayName = "You";
                EcIdentityManager.addIdentity(identity);
                callback();
            }
        };
        if (window.addEventListener) {
            window.addEventListener("message", fun, false);
        } else {
            window.attachEvent("onmessage", fun);
        }
    } else
        callback();
}
<|endoftext|>


<commit_before>/* Magic Mirror
 * Server
 *
 * By Michael Teeuw http://michaelteeuw.nl
 * MIT Licensed.
 */

var express = require("express");
var app = require("express")();
var server = require("http").Server(app);
var io = require("socket.io")(server);
var path = require("path");
var ipfilter = require("express-ipfilter").IpFilter;
var fs = require("fs");
var helmet = require("helmet");

var Server = function(config, callback) {

	var port = config.port;
	if (process.env.MM_PORT) {
		port = process.env.MM_PORT;
	}

	console.log("Starting server on port " + port + " ... ");

	server.listen(port, config.address ? config.address : null);

	if (config.ipWhitelist instanceof Array && config.ipWhitelist.length == 0) {
		console.info("You're using a full whitelist configuration to allow for all IPs")
	}

	app.use(function(req, res, next) {
		var result = ipfilter(config.ipWhitelist, {mode: config.ipWhitelist.length === 0 ? "deny" : "allow", log: false})(req, res, function(err) {
			if (err === undefined) {
				return next();
			}
			console.log(err.message);
			res.status(403).send("This device is not allowed to access your mirror.
 Please check your config.js or config.js.sample to change this.");
		});
	});
	app.use(helmet());

	app.use("/js", express.static(__dirname));
	var directories = ["/config", "/css", "/fonts", "/modules", "/vendor", "/translations", "/tests/configs"];
	var directory;
	for (var i in directories) {
		directory = directories[i];
		app.use(directory, express.static(path.resolve(global.root_path + directory)));
	}

	app.get("/version", function(req,res) {
		res.send(global.version);
	});

	app.get("/config", function(req,res) {
		res.send(config);
	});

	app.get("/", function(req, res) {
		var html = fs.readFileSync(path.resolve(global.root_path + "/index.html"), {encoding: "utf8"});
		html = html.replace("#VERSION#", global.version);

		configFile = "config/config.js";
		if (typeof(global.configuration_file) !== "undefined") {
		    configFile = global.configuration_file;
		}
		html = html.replace("#CONFIG_FILE#", configFile);

		res.send(html);
	});

	if (typeof callback === "function") {
		callback(app, io);
	}
};

module.exports = Server;
<commit_msg>Add warning color when are using full ip whitelist<commit_after>/* Magic Mirror
 * Server
 *
 * By Michael Teeuw http://michaelteeuw.nl
 * MIT Licensed.
 */

var express = require("express");
var app = require("express")();
var server = require("http").Server(app);
var io = require("socket.io")(server);
var path = require("path");
var ipfilter = require("express-ipfilter").IpFilter;
var fs = require("fs");
var helmet = require("helmet");
var Utils = require(__dirname + "/utils.js");

var Server = function(config, callback) {

	var port = config.port;
	if (process.env.MM_PORT) {
		port = process.env.MM_PORT;
	}

	console.log("Starting server on port " + port + " ... ");

	server.listen(port, config.address ? config.address : null);

	if (config.ipWhitelist instanceof Array && config.ipWhitelist.length == 0) {
		console.info(Utils.colors.warn("You're using a full whitelist configuration to allow for all IPs"))
	}

	app.use(function(req, res, next) {
		var result = ipfilter(config.ipWhitelist, {mode: config.ipWhitelist.length === 0 ? "deny" : "allow", log: false})(req, res, function(err) {
			if (err === undefined) {
				return next();
			}
			console.log(err.message);
			res.status(403).send("This device is not allowed to access your mirror.
 Please check your config.js or config.js.sample to change this.");
		});
	});
	app.use(helmet());

	app.use("/js", express.static(__dirname));
	var directories = ["/config", "/css", "/fonts", "/modules", "/vendor", "/translations", "/tests/configs"];
	var directory;
	for (var i in directories) {
		directory = directories[i];
		app.use(directory, express.static(path.resolve(global.root_path + directory)));
	}

	app.get("/version", function(req,res) {
		res.send(global.version);
	});

	app.get("/config", function(req,res) {
		res.send(config);
	});

	app.get("/", function(req, res) {
		var html = fs.readFileSync(path.resolve(global.root_path + "/index.html"), {encoding: "utf8"});
		html = html.replace("#VERSION#", global.version);

		configFile = "config/config.js";
		if (typeof(global.configuration_file) !== "undefined") {
		    configFile = global.configuration_file;
		}
		html = html.replace("#CONFIG_FILE#", configFile);

		res.send(html);
	});

	if (typeof callback === "function") {
		callback(app, io);
	}
};

module.exports = Server;
<|endoftext|>


<commit_before>/**
 * carousel
 * @authors Ping YF (koakumaping@163.com)
 * @date    2016-04-14 10:48:35
 * @version $Id$
 */

(function(factory) {
    "use strict";
    if(typeof exports === "object" && typeof module === "object") {
        module.exports = factory();
    } else if(typeof define === "function" && (define.amd || define.cmd)) {
        define(factory);
    } else {
        window.slider = factory();
    }
})(function(){
    'use strict';
    function slider (selector) {
        this.config = {
            autoPlayTime: 1, // 单位秒
            speed: 600,
            x: 0,
            xCurrent: 0,
            xEnd: 0,
            y: 0,
            yCurrent: 0,
            zIndex: 2,
            direction: 'stay'
        };

        // 定时器
        this.timer;
        this.isPaused = false

        // 选择器
        this.selector = document.querySelectorAll(selector)[0];
        this.length = this.selector.querySelectorAll('li').length;
        this.clientWidth = this.selector.clientWidth;
        this.isRunning = false;

        // 位置
        this.calPosition = 0;
        this.prevCalPosition;
        this.nextCalPosition;

        // 状态
        this.index = 0;
        this.indexPrev;
        this.indexNext;
        this.indexFlag = true;
        this.canMoveX = true;
        this.canMoveY = true;

        // 初始化元素
        this.li = this.selector.querySelectorAll('li');

        this.elment,
        this.elmentPrev,
        this.elmentNext;
        this.init();
    };

    slider.prototype = {
        init: function () {
            var self = this;
            self.addFocus();
            self.setActiveFocus();
            self.requestAnimationFrame();

            // 启动自动播放
            self.autoPlay()
            self.autoPause()

            self.selector.querySelectorAll('ul')[0].addEventListener('touchstart', function (event) {
                event.preventDefault();
                // 清空定时器
                clearInterval(self.timer)

                if (self.isRunning) {
                    return true;
                }

                self.config.x = event.changedTouches[0].pageX;
                self.config.y = event.changedTouches[0].pageY;
            });

            self.selector.querySelectorAll('ul')[0].addEventListener('touchmove', function (event) {
                event.preventDefault();
                if (self.isRunning) {
                    return true;
                }

                self.config.xCurrent = event.changedTouches[0].pageX;
                self.config.yCurrent = event.changedTouches[0].pageY;

                // 上下滑动
                if ( self.canMoveY ) {
                    window.scrollBy(0, self.config.y - self.config.yCurrent);
                    if (Math.abs(self.config.y - self.config.yCurrent) > 12) {
                        self.canMoveX = false;
                    }
                }

                // 左右滑动
                if (self.canMoveX) {
                    if (self.index === 0) {
                        self.indexPrev = self.length - 1;
                        self.indexFlag = false;
                    } else {
                        self.indexPrev = self.index - 1;
                    }

                    if (self.index >= self.length - 1) {
                        self.indexNext = 0;
                        self.indexFlag = false;
                    } else {
                        self.indexNext = self.index + 1;
                    }

                    self.calPosition = self.config.xCurrent - self.config.x;

                    // 防止超出
                    if ( self.length > 1 ){
                        if (self.calPosition >= self.clientWidth) {
                            self.calPosition = self.clientWidth;
                        }

                        if (self.calPosition <= - self.clientWidth) {
                            self.calPosition = - self.clientWidth;
                        }
                    } else {
                        return false
                    }

                    self.elment = self.li[self.index].querySelectorAll('img')[0];

                    var elmentPrev,
                        elmentNext;

                    if (self.calPosition >= 0) {
                        // 向右滑动
                        elmentPrev = self.li[self.indexPrev].querySelectorAll('img')[0];
                    } else {
                        // 向左滑动
                        elmentNext = self.li[self.indexNext].querySelectorAll('img')[0];
                    }

                    var elmentLi = self.li[self.index],
                        elmentLiPrev = self.li[self.indexPrev],
                        elmentLiNext = self.li[self.indexNext];

                    elmentLi.style.visibility = 'visible';

                    self.prevCalPosition = self.calPosition - self.clientWidth;
                    self.nextCalPosition = self.clientWidth + self.calPosition;

                    if ( Math.abs(self.calPosition) > 20 ) {
                        self.canMoveY = false;
                        if (elmentPrev) {
                            elmentLiPrev.style.visibility = 'visible';
                            elmentPrev.style.transform = 'translate3d(' + self.prevCalPosition +'px,0,0)';
                        }

                        if (elmentNext) {
                            elmentLiNext.style.visibility = 'visible';
                            elmentNext.style.transform = 'translate3d(' + self.nextCalPosition +'px,0,0)';
                        }

                        self.elment.style.transform = 'translate3d(' + self.calPosition +'px,0,0)';

                        // 向左滑动
                        if (self.calPosition > 0) {
                            self.config.direction = 'left';
                            if ( self.length > 2 ){
                                elmentLiNext.style.visibility = 'hidden';
                            }
                        } else if (self.calPosition < 0) {
                            self.config.direction = 'right';
                            if ( self.length > 2 ){
                                elmentLiPrev.style.visibility = 'hidden';
                            }
                        } else {
                            self.config.direction = 'stay';
                        }
                    }
                }
            });

            self.selector.querySelectorAll('ul')[0].addEventListener('touchend', function (event) {
                self.canMoveX = true;
                self.canMoveY = true;

                if (self.isRunning) {
                    return true;
                }

                switch (self.config.direction) {
                    case 'left':
                        self.prev();
                        self.config.direction = 'stay';
                        break;
                    case 'right':
                        self.next();
                        self.config.direction = 'stay';
                        break;
                    case 'stay':
                        self.stay();
                        break;
                }

                // 启动自动播放
                self.autoPlay()
            });
        },

        autoPlay: function () {
            var self = this

            if (!self.timer) {
                self.timer = setInterval(function () {
                    if (!self.isPaused) {
                        self.next()
                    }
                }, this.config.autoPlayTime * 1000)
            }
        },

        autoPause: function () {
            var self = this
            document.addEventListener('visibilitychange', function () {
                if(document.visibilityState === 'hidden') {
                    self.isPaused = true
                } else {
                    self.isPaused = false
                }
            })
        },

        prev: function () {

            var self = this;

            var indexPrev,
                indexFlag = true;

            if (self.index === 0) {
                indexPrev = self.length - 1;
                indexFlag = false;
            } else {
                indexPrev = self.index - 1;
            }

            var elment = self.li[self.index].querySelectorAll('img')[0],
                elmentPrev = self.li[self.indexPrev].querySelectorAll('img')[0];

            var elmentLi = self.li[self.index],
                elmentLiPrev = self.li[self.indexPrev];

            elmentLi.style.visibility = 'visible';
            elmentLiPrev.style.visibility = 'visible';

            var start = 0
            var _run = function () {
                self.isRunning = true;

                start ++
                self.prevCalPosition = self.easeOutCubic(start, self.prevCalPosition, self.clientWidth, self.config.speed);
                self.calPosition = self.easeOutCubic(start, self.calPosition, self.clientWidth, self.config.speed);

                elmentPrev.style.transform = 'translate3d(' + self.prevCalPosition +'px,0,0)';
                elment.style.transform = 'translate3d(' + self.calPosition +'px,0,0)';

                if (self.calPosition < self.clientWidth) {
                    requestAnimationFrame(_run);
                } else {
                    self.prevCalPosition = 0;
                    self.calPosition = 0;

                    elmentPrev.style.transform = 'translate3d(' + self.prevCalPosition +'px,0,0)';
                    elment.style.transform = 'translate3d(' + self.calPosition +'px,0,0)';

                    elmentLi.style.visibility = 'hidden';

                    self.isRunning = false;

                    if (!indexFlag) {
                        self.index = self.length - 1;
                    } else {
                        if (self.index > 0) {
                            self.index --;
                        }
                    }
                    self.setActiveFocus()
                }
            }

            _run();
        },

        next: function () {
            var self = this;

            var indexNext,
                indexFlag = true;

            if (self.index >= self.length - 1) {
                indexNext = 0;
                indexFlag = false;
            } else {
                indexNext = self.index + 1;
            }

            var elment =self.li[self.index].querySelector('img');
            var elmentNext = self.li[indexNext].querySelector('img');

            var elmentLi = self.li[self.index];
            var elmentLiNext = self.li[indexNext];

            elmentLi.style.visibility = 'visible';
            elmentLiNext.style.visibility = 'visible';

            // 初始化
            self.x = self.calPosition + self.clientWidth;  //prev

            var start = 0
            var _run = function () {
                self.isRunning = true;

                start ++
                self.x = self.easeOutCubic(start, self.x, -self.clientWidth, self.config.speed);
                self.calPosition = self.easeOutCubic(start, self.calPosition, -self.clientWidth, self.config.speed);

                elmentNext.style.transform = 'translate3d(' + self.x +'px,0,0)';
                elment.style.transform = 'translate3d(' + self.calPosition +'px,0,0)';

                if (self.calPosition > - self.clientWidth) {
                    requestAnimationFrame(_run);
                } else {
                    self.x = 0;
                    self.calPosition = 0;

                    elmentNext.style.transform = 'translate3d(' + self.x +'px,0,0)';
                    elment.style.transform = 'translate3d(' + self.calPosition +'px,0,0)';

                    elmentLi.style.visibility = 'hidden';

                    self.isRunning = false;

                    if (indexFlag) {
                        if (self.index < self.length - 1) {
                            self.index ++;
                        }
                    } else {
                        self.index = 0;
                    }
                    self.setActiveFocus()
                }
            }

            _run();

        },

        stay: function () {
            var self = this;
            self.isRunning = false;
        },

        // 添加指示器
        addFocus: function () {
            var self = this;
            var innerHtml = ''
            var baseHtml = ''
            var $focus = this.selector.querySelector('.focus-horizontal')

            for (var i = 0; i < self.length; ++i) {
                innerHtml += baseHtml
            }

            $focus.innerHTML = innerHtml
        },

        setActiveFocus: function () {

            var $bullets = this.selector.querySelectorAll('.focus-horizontal-bullet')

            for (var i = 0, l = $bullets.length; i < l; ++i) {
                if (i !== this.index) {
                    $bullets[i].className = 'focus-horizontal-bullet'
                } else {
                    $bullets[i].className = 'focus-horizontal-bullet active'
                }
            }
        },

        /*
         * t: current time（当前时间）；
         * b: beginning value（初始值）；
         * c: change in value（变化量）；
         * d: duration（持续时间）。
         * you can visit 'http://easings.net/zh-cn' to get effect
        */
        easeOutCubic: function(t, b, c, d) {
            return c * ((t = t/d - 1) * t * t + 1) + b;
        },

        requestAnimationFrame: function () {
            var lastTime = 0;
            var vendors = ['webkit', 'moz'];
            for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
                window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
                window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] ||    // name has changed in Webkit
                                              window[vendors[x] + 'CancelRequestAnimationFrame'];
            }

            if (!window.requestAnimationFrame) {
                window.requestAnimationFrame = function(callback, element) {
                    var currTime = new Date().getTime();
                    var timeToCall = Math.max(0, 16.7 - (currTime - lastTime));
                    var id = window.setTimeout(function() {
                        callback(currTime + timeToCall);
                    }, timeToCall);
                    lastTime = currTime + timeToCall;
                    return id;
                };
            }
            if (!window.cancelAnimationFrame) {
                window.cancelAnimationFrame = function(id) {
                    clearTimeout(id);
                };
            }
        }
    }

    return slider;
});<commit_msg>修正超链接无法点击问题<commit_after>/**
 * carousel
 * @authors Ping YF (koakumaping@163.com)
 * @date    2016-04-14 10:48:35
 * @version $Id$
 */

(function(factory) {
    "use strict";
    if(typeof exports === "object" && typeof module === "object") {
        module.exports = factory();
    } else if(typeof define === "function" && (define.amd || define.cmd)) {
        define(factory);
    } else {
        window.slider = factory();
    }
})(function(){
    'use strict';
    function slider (selector) {
        this.config = {
            autoPlayTime: 1, // 单位秒
            speed: 600,
            x: 0,
            xCurrent: 0,
            xEnd: 0,
            y: 0,
            yCurrent: 0,
            zIndex: 2,
            direction: 'stay'
        };

        // 定时器
        this.timer;
        this.isPaused = false

        // 选择器
        this.selector = document.querySelectorAll(selector)[0];
        this.length = this.selector.querySelectorAll('li').length;
        this.clientWidth = this.selector.clientWidth;
        this.isRunning = false;

        // 位置
        this.calPosition = 0;
        this.prevCalPosition;
        this.nextCalPosition;

        // 状态
        this.index = 0;
        this.indexPrev;
        this.indexNext;
        this.indexFlag = true;
        this.canMoveX = true;
        this.canMoveY = true;

        // 初始化元素
        this.li = this.selector.querySelectorAll('li');

        this.elment,
        this.elmentPrev,
        this.elmentNext;
        this.init();
    };

    slider.prototype = {
        init: function () {
            var self = this;
            self.addFocus();
            self.setActiveFocus();
            self.requestAnimationFrame();

            // 启动自动播放
            self.autoPlay()
            self.autoPause()

            self.selector.querySelectorAll('ul')[0].addEventListener('touchstart', function (event) {
                // 清空定时器
                clearInterval(self.timer)

                if (self.isRunning) {
                    return true;
                }

                self.config.x = event.changedTouches[0].pageX;
                self.config.y = event.changedTouches[0].pageY;
            });

            self.selector.querySelectorAll('ul')[0].addEventListener('touchmove', function (event) {
                event.preventDefault();
                if (self.isRunning) {
                    return true;
                }

                self.config.xCurrent = event.changedTouches[0].pageX;
                self.config.yCurrent = event.changedTouches[0].pageY;

                // 上下滑动
                if ( self.canMoveY ) {
                    window.scrollBy(0, self.config.y - self.config.yCurrent);
                    if (Math.abs(self.config.y - self.config.yCurrent) > 12) {
                        self.canMoveX = false;
                    }
                }

                // 左右滑动
                if (self.canMoveX) {
                    if (self.index === 0) {
                        self.indexPrev = self.length - 1;
                        self.indexFlag = false;
                    } else {
                        self.indexPrev = self.index - 1;
                    }

                    if (self.index >= self.length - 1) {
                        self.indexNext = 0;
                        self.indexFlag = false;
                    } else {
                        self.indexNext = self.index + 1;
                    }

                    self.calPosition = self.config.xCurrent - self.config.x;

                    // 防止超出
                    if ( self.length > 1 ){
                        if (self.calPosition >= self.clientWidth) {
                            self.calPosition = self.clientWidth;
                        }

                        if (self.calPosition <= - self.clientWidth) {
                            self.calPosition = - self.clientWidth;
                        }
                    } else {
                        return false
                    }

                    self.elment = self.li[self.index].querySelectorAll('img')[0];

                    var elmentPrev,
                        elmentNext;

                    if (self.calPosition >= 0) {
                        // 向右滑动
                        elmentPrev = self.li[self.indexPrev].querySelectorAll('img')[0];
                    } else {
                        // 向左滑动
                        elmentNext = self.li[self.indexNext].querySelectorAll('img')[0];
                    }

                    var elmentLi = self.li[self.index],
                        elmentLiPrev = self.li[self.indexPrev],
                        elmentLiNext = self.li[self.indexNext];

                    elmentLi.style.visibility = 'visible';

                    self.prevCalPosition = self.calPosition - self.clientWidth;
                    self.nextCalPosition = self.clientWidth + self.calPosition;

                    if ( Math.abs(self.calPosition) > 20 ) {
                        self.canMoveY = false;
                        if (elmentPrev) {
                            elmentLiPrev.style.visibility = 'visible';
                            elmentPrev.style.transform = 'translate3d(' + self.prevCalPosition +'px,0,0)';
                        }

                        if (elmentNext) {
                            elmentLiNext.style.visibility = 'visible';
                            elmentNext.style.transform = 'translate3d(' + self.nextCalPosition +'px,0,0)';
                        }

                        self.elment.style.transform = 'translate3d(' + self.calPosition +'px,0,0)';

                        // 向左滑动
                        if (self.calPosition > 0) {
                            self.config.direction = 'left';
                            if ( self.length > 2 ){
                                elmentLiNext.style.visibility = 'hidden';
                            }
                        } else if (self.calPosition < 0) {
                            self.config.direction = 'right';
                            if ( self.length > 2 ){
                                elmentLiPrev.style.visibility = 'hidden';
                            }
                        } else {
                            self.config.direction = 'stay';
                        }
                    }
                }
            });

            self.selector.querySelectorAll('ul')[0].addEventListener('touchend', function (event) {
                self.canMoveX = true;
                self.canMoveY = true;

                if (self.isRunning) {
                    return true;
                }

                switch (self.config.direction) {
                    case 'left':
                        self.prev();
                        self.config.direction = 'stay';
                        break;
                    case 'right':
                        self.next();
                        self.config.direction = 'stay';
                        break;
                    case 'stay':
                        self.stay();
                        break;
                }

                // 启动自动播放
                self.autoPlay()
            });
        },

        autoPlay: function () {
            var self = this

            if (!self.timer) {
                self.timer = setInterval(function () {
                    if (!self.isPaused) {
                        self.next()
                    }
                }, this.config.autoPlayTime * 1000)
            }
        },

        autoPause: function () {
            var self = this
            document.addEventListener('visibilitychange', function () {
                if(document.visibilityState === 'hidden') {
                    self.isPaused = true
                } else {
                    self.isPaused = false
                }
            })
        },

        prev: function () {

            var self = this;

            var indexPrev,
                indexFlag = true;

            if (self.index === 0) {
                indexPrev = self.length - 1;
                indexFlag = false;
            } else {
                indexPrev = self.index - 1;
            }

            var elment = self.li[self.index].querySelectorAll('img')[0],
                elmentPrev = self.li[self.indexPrev].querySelectorAll('img')[0];

            var elmentLi = self.li[self.index],
                elmentLiPrev = self.li[self.indexPrev];

            elmentLi.style.visibility = 'visible';
            elmentLiPrev.style.visibility = 'visible';

            var start = 0
            var _run = function () {
                self.isRunning = true;

                start ++
                self.prevCalPosition = self.easeOutCubic(start, self.prevCalPosition, self.clientWidth, self.config.speed);
                self.calPosition = self.easeOutCubic(start, self.calPosition, self.clientWidth, self.config.speed);

                elmentPrev.style.transform = 'translate3d(' + self.prevCalPosition +'px,0,0)';
                elment.style.transform = 'translate3d(' + self.calPosition +'px,0,0)';

                if (self.calPosition < self.clientWidth) {
                    requestAnimationFrame(_run);
                } else {
                    self.prevCalPosition = 0;
                    self.calPosition = 0;

                    elmentPrev.style.transform = 'translate3d(' + self.prevCalPosition +'px,0,0)';
                    elment.style.transform = 'translate3d(' + self.calPosition +'px,0,0)';

                    elmentLi.style.visibility = 'hidden';

                    self.isRunning = false;

                    if (!indexFlag) {
                        self.index = self.length - 1;
                    } else {
                        if (self.index > 0) {
                            self.index --;
                        }
                    }
                    self.setActiveFocus()
                }
            }

            _run();
        },

        next: function () {
            var self = this;

            var indexNext,
                indexFlag = true;

            if (self.index >= self.length - 1) {
                indexNext = 0;
                indexFlag = false;
            } else {
                indexNext = self.index + 1;
            }

            var elment =self.li[self.index].querySelector('img');
            var elmentNext = self.li[indexNext].querySelector('img');

            var elmentLi = self.li[self.index];
            var elmentLiNext = self.li[indexNext];

            elmentLi.style.visibility = 'visible';
            elmentLiNext.style.visibility = 'visible';

            // 初始化
            self.x = self.calPosition + self.clientWidth;  //prev

            var start = 0
            var _run = function () {
                self.isRunning = true;

                start ++
                self.x = self.easeOutCubic(start, self.x, -self.clientWidth, self.config.speed);
                self.calPosition = self.easeOutCubic(start, self.calPosition, -self.clientWidth, self.config.speed);

                elmentNext.style.transform = 'translate3d(' + self.x +'px,0,0)';
                elment.style.transform = 'translate3d(' + self.calPosition +'px,0,0)';

                if (self.calPosition > - self.clientWidth) {
                    requestAnimationFrame(_run);
                } else {
                    self.x = 0;
                    self.calPosition = 0;

                    elmentNext.style.transform = 'translate3d(' + self.x +'px,0,0)';
                    elment.style.transform = 'translate3d(' + self.calPosition +'px,0,0)';

                    elmentLi.style.visibility = 'hidden';

                    self.isRunning = false;

                    if (indexFlag) {
                        if (self.index < self.length - 1) {
                            self.index ++;
                        }
                    } else {
                        self.index = 0;
                    }
                    self.setActiveFocus()
                }
            }

            _run();

        },

        stay: function () {
            var self = this;
            self.isRunning = false;
        },

        // 添加指示器
        addFocus: function () {
            var self = this;
            var innerHtml = ''
            var baseHtml = ''
            var $focus = this.selector.querySelector('.focus-horizontal')

            for (var i = 0; i < self.length; ++i) {
                innerHtml += baseHtml
            }

            $focus.innerHTML = innerHtml
        },

        setActiveFocus: function () {

            var $bullets = this.selector.querySelectorAll('.focus-horizontal-bullet')

            for (var i = 0, l = $bullets.length; i < l; ++i) {
                if (i !== this.index) {
                    $bullets[i].className = 'focus-horizontal-bullet'
                } else {
                    $bullets[i].className = 'focus-horizontal-bullet active'
                }
            }
        },

        /*
         * t: current time（当前时间）；
         * b: beginning value（初始值）；
         * c: change in value（变化量）；
         * d: duration（持续时间）。
         * you can visit 'http://easings.net/zh-cn' to get effect
        */
        easeOutCubic: function(t, b, c, d) {
            return c * ((t = t/d - 1) * t * t + 1) + b;
        },

        requestAnimationFrame: function () {
            var lastTime = 0;
            var vendors = ['webkit', 'moz'];
            for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
                window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
                window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] ||    // name has changed in Webkit
                                              window[vendors[x] + 'CancelRequestAnimationFrame'];
            }

            if (!window.requestAnimationFrame) {
                window.requestAnimationFrame = function(callback, element) {
                    var currTime = new Date().getTime();
                    var timeToCall = Math.max(0, 16.7 - (currTime - lastTime));
                    var id = window.setTimeout(function() {
                        callback(currTime + timeToCall);
                    }, timeToCall);
                    lastTime = currTime + timeToCall;
                    return id;
                };
            }
            if (!window.cancelAnimationFrame) {
                window.cancelAnimationFrame = function(id) {
                    clearTimeout(id);
                };
            }
        }
    }

    return slider;
});<|endoftext|>


<commit_before>
var access_token = "";

function saveToken(accessToken) {
  access_token = accessToken;
}

// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {

  console.log('statusChangeCallback');
  console.log(response);

  // Logged into your app and Facebook.
  if (response.status === 'connected') {
    saveToken(response.authResponse.accessToken);
    getProfileInfo();
    updateView();
  } else if (response.status === 'not_authorized') {
    document.getElementById('status').innerHTML = 'Please log into this app.';
  } else {
    FB.login(function(response) {
      if (response.authResponse ) {
        saveToken(response.authResponse.accessToken);
        getProfileInfo();
        updateView();
      }
    }, {scope: 'user_about_me,user_location'});
  }
}

// This function is called when someone finishes with the Login
// Button.  See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
  FB.getLoginStatus(function(response) {
    statusChangeCallback(response);
  }, {scope: 'user_about_me,user_location'});
}

function getProfileInfo() {
  // FB.api('/me?field=name,id,location', function(response) {
  //   alert('Successful login for: ' + response.name);
  // });
  $.getJSON("http://127.0.0.1:8020/project-director/weather?token=" + access_token, function(result){
    //response data are now in the result variable
    console.log(result);
    // alert("ID: " + result.info.id);
    // alert("First name: "+ result.info.first_name);
    // alert("Location: "+ result.info.location);
  });
}

function send_request() {

  var myObject = new Object();
  myObject.token = access_token;

  var food_name = new Array("Arrosticini", "Piattone Gigante", "Paninazzo", "Carbonara", "Insalatina");
  var images = new Array(
    "http://www.hermestocchetti.com/sites/default/files/styles/fullsize/public/gallery/4-food-meat/p195bn87uf1gds1qrv1sc3o5c1nv34.jpg?itok=c1-Z_tur",
    "http://www.hermestocchetti.com/sites/default/files/styles/fullsize/public/gallery/4-food-meat/p195bn87ufbhf1fs0ou112464m7.jpg?itok=EKAbMm1x",
    "http://asiastreetfood.com/wp-content/uploads/2014/06/BanhMi.jpg",
    "https://c1.staticflickr.com/5/4001/4283223635_da5e247b5e_b.jpg",
    "https://c4.staticflickr.com/4/3709/9499573644_05a0e270fd_k.jpg"
    );

  var start = new Array(
    "Sei dimagrito rispetto a ieri, ",
    "Sei ingrassato rispetto a ieri, ",
    "Good work, ");
  var middle = new Array(
    "and because it is cloudy",
    "and because i am sad",
    "and because i am happy");
  var end = new Array(
    "you deserve:",
    "you are allowed to eat:",
    "today you have to eat:");

  var start_index = Math.floor((Math.random() * 3));
  var middle_index = Math.floor((Math.random() * 3));
  var end_index = Math.floor((Math.random() * 3));
  var food_index = Math.floor((Math.random() * 5));

  var congrats = start[start_index] + middle[middle_index] + end[end_index];

  // alert(access_token);

  // $.ajax({
  //   crossDomain: true,
  //   type:'POST',
  //   dataType: 'jsonp',
  //   url: "http://127.0.0.1:8000/project-director/facebook",
  //   data: JSON.stringify(myObject),
  //   success: function(data)
  //   {
  //     var obj = jQuery.parseJSON(data);
  //     alert(obj.id);
  //     alert(obj.fist_name);
  //     alert(obj.image_url);
  //     // $('body').append(data);
  //     // if(err == "Errore nell'invio dell'e-mail." || err == "E-mail non valida.") {
  //     //   $('#form-send-message').addClass('form-send-errors')
  //     // }
  //     // else {
  //     //   $('#form-send-message').addClass('form-send-success');
  //     // }
  //   }//,
  //   // error: function(error) {
  //   //   alert(error);
  //   // }
  // });

  // $.getJSON("http://127.0.0.1:8000/project-director/facebook?callback=?&token=" + access_token, function(result){
  //   //response data are now in the result variable
  //   console.log(result);
  //   // var obj = jQuery.parseJSON(result);
  //   // console.log("parsed");
  //   console.log(result.info);
  //   console.log(result.info.first_name);
  //   console.log(result.image.image_url);
  // });

  $('#form').hide();
  $('#flickr_bg').css('background-image', 'url("'+ images[food_index] +'")');
  $('#quote').text(congrats);
  $('.motivational_quote').show();
  $('#title').text(food_name[food_index]);
  $('.subtitle').hide();
  $('.center').addClass('results');
  $('.scroll_down').show();
  $('#second').show();
}

function succ(data) {
  var obj = jQuery.parseJSON(data);
  alert(obj.id);
  alert(obj.fist_name);
  alert(obj.image_url);
}

function updateView() {
  $('.fb-login').hide();
  $('#fb-image').show();
  $('#title').text("Hi Roberto. Insert your health profile!");
  $('.subtitle').text("Height is in cm while Weight is in kg.");
  $('#form').show();
}
<commit_msg>jsonp support added<commit_after>
var access_token = "";

function saveToken(accessToken) {
  access_token = accessToken;
}

// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {

  console.log('statusChangeCallback');
  console.log(response);

  // Logged into your app and Facebook.
  if (response.status === 'connected') {
    saveToken(response.authResponse.accessToken);
    getProfileInfo();
    updateView();
  } else if (response.status === 'not_authorized') {
    document.getElementById('status').innerHTML = 'Please log into this app.';
  } else {
    FB.login(function(response) {
      if (response.authResponse ) {
        saveToken(response.authResponse.accessToken);
        getProfileInfo();
        updateView();
      }
    }, {scope: 'user_about_me,user_location'});
  }
}

// This function is called when someone finishes with the Login
// Button.  See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
  FB.getLoginStatus(function(response) {
    statusChangeCallback(response);
  }, {scope: 'user_about_me,user_location'});
}

function getProfileInfo() {
  // FB.api('/me?field=name,id,location', function(response) {
  //   alert('Successful login for: ' + response.name);
  // });
  $.getJSON("http://127.0.0.1:8020/project-director/weather?callback=?&token=" + access_token, function(result){
    //response data are now in the result variable
    console.log(result);
    // alert("ID: " + result.info.id);
    // alert("First name: "+ result.info.first_name);
    // alert("Location: "+ result.info.location);
  });
}

function send_request() {

  var myObject = new Object();
  myObject.token = access_token;

  var food_name = new Array("Arrosticini", "Piattone Gigante", "Paninazzo", "Carbonara", "Insalatina");
  var images = new Array(
    "http://www.hermestocchetti.com/sites/default/files/styles/fullsize/public/gallery/4-food-meat/p195bn87uf1gds1qrv1sc3o5c1nv34.jpg?itok=c1-Z_tur",
    "http://www.hermestocchetti.com/sites/default/files/styles/fullsize/public/gallery/4-food-meat/p195bn87ufbhf1fs0ou112464m7.jpg?itok=EKAbMm1x",
    "http://asiastreetfood.com/wp-content/uploads/2014/06/BanhMi.jpg",
    "https://c1.staticflickr.com/5/4001/4283223635_da5e247b5e_b.jpg",
    "https://c4.staticflickr.com/4/3709/9499573644_05a0e270fd_k.jpg"
    );

  var start = new Array(
    "Sei dimagrito rispetto a ieri, ",
    "Sei ingrassato rispetto a ieri, ",
    "Good work, ");
  var middle = new Array(
    "and because it is cloudy",
    "and because i am sad",
    "and because i am happy");
  var end = new Array(
    "you deserve:",
    "you are allowed to eat:",
    "today you have to eat:");

  var start_index = Math.floor((Math.random() * 3));
  var middle_index = Math.floor((Math.random() * 3));
  var end_index = Math.floor((Math.random() * 3));
  var food_index = Math.floor((Math.random() * 5));

  var congrats = start[start_index] + middle[middle_index] + end[end_index];

  // alert(access_token);

  // $.ajax({
  //   crossDomain: true,
  //   type:'POST',
  //   dataType: 'jsonp',
  //   url: "http://127.0.0.1:8000/project-director/facebook",
  //   data: JSON.stringify(myObject),
  //   success: function(data)
  //   {
  //     var obj = jQuery.parseJSON(data);
  //     alert(obj.id);
  //     alert(obj.fist_name);
  //     alert(obj.image_url);
  //     // $('body').append(data);
  //     // if(err == "Errore nell'invio dell'e-mail." || err == "E-mail non valida.") {
  //     //   $('#form-send-message').addClass('form-send-errors')
  //     // }
  //     // else {
  //     //   $('#form-send-message').addClass('form-send-success');
  //     // }
  //   }//,
  //   // error: function(error) {
  //   //   alert(error);
  //   // }
  // });

  // $.getJSON("http://127.0.0.1:8000/project-director/facebook?callback=?&token=" + access_token, function(result){
  //   //response data are now in the result variable
  //   console.log(result);
  //   // var obj = jQuery.parseJSON(result);
  //   // console.log("parsed");
  //   console.log(result.info);
  //   console.log(result.info.first_name);
  //   console.log(result.image.image_url);
  // });

  $('#form').hide();
  $('#flickr_bg').css('background-image', 'url("'+ images[food_index] +'")');
  $('#quote').text(congrats);
  $('.motivational_quote').show();
  $('#title').text(food_name[food_index]);
  $('.subtitle').hide();
  $('.center').addClass('results');
  $('.scroll_down').show();
  $('#second').show();
}

function succ(data) {
  var obj = jQuery.parseJSON(data);
  alert(obj.id);
  alert(obj.fist_name);
  alert(obj.image_url);
}

function updateView() {
  $('.fb-login').hide();
  $('#fb-image').show();
  $('#title').text("Hi Roberto. Insert your health profile!");
  $('.subtitle').text("Height is in cm while Weight is in kg.");
  $('#form').show();
}
<|endoftext|>


<commit_before>var social = {
	linkedin: {
		usercallback: undefined,
		callback: function(data) {
			if(typeof this.usercallback !== undefined) {
				this.usercallback(data.count);
			}
		},
		process: function(url, callback) {
			this.usercallback = callback;
			$.getScript("https://www.linkedin.com/countserv/count/share?format=jsonp&callback=social.linkedin.callback&url=" + url);
		}
	},
	facebook: {
		process: function(url, callback) {
			$.get("https://graph.facebook.com/",{id: url},function(response, status){
				callback(response.share);
			});
		}
	},
	reddit: {
		process: function(domain, callback) {
			$.get("https://api.reddit.com/domain/" + domain,function(response, status){
				var results = response.data.children;
				var array = new Array();

				for(var i = 0; i < results.length; i++) {
					var url = results[i].data.url;
					var score = results[i].data.score;

					var old = array.find(function(v){return v.url === url});

					if(typeof old === "undefined") {
						var value = {
							url: url,
							score: score,
							count: 1
						};

						array.push(value);
					} else {
						old.score = old.score + score;
						old.count = old.count + 1;
					}
				}

				callback({
					items: array,
					count: array.reduce(function(total,current){return total + current.count;},0),
					score: array.reduce(function(total,current){return total + current.score;},0),
					find: function(url) {
						return this.items.find(function(item){return item.url === url})
					}
				});
			});
		}
	}
}

function intToString(integer) {
	if(isNaN(integer) || integer <= 0) {
		return "";
	} else if(integer < 1000) {
		return integer;
	} else if(integer < 1000000) {
	    return Math.round(integer / 1000) + "k";
	} else {
		return Math.round(integer / 1000000) + "m";
	}
}
<commit_msg>Update social.js<commit_after>var social = {
	linkedin: {
		usercallback: undefined,
		callback: function(data) {
			if(typeof this.usercallback !== undefined) {
				this.usercallback(data.count);
			}
		},
		process: function(url, callback) {
			this.usercallback = callback;
			$.getScript("https://www.linkedin.com/countserv/count/share?format=jsonp&callback=social.linkedin.callback&url=" + url);
		}
	},
	facebook: {
		process: function(url, callback) {
			$.get("https://graph.facebook.com/",{id: url},function(response, status){
				if(response.hasOwnProperty('share')) {
					callback(response.share);
				} else {
					callback(0);
				}
			});
		}
	},
	reddit: {
		process: function(domain, callback) {
			$.get("https://api.reddit.com/domain/" + domain,function(response, status){
				var results = response.data.children;
				var array = new Array();

				for(var i = 0; i < results.length; i++) {
					var url = results[i].data.url;
					var score = results[i].data.score;

					var old = array.find(function(v){return v.url === url});

					if(typeof old === "undefined") {
						var value = {
							url: url,
							score: score,
							count: 1
						};

						array.push(value);
					} else {
						old.score = old.score + score;
						old.count = old.count + 1;
					}
				}

				callback({
					items: array,
					count: array.reduce(function(total,current){return total + current.count;},0),
					score: array.reduce(function(total,current){return total + current.score;},0),
					find: function(url) {
						return this.items.find(function(item){return item.url === url})
					}
				});
			});
		}
	}
}

function intToString(integer) {
	if(isNaN(integer) || integer <= 0) {
		return "";
	} else if(integer < 1000) {
		return integer;
	} else if(integer < 1000000) {
	    return Math.round(integer / 1000) + "k";
	} else {
		return Math.round(integer / 1000000) + "m";
	}
}
<|endoftext|>