<commit_before>(function($)
{
  var buildListItem = function(image)
  {
     return $('
' +
              '' +
              '
' + image["source"].escapeHTML() + '
' +
              '
Created on: ' +
              '' + new Date(image["created_on"]["$date"]).toLocaleString() + '
' +
              '
Comments: ' +
              '' + image["comments_n"] + '
' +
              '
Score: ' +
              '' + image["score"]["up"] + ' up, ' +
              '' + image["score"]["down"] + ' down, ' +
              '' + image["score"]["fav"] + ' favorite(s)
' +
              '
');
  }

  var bindEvents = function(library, li)
  {
    var onSelect = $(library).data("jquery.library.options").onSelect;

    if(onSelect)
    {
      $(li).on("click", function()
      {
        onSelect($(this).data("guid"));

        $(library).data("jquery.library.selected", li);
      });
    }
  }

  var findGUID = function(a, guid)
  {
    var length = a.length;

    for(var i = 0; i < length; i++)
    {
      if(a[i]["guid"] == guid)
      {
        return i;
      }
    }

    return -1;
  }

  var methods =
  {
    update: function()
    {
      var lastUpdate = $(this).data("lastUpdate");

      if(lastUpdate == null || (new Date().getTime() - lastUpdate) / 1000 > $(this).data("jquery.library.options").requestLimit)
      {
        var opts = $(this).data("jquery.library.options");

        if(!opts.silent)
        {
          setTimeout(function() { $.mobile.loading("show"); }, 1);
        }

        methods.loadPage.apply(this, [0])
          .always(function()
          {
            if(!opts.silent)
            {
              setTimeout(function() { $.mobile.loading("hide"); }, 1);
            }
          });

        $(this).data("lastUpdate", new Date().getTime());
      }
    },
    nextPage: function(triggerNext)
    {
      var page = $(this).data("jquery.library.tail");
      var library = this;

      return methods.loadPage.apply(this, [page + 1, triggerNext])
        .done(function(images)
        {
          if(images.length > 0)
          {
            $(library).data("jquery.library.tail", page + 1);
          }
        });
    },
    loadPage: function(page, triggerNext)
    {
      var opts = $(this).data("jquery.library.options");
      var f = opts.onLoad;

      if(f)
      {
        var library = this;

        return f(page, $(this).data("jquery.library.options").pageSize)
          .done(function(images)
          {
            if(images && images.length > 0)
            {
              $(images).each(function()
              {
                methods.touch.apply(library, [this, true, false]);
              });

              if(opts.onCompare)
              {
                methods.sort.apply(library);
              }

              if(triggerNext)
              {
                methods.next.apply(library);
              }
            }
          })
          .fail(function()
          {
            if(!opts.silent)
            {
              navigator.notification.alert("Couldn't load images, please try again.", null, "Request failed", "Ok");
            }
          });
      }

      return null;
    },
    touch: function(image, insert, sort)
    {
      var opts = $(this).data("jquery.library.options");
      var objects = $(this).data("jquery.library.objects");
      var m = $(this).data("jquery.library.map");

      // test if image has already been inserted:
      var inserted = false;
      var li = m[image["guid"]];

      if(li)
      {
        var index = findGUID(objects, image["guid"]);
        var old = objects[index];

        // image found => update details (if necessary):
        if(old["comments_n"] != image["comments_n"]       ||
           old["score"]["up"] != image["score"]["up"]     ||
           old["score"]["down"] != image["score"]["down"] ||
           old["score"]["fav"] != image["score"]["fav"])
        {
          $(li).find('span[data-field="comments_n"]').html(image["comments_n"]);
          $(li).find('span[data-field="up"]').html(image["score"]["up"]);
          $(li).find('span[data-field="down"]').html(image["score"]["down"]);
          $(li).find('span[data-field="fav"]').html(image["score"]["fav"]);
        }
      }
      else if(insert)
      {
        // insert new image:
        objects.push(image);

        if(!sort)
        {
          var el = buildListItem(image);
          bindEvents(this, el);

          m[image["guid"]] = el;

          $(this).append(el);
        }

        if(opts.onNewImage)
        {
          opts.onNewImage(image);
        }

        inserted = true;
      }

      // sort list:
      var compare = opts.onCompare;

      if(sort && compare)
      {
        methods.sort.apply(this);
      }
      else
      {
        $(this).listview("refresh");
      }

      // load thumbnail:
      if(inserted)
      {
        var client = new MeatStore().createClient();
        var obj = this;

        client.getThumbnail(image["source"])
          .success(function(thumbnail)
          {
            $(obj).find('img[data-source="' + image["source"].escapeQuotes() + '"]').attr("src", thumbnail);
          })
          .fail(function(r)
          {
            $(obj).find('img[data-source="' + image["source"].escapeQuotes() + '"]').attr("src", "images/image-missing.png");
          });
      }
    },
    remove: function(image)
    {
      var li = $(this).find('li[data-guid="' + image["guid"] + '"]').first();

      if(li.get(0))
      {
        $(li).remove();
      }
    },
    clear: function()
    {
      var library = $(this);

      library.find("li").remove();
      library.listview("refresh");
      library.data("jquery.library.selected", null);
      library.data("jquery.library.tail", 0);
      library.data("jquery.library.objects", new Array());
      library.data("jquery.library.map", {});
    },
    sort: function()
    {
      var library = $(this);
      var compare = library.data("jquery.library.options").onCompare;

      if(compare)
      {
        var objects = library.data("jquery.library.objects");
        var m = library.data("jquery.library.map");

        objects.sort(compare);

        var old = library.find("li").detach();

        $.each(objects, function(i, image)
        {
          library.append(m[image["guid"]]);
        });

        library.listview("refresh");
      }
    },
    next: function()
    {
      var li = $(this).data("jquery.library.selected");
      var n = $(li).next();

      if(n && n.get(0))
      {
        $(n).click();
      }
      else
      {
        methods.nextPage.apply(this, [true]);
      }
    },
    prev: function(f)
    {
      var li = $(this).data("jquery.library.selected");
      var p = $(li).prev();
      var success = false;

      if(p && p.get(0))
      {
        $(p).click();
        success = true;
      }

      if(f)
      {
        f(success);
      }
    }
  };

  function createLibrary(obj, options)
  {
    var sel = $(obj);

    if(!sel.data("jquery.library"))
    {
      sel.data("jquery.library", true);
      sel.data("jquery.library.tail", 0);
      sel.data("jquery.library.objects", new Array());
      sel.data("jquery.library.map", {});
    }

    sel.data("jquery.library.options",
             $.extend({pageSize: 10, onLoad: null, onCompare: null, requestLimit: 0, onNewMessage: null, silent: false},
             options));
  }

  $.fn.library = function(args)
  {
    if(methods[args])
    {
      var parameters = Array.prototype.slice.call(arguments, 1);

      return this.each(function()
      {
        if($(this).data("jquery.library"))
        {
          methods[args].apply(this, parameters);

          return this;
        }
        else
        {
          return null;
        }
      });
    }
    else if(typeof args === 'object' || !args)
    {
      return this.each(function()
      {
        createLibrary(this, args);
      });
    }
  }
}(jQuery));
<commit_msg>jquery.library refresh() method, show message if library is empty<commit_after>(function($)
{
  var buildListItem = function(image)
  {
     return $('
' +
              '' +
              '
' + image["source"].escapeHTML() + '
' +
              '
Created on: ' +
              '' + new Date(image["created_on"]["$date"]).toLocaleString() + '
' +
              '
Comments: ' +
              '' + image["comments_n"] + '
' +
              '
Score: ' +
              '' + image["score"]["up"] + ' up, ' +
              '' + image["score"]["down"] + ' down, ' +
              '' + image["score"]["fav"] + ' favorite(s)
' +
              '
');
  }

  var bindEvents = function(library, li)
  {
    var onSelect = $(library).data("jquery.library.options").onSelect;

    if(onSelect)
    {
      $(li).on("click", function()
      {
        onSelect($(this).data("guid"));

        $(library).data("jquery.library.selected", li);
      });
    }
  }

  var findGUID = function(a, guid)
  {
    var length = a.length;

    for(var i = 0; i < length; i++)
    {
      if(a[i]["guid"] == guid)
      {
        return i;
      }
    }

    return -1;
  }

  var methods =
  {
    update: function()
    {
      var lastUpdate = $(this).data("lastUpdate");

      if(lastUpdate == null || (new Date().getTime() - lastUpdate) / 1000 > $(this).data("jquery.library.options").requestLimit)
      {
        var opts = $(this).data("jquery.library.options");

        if(!opts.silent)
        {
          setTimeout(function() { $.mobile.loading("show"); }, 1);
        }

        methods.loadPage.apply(this, [0])
          .always(function()
          {
            if(!opts.silent)
            {
              setTimeout(function() { $.mobile.loading("hide"); }, 1);
            }
          });

        $(this).data("lastUpdate", new Date().getTime());
      }
    },
    nextPage: function(triggerNext)
    {
      var page = $(this).data("jquery.library.tail");
      var library = this;

      return methods.loadPage.apply(this, [page + 1, triggerNext])
        .done(function(images)
        {
          if(images.length > 0)
          {
            $(library).data("jquery.library.tail", page + 1);
          }
        });
    },
    loadPage: function(page, triggerNext)
    {
      var opts = $(this).data("jquery.library.options");
      var f = opts.onLoad;

      if(f)
      {
        var library = this;

        return f(page, $(this).data("jquery.library.options").pageSize)
          .done(function(images)
          {
            if(images && images.length > 0)
            {
              $(images).each(function()
              {
                methods.touch.apply(library, [this, true, false]);
              });

              if(opts.onCompare)
              {
                methods.sort.apply(library);
              }

              if(triggerNext)
              {
                methods.next.apply(library);
              }
            }
          })
          .fail(function()
          {
            if(!opts.silent)
            {
              navigator.notification.alert("Couldn't load images, please try again.", null, "Request failed", "Ok");
            }
          });
      }

      return null;
    },
    touch: function(image, insert, sort)
    {
      var opts = $(this).data("jquery.library.options");
      var objects = $(this).data("jquery.library.objects");
      var m = $(this).data("jquery.library.map");

      // test if image has already been inserted:
      var inserted = false;
      var li = m[image["guid"]];

      if(li)
      {
        var index = findGUID(objects, image["guid"]);
        var old = objects[index];

        // image found => update details (if necessary):
        if(old["comments_n"] != image["comments_n"]       ||
           old["score"]["up"] != image["score"]["up"]     ||
           old["score"]["down"] != image["score"]["down"] ||
           old["score"]["fav"] != image["score"]["fav"])
        {
          $(li).find('span[data-field="comments_n"]').html(image["comments_n"]);
          $(li).find('span[data-field="up"]').html(image["score"]["up"]);
          $(li).find('span[data-field="down"]').html(image["score"]["down"]);
          $(li).find('span[data-field="fav"]').html(image["score"]["fav"]);
        }
      }
      else if(insert)
      {
        // insert new image:
        objects.push(image);

        if(!sort)
        {
          var el = buildListItem(image);
          bindEvents(this, el);

          m[image["guid"]] = el;

          $(this).append(el);
        }

        if(opts.onNewImage)
        {
          opts.onNewImage(image);
        }

        inserted = true;
      }

      // sort list:
      var compare = opts.onCompare;

      if(sort && compare)
      {
        methods.sort.apply(this);
      }
      else
      {
        methods.refresh.apply(this);
      }

      // load thumbnail:
      if(inserted)
      {
        var client = new MeatStore().createClient();
        var obj = this;

        client.getThumbnail(image["source"])
          .success(function(thumbnail)
          {
            $(obj).find('img[data-source="' + image["source"].escapeQuotes() + '"]').attr("src", thumbnail);
          })
          .fail(function(r)
          {
            $(obj).find('img[data-source="' + image["source"].escapeQuotes() + '"]').attr("src", "images/image-missing.png");
          });
      }
    },
    remove: function(image)
    {
      var li = $(this).find('li[data-guid="' + image["guid"] + '"]').first();

      if(li.get(0))
      {
        $(li).remove();
      }
    },
    clear: function()
    {
      var library = $(this);

      library.find("li").remove();
      library.data("jquery.library.selected", null);
      library.data("jquery.library.tail", 0);
      library.data("jquery.library.objects", new Array());
      library.data("jquery.library.map", {});

      methods.refresh.apply(this);
    },
    sort: function()
    {
      var library = $(this);
      var compare = library.data("jquery.library.options").onCompare;

      if(compare)
      {
        var objects = library.data("jquery.library.objects");
        var m = library.data("jquery.library.map");

        objects.sort(compare);

        var old = library.find("li").detach();

        $.each(objects, function(i, image)
        {
          library.append(m[image["guid"]]);
        });

        methods.refresh.apply(this);
      }
    },
    next: function()
    {
      var li = $(this).data("jquery.library.selected");
      var n = $(li).next();

      if(n && n.get(0))
      {
        $(n).click();
      }
      else
      {
        methods.nextPage.apply(this, [true]);
      }
    },
    prev: function(f)
    {
      var li = $(this).data("jquery.library.selected");
      var p = $(li).prev();
      var success = false;

      if(p && p.get(0))
      {
        $(p).click();
        success = true;
      }

      if(f)
      {
        f(success);
      }
    },
    refresh: function()
    {
      var library = $(this);
      var objects = library.data("jquery.library.objects");
      var el = library.data("jquery.library.emptyNotification");

      if(objects.length == 0 && !el)
      {
        var el = $("
This library is empty.
");

        library.append(el);
        library.data("jquery.library.emptyNotification", el);
      }
      else if(objects.length && el)
      {
        el.remove();
        library.data("jquery.library.emptyNotification", null);
      }

      library.listview("refresh");
    }
  };

  function createLibrary(obj, options)
  {
    var sel = $(obj);

    if(!sel.data("jquery.library"))
    {
      sel.data("jquery.library", true);
      sel.data("jquery.library.tail", 0);
      sel.data("jquery.library.objects", new Array());
      sel.data("jquery.library.map", {});
      sel.data("jquery.emptyNotification", null);

      methods.refresh.apply(obj);
    }

    sel.data("jquery.library.options",
             $.extend({pageSize: 10, onLoad: null, onCompare: null, requestLimit: 0, onNewMessage: null, silent: false},
             options));
  }

  $.fn.library = function(args)
  {
    if(methods[args])
    {
      var parameters = Array.prototype.slice.call(arguments, 1);

      return this.each(function()
      {
        if($(this).data("jquery.library"))
        {
          methods[args].apply(this, parameters);

          return this;
        }
        else
        {
          return null;
        }
      });
    }
    else if(typeof args === 'object' || !args)
    {
      return this.each(function()
      {
        createLibrary(this, args);
      });
    }
  }
}(jQuery));
<|endoftext|>


<commit_before>// Debug.js v3.4.0

//---------------------------------------------------------------------------
// ★Popup_Debugクラス  poptest関連のポップアップメニュー表示用
//---------------------------------------------------------------------------
ui.popupmgr.addpopup('debug',
{
	formname : 'testform',
	disable_remove : true,

	//------------------------------------------------------------------------------
	// makeForm() URL入力のポップアップメニューを作成する
	//------------------------------------------------------------------------------
	makeForm : function(){
		this.settitle("pop_test", "pop_test");

		this.addTextArea({name:"testarea", id:"testarea", cols:'40', rows:'16', wrap:'off'});
		this.form.testarea.style.fontSize = '10pt';
		this.addBR();

		var debug = ui.debug;
		if(ui.debugmode){
			this.addExecButton("テスト", "Test", function(){ debug.starttest();}, {name:'starttest'});
			this.addText(" ", " ");
		}

		this.addExecButton("T1", "T1", function(){ debug.perfeval();});
		this.addExecButton("T2", "T2", function(){ debug.painteval()});
		this.addExecButton("T3", "T3", function(){ debug.resizeeval()});
		this.addText(" ", " ");

		if(ui.debugmode){
			this.addExecButton("Perf", "Perf", function(){ debug.loadperf();});
		}
		if(pzpr.env.storage.localST){
			this.addExecButton("DB", "DB", function(){ debug.dispdatabase();});
		}
		this.addBR();

		this.addExecButton("Save", "Save", function(){ debug.filesave()});
		this.addExecButton("PBSave", "PBSave", function(){ debug.filesave_pencilbox()});
		this.addText(" ", " ");

		this.addExecButton("Load", "Load", function(){ debug.fileopen();});
		this.addExecButton("消去", "Cls", function(){ debug.erasetext();});
		this.addCancelButton();

		/* テスト用文字列出力要素を追加 */
		if(ui.debugmode && !getEL('testdiv')){
			var el = document.createElement('div');
			el.id = 'testdiv';
			el.style.textAlign  = 'left';
			el.style.fontSize   = '8pt';
			el.style.lineHeight = '100%';
			document.body.appendChild(el);
		}
	},

	remove : function(){
		/* removeさせない */
	},
	show : function(px,py){
		if(!this.pop){
			this.makeElement();
			this.makeForm();
			this.setEvent();
		}
		this.pop.style.display = 'inline';
		this.pop.style.left = '40px';
		this.pop.style.top  = '80px';
	}
});

//---------------------------------------------------------------------------
// ★Debugクラス  poptest関連の実行関数など
//---------------------------------------------------------------------------
ui.debug =
{
	extend : function(proto){
		for(var name in proto){ this[name] = proto[name];}
	},

	// debugmode===true時はオーバーライドされます
	keydown : function(ca){
		var kc = ui.puzzle.key;
		if(!ui.debugmode){
			if(kc.isALT && ca==='p'){ this.disppoptest();}
			else{ return false;}
		}
		else{
			if(ca=='F7'){ this.accheck1();}
			else if(kc.isALT  && ca==='p'){ this.disppoptest();}
			else if(kc.isCTRL && ca=='F9'){ this.starttest();}
			else if(kc.isCTRL && kc.isSHIFT && ca=='F10'){ this.all_test();}
			else{ return false;}
		}
		kc.stopEvent();	/* カーソルを移動させない */
		return true;
	},
	disppoptest : function(){
		ui.popupmgr.popups.debug.show();
	},

	starttest : function(){},

	filesave : function(){
		this.setTA(ui.puzzle.getFileData(pzpr.consts.FILE_PZPH));
	},
	filesave_pencilbox : function(){
		if(pzpr.url.info[ui.puzzle.pid].exists.kanpen){
			this.setTA(ui.puzzle.getFileData(pzpr.consts.FILE_PBOX));
		}
		else{
			this.setTA("");
		}
	},

	fileopen : function(){
		ui.puzzle.open(this.getTA());
	},

	erasetext : function(){
		this.setTA('');
		if(ui.debugmode){ getEL('testdiv').innerHTML = '';}
	},

	perfeval : function(){
		var ans = ui.puzzle.checker;
		this.timeeval("正答判定測定", function(){ ans.checkAns();});
	},
	painteval : function(){
		this.timeeval("描画時間測定", function(){ ui.puzzle.redraw();});
	},
	resizeeval : function(){
		this.timeeval("resize描画測定", function(){ ui.puzzle.adjustCanvasSize();});
	},
	timeeval : function(text,func){
		this.addTA(text);
		var count=0, old = pzpr.util.currentTime();
		while(pzpr.util.currentTime() - old < 3000){
			count++;

			func();
		}
		var time = pzpr.util.currentTime() - old;

		this.addTA("測定データ "+time+"ms / "+count+"回\n"+"平均時間   "+(time/count)+"ms")
	},

	dispdatabase : function(){
		var text = "";
		for(var i=0;i<localStorage.length;i++){
			var key = localStorage.key(i);
			if(key.match(/^pzprv3/)){
				text += (""+key+" "+localStorage[key]+"\n");
			}
		}
		this.setTA(text);
	},

	getTA : function(){ return document.testform.testarea.value;},
	setTA : function(str){ document.testform.testarea.value  = str;},
	addTA : function(str){ document.testform.testarea.value += (str+"\n");},

	includeDebugScript : function(filename){
		if(!!this.includedScript[filename]){ return;}
		var _script = document.createElement('script');
		_script.type = 'text/javascript';
		_script.src = ui.util.getpath()+'../tests/script/'+filename;
		document.body.appendChild(_script);
		this.includedScript[filename] = true;
	},
	includedScript : {}
};
<commit_msg>ui/Debug: IE8以下でform要素のname属性が変更できずエラーとなるのを修正しました<commit_after>// Debug.js v3.4.0

//---------------------------------------------------------------------------
// ★Popup_Debugクラス  poptest関連のポップアップメニュー表示用
//---------------------------------------------------------------------------
ui.popupmgr.addpopup('debug',
{
	formname : 'testform',
	disable_remove : true,

	//------------------------------------------------------------------------------
	// makeForm() URL入力のポップアップメニューを作成する
	//------------------------------------------------------------------------------
	makeForm : function(){
		this.settitle("pop_test", "pop_test");

		this.addTextArea({name:"testarea", id:"testarea", cols:'40', rows:'16', wrap:'off'});
		this.form.testarea.style.fontSize = '10pt';
		this.addBR();

		var debug = ui.debug;
		if(ui.debugmode){
			this.addExecButton("テスト", "Test", function(){ debug.starttest();}, {name:'starttest'});
			this.addText(" ", " ");
		}

		this.addExecButton("T1", "T1", function(){ debug.perfeval();});
		this.addExecButton("T2", "T2", function(){ debug.painteval()});
		this.addExecButton("T3", "T3", function(){ debug.resizeeval()});
		this.addText(" ", " ");

		if(ui.debugmode){
			this.addExecButton("Perf", "Perf", function(){ debug.loadperf();});
		}
		if(pzpr.env.storage.localST){
			this.addExecButton("DB", "DB", function(){ debug.dispdatabase();});
		}
		this.addBR();

		this.addExecButton("Save", "Save", function(){ debug.filesave()});
		this.addExecButton("PBSave", "PBSave", function(){ debug.filesave_pencilbox()});
		this.addText(" ", " ");

		this.addExecButton("Load", "Load", function(){ debug.fileopen();});
		this.addExecButton("消去", "Cls", function(){ debug.erasetext();});
		this.addCancelButton();

		/* テスト用文字列出力要素を追加 */
		if(ui.debugmode && !getEL('testdiv')){
			var el = document.createElement('div');
			el.id = 'testdiv';
			el.style.textAlign  = 'left';
			el.style.fontSize   = '8pt';
			el.style.lineHeight = '100%';
			document.body.appendChild(el);
		}
	},

	remove : function(){
		/* removeさせない */
	},
	show : function(px,py){
		if(!this.pop){
			this.makeElement();
			this.makeForm();
			this.setEvent();
		}
		this.pop.style.display = 'inline';
		this.pop.style.left = '40px';
		this.pop.style.top  = '80px';
	}
});

//---------------------------------------------------------------------------
// ★Debugクラス  poptest関連の実行関数など
//---------------------------------------------------------------------------
ui.debug =
{
	extend : function(proto){
		for(var name in proto){ this[name] = proto[name];}
	},

	// debugmode===true時はオーバーライドされます
	keydown : function(ca){
		var kc = ui.puzzle.key;
		if(!ui.debugmode){
			if(kc.isALT && ca==='p'){ this.disppoptest();}
			else{ return false;}
		}
		else{
			if(ca=='F7'){ this.accheck1();}
			else if(kc.isALT  && ca==='p'){ this.disppoptest();}
			else if(kc.isCTRL && ca=='F9'){ this.starttest();}
			else if(kc.isCTRL && kc.isSHIFT && ca=='F10'){ this.all_test();}
			else{ return false;}
		}
		kc.stopEvent();	/* カーソルを移動させない */
		return true;
	},
	disppoptest : function(){
		ui.popupmgr.popups.debug.show();
	},

	starttest : function(){},

	filesave : function(){
		this.setTA(ui.puzzle.getFileData(pzpr.consts.FILE_PZPH));
	},
	filesave_pencilbox : function(){
		if(pzpr.url.info[ui.puzzle.pid].exists.kanpen){
			this.setTA(ui.puzzle.getFileData(pzpr.consts.FILE_PBOX));
		}
		else{
			this.setTA("");
		}
	},

	fileopen : function(){
		ui.puzzle.open(this.getTA());
	},

	erasetext : function(){
		this.setTA('');
		if(ui.debugmode){ getEL('testdiv').innerHTML = '';}
	},

	perfeval : function(){
		var ans = ui.puzzle.checker;
		this.timeeval("正答判定測定", function(){ ans.checkAns();});
	},
	painteval : function(){
		this.timeeval("描画時間測定", function(){ ui.puzzle.redraw();});
	},
	resizeeval : function(){
		this.timeeval("resize描画測定", function(){ ui.puzzle.adjustCanvasSize();});
	},
	timeeval : function(text,func){
		this.addTA(text);
		var count=0, old = pzpr.util.currentTime();
		while(pzpr.util.currentTime() - old < 3000){
			count++;

			func();
		}
		var time = pzpr.util.currentTime() - old;

		this.addTA("測定データ "+time+"ms / "+count+"回\n"+"平均時間   "+(time/count)+"ms")
	},

	dispdatabase : function(){
		var text = "";
		for(var i=0;i<localStorage.length;i++){
			var key = localStorage.key(i);
			if(key.match(/^pzprv3/)){
				text += (""+key+" "+localStorage[key]+"\n");
			}
		}
		this.setTA(text);
	},

	getTA : function(){ return document.getElementById('testarea').value;},
	setTA : function(str){ document.getElementById('testarea').value  = str;},
	addTA : function(str){ document.getElementById('testarea').value += (str+"\n");},

	includeDebugScript : function(filename){
		if(!!this.includedScript[filename]){ return;}
		var _script = document.createElement('script');
		_script.type = 'text/javascript';
		_script.src = ui.util.getpath()+'../tests/script/'+filename;
		document.body.appendChild(_script);
		this.includedScript[filename] = true;
	},
	includedScript : {}
};
<|endoftext|>


<commit_before>/**
 * @author Alexey Kuzmin <alex.s.kuzmin@gmail.com>
 * @fileoverview JavaScript implementation of JSON Pointer.
 * @see http://tools.ietf.org/html/rfc6901
 */

;(function() {
  'use strict';

  /**
   * List of special characters and their escape sequences.
   * Special characters will be unescaped in order they are listed.
   * Section 3 of spec.
   * @type {Array.<Array.<string>>}
   * @const
   */
  var SPECIAL_CHARACTERS = [
    ['/', '~1'],
    ['~', '~0']
  ];

  /**
   * Tokens' separator in JSON pointer string.
   * Section 3 of spec.
   * @type {string}
   * @const
   */
  var TOKENS_SEPARATOR = '/';

  /**
   * Prefix for error messages.
   * @type {string}
   * @const
   */
  var ERROR_MESSAGE_PREFIX = 'JSON Pointer: ';

  /**
   * Validates non-empty pointer string.
   * @type {RegExp}
   * @const
   */
  var NON_EMPTY_POINTER_REGEXP = /(\/[^\/]*)+/;

  /**
   * Returns |target| object's value pointed by |pointer|, returns undefined
   * if |pointer| points to non-existing value.
   * If |pointer| is not provided returns curried function bound to |target|.
   * @param {!string} target JSON document.
   * @param {string=} pointer JSON Pointer string. Optional.
   * @return {(*|Function)} Some value or function.
   */
  function getPointedValue(target, pointer) {
    target = JSON.parse(target);

    var pointerIsValid = isValidJSONPointer(pointer);
    if (!pointerIsValid) {
      throw getError('Pointer is not valid.');
    }

    var tokensList = parsePointer(pointer);
    var token;
    var value = target;

    while (!isUndefined(value) && !isUndefined(token = tokensList.pop())) {
      value = getValue(value, token);
    }

    return value;
  }

  /**
   * Returns true if given |pointer| is valid, returns false otherwise.
   * @param {string} pointer
   * @returns {boolean} Whether pointer is valid.
   */
  function isValidJSONPointer(pointer) {
    switch (true) {
      case !isString(pointer):
        return false;

      case '' === pointer:
        return true;

      case NON_EMPTY_POINTER_REGEXP.test(pointer):
        return true;

      default:
        return false;
    }
  }

  /**
   * Returns tokens list for given |pointer|. List is reversed, e.g.
   *     '/simple/path' -> ['path', 'simple']
   * @param {!string} pointer JSON pointer string.
   * @returns {Array} List of tokens.
   */
  function parsePointer(pointer) {
    var tokens = pointer.split(TOKENS_SEPARATOR).reverse();
    tokens.pop();  // Last item is always an empty string in any valid pointer.
    return tokens;
  }

  /**
   * Decodes all escape sequences in given |rawReferenceToken|.
   * @param {!string} rawReferenceToken
   * @returns {string} Unescaped reference token.
   */
  function unescapeReferenceToken(rawReferenceToken) {
    var referenceToken = rawReferenceToken;
    var character;
    var escapeSequence;
    var replaceRegExp;

    SPECIAL_CHARACTERS.forEach(function(pair) {
      character = pair[0];
      escapeSequence = pair[1];
      replaceRegExp = new RegExp(escapeSequence, 'g');
      referenceToken = referenceToken.replace(replaceRegExp, character);
    });

    return referenceToken;
  }

  /**
   * Returns value pointed by |token| in evaluation |context|.
   * Throws an exception if any error occurs.
   * @param {*} context Current evaluation context.
   * @param {!string} token Unescaped reference token.
   * @returns {*} Some value of undefined if value if not found.
   */
  function getValue(context, token) {
    // Section 4 of spec.

    token = unescapeReferenceToken(token);

    if (isArray(context)) {
      if ('-' === token) {
        throw getError('Implementation does not support "-" token.');
      }
      if (!isNumber(token)) {
        throw getError('Non-number tokens cannot be used in array context.');
      }
      if (token.length > 1 && '0' === token[0]) {
        throw getError(
            'Token with leading zero cannot be used in array context.');
      }
      return context[token];
    }

    if (isObject(context)) {
      return context[token];
    }

    // Context is not an array and is not an object.
    // Token evaluation is not possible.
    return;  // undefined
  }

  /**
   * Returns Error instance for throwing.
   * @param {string} message Error message.
   * @returns {Error}
   */
  function getError(message) {
    return new Error(ERROR_MESSAGE_PREFIX + message);
  }

  function isObject(o) {
    return 'object' === typeof o && null !== o;
  }

  function isArray(a) {
    return Array.isArray(a);
  }

  function isNumber(n) {
    return !isNaN(Number(n));
  }

  function isString(s) {
    return 'string' === typeof s || s instanceof String;
  }

  function isUndefined(v) {
    return 'undefined' === typeof v;
  }

  // Expose API

  var jsonPointer = {
    get: getPointedValue
  };

  if ('object' === typeof exports) {
    // Node.js
    module.exports = jsonPointer;
  } else if ('function' === typeof define && define.amd) {
    // AMD
    define(function() {
      return jsonPointer;
    });
  } else {
    // Browser
    this.jsonPointer = jsonPointer;
  }

}).call((function() {
  'use strict';
  return this || (typeof window !== 'undefined' ? window : global);
})());
<commit_msg>Remove redundant line from JSDoc<commit_after>/**
 * @author Alexey Kuzmin <alex.s.kuzmin@gmail.com>
 * @fileoverview JavaScript implementation of JSON Pointer.
 * @see http://tools.ietf.org/html/rfc6901
 */

;(function() {
  'use strict';

  /**
   * List of special characters and their escape sequences.
   * Special characters will be unescaped in order they are listed.
   * Section 3 of spec.
   * @type {Array.<Array.<string>>}
   * @const
   */
  var SPECIAL_CHARACTERS = [
    ['/', '~1'],
    ['~', '~0']
  ];

  /**
   * Tokens' separator in JSON pointer string.
   * Section 3 of spec.
   * @type {string}
   * @const
   */
  var TOKENS_SEPARATOR = '/';

  /**
   * Prefix for error messages.
   * @type {string}
   * @const
   */
  var ERROR_MESSAGE_PREFIX = 'JSON Pointer: ';

  /**
   * Validates non-empty pointer string.
   * @type {RegExp}
   * @const
   */
  var NON_EMPTY_POINTER_REGEXP = /(\/[^\/]*)+/;

  /**
   * Returns |target| object's value pointed by |pointer|, returns undefined
   * if |pointer| points to non-existing value.
   * @param {!string} target JSON document.
   * @param {string=} pointer JSON Pointer string. Optional.
   * @return {(*|Function)} Some value or function.
   */
  function getPointedValue(target, pointer) {
    target = JSON.parse(target);

    var pointerIsValid = isValidJSONPointer(pointer);
    if (!pointerIsValid) {
      throw getError('Pointer is not valid.');
    }

    var tokensList = parsePointer(pointer);
    var token;
    var value = target;

    while (!isUndefined(value) && !isUndefined(token = tokensList.pop())) {
      value = getValue(value, token);
    }

    return value;
  }

  /**
   * Returns true if given |pointer| is valid, returns false otherwise.
   * @param {string} pointer
   * @returns {boolean} Whether pointer is valid.
   */
  function isValidJSONPointer(pointer) {
    switch (true) {
      case !isString(pointer):
        return false;

      case '' === pointer:
        return true;

      case NON_EMPTY_POINTER_REGEXP.test(pointer):
        return true;

      default:
        return false;
    }
  }

  /**
   * Returns tokens list for given |pointer|. List is reversed, e.g.
   *     '/simple/path' -> ['path', 'simple']
   * @param {!string} pointer JSON pointer string.
   * @returns {Array} List of tokens.
   */
  function parsePointer(pointer) {
    var tokens = pointer.split(TOKENS_SEPARATOR).reverse();
    tokens.pop();  // Last item is always an empty string in any valid pointer.
    return tokens;
  }

  /**
   * Decodes all escape sequences in given |rawReferenceToken|.
   * @param {!string} rawReferenceToken
   * @returns {string} Unescaped reference token.
   */
  function unescapeReferenceToken(rawReferenceToken) {
    var referenceToken = rawReferenceToken;
    var character;
    var escapeSequence;
    var replaceRegExp;

    SPECIAL_CHARACTERS.forEach(function(pair) {
      character = pair[0];
      escapeSequence = pair[1];
      replaceRegExp = new RegExp(escapeSequence, 'g');
      referenceToken = referenceToken.replace(replaceRegExp, character);
    });

    return referenceToken;
  }

  /**
   * Returns value pointed by |token| in evaluation |context|.
   * Throws an exception if any error occurs.
   * @param {*} context Current evaluation context.
   * @param {!string} token Unescaped reference token.
   * @returns {*} Some value of undefined if value if not found.
   */
  function getValue(context, token) {
    // Section 4 of spec.

    token = unescapeReferenceToken(token);

    if (isArray(context)) {
      if ('-' === token) {
        throw getError('Implementation does not support "-" token.');
      }
      if (!isNumber(token)) {
        throw getError('Non-number tokens cannot be used in array context.');
      }
      if (token.length > 1 && '0' === token[0]) {
        throw getError(
            'Token with leading zero cannot be used in array context.');
      }
      return context[token];
    }

    if (isObject(context)) {
      return context[token];
    }

    // Context is not an array and is not an object.
    // Token evaluation is not possible.
    return;  // undefined
  }

  /**
   * Returns Error instance for throwing.
   * @param {string} message Error message.
   * @returns {Error}
   */
  function getError(message) {
    return new Error(ERROR_MESSAGE_PREFIX + message);
  }

  function isObject(o) {
    return 'object' === typeof o && null !== o;
  }

  function isArray(a) {
    return Array.isArray(a);
  }

  function isNumber(n) {
    return !isNaN(Number(n));
  }

  function isString(s) {
    return 'string' === typeof s || s instanceof String;
  }

  function isUndefined(v) {
    return 'undefined' === typeof v;
  }

  // Expose API

  var jsonPointer = {
    get: getPointedValue
  };

  if ('object' === typeof exports) {
    // Node.js
    module.exports = jsonPointer;
  } else if ('function' === typeof define && define.amd) {
    // AMD
    define(function() {
      return jsonPointer;
    });
  } else {
    // Browser
    this.jsonPointer = jsonPointer;
  }

}).call((function() {
  'use strict';
  return this || (typeof window !== 'undefined' ? window : global);
})());
<|endoftext|>


<commit_before>function classificacao(event) {
    if (!event) {
        return false;
    }
    switch (event.classificacaoEtaria) {
        case 'Livre':
            return 'clivre';

        case '18 anos':
            return 'c18';

        case '16 anos':
            return 'c16';

        case '14 anos':
            return 'c14';

        case '12 anos':
            return 'c12';

        case '10 anos':
            return 'c10';
    }
}
angular.module('mapasculturais.controllers', [])

    .controller('eventsCtrl', [
        '$scope', 'mapas.service.event', 'FavoriteEvents', function ($scope, eventApi, FavoriteEvents) {
            var api = eventApi(window.config.url);
            var _limit = 25;
            var _page = 1;
            var _endData = false;
            var _lastGroup = null;
            var _now = moment().format('YMMDDHH') - 2;

            $scope.groups = [];
            $scope.notFound = false;

            $scope.filters = {};

            $scope.moreDataCanBeLoaded = function () {
                return !_endData;
            }

            $scope.loadMore = function () {
                var events;
                var params = {
                    '@limit': _limit,
                    '@page': _page
                };

                if($scope.filters.keyword){
                    params['@keyword'] = '%' + $scope.filters.keyword + '%';
                }

                if($scope.filters.linguagem){
                    params['term:linguagem'] = $IN($scope.filters.linguagem);
                }

                if($scope.filters.verified){
                    params['isVerified'] = $EQ('true');
                }

                if ($scope.findFunction) {
                    var entityId = $scope.findEntityId;
                    events = api[$scope.findFunction](entityId, $scope.filters.from, $scope.filters.to, params);
                } else {
                    events = api.find($scope.filters.from, $scope.filters.to, params);
                }

                _page++;

                events.then(function (rs) {
                    if (rs.length < _limit) {
                        _endData = true;
                    }
                    rs.forEach(function(event) {
                        event.favorite = FavoriteEvents.isFavorite(event);
                    })

                    if(_page === 2 && rs.length === 0){
                        $scope.notFound = true;
                    }

                    var _groups = api.group('YYYY-MM-DD HH:mm', rs);

                    _groups.forEach(function (e) {
                        if ($scope.filters.hidePast && e.date.format('YMMDDHH') < _now) {
                            return;
                        }

                        if (_lastGroup && _lastGroup.date.format('YYYY-MM-DD HH:mm') === e.date.format('YYYY-MM-DD HH:mm')) {
                            e.events.forEach(function (event) {
                                _lastGroup.events.push(event);
                            });
                        } else {
                            $scope.groups.push(e);
                        }
                        _lastGroup = e;
                    });
                    $scope.$broadcast('scroll.infiniteScrollComplete');

                });
            };

            $scope.applyFilters = function(){
                $scope.$broadcast('scroll.infiniteScrollComplete');
                $scope.groups = [];
                $scope.notFound = false;
                _page = 1;
                _endData = false;
            }

            $scope.showCalendar = function (group) {
                var numDays = 6
                return group.format('X') < moment().add(numDays, 'days').format('X')
            }

            $scope.classificacao = classificacao;

            $scope.favorite = FavoriteEvents.favorite
        }])

    .controller('eventCtrl', [
        '$scope', '$stateParams', 'mapas.service.event', 'FavoriteEvents', function ($scope, $stateParams, eventApi, FavoriteEvents) {
            var api = eventApi(window.config.url);
            api.util.applyMe.apply($scope);

            $scope.entity = null;

            api.findOne({id: $EQ($stateParams.entity)}).then(function (entity) {
                $scope.entity = entity;
            });

            $scope.favorite = FavoriteEvents.favorite;

            $scope.classificacao = classificacao;

        }])

    .controller('spacesCtrl', [
        '$scope', 'MenuState', 'mapas.service.space', function ($scope, MenuState, spaceApi) {
            var api = spaceApi(window.config.url);
            var _limit = 50;
            var _page = 1;
            var _endData = false;

            api.util.applyMe.apply($scope);

            MenuState.activeMenu('spaces');

            $scope.entities = [];

            $scope.filters = {
                keyword: ''
            };

            $scope.$watch('filters', function () {
                $scope.entities = [];
                _page = 1;
                _endData = false;
            });

            $scope.moreDataCanBeLoaded = function () {
                return !_endData;
            }

            $scope.loadMore = function(){
                var params = {
                    '@limit': _limit,
                    '@page': _page,
                    '@order': 'name ASC',
                    '@select': api._select + ',endereco'
                };

                if($scope.filters.keyword){
                    params['@keyword'] = $scope.filters.keyword;
                }

                _page++;

                api.find(params).then(function(rs){
                    if (rs.length < _limit) {
                        _endData = true;
                    }

                    rs.forEach(function(entity){
                        $scope.entities.push(entity);
                    });

                    $scope.$broadcast('scroll.infiniteScrollComplete');
                });
            }
        }])

    .controller('spaceCtrl', [
        '$scope', '$stateParams', 'mapas.service.space', 'mapas.service.event', function ($scope, $stateParams, spaceApi, eventApi) {
            var api = spaceApi(window.config.url);
            api.util.applyMe.apply($scope);

            $scope.entity = null;

            api.findOne({id: $EQ($stateParams.entity)}).then(function (entity) {
                $scope.entity = entity;
            });
        }])

    .controller('agentCtrl', [
        '$scope', '$stateParams', 'mapas.service.agent', 'mapas.service.event', function ($scope, $stateParams, agentApi, eventApi) {
            var api = agentApi(window.config.url);
            api.util.applyMe.apply($scope);

            $scope.entity = null;

            api.findOne({id: $EQ($stateParams.entity)}).then(function (entity) {
                $scope.entity = entity;
            });
        }])

    .controller('projectCtrl', [
        '$scope', '$stateParams', 'mapas.service.project', 'mapas.service.event', function ($scope, $stateParams, projectApi, eventApi) {
            var api = projectApi(window.config.url);
            api.util.applyMe.apply($scope);

            $scope.entity = null;

            api.findOne({id: $EQ($stateParams.entity)}).then(function (entity) {
                $scope.entity = entity;
            });
        }])

    .controller('mapCtrl', function ($scope, $ionicPlatform, MapState) {

        var map;

        $scope.map_state = MapState;

        $ionicPlatform.ready(function(MapState) {

            var map_wrapper = angular.element(document.querySelector("#map-wrapper"));
            $scope.frameHeight = map_wrapper[0].clientHeight;

            // Getting the map selector in DOM
            var div = document.getElementById("map_canvas");

            // Invoking Map using Google Map SDK v2 by dubcanada
            map = plugin.google.maps.Map.getMap(div, $scope.map_state.options);

            map.setClickable(true);
            // Capturing event when Map load are ready.
            map.addEventListener(plugin.google.maps.event.MAP_READY, function(){

                // Defining markers for demo
                // var markers = [{
                //     position: setPosition(-19.9178713, -43.9603117),
                //     title: "Marker 1"
                // }, {
                //     position: setPosition(-19.8363826, -43.9787167),
                //     title: "Marker 2"
                // }];
                //
                // // Bind markers
                // for (var i = 0; i < markers.length; i++) {
                //     map.addMarker({
                //         'marker': markers[i],
                //         'position': markers[i].position
                //     }, function(marker) {
                //
                //         // Defining event for each marker
                //         marker.on("click", function() {
                //             alert(marker.get('marker').title);
                //         });
                //
                //     });
                // }
            });

            // Function that return a LatLng Object to Map
            // function setPosition(lat, lng) {
            //     return new plugin.google.maps.LatLng(lat, lng);
            // }
      });
    })

    .controller('aboutCtrl', function ($scope) {

    })

    .controller('favoritesCtrl', ['$scope', 'MenuState', 'FavoriteEvents', function ($scope, MenuState, FavoriteEvents) {
        MenuState.activeMenu('map');

        $scope.events = FavoriteEvents.favorites;
        $scope.favorite = FavoriteEvents.favorite;
    }])

    .controller('messagesCtrl', function ($scope) {

    })

    .controller('navCtrl', function ($scope, MenuState, $location, $ionicSideMenuDelegate, $timeout, $ionicLoading) {

        $scope.show_filter_search_menu = true;
        $scope.show_share_buttom = false;
        $scope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
            // var new_location_path = newVal.split('#')[1];
            // var old_location_path = oldVal.split('#')[1];

            switch(toState.name){
                case 'menu.spaces':
                    MenuState.activeMenu('spaces');
                    break;
                case 'menu.space':
                    MenuState.activeMenu('spaces');
                    break;

                case 'menu.agents':
                    MenuState.activeMenu('agents');
                    break;
                case 'menu.agent':
                    MenuState.activeMenu('agents');
                    break;

                case 'menu.projects':
                    MenuState.activeMenu('projects');
                    break;
                case 'menu.project':
                    MenuState.activeMenu('projects');
                    break;

                case 'menu.events':
                    MenuState.activeMenu('events');
                    break;
                case 'menu.event':
                    MenuState.activeMenu('events');
                    break;

                case 'menu.map':
                    MenuState.activeMenu('map');
                    break;

                case 'menu.favorites':
                    MenuState.activeMenu('favorites');
                    break;

                case 'menu.about':
                    MenuState.activeMenu('about');
                    break;

            }

            if (toState.name == 'menu.events') {
                $scope.show_filter_search_menu = true;
            } else {
                $scope.show_filter_search_menu = false;
            }
            $ionicLoading.show();
        });

        $scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
            $ionicLoading.hide();
        });
    })
<commit_msg>pins dos espaços com eventos no mapa<commit_after>function classificacao(event) {
    if (!event) {
        return false;
    }
    switch (event.classificacaoEtaria) {
        case 'Livre':
            return 'clivre';

        case '18 anos':
            return 'c18';

        case '16 anos':
            return 'c16';

        case '14 anos':
            return 'c14';

        case '12 anos':
            return 'c12';

        case '10 anos':
            return 'c10';
    }
}
angular.module('mapasculturais.controllers', [])

    .controller('eventsCtrl', [
        '$scope', 'mapas.service.event', 'FavoriteEvents', function ($scope, eventApi, FavoriteEvents) {
            var api = eventApi(window.config.url);
            var _limit = 25;
            var _page = 1;
            var _endData = false;
            var _lastGroup = null;
            var _now = moment().format('YMMDDHH') - 2;

            $scope.groups = [];
            $scope.notFound = false;

            $scope.filters = {};

            $scope.moreDataCanBeLoaded = function () {
                return !_endData;
            }

            $scope.loadMore = function () {
                var events;
                var params = {
                    '@limit': _limit,
                    '@page': _page
                };

                if($scope.filters.keyword){
                    params['@keyword'] = '%' + $scope.filters.keyword + '%';
                }

                if($scope.filters.linguagem){
                    params['term:linguagem'] = $IN($scope.filters.linguagem);
                }

                if($scope.filters.verified){
                    params['isVerified'] = $EQ('true');
                }

                if ($scope.findFunction) {
                    var entityId = $scope.findEntityId;
                    events = api[$scope.findFunction](entityId, $scope.filters.from, $scope.filters.to, params);
                } else {
                    events = api.find($scope.filters.from, $scope.filters.to, params);
                }

                _page++;

                events.then(function (rs) {
                    if (rs.length < _limit) {
                        _endData = true;
                    }
                    rs.forEach(function(event) {
                        event.favorite = FavoriteEvents.isFavorite(event);
                    })

                    if(_page === 2 && rs.length === 0){
                        $scope.notFound = true;
                    }

                    var _groups = api.group('YYYY-MM-DD HH:mm', rs);

                    _groups.forEach(function (e) {
                        if ($scope.filters.hidePast && e.date.format('YMMDDHH') < _now) {
                            return;
                        }

                        if (_lastGroup && _lastGroup.date.format('YYYY-MM-DD HH:mm') === e.date.format('YYYY-MM-DD HH:mm')) {
                            e.events.forEach(function (event) {
                                _lastGroup.events.push(event);
                            });
                        } else {
                            $scope.groups.push(e);
                        }
                        _lastGroup = e;
                    });
                    $scope.$broadcast('scroll.infiniteScrollComplete');

                });
            };

            $scope.applyFilters = function(){
                $scope.$broadcast('scroll.infiniteScrollComplete');
                $scope.groups = [];
                $scope.notFound = false;
                _page = 1;
                _endData = false;
            }

            $scope.showCalendar = function (group) {
                var numDays = 6
                return group.format('X') < moment().add(numDays, 'days').format('X')
            }

            $scope.classificacao = classificacao;

            $scope.favorite = FavoriteEvents.favorite
        }])

    .controller('eventCtrl', [
        '$scope', '$stateParams', 'mapas.service.event', 'FavoriteEvents', function ($scope, $stateParams, eventApi, FavoriteEvents) {
            var api = eventApi(window.config.url);
            api.util.applyMe.apply($scope);

            $scope.entity = null;

            api.findOne({id: $EQ($stateParams.entity)}).then(function (entity) {
                $scope.entity = entity;
            });

            $scope.favorite = FavoriteEvents.favorite;

            $scope.classificacao = classificacao;

        }])

    .controller('spacesCtrl', [
        '$scope', 'MenuState', 'mapas.service.space', function ($scope, MenuState, spaceApi) {
            var api = spaceApi(window.config.url);
            var _limit = 50;
            var _page = 1;
            var _endData = false;

            api.util.applyMe.apply($scope);

            MenuState.activeMenu('spaces');

            $scope.entities = [];

            $scope.filters = {
                keyword: ''
            };

            $scope.$watch('filters', function () {
                $scope.entities = [];
                _page = 1;
                _endData = false;
            });

            $scope.moreDataCanBeLoaded = function () {
                return !_endData;
            }

            $scope.loadMore = function(){
                var params = {
                    '@limit': _limit,
                    '@page': _page,
                    '@order': 'name ASC',
                    '@select': api._select + ',endereco'
                };

                if($scope.filters.keyword){
                    params['@keyword'] = $scope.filters.keyword;
                }

                _page++;

                api.find(params).then(function(rs){
                    if (rs.length < _limit) {
                        _endData = true;
                    }

                    rs.forEach(function(entity){
                        $scope.entities.push(entity);
                    });

                    $scope.$broadcast('scroll.infiniteScrollComplete');
                });
            }
        }])

    .controller('spaceCtrl', [
        '$scope', '$stateParams', 'mapas.service.space', 'mapas.service.event', function ($scope, $stateParams, spaceApi, eventApi) {
            var api = spaceApi(window.config.url);
            api.util.applyMe.apply($scope);

            $scope.entity = null;

            api.findOne({id: $EQ($stateParams.entity)}).then(function (entity) {
                $scope.entity = entity;
            });
        }])

    .controller('agentCtrl', [
        '$scope', '$stateParams', 'mapas.service.agent', 'mapas.service.event', function ($scope, $stateParams, agentApi, eventApi) {
            var api = agentApi(window.config.url);
            api.util.applyMe.apply($scope);

            $scope.entity = null;

            api.findOne({id: $EQ($stateParams.entity)}).then(function (entity) {
                $scope.entity = entity;
            });
        }])

    .controller('projectCtrl', [
        '$scope', '$stateParams', 'mapas.service.project', 'mapas.service.event', function ($scope, $stateParams, projectApi, eventApi) {
            var api = projectApi(window.config.url);
            api.util.applyMe.apply($scope);

            $scope.entity = null;

            api.findOne({id: $EQ($stateParams.entity)}).then(function (entity) {
                $scope.entity = entity;
            });
        }])

    .controller('mapCtrl', ['$scope', '$ionicPlatform', 'MapState', 'mapas.service.space', function ($scope, $ionicPlatform, MapState, spaceApi) {
        var api = spaceApi(window.config.url);
        api.util.applyMe.apply($scope);
        var map;

        $scope.map_state = MapState;

        var _spaces = api.findByEvents({
            '@from': '2016-03-18',
            '@to': '2016-04-18'
        });

        $ionicPlatform.ready(function(MapState) {

            var map_wrapper = angular.element(document.querySelector("#map-wrapper"));
            $scope.frameHeight = map_wrapper[0].clientHeight;

            // Getting the map selector in DOM
            var div = document.getElementById("map_canvas");

            // Invoking Map using Google Map SDK v2 by dubcanada
            map = plugin.google.maps.Map.getMap(div, $scope.map_state.options);

            map.setClickable(true);
            // Capturing event when Map load are ready.
            map.addEventListener(plugin.google.maps.event.MAP_READY, function(){
                _spaces.then(function(spaces){
                    spaces.forEach(function(space){
                        var pin = {
                            title: space.name,
    //                        icon: iconName,
                            visible: true,
                            position: new plugin.google.maps.LatLng(
                                space.location.latitude,
                                space.location.longitude),
                        };

                        map.addMarker(pin, function(marker){
                            space.marker = marker;
//                            marker.addEventListener(
//                                plugin.google.maps.event.MARKER_CLICK,
//                                function(){
//                                    marker.hideInfoWindow();
//                                    map.setClickable(false);
//                                    $scope.showConfirm(space);
//                                });
                        });
                    });
                });
                // Defining markers for demo
                // var markers = [{
                //     position: setPosition(-19.9178713, -43.9603117),
                //     title: "Marker 1"
                // }, {
                //     position: setPosition(-19.8363826, -43.9787167),
                //     title: "Marker 2"
                // }];
                //
                // // Bind markers
                // for (var i = 0; i < markers.length; i++) {
                //     map.addMarker({
                //         'marker': markers[i],
                //         'position': markers[i].position
                //     }, function(marker) {
                //
                //         // Defining event for each marker
                //         marker.on("click", function() {
                //             alert(marker.get('marker').title);
                //         });
                //
                //     });
                // }
            });

            // Function that return a LatLng Object to Map
            // function setPosition(lat, lng) {
            //     return new plugin.google.maps.LatLng(lat, lng);
            // }
      });
    }])

    .controller('aboutCtrl', function ($scope) {

    })

    .controller('favoritesCtrl', ['$scope', 'MenuState', 'FavoriteEvents', function ($scope, MenuState, FavoriteEvents) {
        MenuState.activeMenu('map');

        $scope.events = FavoriteEvents.favorites;
        $scope.favorite = FavoriteEvents.favorite;
    }])

    .controller('messagesCtrl', function ($scope) {

    })

    .controller('navCtrl', function ($scope, MenuState, $location, $ionicSideMenuDelegate, $timeout, $ionicLoading) {

        $scope.show_filter_search_menu = true;
        $scope.show_share_buttom = false;
        $scope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
            // var new_location_path = newVal.split('#')[1];
            // var old_location_path = oldVal.split('#')[1];

            switch(toState.name){
                case 'menu.spaces':
                    MenuState.activeMenu('spaces');
                    break;
                case 'menu.space':
                    MenuState.activeMenu('spaces');
                    break;

                case 'menu.agents':
                    MenuState.activeMenu('agents');
                    break;
                case 'menu.agent':
                    MenuState.activeMenu('agents');
                    break;

                case 'menu.projects':
                    MenuState.activeMenu('projects');
                    break;
                case 'menu.project':
                    MenuState.activeMenu('projects');
                    break;

                case 'menu.events':
                    MenuState.activeMenu('events');
                    break;
                case 'menu.event':
                    MenuState.activeMenu('events');
                    break;

                case 'menu.map':
                    MenuState.activeMenu('map');
                    break;

                case 'menu.favorites':
                    MenuState.activeMenu('favorites');
                    break;

                case 'menu.about':
                    MenuState.activeMenu('about');
                    break;

            }

            if (toState.name == 'menu.events') {
                $scope.show_filter_search_menu = true;
            } else {
                $scope.show_filter_search_menu = false;
            }
            $ionicLoading.show();
        });

        $scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
            $ionicLoading.hide();
        });
    })
<|endoftext|>


<commit_before>angular.module('app.controllers', ['ngCordova','720kb.datepicker',])

.controller('accueilCtrl', ['$scope', '$stateParams', '$http', 'CustomFactory', 'BlankService',// The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller
// You can include any angular dependencies as parameters for this function
// TIP: Access Route Parameters for your page via $stateParams.parameterName
function ($scope, $stateParams, $http, CustomFactory, BlankService) {
		console.log("coucou");
		BlankService.sendMessage();
		$http({
  	method: 'GET',
  	url: 'http://NANTES-0156.sii.fr:4444/' + 'getAllEvent'
	}).then(function successCallback(response) {
		$scope.ListEvent = response.data.ArrayList;

		$scope.passEvent = function (event){
			CustomFactory.saveEvent(event);
		}
		console.log( $scope.ListEvent);
	}, function erroCallabck(response) {
		console.log("Il y a eu des erreurs");
		console.log(response);
		});

}])

.controller('rechercheCtrl', ['$scope', '$stateParams', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller
// You can include any angular dependencies as parameters for this function
// TIP: Access Route Parameters for your page via $stateParams.parameterName
function ($scope, $stateParams) {

}])

.controller('carteCtrl', ['$scope', '$stateParams', '$http','$compile','CustomFactory','$window',// The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller
// You can include any angular dependencies as parameters for this function
// TIP: Access Route Parameters for your page via $stateParams.parameterName
function ($scope, $stateParams, $http, $compile,CustomFactory,$window) {

	$scope.addMarker = function (pos, texte, numero){
		var mark = new google.maps.Marker({position:pos});
		mark.setMap($scope.map);
		var infoEvent = new google.maps.InfoWindow({
			content: "

" +
					"

" + texte + " Le " + numero + "

***

"
		});
		mark.addListener('click', function(){
			infoEvent.open($scope.map, mark);
		})
	}

	$scope.getDetailsEvent = function(event){
		CustomFactory.saveEvent(event);
		$window.location.href="/#/side-menu21/page13"
	}

	$http({
		method: 'GET',
		url: 'http://NANTES-0156.sii.fr:4444/' + 'getAllEvent'
	}).then(function successCallback(response) {
		$scope.ListEvent = response.data.ArrayList;

		var options = {timeout: 10000, enableHighAccuracy: true};
		var latLng = new google.maps.LatLng(47.2112216, -1.5570168);
		var mapOptions = {
				center: latLng,
				zoom: 15,
				mapTypeId: google.maps.MapTypeId.ROADMAP
			};
		$scope.map = new google.maps.Map(document.getElementById("map"), mapOptions);
		var infowindow = new google.maps.InfoWindow();
		google.maps.event.addListener($scope.map, 'click', function(evt) {
	    evt.stop()
	    console.log(evt.placeId);
			if (evt.placeId != null){
	    infowindow.setContent(evt.placeId+"<button type='button'>Creer un évenement</button>");
	    infowindow.setPosition(evt.latLng);
	    infowindow.open($scope.map);
		}
	  });

		var service = new google.maps.places.PlacesService($scope.map);

		$scope.addMarker = function (place,marker,i){
			marker.addListener('click', function() {
				var contentPlace = '

'+ place.name + '

'+ place.address_components[0].short_name + " " + place.address_components[1].short_name + " " + place.address_components[2].short_name +'

 ------------------------------------------------------------------------------------------------
';
				var contentEvent = '

'+ $scope.ListEvent[i-1].Name +'

'+ $scope.ListEvent[i-1].Description +'

'+ 'Du ' + $scope.ListEvent[i-1].Datestart + ' au ' + $scope.ListEvent[i-1].Dateend +'
 <button type="button" onclick="getDetailsEvent('+ $scope.ListEvent[i-1] +')">Voir l evenement</button>
';
				var compileEvent = $compile(contentEvent)($scope);
				infowindow.setContent(contentPlace + contentEvent);
				infowindow.open(map, this);
			});
		}
		for ( var identDorian=0; identDorian<$scope.ListEvent.length; identDorian++){
			service.getDetails({
				 placeId: $scope.ListEvent[identDorian].Placeid
			 }, function(place, status) {
				 if (status === google.maps.places.PlacesServiceStatus.OK) {
					 var marker = new google.maps.Marker({
						 map: $scope.map,
						 position: place.geometry.location
					 });
					 console.log(identDorian);
					 $scope.addMarker(place,marker,identDorian);
				 }
			 });
		}
	}, function erroCallabck(response) {
		console.log("Il y a eu des erreurs dans la map!")
	});

}])

.controller('footEnSalleCtrl', ['$scope', '$stateParams', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller
// You can include any angular dependencies as parameters for this function
// TIP: Access Route Parameters for your page via $stateParams.parameterName
function ($scope, $stateParams) {

  //sum to test jasmine/karma
  $scope.sum = function() {
   $scope.z = $scope.x + $scope.y;
  };

}])

.controller('afterworkCtrl', ['$scope', '$stateParams', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller
// You can include any angular dependencies as parameters for this function
// TIP: Access Route Parameters for your page via $stateParams.parameterName
function ($scope, $stateParams) {

}])

.controller('dejTechCtrl', ['$scope', '$stateParams', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller
// You can include any angular dependencies as parameters for this function
// TIP: Access Route Parameters for your page via $stateParams.parameterName
function ($scope, $stateParams) {

}])

.controller('menuCtrl', ['$scope', '$stateParams', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller
// You can include any angular dependencies as parameters for this function
// TIP: Access Route Parameters for your page via $stateParams.parameterName
function ($scope, $stateParams) {

}])

.controller('mesVenementsCtrl', ['$scope', '$stateParams', '$cordovaDatePicker',// The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller
// You can include any angular dependencies as parameters for this function
// TIP: Access Route Parameters for your page via $stateParams.parameterName
function ($scope, $stateParams, $cordovaDatePicker) {

}])

.controller('crErUnVenementCtrl', ['$scope', '$stateParams','$window', '$cordovaDatePicker', '$http','CustomFactory','ConnectedUserService',// The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller
// You can include any angular dependencies as parameters for this function
// TIP: Access Route Parameters for your page via $stateParams.parameterName
function ($scope, $stateParams, $window, $cordovaDatePicker, $http, CustomFactory, ConnectedUserService) {
	console.log("Creation d'un evenement");
	$scope.saveEvent = function(){
		var send = true;

		if(document.getElementById("selectedDate").value == ""){
			$scope.erreurDate = ": Date invalide"
			send= false;
		}else{
			$scope.erreurDate = ""
		}
		if(document.getElementById("horaireDebut").value == ""){
			$scope.erreurHoraireDebut = ": Heure invalide";
			send = false;
		}else{
			$scope.erreurHoraireDebut = "";
		}
		if(document.getElementById("horaireFin").value == ""){
			$scope.erreurHoraireFin = ": Heure invalide";
			send = false;
		}else{
			$scope.erreurHoraireFin = "";
		}
		if(document.getElementById("lieu").value == ""){
			$scope.erreurLieu = ": Lieu invalide";
			send = false;
		}else {
			$scope.erreurLieu = ""
		}

		if (send){
			var ownerToSend = ConnectedUserService.getConnectedUser();
			console.log(ownerToSend);
			$http({
				method: 'POST',
				url: 'http://localhost:4444/saveEvent',
				data: {
					Name: document.getElementById("nomEvenement").value,
					Datestart: document.getElementById("selectedDate").value + " " + document.getElementById("horaireDebut").value,
					Dateend: document.getElementById("selectedDate").value + " " + document.getElementById("horaireFin").value,
					Placeid: document.getElementById("lieu").value,
					Description: document.getElementById("description").value,
					Image: document.getElementById("image").value,
					Iscanceled: 0,
					Owner: ownerToSend
				}
			}).then(function successCallback(response) {
				console.log("message send");
				console.log(response.data.Event);
				CustomFactory.saveEvent(response.data.Event);
				$window.location.href = 'menu.detailsEvent';
			}, function erroCallabck(response) {
				console.log(response);
				console.log("Envoi formulaire creation d'evenement: Il y a eu des erreurs!");
			});
		}

	}

}])

.controller('suggestionCtrl', ['$scope', '$stateParams','$http','ConnectedUserService', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller
// You can include any angular dependencies as parameters for this function
// TIP: Access Route Parameters for your page via $stateParams.parameterName
function ($scope, $stateParams, $http, ConnectedUserService) {
  $http({
    method: 'GET',
    url: 'http://NANTES-0156.sii.fr:4444/' + '/getPerson?id=1'
  }).then(function successCallback(response) {
		ConnectedUserService.setConnectedUser(response.data.Person);
  }, function erroCallabck(response) {
    console.log("Il y a eu des erreurs!")
  });

}])

.controller('evaluerEvenementCtrl', ['$scope', '$stateParams', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller
// You can include any angular dependencies as parameters for this function
// TIP: Access Route Parameters for your page via $stateParams.parameterName
function ($scope, $stateParams) {

}])

.controller('detailsEventCtrl', ['$scope', '$stateParams', '$http','CustomFactory',// The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller
// You can include any angular dependencies as parameters for this function
// TIP: Access Route Parameters for your page via $stateParams.parameterName
function ($scope, $stateParams, $http, CustomFactory) {

	var event = CustomFactory.getEvent();
	$scope.getCommentMargin = function(owner){
		if (owner == null){
			return "0%";
		}else {
			return "5%";
		}
	}
	$scope.detailsParticipant = function(){
		var div = document.getElementById("participantDiv");
		if (div.style.display == 'none'){
			div.style.display = 'block';
		}else{
			div.style.display = 'none';
		}
	}
	$scope.TitleEvent = event.Name;
	$scope.sourceImgEvent = "img/defaultImage.jpg";
	$scope.descriptionEvent = event.Description;
	$scope.dateStartEvent = event.Datestart;

	$http({
		method: 'GET',
		url: 'http://NANTES-0156.sii.fr:4444/' + 'getCommentByEvent?id=' + $stateParams.id
	}).then(function successCallback(response) {
		$scope.ListComment = response.data;
	}, function erroCallabck(response) {
		console.log("Il y a eu des erreurs!")
	});

	$http({
		method: 'GET',
		url: 'http://localhost:4444/getAllParticipantById?id=' + $stateParams.id
	}).then(function successCallback(response) {
		$scope.ListParticipant = response.data;
		$scope.nbParticipants = $scope.ListParticipant.length;
	}, function erroCallabck(response) {
		console.log("Participant: Il y a eu des erreurs!")
	});
	/*console.log($stateParams.event)
	console.log($stateParams.event.Name)*/
}])
<commit_msg> gmaps with event<commit_after>angular.module('app.controllers', ['ngCordova','720kb.datepicker',])

.controller('accueilCtrl', ['$scope', '$stateParams', '$http', 'CustomFactory', 'BlankService',// The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller
// You can include any angular dependencies as parameters for this function
// TIP: Access Route Parameters for your page via $stateParams.parameterName
function ($scope, $stateParams, $http, CustomFactory, BlankService) {
		console.log("coucou");
		BlankService.sendMessage();
		$http({
  	method: 'GET',
  	url: 'http://NANTES-0156.sii.fr:4444/' + 'getAllEvent'
	}).then(function successCallback(response) {
		$scope.ListEvent = response.data.ArrayList;

		$scope.passEvent = function (event){
			CustomFactory.saveEvent(event);
		}
		console.log( $scope.ListEvent);
	}, function erroCallabck(response) {
		console.log("Il y a eu des erreurs");
		console.log(response);
		});

}])

.controller('rechercheCtrl', ['$scope', '$stateParams', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller
// You can include any angular dependencies as parameters for this function
// TIP: Access Route Parameters for your page via $stateParams.parameterName
function ($scope, $stateParams) {

}])

.controller('carteCtrl', ['$scope', '$stateParams', '$http','$compile','CustomFactory','$window',// The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller
// You can include any angular dependencies as parameters for this function
// TIP: Access Route Parameters for your page via $stateParams.parameterName
function ($scope, $stateParams, $http, $compile,CustomFactory,$window) {

	$scope.addMarker = function (pos, texte, numero){
		var mark = new google.maps.Marker({position:pos});
		mark.setMap($scope.map);
		var infoEvent = new google.maps.InfoWindow({
			content: "

" +
					"

" + texte + " Le " + numero + "

***

"
		});
		mark.addListener('click', function(){
			infoEvent.open($scope.map, mark);
		})
	}

	$http({
		method: 'GET',
		url: 'http://NANTES-0156.sii.fr:4444/' + 'getAllEvent'
	}).then(function successCallback(response) {
		$scope.ListEvent = response.data.ArrayList;

		var options = {timeout: 10000, enableHighAccuracy: true};
		var latLng = new google.maps.LatLng(47.2112216, -1.5570168);
		var mapOptions = {
				center: latLng,
				zoom: 15,
				mapTypeId: google.maps.MapTypeId.ROADMAP
			};
		$scope.map = new google.maps.Map(document.getElementById("map"), mapOptions);
		var infowindow = new google.maps.InfoWindow();
		var service = new google.maps.places.PlacesService($scope.map);

		google.maps.event.addListener($scope.map, 'click', function(evt) {
	    evt.stop();
			if (evt.placeId != null){
			service.getDetails({
				 placeId: evt.placeId
			 }, function(place, status) {
				 if (status === google.maps.places.PlacesServiceStatus.OK) {
					var contentPlace = '

'+ place.name + '

'+ place.address_components[0].short_name + " " + place.address_components[1].short_name + " " + place.address_components[2].short_name +'

 <button type=\"button\" onclick=\'CustomFactory.saveEvent('+ JSON.stringify(event) +'); $window.location.href=\"/#/side-menu21/page13\";\'>Creer un évenement</button>
';
					var compilePlace = $compile(contentPlace)($scope);
					infowindow.setContent(contentPlace);
	      	infowindow.setPosition(evt.latLng);
	      	infowindow.open($scope.map);
				}
	   	});
	 	}
	});

		$scope.addMarker = function (place,marker){
			marker.addListener('click', function() {
				//var event =  $scope.hashTable[place.place_id];
				var contentPlace = '

'+ place.name + '

'+ place.address_components[0].short_name + " " + place.address_components[1].short_name + " " + place.address_components[2].short_name +'

 ------------------------------------------------------------------------------------------------
';
				var contentEvent= "";
				for (var key in $scope.hashTable[place.place_id]){
					event = $scope.hashTable[place.place_id][key];
					contentEvent = contentEvent + '

'+ event.Name +'

'+ event.Description +'

'+ 'Du ' + event.Datestart + ' au ' + event.Dateend +'
 <button type=\'button\' onclick=\'CustomFactory.saveEvent('+ JSON.stringify(event) +'); $window.location.href=\"/#/side-menu21/page13\";\'>Voir l\'évenement</button>

';
				}
				var content = contentPlace + contentEvent
				var compileEvent = $compile(content)($scope);
				infowindow.setContent(content);
				infowindow.open(map, this);
			});
		}

		$scope.hashTable = {};
		for ( $scope.i=0; $scope.i<$scope.ListEvent.length; $scope.i++){
			if ($scope.hashTable[$scope.ListEvent[$scope.i].Placeid] == null){
				$scope.hashTable[$scope.ListEvent[$scope.i].Placeid] = [];
			}
			$scope.hashTable[$scope.ListEvent[$scope.i].Placeid].push($scope.ListEvent[$scope.i]);
			service.getDetails({
				 placeId: $scope.ListEvent[$scope.i].Placeid
			 }, function(place, status) {
				 if (status === google.maps.places.PlacesServiceStatus.OK) {
					 var marker = new google.maps.Marker({
						 map: $scope.map,
						 position: place.geometry.location
					 });
					 $scope.addMarker(place,marker);
				 }
			 });

		}
	}, function erroCallabck(response) {
		console.log("Il y a eu des erreurs dans la map!")
	});

}])

.controller('footEnSalleCtrl', ['$scope', '$stateParams', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller
// You can include any angular dependencies as parameters for this function
// TIP: Access Route Parameters for your page via $stateParams.parameterName
function ($scope, $stateParams) {

  //sum to test jasmine/karma
  $scope.sum = function() {
   $scope.z = $scope.x + $scope.y;
  };

}])

.controller('afterworkCtrl', ['$scope', '$stateParams', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller
// You can include any angular dependencies as parameters for this function
// TIP: Access Route Parameters for your page via $stateParams.parameterName
function ($scope, $stateParams) {

}])

.controller('dejTechCtrl', ['$scope', '$stateParams', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller
// You can include any angular dependencies as parameters for this function
// TIP: Access Route Parameters for your page via $stateParams.parameterName
function ($scope, $stateParams) {

}])

.controller('menuCtrl', ['$scope', '$stateParams', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller
// You can include any angular dependencies as parameters for this function
// TIP: Access Route Parameters for your page via $stateParams.parameterName
function ($scope, $stateParams) {

}])

.controller('mesVenementsCtrl', ['$scope', '$stateParams', '$cordovaDatePicker',// The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller
// You can include any angular dependencies as parameters for this function
// TIP: Access Route Parameters for your page via $stateParams.parameterName
function ($scope, $stateParams, $cordovaDatePicker) {

}])

.controller('crErUnVenementCtrl', ['$scope', '$stateParams','$window', '$cordovaDatePicker', '$http','CustomFactory','ConnectedUserService',// The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller
// You can include any angular dependencies as parameters for this function
// TIP: Access Route Parameters for your page via $stateParams.parameterName
function ($scope, $stateParams, $window, $cordovaDatePicker, $http, CustomFactory, ConnectedUserService) {
	console.log("Creation d'un evenement");
	$scope.saveEvent = function(){
		var send = true;

		if(document.getElementById("selectedDate").value == ""){
			$scope.erreurDate = ": Date invalide"
			send= false;
		}else{
			$scope.erreurDate = ""
		}
		if(document.getElementById("horaireDebut").value == ""){
			$scope.erreurHoraireDebut = ": Heure invalide";
			send = false;
		}else{
			$scope.erreurHoraireDebut = "";
		}
		if(document.getElementById("horaireFin").value == ""){
			$scope.erreurHoraireFin = ": Heure invalide";
			send = false;
		}else{
			$scope.erreurHoraireFin = "";
		}
		if(document.getElementById("lieu").value == ""){
			$scope.erreurLieu = ": Lieu invalide";
			send = false;
		}else {
			$scope.erreurLieu = ""
		}

		if (send){
			var ownerToSend = ConnectedUserService.getConnectedUser();
			console.log(ownerToSend);
			$http({
				method: 'POST',
				url: 'http://localhost:4444/saveEvent',
				data: {
					Name: document.getElementById("nomEvenement").value,
					Datestart: document.getElementById("selectedDate").value + " " + document.getElementById("horaireDebut").value,
					Dateend: document.getElementById("selectedDate").value + " " + document.getElementById("horaireFin").value,
					Placeid: document.getElementById("lieu").value,
					Description: document.getElementById("description").value,
					Image: document.getElementById("image").value,
					Iscanceled: 0,
					Owner: ownerToSend
				}
			}).then(function successCallback(response) {
				console.log("message send");
				console.log(response.data.Event);
				CustomFactory.saveEvent(response.data.Event);
				$window.location.href = 'menu.detailsEvent';
			}, function erroCallabck(response) {
				console.log(response);
				console.log("Envoi formulaire creation d'evenement: Il y a eu des erreurs!");
			});
		}

	}

}])

.controller('suggestionCtrl', ['$scope', '$stateParams','$http','ConnectedUserService', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller
// You can include any angular dependencies as parameters for this function
// TIP: Access Route Parameters for your page via $stateParams.parameterName
function ($scope, $stateParams, $http, ConnectedUserService) {
  $http({
    method: 'GET',
    url: 'http://NANTES-0156.sii.fr:4444/' + '/getPerson?id=1'
  }).then(function successCallback(response) {
		ConnectedUserService.setConnectedUser(response.data.Person);
  }, function erroCallabck(response) {
    console.log("Il y a eu des erreurs!")
  });

}])

.controller('evaluerEvenementCtrl', ['$scope', '$stateParams', // The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller
// You can include any angular dependencies as parameters for this function
// TIP: Access Route Parameters for your page via $stateParams.parameterName
function ($scope, $stateParams) {

}])

.controller('detailsEventCtrl', ['$scope', '$stateParams', '$http','CustomFactory',// The following is the constructor function for this page's controller. See https://docs.angularjs.org/guide/controller
// You can include any angular dependencies as parameters for this function
// TIP: Access Route Parameters for your page via $stateParams.parameterName
function ($scope, $stateParams, $http, CustomFactory) {

	var event = CustomFactory.getEvent();
	$scope.getCommentMargin = function(owner){
		if (owner == null){
			return "0%";
		}else {
			return "5%";
		}
	}
	$scope.detailsParticipant = function(){
		var div = document.getElementById("participantDiv");
		if (div.style.display == 'none'){
			div.style.display = 'block';
		}else{
			div.style.display = 'none';
		}
	}
	$scope.TitleEvent = event.Name;
	$scope.sourceImgEvent = "img/defaultImage.jpg";
	$scope.descriptionEvent = event.Description;
	$scope.dateStartEvent = event.Datestart;

	$http({
		method: 'GET',
		url: 'http://NANTES-0156.sii.fr:4444/' + 'getCommentByEvent?id=' + $stateParams.id
	}).then(function successCallback(response) {
		$scope.ListComment = response.data;
	}, function erroCallabck(response) {
		console.log("Il y a eu des erreurs!")
	});

	$http({
		method: 'GET',
		url: 'http://localhost:4444/getAllParticipantById?id=' + $stateParams.id
	}).then(function successCallback(response) {
		$scope.ListParticipant = response.data;
		$scope.nbParticipants = $scope.ListParticipant.length;
	}, function erroCallabck(response) {
		console.log("Participant: Il y a eu des erreurs!")
	});
	/*console.log($stateParams.event)
	console.log($stateParams.event.Name)*/
}])
<|endoftext|>


<commit_before>angular.module('sheHacksApp.controllers', ['LocalStorageModule'])

    .controller('MenuController', function ($scope, $rootScope, Platform, MenuService) {
        $scope.list = MenuService.all();

        $scope.$on('$viewContentLoaded', function () {
            $rootScope.noNetwork = !hasNetworkConnectivity();
        });

        $scope.openLeft = function () {
            $scope.sideMenuController.toggleLeft();
        };

        $scope.closeMenu = function () {
            $scope.sideMenuController.close();
        }

        Platform.ready(function () {
            // hide the status bar using the StatusBar plugin
            StatusBar.hide();
        });

    })

    .controller('VenueController', function ($scope, $rootScope, EventsService) {
        $scope.title = "Venue & Map";
        $rootScope.noNetwork = false;

        EventsService.getEvents().then(function (success) {
            $scope.event = success[0];
            $scope.firstDay = $scope.event.eventDays[0];
            $scope.secondDay = $scope.event.eventDays[1];
        }, function (error) {
            console.log("error: " + error);
            $scope.updateStatus = "Unable to retrieve latest data";
        }, function (update) {
            $scope.event = update[0];
            $scope.firstDay = $scope.event.eventDays[0];
            $scope.secondDay = $scope.event.eventDays[1];
        });

        $scope.$on('$viewContentLoaded', function () {
            // We need to check for connection status before attempting to connect to the google maps API otherwise bad things happen
            if (hasNetworkConnectivity()) {
                init();
            } else {
                $rootScope.noNetwork = true;
                console.log("No network detected, cannot initialize map")
            }
        });

        function init() {
            console.log("initializing google maps")

            var googlePos = new google.maps.LatLng(-33.8665433, 151.1956316);

            //TODO: fix map centering to allow for infoWindow
            var mapOptions = {
                center: googlePos,
                zoom: 16,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

            var marker = new google.maps.Marker({
                position: googlePos,
                map: map,
                title: 'Google Sydney'
            });

            var infowindow = new google.maps.InfoWindow({
                content: "
Google Sydney
"
            });

            // Stop the side bar from dragging when mousedown/tapdown on the map
            google.maps.event.addDomListener(document.getElementById('map-canvas'), 'mousedown', function (e) {
                e.preventDefault();
                return false;
            });

            $scope.map = map;
//            infowindow.open(map, marker);
        };

    })

    .controller('SponsorsController', function ($scope, SponsorsService) {
        $scope.title = "Sponsors";

        SponsorsService.getSponsors().then(function (success) {
            $scope.sponsors = success;
        }, function (error) {
            console.log("error: " + error);
            $scope.updateStatus = "Unable to retrieve latest data";
        }, function (update) {
            $scope.sponsors = update;
        });

        // opens links in browser instead of on top of app
        $scope.openLink = function (link) {
            console.log(link);
            window.open('http://' + link, '_system');
        };

        $scope.onRefresh = refreshPageContent(SponsorsService.getSponsors, $scope, "sponsors");
    })

    .controller('ProgramController', function ($scope, ProgramService) {
        $scope.title = "Program";

        ProgramService.getProgram().then(function (success) {
            $scope.schedule = success;
        }, function (error) {
            $scope.updateStatus = "Unable to retrieve latest data";
        }, function (update) {
            $scope.schedule = update;
        });

        $scope.onRefresh = refreshPageContent(ProgramService.getProgram, $scope, "schedule");
    })

    .controller('PrizesController', function ($scope, PrizesService) {
        $scope.title = "Prize Categories";
        PrizesService.getPrizes().then(function (data) {
            $scope.prizes = data;
        }, function (error) {
            $scope.updateStatus = "Unable to retrieve latest data";
        }, function (update) {
            $scope.prizes = update;
        });

        $scope.onRefresh = refreshPageContent(PrizesService.getPrizes, $scope, "prizes");

    })

    .controller('AboutController', function ($scope, CreditsService) {
        $scope.title = "About";

        CreditsService.getCredits().then(function (data) {
            $scope.people = data;
        }, function (error) {
            $scope.updateStatus = "Unable to retrieve latest data";
        }, function (update) {
            $scope.people = update;
        });

        $scope.onRefresh = refreshPageContent(CreditsService.getCredits, $scope, "people");
    });

function refreshPageContent(promise, $scope, collectionName) {
    return function() {
        console.log("in refresh page content") ;
        promise().then(function(success) {
            $scope[collectionName] = success;
        });
        $scope.$broadcast('scroll.refreshComplete');
    };
}

//Think we're all good now. Have added the cordova network plugin
function hasNetworkConnectivity() {
    console.log("navigator.onLine " + navigator.onLine);
    return navigator.onLine;
}
<commit_msg>fixes #36 but the map doesn't seem to re-draw correctly<commit_after>angular.module('sheHacksApp.controllers', ['LocalStorageModule'])

    .controller('MenuController', function ($scope, $rootScope, Platform, MenuService) {
        $scope.list = MenuService.all();

        $scope.openLeft = function () {
            $scope.sideMenuController.toggleLeft();
        };

        $scope.closeMenu = function () {
            $scope.sideMenuController.close();
        }

        Platform.ready(function () {
            // hide the status bar using the StatusBar plugin
            try {
                StatusBar.hide();
            } catch (e) {
                console.log("Cannot find StatusBar")
            }
        });

    })

    .controller('VenueController', function ($scope, $rootScope, EventsService) {
        $scope.title = "Venue & Map";

        EventsService.getEvents().then(function (success) {
            $scope.event = success[0];
            $scope.firstDay = $scope.event.eventDays[0];
            $scope.secondDay = $scope.event.eventDays[1];
        }, function (error) {
            console.log("error: " + error);
            $scope.updateStatus = "Unable to retrieve latest data";
        }, function (update) {
            $scope.event = update[0];
            $scope.firstDay = $scope.event.eventDays[0];
            $scope.secondDay = $scope.event.eventDays[1];
        });

        $rootScope.$watch('noNetwork', function() {
            console.log("watch fired");
            toggleMapVisibility();
        });

        $scope.$on('$viewContentLoaded', function () {
            toggleMapVisibility();
        });

        function toggleMapVisibility() {
            // We need to check for connection status before attempting to connect to the google maps API otherwise bad things happen
            if (!$rootScope.noNetwork) {
                console.log("Network detected, initializing map")
                init();
            } else {
                console.log("No network detected, cannot initialize map")
            }
        }

        function init() {
            var googlePos = new google.maps.LatLng(-33.8665433, 151.1956316);

            //TODO: fix map centering to allow for infoWindow
            var mapOptions = {
                center: googlePos,
                zoom: 16,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

            var marker = new google.maps.Marker({
                position: googlePos,
                map: map,
                title: 'Google Sydney'
            });

            var infowindow = new google.maps.InfoWindow({
                content: "
Google Sydney
"
            });

            // Stop the side bar from dragging when mousedown/tapdown on the map
            google.maps.event.addDomListener(document.getElementById('map-canvas'), 'mousedown', function (e) {
                e.preventDefault();
                return false;
            });

            $scope.map = map;
//            infowindow.open(map, marker);
        };

    })

    .controller('SponsorsController', function ($scope, SponsorsService) {
        $scope.title = "Sponsors";

        SponsorsService.getSponsors().then(function (success) {
            $scope.sponsors = success;
        }, function (error) {
            console.log("error: " + error);
            $scope.updateStatus = "Unable to retrieve latest data";
        }, function (update) {
            $scope.sponsors = update;
        });

        // opens links in browser instead of on top of app
        $scope.openLink = function (link) {
            console.log(link);
            window.open('http://' + link, '_system');
        };

        $scope.onRefresh = refreshPageContent(SponsorsService.getSponsors, $scope, "sponsors");
    })

    .controller('ProgramController', function ($scope, ProgramService) {
        $scope.title = "Program";

        ProgramService.getProgram().then(function (success) {
            $scope.schedule = success;
        }, function (error) {
            $scope.updateStatus = "Unable to retrieve latest data";
        }, function (update) {
            $scope.schedule = update;
        });

        $scope.onRefresh = refreshPageContent(ProgramService.getProgram, $scope, "schedule");
    })

    .controller('PrizesController', function ($scope, PrizesService) {
        $scope.title = "Prize Categories";
        PrizesService.getPrizes().then(function (data) {
            $scope.prizes = data;
        }, function (error) {
            $scope.updateStatus = "Unable to retrieve latest data";
        }, function (update) {
            $scope.prizes = update;
        });

        $scope.onRefresh = refreshPageContent(PrizesService.getPrizes, $scope, "prizes");

    })

    .controller('AboutController', function ($scope, CreditsService) {
        $scope.title = "About";

        CreditsService.getCredits().then(function (data) {
            $scope.people = data;
        }, function (error) {
            $scope.updateStatus = "Unable to retrieve latest data";
        }, function (update) {
            $scope.people = update;
        });

        $scope.onRefresh = refreshPageContent(CreditsService.getCredits, $scope, "people");
    });

function refreshPageContent(promise, $scope, collectionName) {
    return function() {
        console.log("in refresh page content") ;
        promise().then(function(success) {
            $scope[collectionName] = success;
        });
        $scope.$broadcast('scroll.refreshComplete');
    };
}<|endoftext|>