<commit_before>/*
		=========================================================================================
 		*
		*	SwipeListener
 		*
 		=========================================================================================
		*----------------------------------------------------------------------------------------
 		*
 		*	listen to swipe events within an element - for desktop & mobile/touch
 		*
 		=========================================================================================
		*
		*   author          >>  Christopher Miles
		*
		*   site            >>  http://ChristopherMil.es
		*   github          >>  http://github.com/creatologist
		*
		=========================================================================================
*/

//===============================================================================================
//-----------------------------------------------------------------------------------------------

var SwipeListener = function( element, options, finishCallback ) {
	this.element = element;

	this.startTime;

	this.offsetX = element.offsetLeft;
	this.offsetY = element.offsetTop;

	this.reset();

	this.minX = 0;
	this.minY = 0;

	this.deltaX = 0;
	this.deltaY = 0;

	this.width = element.offsetWidth;
	this.height = element.offsetHeight;

	this.options = options || {};

	if ( this.element.addEventListener) {
	    this.element.addEventListener('mousedown', this, false);
	    this.element.addEventListener('touchstart', this, false);

	    this.element.addEventListener('drag', this, false);
	    this.element.addEventListener('touchmove', this, false);

	    window.addEventListener('mouseup', this, false);
	    window.addEventListener('touchleave', this, false);
	    window.addEventListener('touchcancel', this, false);

	    // if using window.ontouchend already, add our func into old func
	    var self = this;
	    if ( window.ontouchend ) {
	    	var rand = 'ontouchend' + Math.random();
	    	window[ rand ] = window.ontouchend;
	    	window.ontouchend = function( e ) {
	    		window[ rand ].call( e );
	    		self.onTouchEnd( e );
	    	};
	    } else {
	    	window.ontouchend = function( e ) {
	    		self.onTouchEnd( e );
	    	};
	    }

	    //this.element.addEventListener('click', this, false);
	    window.addEventListener('resize', this, false);
	}

	if ( this.options.minX ) this.minX = this.options.minX / this.width;
	if ( this.options.minY ) this.minY = this.options.minY / this.height;

	if ( this.options.minXPercent ) this.minX = this.options.minXPercent;
	if ( this.options.minYPercent ) this.minY = this.options.minYPercent;

	this.onResize();

	if ( typeof options == 'function' ) options( this );
	else if ( finishCallback && typeof finishCallback == 'function' ) finishCallback( this );
};

SwipeListener.prototype = {
	reset: function() {
		this.x = 0;
		this.y = 0;

		this.startX = 0;
		this.startY = 0;

		this.endX = 0;
		this.endY = 0;

		this.globalX = 0;
		this.globalY = 0;

		this.globalStartX = 0;
		this.globalStartY = 0;

		this.globalEndX = 0;
		this.globalEndY = 0;
	},
	isTouchDevice: function() {
		return 'ontouchstart' in window || 'onmsgesturechange' in window;
	},

	handleEvent: function(e) {
	    switch (e.type) {
	    	case 'mousedown':
	    	case 'touchstart': this.onTouchStart(e); break;

	    	case 'drag':
	    	case 'mousemove':
	    	case 'touchmove': this.onTouchMove(e); break;

	    	case 'mouseup':
	    	case 'touchcancel':
	    	case 'touchleave':
	    	case 'touchend': this.onTouchEnd(e); break;

	    	case 'resize': this.onResize( e ); break;
	    }
	},

	onTouchStart : function( e ) {
		//e.preventDefault();
		//e.stopPropagation();
		this.startTime = new Date();

		if ( e.touches && e.touches[0] ) {
			this.globalStartX = e.touches[0].pageX;
			this.globalStartY = e.touches[0].pageY;
		} else {
			this.globalStartX = e.x;
			this.globalStartY = e.y;
		}

		this.startX = this.globalStartX - this.offsetX;
		this.startY = this.globalStartY - this.offsetY;

		if ( this.options.onTouchStart ) this.options.onTouchStart( this );
	},
	onTouchMove : function( e ) {

		e.preventDefault();
		//e.stopPropagation();
		if ( e.touches && e.touches[0] ) {
			this.globalX = e.touches[0].pageX;
			this.globalY = e.touches[0].pageY;
		} else {
			this.globalX = e.x;
			this.globalY = e.y;
		}

		this.x = this.globalX - this.offsetX;
		this.y = this.globalY - this.offsetY;

		if ( this.options.onTouchMove ) this.options.onTouchMove( this );
	},
	onTouchEnd : function( e ) {
		//e.preventDefault();
		//e.stopPropagation();
		var dTime = new Date() - this.startTime;

		if ( e.touches && e.touches[0] ) {
			this.globalEndX = e.touches[0].pageX;
			this.globalEndY = e.touches[0].pageY;
		} else {
			this.globalEndX = e.x;
			this.globalEndY = e.y;
		}

		this.endX = this.globalEndX - this.offsetX;
		this.endY = this.globalEndY - this.offsetY;

		var dX = this.globalEndX - this.globalStartX;
		var dY = this.globalEndY - this.globalStartY;

		this.deltaX = dX;
		this.deltaY = dY;

		var x = Math.abs( dX );
		var y = Math.abs( dY );

		var pX = x / this.width;
		var pY = y / this.height;

		if ( this.options.onTouchEnd ) this.options.onTouchEnd( this );

		if ( x > y ) {

			if ( this.minX < pX ) {
				if ( dX < 0 ) {
					if ( this.options.onSwipeLeft ) {
						 this.options.onSwipeLeft( this );
					}
				} else {
					if ( this.options.onSwipeRight ) {
						this.options.onSwipeRight( this );
					}
				}
			}
		} else {

			if ( this.minY < pY ) {
				if ( dY < 0 ) {
					if ( this.options.onSwipeUp ) {
						this.options.onSwipeUp( this );
					}
				} else {
					if ( this.options.onSwipeDown ) {
						this.options.onSwipeDown( this );
					}
				}
			}
		}

	},

	onResize: function( e ) {

		this.width = this.element.offsetWidth;
		this.height = this.element.offsetHeight;
		//this.width = this.element.getBoundingClientRect().width;
		//this.height = this.element.getBoundingClientRect().width;

		if ( this.options.onResize ) this.options.onResize( this );

	}
};<commit_msg>mobile fix<commit_after>/*
		=========================================================================================
 		*
		*	SwipeListener
 		*
 		=========================================================================================
		*----------------------------------------------------------------------------------------
 		*
 		*	listen to swipe events within an element - for desktop & mobile/touch
 		*
 		=========================================================================================
		*
		*   author          >>  Christopher Miles
		*
		*   site            >>  http://ChristopherMil.es
		*   github          >>  http://github.com/creatologist
		*
		=========================================================================================
*/

//===============================================================================================
//-----------------------------------------------------------------------------------------------

var SwipeListener = function( element, options, finishCallback ) {
	this.element = element;

	this.startTime;

	this.offsetX = element.offsetLeft;
	this.offsetY = element.offsetTop;

	this.reset();

	this.minX = 0;
	this.minY = 0;

	this.deltaX = 0;
	this.deltaY = 0;

	this.width = element.offsetWidth;
	this.height = element.offsetHeight;

	this.options = options || {};

	if ( this.element.addEventListener) {
	    this.element.addEventListener('mousedown', this, false);
	    this.element.addEventListener('touchstart', this, false);

	    this.element.addEventListener('drag', this, false);
	    this.element.addEventListener('touchmove', this, false);

	    window.addEventListener('mouseup', this, false);
	    window.addEventListener('touchleave', this, false);
	    window.addEventListener('touchcancel', this, false);

	    // if using window.ontouchend already, add our func into old func
	    var self = this;
	    if ( window.ontouchend ) {
	    	var rand = 'ontouchend' + Math.random();
	    	window[ rand ] = window.ontouchend;
	    	window.ontouchend = function( e ) {
	    		window[ rand ].call( e );
	    		self.onTouchEnd( e );
	    	};
	    } else {
	    	window.ontouchend = function( e ) {
	    		self.onTouchEnd( e );
	    	};
	    }

	    //this.element.addEventListener('click', this, false);
	    window.addEventListener('resize', this, false);
	}

	if ( this.options.minX ) this.minX = this.options.minX / this.width;
	if ( this.options.minY ) this.minY = this.options.minY / this.height;

	if ( this.options.minXPercent ) this.minX = this.options.minXPercent;
	if ( this.options.minYPercent ) this.minY = this.options.minYPercent;

	this.onResize();

	if ( typeof options == 'function' ) options( this );
	else if ( finishCallback && typeof finishCallback == 'function' ) finishCallback( this );
};

SwipeListener.prototype = {
	reset: function() {
		this.x = 0;
		this.y = 0;

		this.startX = 0;
		this.startY = 0;

		this.endX = 0;
		this.endY = 0;

		this.globalX = 0;
		this.globalY = 0;

		this.globalStartX = 0;
		this.globalStartY = 0;

		this.globalEndX = 0;
		this.globalEndY = 0;
	},
	isTouchDevice: function() {
		return 'ontouchstart' in window || 'onmsgesturechange' in window;
	},

	handleEvent: function(e) {
	    switch (e.type) {
	    	case 'mousedown':
	    	case 'touchstart': this.onTouchStart(e); break;

	    	case 'drag':
	    	case 'mousemove':
	    	case 'touchmove': this.onTouchMove(e); break;

	    	case 'mouseup':
	    	case 'touchcancel':
	    	case 'touchleave':
	    	case 'touchend': this.onTouchEnd(e); break;

	    	case 'resize': this.onResize( e ); break;
	    }
	},

	onTouchStart : function( e ) {
		//e.preventDefault();
		//e.stopPropagation();
		this.startTime = new Date();

		if ( e.touches && e.touches[0] ) {
			this.globalStartX = e.touches[0].pageX;
			this.globalStartY = e.touches[0].pageY;
		} else {
			this.globalStartX = e.x;
			this.globalStartY = e.y;
		}

		this.startX = this.globalStartX - this.offsetX;
		this.startY = this.globalStartY - this.offsetY;

		if ( this.options.onTouchStart ) this.options.onTouchStart( this );
	},
	onTouchMove : function( e ) {

		e.preventDefault();
		//e.stopPropagation();
		if ( e.touches && e.touches[0] ) {
			this.globalX = e.touches[0].pageX;
			this.globalY = e.touches[0].pageY;
		} else {
			this.globalX = e.x;
			this.globalY = e.y;
		}

		this.x = this.globalX - this.offsetX;
		this.y = this.globalY - this.offsetY;

		if ( this.options.onTouchMove ) this.options.onTouchMove( this );
	},
	onTouchEnd : function( e ) {
		//e.preventDefault();
		//e.stopPropagation();
		var dTime = new Date() - this.startTime;

		if ( e.touches ) {
			if ( e.touches[0] ) {
				this.globalEndX = e.touches[0].pageX;
				this.globalEndY = e.touches[0].pageY;
			} else {
				this.globalEndX = this.globalX;
				this.globalEndY = this.globalY;
			}

		} else {
			this.globalEndX = e.x;
			this.globalEndY = e.y;
		}

		this.endX = this.globalEndX - this.offsetX;
		this.endY = this.globalEndY - this.offsetY;

		var dX = this.globalEndX - this.globalStartX;
		var dY = this.globalEndY - this.globalStartY;

		this.deltaX = dX;
		this.deltaY = dY;

		var x = Math.abs( dX );
		var y = Math.abs( dY );

		var pX = x / this.width;
		var pY = y / this.height;

		if ( this.options.onTouchEnd ) this.options.onTouchEnd( this );

		if ( x > y ) {

			if ( this.minX < pX ) {
				if ( dX < 0 ) {
					if ( this.options.onSwipeLeft ) {
						 this.options.onSwipeLeft( this );
					}
				} else {
					if ( this.options.onSwipeRight ) {
						this.options.onSwipeRight( this );
					}
				}
			}
		} else {

			if ( this.minY < pY ) {
				if ( dY < 0 ) {
					if ( this.options.onSwipeUp ) {
						this.options.onSwipeUp( this );
					}
				} else {
					if ( this.options.onSwipeDown ) {
						this.options.onSwipeDown( this );
					}
				}
			}
		}

	},

	onResize: function( e ) {

		this.width = this.element.offsetWidth;
		this.height = this.element.offsetHeight;
		//this.width = this.element.getBoundingClientRect().width;
		//this.height = this.element.getBoundingClientRect().width;

		if ( this.options.onResize ) this.options.onResize( this );

	}
};<|endoftext|>


<commit_before>// Copyright 2016, University of Colorado Boulder

/**
 * ObjectIO is the root of the IO Type hierarchy.  All wrapper types extend from ObjectIO.  This is an abstract class
 * and should not be instantiated directly.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Andrew Adare (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var phetioInherit = require( 'PHET_IO/phetioInherit' );
  var phetioNamespace = require( 'PHET_IO/phetioNamespace' );

  /**
   * Main constructor for ObjectIO base wrapper type.
   * @param {Object} instance
   * @param {string} phetioID
   * @constructor
   */
  function ObjectIO( instance, phetioID ) {
    assert && assert( instance, 'instance should be truthy' );
    assert && assert( phetioID, 'phetioID should be truthy' );

    // @public
    this.instance = instance;

    // @public
    this.phetioID = phetioID;
  }

  // ObjectIO inherits from window.Object because it starts with its prototype in phetioInherit.inheritBase
  // However, when serialized, the ObjectIO supertype is reported as null (not sent in the JSON).
  phetioInherit( window.Object, 'ObjectIO', ObjectIO, {}, {
    documentation: 'The root of the wrapper object hierarchy',

    /**
     * Decodes the object from a state, used in phetio.setState.  This should be overridden
     * by subclasses.
     * @param {Object} o
     * @returns {Object}
     */
    fromStateObject: function( o ) {
      return o;
    },

    /**
     * Return the json that ObjectIO is wrapping.  Subclasses provide their own
     * toStateObject implementation to provide structure-based representations.
     * @param {Object} o
     * @returns {Object}
     */
    toStateObject: function( o ) {
      return o;
    }
  } );

  phetioNamespace.register( 'ObjectIO', ObjectIO );

  return ObjectIO;
} );<commit_msg>Clarified nature of ObjectIO, see https://github.com/phetsims/phet-io/issues/1276<commit_after>// Copyright 2016, University of Colorado Boulder

/**
 * ObjectIO is the root of the IO Type hierarchy.  All wrapper types extend from ObjectIO.  This type can be subtyped or
 * used directly for types that only need toStateObject/fromStateObject.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Andrew Adare (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var phetioInherit = require( 'PHET_IO/phetioInherit' );
  var phetioNamespace = require( 'PHET_IO/phetioNamespace' );

  /**
   * Main constructor for ObjectIO base wrapper type.
   * @param {Object} instance
   * @param {string} phetioID
   * @constructor
   * @abstract
   */
  function ObjectIO( instance, phetioID ) {
    assert && assert( instance, 'instance should be truthy' );
    assert && assert( phetioID, 'phetioID should be truthy' );

    // @public
    this.instance = instance;

    // @public
    this.phetioID = phetioID;
  }

  // ObjectIO inherits from window.Object because it starts with its prototype in phetioInherit.inheritBase
  // However, when serialized, the ObjectIO supertype is reported as null (not sent in the JSON).
  phetioInherit( window.Object, 'ObjectIO', ObjectIO, {}, {
    documentation: 'The root of the wrapper object hierarchy',

    /**
     * Decodes the object from a state, used in phetio.setState.  This can be overridden by subclasses, or types can
     * use ObjectIO type directly to use this implementation.
     * @param {Object} o
     * @returns {Object}
     */
    fromStateObject: function( o ) {
      return o;
    },

    /**
     * Return the json that ObjectIO is wrapping.  This can be overriden by subclasses, or types can use ObjectIO type
     * directly to use this implementation.
     * @param {Object} o
     * @returns {Object}
     */
    toStateObject: function( o ) {
      return o;
    }
  } );

  phetioNamespace.register( 'ObjectIO', ObjectIO );

  return ObjectIO;
} );<|endoftext|>


<commit_before>var map;
function init() {
    var apisToLoad;
    var loadCallback = function() {
        if (--apisToLoad === 0) {
            signin(true, userAuthed);
        }
    };

    $("#signInButton").text("Signing in ...");
    apisToLoad = 2;
    apiRoot = 'https://donate-backend.appspot.com/_ah/api';
    gapi.client.load('donate', 'v1', loadCallback, apiRoot);
    gapi.client.load('oauth2', 'v2', loadCallback);
}

function signin(mode, authorizeCallback) {
    gapi.auth.authorize({client_id:"760560844994-04u6qkvpf481an26cnhkaauaf2dvjfk0.apps.googleusercontent.com",
            scope: ["https://www.googleapis.com/auth/plus.login", "https://www.googleapis.com/auth/userinfo.email"],
            immediate: mode},
        authorizeCallback);
}

function userAuthed() {
    var request = gapi.client.oauth2.userinfo.get().execute(function(resp) {
        if (!resp.code) {
            gapi.client.oauth2.user.create().execute(function(resp) {
                if (!resp.code) {
                    signedIn();
                }
            });
        }
    });
}

function auth() {
    signin(false, userAuthed);
}

function deauth() {
    gapi.auth.setToken(null);
    $("#signInButton").show();
    $("#signInButton").text("Sign in");
    $("#signOutButton").hide();
}

function signedIn() {
    $("#signInButton").hide();
    $("#signOutButton").show();
    jumpToPage();
}

$(document).ready(function() {
    $(window).bind( 'hashchange', function(e) {
        jumpToPage();
    });

    $("#newQuestionModal").on('click','#save',function(e) {
        console.log(e);
        //$("#unanswered").html("");
        //
        var form = $(e.target).parent().parent();
        NProgress.start();
        var question = form.find("#question_text")[0].value;
        var answer = form.find("#answer_text")[0].value;
        var language = form.find("#language_code")[0].value;
        var category = form.find("#category")[0].value;
        $("#newQuestionModal").modal('hide');

        var createItems = {"question":question, "answer":answer, "language":language, "category":category};
        gapi.client.donate.faqitem.create(createItems).execute(function(resp) {
            NProgress.done();
            if (resp.code) {
                console.log(resp);
                $('#errorModalText').text("Error: "+resp.message);
                $('#errorModalLabel').append("Error Code "+resp.code);
                $('#errorModal').modal();
            }
        });
    });

    $("#newQuestionModal").on('click','.cat',function(e) {
        var p = $(e.target).parent().parent().parent();
        console.log(p);
        console.log(p);
        p.find("#category").prop('value', e.target.id);
        p.find("#dropdownMenuTitle").text(e.target.textContent);
    });
});

function jumpToPage() {
    var location = window.location.hash;
    if (location.match("^#home")) {
        $('nav').removeClass('fixed');
        $('nav li.active').removeClass('active');
        $('nav a#home_link').parent().addClass('active');
        showHome();
    }

    if (location.match("^#faq")) {
        $('nav').removeClass('fixed');
        $('nav li.active').removeClass('active');
        $('nav a#faq_link').parent().addClass('active');
        loadFAQ();
    }

    if (location.match("^#sharing")) {
        $('nav').removeClass('fixed');
        $('nav li.active').removeClass('active');
        $('nav a#sharing_link').parent().addClass('active');
        loadSharing();
    }

    if (location.match("^#map")) {
        $('nav').removeClass('fixed');
        $('nav li.active').removeClass('active');
        $('nav a#map_link').parent().addClass('active');
        showMap();
    }
<<<<<<< Updated upstream
=======

>>>>>>> Stashed changes
}

function loadFAQ() {
    $("#home").hide();
    $("#sharing").hide();
    $("#faq").show();
    $("#map_container").hide();
    gapi.client.donate.faqcat.list().execute(function(cats) {
        gapi.client.donate.faqitem.list({"answered":true}).execute(function(items) {
            var items_by_cat = {};
            var html = "";
            var popup_html = '
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenuTitle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">Choose Category</button>
';
            var askbutton = '
Didn\'t find what you need? Ask a question!
';

            if(items.items === undefined) {
                html += askbutton;
                $("#faq").html(html);
            } else {
                items.items.forEach(function parseItems(item, index, all) {
                    console.log(item);
                    if (item.category in items_by_cat) {
                        items_by_cat[item.category].push(item);
                    } else {
                        items_by_cat[item.category] = [item];
                    }
                });

                html += "
";
                html += "

Inhalt
";

                cats.items.forEach(function generateHTML(cat, catindex, all) {
                    items = items_by_cat[cat.id];
                    if (items != undefined) {
                        html += '' + cat.name + "
";
                    }

                    popup_html += '
' + cat.name + '
';
                });

                html += "
";
                html += "
";

                cats.items.forEach(function generateHTML(cat, catindex, all) {
                    items = items_by_cat[cat.id];
                    if (items != undefined) {
                        html += '
' + cat.name + "
";
                        html += "
";
                        items.forEach(function addQuestionToHTML(item, index, all) {
                            html += '

';
                            html += item.question;
                            html += '

';
                            html += item.answer;
                            html += '

';
                        });

                        html += '
';
                    }
                });

                html += askbutton;
                $("#faq").html(html);
                $("#newQuestionModalText").append(popup_html);
            }
        });
    });
}

function loadSharing() {
    $("#home").hide();
    $("#sharing").show();
    $("#faq").hide();
    $("#map_container").hide();
}

function showHome() {
    $("#home").show();
    $("#sharing").hide();
    $("#faq").hide();
    $("#map_container").hide();
}

function showMap() {
    $("#home").hide();
    $("#sharing").hide();
    $("#faq").hide();
    $("#map_container").show();
    loadMapIfNeeded();
}

function onLocationFound(e) {
    var radius = e.accuracy / 2;
    L.circle(e.latlng, radius).addTo(map);
}

function loadMapData() {
    //load authorities
    var authortiesUrl = 'https://raw.githubusercontent.com/germany-says-welcome/refugees-welcome-app/master/app/src/main/assets/authorities.json';
    $.getJSON(authortiesUrl, function(data) {
        data.forEach(function (entry) {
        var popup = '' + entry.adresse + '
';
        popup += entry.telefon ? ' ' + entry.telefon + '' + '   ' : '';
        popup += entry.fax ? ' ' + entry.fax + '
' : '';
        popup += entry.offnungszeiten ? ' ' + entry.offnungszeiten + '
' : '';
        popup += entry.website ? ' ' + entry.website + '
' : '';
        popup += 'Data from www.amt-de.com';

        //bind the authority to it's category
        L.marker([entry.location.lat, entry.location.lng]).addTo(authorities)
            .bindPopup(popup);
        });
    });

    //load wifi hotspots
    $.ajax({
        type: "GET",
        url: "http://www.freifunk-karte.de/fetch.php?content=gpxfile",
        dataType: "xml",
        success: function (xml) {
            $(xml).find("wpt").each(function() {
                var longitude = $(this).attr("lon");
                var latitude = $(this).attr("lat");
                var name = $(this).find("name").first().text();

                var marker = L.marker([latitude, longitude]);
                marker.bindPopup(name);
                wifi.addLayer(marker);
            });
        }
    });
}

function loadMap() {
    //create layer groups in order to be accessible from loadMapData
    authorities = L.layerGroup();
    wifi = L.markerClusterGroup();

    //cologne as default location
    map = L.map('map', {
        center: [50.9485795, 6.9448561],
        //default zoom state
        zoom: 13,
        //just use authorities as default layer
        layers: [authorities]
    });

    //selectable layers
    var overlayMaps = {
        "Authorities": authorities,
        "Wifi": wifi
    };

    L.control.layers(overlayMaps).addTo(map);

    mapLink = 'OpenStreetMap';
    L.tileLayer(
        'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© ' + mapLink + ' Contributors',
        maxZoom: 18
    }).addTo(map);

    map.locate({setView: true, maxZoom: 16});
    //switch to current gps position if found
    map.on('locationfound', onLocationFound);
    loadMapData();
}

function loadMapIfNeeded() {
    if (map === undefined) {
        loadMap();
    }
}

$("#map_container").hide();

jumpToPage();
<commit_msg>Optimized and fixed JS<commit_after>var map;

function init() {
  var apisToLoad;
  var loadCallback = function () {
    if (--apisToLoad === 0) {
      signin(true, userAuthed);
    }
  };

  $("#signInButton").text("Signing in ...");
  apisToLoad = 2;
  apiRoot = 'https://donate-backend.appspot.com/_ah/api';
  gapi.client.load('donate', 'v1', loadCallback, apiRoot);
  gapi.client.load('oauth2', 'v2', loadCallback);
}

function signin(mode, authorizeCallback) {
  gapi.auth.authorize({
      client_id: "760560844994-04u6qkvpf481an26cnhkaauaf2dvjfk0.apps.googleusercontent.com",
      scope: ["https://www.googleapis.com/auth/plus.login", "https://www.googleapis.com/auth/userinfo.email"],
      immediate: mode
    },
    authorizeCallback);
}

function userAuthed() {
  var request = gapi.client.oauth2.userinfo.get().execute(function (resp) {
    if (!resp.code) {
      gapi.client.oauth2.user.create().execute(function (resp) {
        if (!resp.code) {
          signedIn();
        }
      });
    }
  });
}

function auth() {
  signin(false, userAuthed);
}

function deauth() {
  gapi.auth.setToken(null);
  $("#signInButton").show();
  $("#signInButton").text("Sign in");
  $("#signOutButton").hide();
}

function signedIn() {
  $("#signInButton").hide();
  $("#signOutButton").show();
  jumpToPage();
}

$(document).ready(function () {
  $(window).bind('hashchange', function (e) {
    jumpToPage();
  });

  $("#newQuestionModal").on('click', '#save', function (e) {
    console.log(e);
    //$("#unanswered").html("");
    //
    var form = $(e.target).parent().parent();
    NProgress.start();
    var question = form.find("#question_text")[0].value;
    var answer = form.find("#answer_text")[0].value;
    var language = form.find("#language_code")[0].value;
    var category = form.find("#category")[0].value;
    $("#newQuestionModal").modal('hide');

    var createItems = {"question": question, "answer": answer, "language": language, "category": category};
    gapi.client.donate.faqitem.create(createItems).execute(function (resp) {
      NProgress.done();
      if (resp.code) {
        console.log(resp);
        $('#errorModalText').text("Error: " + resp.message);
        $('#errorModalLabel').append("Error Code " + resp.code);
        $('#errorModal').modal();
      }
    });
  });

  $("#newQuestionModal").on('click', '.cat', function (e) {
    var p = $(e.target).parent().parent().parent();
    console.log(p);
    console.log(p);
    p.find("#category").prop('value', e.target.id);
    p.find("#dropdownMenuTitle").text(e.target.textContent);
  });
});

function jumpToPage() {
  var location = window.location.hash;
  if (location.match("^#home")) {
    $('nav').removeClass('fixed');
    $('nav li.active').removeClass('active');
    $('nav a#home_link').parent().addClass('active');
    showHome();
  }

  if (location.match("^#faq")) {
    $('nav').removeClass('fixed');
    $('nav li.active').removeClass('active');
    $('nav a#faq_link').parent().addClass('active');
    loadFAQ();
  }

  if (location.match("^#sharing")) {
    $('nav').removeClass('fixed');
    $('nav li.active').removeClass('active');
    $('nav a#sharing_link').parent().addClass('active');
    loadSharing();
  }

  if (location.match("^#map")) {
    $('nav').removeClass('fixed');
    $('nav li.active').removeClass('active');
    $('nav a#map_link').parent().addClass('active');
    showMap();
  }
}

function loadFAQ() {
  $("#home").hide();
  $("#sharing").hide();
  $("#faq").show();
  $("#map_container").hide();
  gapi.client.donate.faqcat.list().execute(function (cats) {
    gapi.client.donate.faqitem.list({"answered": true}).execute(function (items) {
      var items_by_cat = {};
      var html = "";
      var popup_html = '
<button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenuTitle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">Choose Category</button>
';
      var askbutton = '
Didn\'t find what you need? Ask a question!
';

      if (items.items === undefined) {
        html += askbutton;
        $("#faq").html(html);
      } else {
        items.items.forEach(function parseItems(item, index, all) {
          console.log(item);
          if (item.category in items_by_cat) {
            items_by_cat[item.category].push(item);
          } else {
            items_by_cat[item.category] = [item];
          }
        });

        html += "
";
        html += "

Inhalt
";

        cats.items.forEach(function generateHTML(cat, catindex, all) {
          items = items_by_cat[cat.id];
          if (items != undefined) {
            html += '' + cat.name + "
";
          }

          popup_html += '
' + cat.name + '
';
        });

        html += "
";
        html += "
";

        cats.items.forEach(function generateHTML(cat, catindex, all) {
          items = items_by_cat[cat.id];
          if (items != undefined) {
            html += '
' + cat.name + "
";
            html += "
";
            items.forEach(function addQuestionToHTML(item, index, all) {
              html += '

';
              html += item.question;
              html += '

';
              html += item.answer;
              html += '

';
            });

            html += '
';
          }
        });

        html += askbutton;
        $("#faq").html(html);
        $("#newQuestionModalText").append(popup_html);
      }
    });
  });
}

function loadSharing() {
  $("#home").hide();
  $("#sharing").show();
  $("#faq").hide();
  $("#map_container").hide();
}

function showHome() {
  $("#home").show();
  $("#sharing").hide();
  $("#faq").hide();
  $("#map_container").hide();
}

function showMap() {
  $("#home").hide();
  $("#sharing").hide();
  $("#faq").hide();
  $("#map_container").show();
  loadMapIfNeeded();
}

function onLocationFound(e) {
  var radius = e.accuracy / 2;
  L.circle(e.latlng, radius).addTo(map);
}

function loadMapData() {
  //load authorities
  var authortiesUrl = 'https://raw.githubusercontent.com/germany-says-welcome/refugees-welcome-app/master/app/src/main/assets/authorities.json';
  $.getJSON(authortiesUrl, function (data) {
    data.forEach(function (entry) {
      var popup = '' + entry.adresse + '
';
      popup += entry.telefon ? ' ' + entry.telefon + '' + '   ' : '';
      popup += entry.fax ? ' ' + entry.fax + '
' : '';
      popup += entry.offnungszeiten ? ' ' + entry.offnungszeiten + '
' : '';
      popup += entry.website ? ' ' + entry.website + '
' : '';
      popup += 'Data from www.amt-de.com';

      //bind the authority to it's category
      L.marker([entry.location.lat, entry.location.lng]).addTo(authorities)
        .bindPopup(popup);
    });
  });

  //load wifi hotspots
  $.ajax({
    type: "GET",
    url: "http://www.freifunk-karte.de/fetch.php?content=gpxfile",
    dataType: "xml",
    success: function (xml) {
      $(xml).find("wpt").each(function () {
        var longitude = $(this).attr("lon");
        var latitude = $(this).attr("lat");
        var name = $(this).find("name").first().text();

        var marker = L.marker([latitude, longitude]);
        marker.bindPopup(name);
        wifi.addLayer(marker);
      });
    }
  });
}

function loadMap() {
  //create layer groups in order to be accessible from loadMapData
  authorities = L.layerGroup();
  wifi = L.markerClusterGroup();

  //cologne as default location
  map = L.map('map', {
    center: [50.9485795, 6.9448561],
    //default zoom state
    zoom: 13,
    //just use authorities as default layer
    layers: [authorities]
  });

  //selectable layers
  var overlayMaps = {
    "Authorities": authorities,
    "Wifi": wifi
  };

  L.control.layers(overlayMaps).addTo(map);

  mapLink = 'OpenStreetMap';
  L.tileLayer(
    'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
      attribution: '© ' + mapLink + ' Contributors',
      maxZoom: 18
    }).addTo(map);

  map.locate({setView: true, maxZoom: 16});
  //switch to current gps position if found
  map.on('locationfound', onLocationFound);
  loadMapData();
}

function loadMapIfNeeded() {
  if (map === undefined) {
    loadMap();
  }
}

$("#map_container").hide();

jumpToPage();
<|endoftext|>


<commit_before>var App = window.election;

function createDocument(preview,download) {
  jQuery.data( document.body, "psc-locked", "1");
  nastavObec();
  var today = new Date();
  var dd = today.getDate();
  var mm = today.getMonth() + 1;
  var yyyy = today.getFullYear();
  if (dd < 10) {
    dd = '0' + dd
  }
  if (mm < 10) {
    mm = '0' + mm
  }

  // playground requires you to assign document definition to a variable called dd
  var paragraph, localaddress = [], noTP = [], vyhlasenie = [], signature = [], idPhoto = [];
  var signaturedata = signaturePad.toDataURL();
  if (signaturedata.length > 10) {
    $('#signature').val(signaturedata);
  }

  signature2 = [];
  if ($('#signature').val() != '') {
    signature =
            [
              {text: '', style: 'space'},
              {
                text: ['V ', {text: $('#addressforeign-city').val(), style: 'value'}],
                style: 'footer',
              },
              {
                text: ['Dátum: ', {text: '' + dd + '. ' + mm + '. ' + yyyy, style: 'value'}],
                style: 'footer',
              },
              {
                image: $('#signature').val(), width: 120, style: 'signatureStyle'
              },
              {
                text: '                      Podpis                      ',
                style: 'signatureTextStyle'
              }
            ];

    var signature2 = [
      {text: '', style: 'space'},
      {
        text: ['V ', {text: $('#addressforeign-city').val(), style: 'value'}],
        style: 'footer',
      },
      {
        text: ['Dátum: ', {text: '' + dd + '. ' + mm + '. ' + yyyy, style: 'value'}],
        style: 'footer',
      },
      {
        image: $('#signature').val(), width: 150, alignment: 'right'
      },
      {
        text: '                      Podpis                      ',
        style: 'signatureTextStyle'
      }
    ];
  }
  if ($('#camera-input')[0].files.length > 0) {
    idPhoto =
            [
              {
                image: $('#camera-preview').attr('src'),
                pageBreak: 'before',
                style: 'signature'
              }
            ]
  }

  if (App.request_form == 'volbaPostouSTrvalymPobytom') {
    paragraph = 'Podľa § 60 ods. 1 zákona č. 180/2014 Z. z. o podmienkach výkonu volebného práva a o zmene a doplnení niektorých zákonov žiadam o voľbu poštou pre voľby do Národnej rady Slovenskej republiky v roku 2016.';
    localaddress = [
      {text: '', style: 'spacesmall'},
      {
        text: 'Adresa trvalého pobytu v Slovenskej republike:',
        style: 'line',
        //style: 'header',
        bold: true
      },
      {
        columns: [
          {text: 'Ulica: ', style: 'line',},
          {text: $('#addressslovakia-street').val().toUpperCase(), style: 'value'},
          {text: ''}
        ]
      },
      {
        columns: [
          {text: 'Číslo domu: ', style: 'line',},
          {text: $('#addressslovakia-streetno').val().toUpperCase(), style: 'value'},
          {text: ''}
        ]
      },
      {
        columns: [
          {text: 'Obec: ', style: 'line',},
          {text: getObec().toUpperCase(), style: 'value'},
          {text: ''}
        ]
      },
      {
        columns: [
          {text: 'PSČ: ', style: 'line',},
          {text: $('#addressslovakia-zip').val(), style: 'value'},
          {text: ''}
        ]
      },
      {text: '', style: 'spacesmall'},
      {
        text: 'Adresa miesta pobytu v cudzine (pre zaslanie hlasovacích lístkov a obálok):',
        style: 'line',
        //style: 'header',
        bold: true
      }
    ];
  } else if (App.request_form == 'volbaPostouBezTrvalehoPobytu') {
    paragraph = 'Podľa   § 59 ods. 1   zákona   č. 180/2014 Z. z. o podmienkach výkonu volebného práva a o zmene a doplnení niektorých zákonov žiadam o voľbu poštou pre voľby do Národnej rady Slovenskej republiky v roku 2016 a o zaslanie hlasovacích lístkov a obálok na adresu:';
    noTP = [

      {text: '', style: 'spacesmall'},
      {
        text: 'Prílohy:',
        style: 'header',
        alignment: 'left'
      },
      {
        ul: [
          'čestné vyhlásenie voliča, že nemá trvalý pobyt na území Slovenskej republiky.',
          'fotokópia časti cestovného dokladu Slovenskej republiky s osobnými údajmi voliča alebo fotokópia osvedčenia o štátnom občianstve Slovenskej republiky voliča.',
        ]
      }
    ];
    vyhlasenie = [
      {
        text: $('#basicinfo-name').val() + ' ' + $('#basicinfo-lastname').val() + ' ' + $('#basicinfo-birthno').val(),
        alignment: 'center',
        pageBreak: 'before'
      },
      {
        text: getAddressOneLine('addressforeign'),
        alignment: 'center',
      },

      {text: '', style: 'space'},
      {
        text: 'ČESTNÉ VYHLÁSENIE',
        style: 'header',
        alignment: 'center'
      },
      {text: '', style: 'space'},
      {
        text: 'Na účely voľby poštou do Národnej rady Slovenskej republiky v roku 2016',
        alignment: 'center'
      },
      {text: '', style: 'space'},
      {
        text: 'čestne vyhlasujem,',
        style: 'header',
        alignment: 'center'
      },
      {text: '', style: 'space'},
      {
        text: 'že nemám trvalý pobyt na území Slovenskej republiky.'
      },
      signature2
    ];

  }

  if (App.request_form === "volbaPostouSTrvalymPobytom" || App.request_form === "volbaPostouBezTrvalehoPobytu") {
    formContent = [
      {
        text: 'Žiadosť',
        style: 'header',
        alignment: 'center'
      },
      {
        text: 'o voľbu poštou',
        style: 'header',
        alignment: 'center'
      },
      {
        text: 'pre voľby do Národnej rady Slovenskej republiky v roku 2016',
        style: 'header',
        alignment: 'center'
      },
      {text: '', style: 'space'},
      {
        text: $('#adresa').val(),
        style: 'address',
      },
      {text: '', style: 'space'},
      {
        text: [
          paragraph
        ],
      },
      {text: '', style: 'spacesmall'},
      {
        columns: [
          {text: 'Meno: ', style: 'line',},
          {text: $('#basicinfo-name').val().toUpperCase(), style: 'value'},
          {text: ''}
        ]
      },
      {
        columns: [
          {text: 'Priezvisko: ', style: 'line',},
          {text: $('#basicinfo-lastname').val().toUpperCase(), style: 'value'},
          {text: ''}
        ]
      },
      {
        columns: [
          {text: 'Rodné priezvisko: ', style: 'line',},
          {text: $('#basicinfo-maidenlastname').val().toUpperCase(), style: 'value'},
          {text: ''}
        ]
      },
      {
        columns: [
          {text: 'Rodné číslo: ', style: 'line',},
          {text: $('#basicinfo-birthno').val().toUpperCase(), style: 'value'},
          {text: ''}
        ]
      },
      localaddress,
      {
        columns: [
          {text: 'Ulica: ', style: 'line',},
          {text: $('#addressforeign-street').val().toUpperCase(), style: 'value'},
          {text: ''}
        ]
      },
      {
        columns: [
          {text: 'Číslo domu: ', style: 'line',},
          {text: $('#addressforeign-streetno').val().toUpperCase(), style: 'value'},
          {text: ''}
        ]
      },
      {
        columns: [
          {text: 'Obec: ', style: 'line',},
          {text: $('#addressforeign-city').val().toUpperCase(), style: 'value'},
          {text: ''}
        ]
      },
      {
        columns: [
          {text: 'PSČ: ', style: 'line',},
          {text: $('#addressforeign-zip').val(), style: 'value'},
          {text: ''}
        ]
      },
      {
        columns: [
          {text: 'Štát: ', style: 'line',},
          {text: $('#addressforeign-country').val().toUpperCase(), style: 'value'},
          {text: ''}
        ]
      },
      noTP
    ]
  }
  if (App.request_form === "ziadostOPreukazPostou") {
    preukazHeader = 'Žiadosť o vydanie hlasovacieho preukazu';
    preukazDelivery = [
      {
        text: 'Hlasovací preukaz žiadam zaslať na adresu:',
        style: 'line',
        alignment: 'left'
      },
      {
        columns: [
          {
            text: ['Meno: ', {text: $('#basicinfo-name').val().toUpperCase(), style: 'value'}],
          },
          {
            text: ['Priezvisko: ', {text: $('#basicinfo-lastname').val().toUpperCase(), style: 'value'}],
          }
        ]
      },
      {
        text: ['Adresa: ', {text: getAddressOneLine('addressforeign').toUpperCase(), style: 'value'}],
        style: 'line'
      }
    ]
  }

  if (App.request_form === "ziadostOPreukaPreSplnomocnenca") {
    preukazHeader = 'Žiadosť o vydanie hlasovacieho preukazu a splnomocnenie na jeho prevzatie';
    preukazDelivery = [
      {
        text: 'Na prevzatie hlasovacieho preukazu podľa § 46 ods. 6 zákona  splnomocňujem:',
        style: 'line',
        alignment: 'left'
      },
      {
        columns: [
          {
            text: ['Meno: ', {text: $('#proxy-name').val().toUpperCase(), style: 'value'}],
          },
          {
            text: ['Priezvisko: ', {text: $('#proxy-lastname').val().toUpperCase(), style: 'value'}],
          }
        ]
      },
      {
        text: ['Číslo občianskeho preukazu: ', {text: $('#proxy-idno').val().toUpperCase(), style: 'value'}],
        style: 'line'
      }
    ]
  }

  if (App.request_form === "ziadostOPreukazPostou" || App.request_form === "ziadostOPreukaPreSplnomocnenca") {
    formContent = [
      {
        text: $('#adresa').val(),
        style: 'address',
      },
      {text: '', style: 'space'},
      {
        text: preukazHeader,
        style: 'header',
        alignment: 'left'
      },
      {text: '', style: 'space'},
      {
        columns: [
          {
            text: ['Meno: ', {text: $('#basicinfo-name').val().toUpperCase(), style: 'value'}],
            style: 'line',
          },
          {
            text: ['Priezvisko: ', {text: $('#basicinfo-lastname').val().toUpperCase(), style: 'value'}],
            style: 'line',
          },
        ]
      },
      {
        columns: [
          {
            text: ['Rodné číslo: ', {text: $('#basicinfo-birthno').val(), style: 'value'}],
            style: 'line',
          },
          {
            text: ['Štátna príslušnosť: ', {text: 'Slovenská republika'.toUpperCase(), style: 'value'}],
            style: 'line',
          },
        ]
      },
      {
        text: ['Adresa trvalého pobytu: ', {text: getAddressOneLine('addressslovakia').toUpperCase(), style: 'value'}],
        style: 'line',
      },
      {text: '', style: 'space'},
      {
        text: 'žiadam',
        style: 'header',
        alignment: 'center'
      },
      {text: '', style: 'space'},
      {
        text: [
          {text: 'podľa § 46 zákona č. 180/2014 Z. z. o podmienkach výkonu volebného práva a o zmene a doplnení niektorých zákonov '},
          {text: 'o vydanie hlasovacieho preukazu', bold: true},
          {text: ' pre voľby do Národnej rady Slovenskej republiky v roku 2016.'},
        ]
      },
      {text: '', style: 'space'},
      preukazDelivery
    ]
  }
  var dd = {
	pageSize: 'A4',
	info: {
		title: 'Žiadosť o účasť vo voľbách',
		author: 'volby.digital',
		subject: 'Žiadosť o účasť vo voľbách',
	},
    content: [
      formContent,
      signature,
      vyhlasenie,
      idPhoto,
    ],
    styles: {
      header: {
        fontSize: 12,
        bold: true,
        alignment: 'justify'
      },
      value: {
        fontSize: 12,
        bold: true,
        margin: [0, 7, 0, 0],
        decoration: 'underline',
        decorationStyle: 'dotted'
      },
      address: {
        fontSize: 12,
        italic: true,
        alignment: 'justify',
        margin: [260, 10, 10, 10],
      },
      line: {
        fontSize: 12,
        margin: [0, 7, 0, 0],
        padding: [0, 0, 0, 0]
      },
      footer: {
        fontSize: 12,
        margin: [0, 0, 0, 0],
        padding: [0, 0, 0, 0]
      },
      space: {
        fontSize: 12,
        margin: [0, 40, 0, 0]
      },
      spacesmall: {
        fontSize: 12,
        margin: [0, 20, 0, 0]
      },
      signatureStyle: {
        margin: [0, -60, 0, 0],
        alignment: 'right'
      },
      signatureTextStyle: {
        decoration: 'overline',
        decorationStyle: 'dotted',
        alignment: 'right',
        margin: [30, 10],
        fontSize: 9
      }
    }
  }

  var name = "ziadost";
  if(preview){
	  if (App.request_form === "ziadostOPreukazPostou" || App.request_form === "ziadostOPreukaPreSplnomocnenca") {
		  name = "ziadost-o-hlasovaci-preukaz.pdf";
	  }else{
		  name = "ziadost-o-volbu-postou.pdf";
	  }
  }else{
	  if (App.request_form === "ziadostOPreukazPostou" || App.request_form === "ziadostOPreukaPreSplnomocnenca") {
		  name = "ziadost-o-hlasovaci-preukaz-nahlad.pdf";
	  }else{
		  name = "ziadost-o-volbu-postou-nahlad.pdf";
	  }
  }

  if(detectIE() || isAndroid() || download){
	  pdfMake.createPdf(dd).download(name);
  }else{

	  if (preview === true) {
		pdfMake.createPdf(dd).getDataUrl(function (result) {
		  $('#preview').attr('src', result);
		});
	  } else {
		pdfMake.createPdf(dd).getDataUrl(function (result) {
		  $('#final').attr('src', result);
		});
	  }
  }
}
<commit_msg>Doplnenie Poste Restante, Textov, formatovanie + jednostranova ziadost<commit_after>var App = window.election;

function createDocument(preview,download) {
  jQuery.data( document.body, "psc-locked", "1");
  nastavObec();
  var today = new Date();
  var dd = today.getDate();
  var mm = today.getMonth() + 1;
  var yyyy = today.getFullYear();
  if (dd < 10) {
    dd = '0' + dd
  }
  if (mm < 10) {
    mm = '0' + mm
  }

  // playground requires you to assign document definition to a variable called dd
  var paragraph, localaddress = [], noTP = [], signature = [], idPhoto = [];
  var signaturedata = signaturePad.toDataURL();
  if (signaturedata.length > 10) {
    $('#signature').val(signaturedata);
  }

  signature2 = [];
  if ($('#signature').val() != '') {
    signature =
            [
              {text: '', style: 'space'},
              {
                text: ['V ', {text: $('#addressforeign-city').val(), style: 'value'}],
                style: 'footer',
              },
              {
                text: ['Dátum: ', {text: '' + dd + '. ' + mm + '. ' + yyyy, style: 'value'}],
                style: 'footer',
              },
              {
                image: $('#signature').val(), width: 120, style: 'signatureStyle'
              },
              {
                text: '                      Podpis                      ',
                style: 'signatureTextStyle'
              }
            ];

    var signature2 = [
      {text: '', style: 'space'},
      {
        text: ['V ', {text: $('#addressforeign-city').val(), style: 'value'}],
        style: 'footer',
      },
      {
        text: ['Dátum: ', {text: '' + dd + '. ' + mm + '. ' + yyyy, style: 'value'}],
        style: 'footer',
      },
      {
        image: $('#signature').val(), width: 150, alignment: 'right'
      },
      {
        text: '                      Podpis                      ',
        style: 'signatureTextStyle'
      }
    ];
  }
  if ($('#camera-input')[0].files.length > 0) {
    idPhoto =
            [
              {
                image: $('#camera-preview').attr('src'),
                pageBreak: 'before',
                style: 'signature'
              }
            ]
  }

  if (App.request_form == 'volbaPostouSTrvalymPobytom') {
    paragraph = 'Podľa § 60 ods. 1 zákona č. 180/2014 Z. z. o podmienkach výkonu volebného práva a o zmene a doplnení niektorých zákonov žiadam o voľbu poštou pre voľby do Národnej rady Slovenskej republiky v roku 2016.';
    localaddress = [
      {text: '', style: 'spacesmall'},
      {
        text: 'Adresa trvalého pobytu v Slovenskej republike:',
        style: 'line',
        //style: 'header',
        bold: true
      },
      {
        columns: [
          {text: 'Ulica: ', style: 'line',},
          {text: $('#addressslovakia-street').val().toUpperCase(), style: 'value'},
          {text: ''}
        ]
      },
      {
        columns: [
          {text: 'Číslo domu: ', style: 'line',},
          {text: $('#addressslovakia-streetno').val().toUpperCase(), style: 'value'},
          {text: ''}
        ]
      },
      {
        columns: [
          {text: 'Obec: ', style: 'line',},
          {text: getObec().toUpperCase(), style: 'value'},
          {text: ''}
        ]
      },
      {
        columns: [
          {text: 'PSČ: ', style: 'line',},
          {text: $('#addressslovakia-zip').val(), style: 'value'},
          {text: ''}
        ]
      },
      {text: '', style: 'spacesmall'},
      {
        text: 'Adresa miesta pobytu v cudzine (pre zaslanie hlasovacích lístkov a obálok):',
        style: 'line',
        //style: 'header',
        bold: true
      }
    ];
  } else if (App.request_form == 'volbaPostouBezTrvalehoPobytu') {
    paragraph = 'Podľa § 59 ods. 1 zákona č. 180/2014 Z. z. o podmienkach výkonu volebného práva a o zmene a doplnení niektorých zákonov žiadam o voľbu poštou pre voľby do Národnej rady Slovenskej republiky v roku 2016 a o zaslanie hlasovacích lístkov a obálok na adresu:';
    noTP = [

      {text: '', style: 'space'},
	  {
        text: 'Čestne vyhlasujem, že nemám trvalý pobyt na území Slovenskej republiky.',
        style: 'header',
      },
      {text: '', style: 'space'},
      {
        text: 'Prílohy:',
        style: 'header',
        alignment: 'left'
      },
      {
        ul: [
          'fotokópia časti cestovného dokladu Slovenskej republiky s osobnými údajmi voliča alebo fotokópia osvedčenia o štátnom občianstve Slovenskej republiky voliča.',
        ]
      }
    ];
  }

  if (App.request_form === "volbaPostouSTrvalymPobytom" || App.request_form === "volbaPostouBezTrvalehoPobytu") {

	formContent = [
      {
        text: 'Žiadosť',
        style: 'header',
        alignment: 'center'
      },
      {
        text: 'o voľbu poštou',
        style: 'header',
        alignment: 'center'
      },
      {
        text: 'pre voľby do Národnej rady Slovenskej republiky v roku 2016',
        style: 'header',
        alignment: 'center'
      },
      {text: '', style: 'space'},
      {
        text: $('#adresa').val(),
        style: 'address',
      },
      {text: '', style: 'space'},
      {
        text: [
          paragraph
        ],
      },
      {text: '', style: 'spacesmall'},
      {
        columns: [
          {text: 'Meno: ', style: 'line',},
          {text: $('#basicinfo-name').val().toUpperCase(), style: 'value'},
          {text: ''}
        ]
      },
      {
        columns: [
          {text: 'Priezvisko: ', style: 'line',},
          {text: $('#basicinfo-lastname').val().toUpperCase(), style: 'value'},
          {text: ''}
        ]
      },
      {
        columns: [
          {text: 'Rodné priezvisko: ', style: 'line',},
          {text: $('#basicinfo-maidenlastname').val().toUpperCase(), style: 'value'},
          {text: ''}
        ]
      },
      {
        columns: [
          {text: 'Rodné číslo: ', style: 'line',},
          {text: $('#basicinfo-birthno').val().toUpperCase(), style: 'value'},
          {text: ''}
        ]
      },
      localaddress,
      {
        columns: [
          {text: ( App.poste_res ? 'Adresa v cudzine:' : 'Ulica: '), style: 'line',},
          {text: ( App.poste_res ? 'Poste Restante' : $('#addressforeign-street').val().toUpperCase() ), style: 'value'},
          {text: ''}
        ]
      },
      {
        columns: [
          {text: ( App.poste_res ? ' ' : 'Číslo domu: '), style: 'line',},
          {text: ( App.poste_res ? ' ' : $('#addressforeign-streetno').val().toUpperCase() ), style: 'value'},
          {text: ''}
        ]
      },
      {
        columns: [
          {text: ( App.poste_res ? ' ' : 'Obec: '), style: 'line',},
          {text: $('#addressforeign-city').val().toUpperCase(), style: 'value'},
          {text: ''}
        ]
      },
      {
        columns: [
          {text: ( App.poste_res ? ' ' : 'PSČ: '), style: 'line',},
          {text: $('#addressforeign-zip').val(), style: 'value'},
          {text: ''}
        ]
      },
      {
        columns: [
          {text: ( App.poste_res ? ' ' : 'Štát: '), style: 'line',},
          {text: $('#addressforeign-country').val().toUpperCase(), style: 'value'},
          {text: ''}
        ]
      },
      noTP
    ]
  }
  if (App.request_form === "ziadostOPreukazPostou") {
    preukazHeader = 'Žiadosť o vydanie hlasovacieho preukazu';
    preukazDelivery = [
      {
        text: 'Hlasovací preukaz žiadam zaslať na adresu:',
        style: 'line',
        alignment: 'left'
      },
      {
        columns: [
          {
            text: ['Meno: ', {text: $('#basicinfo-name').val().toUpperCase(), style: 'value'}],
          },
          {
            text: ['Priezvisko: ', {text: $('#basicinfo-lastname').val().toUpperCase(), style: 'value'}],
          }
        ]
      },
      {
        text: ['Adresa: ', {text: getAddressOneLine('addressforeign').toUpperCase(), style: 'value'}],
        style: 'line'
      }
    ]
  }

  if (App.request_form === "ziadostOPreukaPreSplnomocnenca") {
    preukazHeader = 'Žiadosť o vydanie hlasovacieho preukazu a splnomocnenie na jeho prevzatie';
    preukazDelivery = [
      {
        text: 'Na prevzatie hlasovacieho preukazu podľa § 46 ods. 6 zákona  splnomocňujem:',
        style: 'line',
        alignment: 'left'
      },
      {
        columns: [
          {
            text: ['Meno: ', {text: $('#proxy-name').val().toUpperCase(), style: 'value'}],
          },
          {
            text: ['Priezvisko: ', {text: $('#proxy-lastname').val().toUpperCase(), style: 'value'}],
          }
        ]
      },
      {
        text: ['Číslo občianskeho preukazu: ', {text: $('#proxy-idno').val().toUpperCase(), style: 'value'}],
        style: 'line'
      }
    ]
  }

  if (App.request_form === "ziadostOPreukazPostou" || App.request_form === "ziadostOPreukaPreSplnomocnenca") {
    formContent = [
      {
        text: $('#adresa').val(),
        style: 'address',
      },
      {text: '', style: 'space'},
      {
        text: preukazHeader,
        style: 'header',
        alignment: 'left'
      },
      {text: '', style: 'space'},
      {
        columns: [
          {
            text: ['Meno: ', {text: $('#basicinfo-name').val().toUpperCase(), style: 'value'}],
            style: 'line',
          },
          {
            text: ['Priezvisko: ', {text: $('#basicinfo-lastname').val().toUpperCase(), style: 'value'}],
            style: 'line',
          },
        ]
      },
      {
        columns: [
          {
            text: ['Rodné číslo: ', {text: $('#basicinfo-birthno').val(), style: 'value'}],
            style: 'line',
          },
          {
            text: ['Štátna príslušnosť: ', {text: 'Slovenská republika'.toUpperCase(), style: 'value'}],
            style: 'line',
          },
        ]
      },
      {
        text: ['Adresa trvalého pobytu: ', {text: getAddressOneLine('addressslovakia').toUpperCase(), style: 'value'}],
        style: 'line',
      },
      {text: '', style: 'space'},
      {
        text: 'žiadam',
        style: 'header',
        alignment: 'center'
      },
      {text: '', style: 'space'},
      {
        text: [
          {text: 'podľa § 46 zákona č. 180/2014 Z. z. o podmienkach výkonu volebného práva a o zmene a doplnení niektorých zákonov '},
          {text: 'o vydanie hlasovacieho preukazu', bold: true},
          {text: ' pre voľby do Národnej rady Slovenskej republiky v roku 2016.'},
        ]
      },
      {text: '', style: 'space'},
      preukazDelivery
    ]
  }
  var dd = {
	pageSize: 'A4',
	info: {
		title: 'Žiadosť o účasť vo voľbách',
		author: 'volby.digital',
		subject: 'Žiadosť o účasť vo voľbách',
	},
    content: [
      formContent,
      signature,
      idPhoto,
    ],
    styles: {
      header: {
        fontSize: 12,
        bold: true,
        alignment: 'justify'
      },
      value: {
        fontSize: 12,
        bold: true,
        margin: [0, 7, 0, 0],
        decoration: 'underline',
        decorationStyle: 'dotted'
      },
      address: {
        fontSize: 12,
        italic: true,
        alignment: 'justify',
        margin: [260, 10, 10, 10],
      },
      line: {
        fontSize: 12,
        margin: [0, 7, 0, 0],
        padding: [0, 0, 0, 0]
      },
      footer: {
        fontSize: 12,
        margin: [0, 0, 0, 0],
        padding: [0, 0, 0, 0]
      },
      space: {
        fontSize: 12,
        margin: [0, 40, 0, 0]
      },
      spacesmall: {
        fontSize: 12,
        margin: [0, 20, 0, 0]
      },
      signatureStyle: {
        margin: [0, -60, 0, 0],
        alignment: 'right'
      },
      signatureTextStyle: {
        decoration: 'overline',
        decorationStyle: 'dotted',
        alignment: 'right',
        margin: [30, 10],
        fontSize: 9
      }
    }
  }

  var name = "ziadost";
  if(preview){
	  if (App.request_form === "ziadostOPreukazPostou" || App.request_form === "ziadostOPreukaPreSplnomocnenca") {
		  name = "ziadost-o-hlasovaci-preukaz.pdf";
	  }else{
		  name = "ziadost-o-volbu-postou.pdf";
	  }
  }else{
	  if (App.request_form === "ziadostOPreukazPostou" || App.request_form === "ziadostOPreukaPreSplnomocnenca") {
		  name = "ziadost-o-hlasovaci-preukaz-nahlad.pdf";
	  }else{
		  name = "ziadost-o-volbu-postou-nahlad.pdf";
	  }
  }

  if(detectIE() || isAndroid() || download){
	  pdfMake.createPdf(dd).download(name);
  }else{

	  if (preview === true) {
		pdfMake.createPdf(dd).getDataUrl(function (result) {
		  $('#preview').attr('src', result);
		});
	  } else {
		pdfMake.createPdf(dd).getDataUrl(function (result) {
		  $('#final').attr('src', result);
		});
	  }
  }
}
<|endoftext|>


<commit_before>var GROUND_LAYER = 0;
var DETAILS_LAYER = 1;

var TILE_GRASS0 = 1;
var TILE_GRASS1 = 2;
var TILE_GRASS2 = 3;
var TILE_GRASS3 = 4;

var tiledMap;

var TILE_SIZE;
var MAP_SIZE;
var INV_TILE_SIZE;
var HALF_TILE_SIZE;
var MAP_CENTER;

var GROW_SPEED = 10;
var GRASS_MAX = 3;

var grassLevel = [];

function map_init()
{
    // Load map
    tiledMap = getTiledMap("map.tmx");

    // Set constants
    TILE_SIZE = tiledMap.getTileSize();
    MAP_SIZE = tiledMap.getSize().x;
    INV_TILE_SIZE = 1 / TILE_SIZE;
    HALF_TILE_SIZE = TILE_SIZE / 2;
    MAP_CENTER = new Vector2(MAP_SIZE * TILE_SIZE / 2, MAP_SIZE * TILE_SIZE / 2);

    // Set grass amounts
    for (var y = 0; y < MAP_SIZE; ++y)
    {
        grassLevel[y] = [];
        for (var x = 0; x < MAP_SIZE; ++x)
        {
            var val = tiledMap.getTileAt(GROUND_LAYER, x, y);
            if (val == TILE_GRASS0)
                grassLevel[y][x] = 0;
            else if (val == TILE_GRASS1)
                grassLevel[y][x] = 1;
            else if (val == TILE_GRASS2)
                grassLevel[y][x] = 2;
            else if (val == TILE_GRASS3)
                grassLevel[y][x] = 3;
            else
                grassLevel[y][x] = 0;
        }
    }
}

function worldToMap(world)
{
    return new Vector2(Math.floor(world.x * INV_TILE_SIZE), Math.floor(world.y * INV_TILE_SIZE));
}

function mapToWorld(map)
{
    return new Vector2(map.x * TILE_SIZE + HALF_TILE_SIZE, map.y * TILE_SIZE + HALF_TILE_SIZE);
}

function map_getGrassAt(mapPos)
{
    if (mapPos.x < 0 || mapPos.y < 0 || mapPos.x >= MAP_SIZE || mapPos.y >= MAP_SIZE) return 0;
    return grassLevel[mapPos.y][mapPos.x];
}

function map_setGrassAt(mapPos, value)
{
    if (mapPos.x < 0 || mapPos.y < 0 || mapPos.x >= MAP_SIZE || mapPos.y >= MAP_SIZE) return;
    grassLevel[mapPos.y][mapPos.x] = value;
    if (value <= 0) tiledMap.setTileAt(GROUND_LAYER, mapPos.x, mapPos.y, TILE_GRASS0);
    else if (value <= 1) tiledMap.setTileAt(GROUND_LAYER, mapPos.x, mapPos.y, TILE_GRASS1);
    else if (value <= 2) tiledMap.setTileAt(GROUND_LAYER, mapPos.x, mapPos.y, TILE_GRASS2);
    else if (value <= 3) tiledMap.setTileAt(GROUND_LAYER, mapPos.x, mapPos.y, TILE_GRASS3);
}
<commit_msg>Fixed the map (don't know if it works)<commit_after>var GROUND_LAYER = 0;
var DETAILS_LAYER = 1;

var TILE_GRASS0 = 1;
var TILE_GRASS1 = 2;
var TILE_GRASS2 = 3;
var TILE_GRASS3 = 4;

var tiledMap;

var TILE_SIZE;
var MAP_SIZE;
var INV_TILE_SIZE;
var HALF_TILE_SIZE;
var MAP_CENTER;

var GROW_SPEED = 10;
var GRASS_MAX = 3;

var grassLevel;

function map_init()
{
    // Load map
    tiledMap = getFreshTiledMap("map.tmx");

    grassLevel = [];

    // Set constants
    TILE_SIZE = tiledMap.getTileSize();
    MAP_SIZE = tiledMap.getSize().x;
    INV_TILE_SIZE = 1 / TILE_SIZE;
    HALF_TILE_SIZE = TILE_SIZE / 2;
    MAP_CENTER = new Vector2(MAP_SIZE * TILE_SIZE / 2, MAP_SIZE * TILE_SIZE / 2);

    // Set grass amounts
    for (var y = 0; y < MAP_SIZE; ++y)
    {
        grassLevel[y] = [];
        for (var x = 0; x < MAP_SIZE; ++x)
        {
            var val = tiledMap.getTileAt(GROUND_LAYER, x, y);
            if (val == TILE_GRASS0)
                grassLevel[y][x] = 0;
            else if (val == TILE_GRASS1)
                grassLevel[y][x] = 1;
            else if (val == TILE_GRASS2)
                grassLevel[y][x] = 2;
            else if (val == TILE_GRASS3)
                grassLevel[y][x] = 3;
            else
                grassLevel[y][x] = 0;
        }
    }
}

function worldToMap(world)
{
    return new Vector2(Math.floor(world.x * INV_TILE_SIZE), Math.floor(world.y * INV_TILE_SIZE));
}

function mapToWorld(map)
{
    return new Vector2(map.x * TILE_SIZE + HALF_TILE_SIZE, map.y * TILE_SIZE + HALF_TILE_SIZE);
}

function map_getGrassAt(mapPos)
{
    if (mapPos.x < 0 || mapPos.y < 0 || mapPos.x >= MAP_SIZE || mapPos.y >= MAP_SIZE) return 0;
    return grassLevel[mapPos.y][mapPos.x];
}

function map_setGrassAt(mapPos, value)
{
    if (mapPos.x < 0 || mapPos.y < 0 || mapPos.x >= MAP_SIZE || mapPos.y >= MAP_SIZE) return;
    grassLevel[mapPos.y][mapPos.x] = value;
    if (value <= 0) tiledMap.setTileAt(GROUND_LAYER, mapPos.x, mapPos.y, TILE_GRASS0);
    else if (value <= 1) tiledMap.setTileAt(GROUND_LAYER, mapPos.x, mapPos.y, TILE_GRASS1);
    else if (value <= 2) tiledMap.setTileAt(GROUND_LAYER, mapPos.x, mapPos.y, TILE_GRASS2);
    else if (value <= 3) tiledMap.setTileAt(GROUND_LAYER, mapPos.x, mapPos.y, TILE_GRASS3);
}
<|endoftext|>


<commit_before>$(document).ready(function(){
    var dataset = {'id': 'guest'};
    connectServer('POST',
                  JSON.stringify(dataset),
                  'request',
                  function(data){
        if(data["status"] == "0"){
            $('#update_date').html('更新時間：' + data['message']['time'] + '　　　瀏覽次數：' + data['message']['counter']);
            $('#update_message').html(data['message']['message']);
            $('#requesting').hide();

            var statistic_sale = [0, 0, 0, 0, 0], statistic_total = [0, 0, 0, 0, 0], statistic_price = [400, 700, 1000, 1500];
            for(var i = 0; i < data['statistics'].length; i++){
                statistic_total[data['statistics'][i]['type']] += parseInt(data['statistics'][i]['num']);
                statistic_total[4] += parseInt(data['statistics'][i]['num']);
                if(parseInt(data['statistics'][i]['state']) == 2){
                    statistic_sale[data['statistics'][i]['type']] += parseInt(data['statistics'][i]['num']);
                    statistic_sale[4] += parseInt(data['statistics'][i]['num']);
                }
            }
            for(var i = 0; i < 4; i++){
                var rate = ((statistic_sale[i] / statistic_total[i]) * 100).toFixed(1);
                $('#statistic_label_' + i).html(statistic_price[i] + '元：' + rate + '%');
                $('#statistic_bar_progress_' + i).css('width', (rate * 1.7).toFixed());
            }

            $('#statistic_label_total').html("總計：" + (statistic_sale[4] / statistic_total[4] * 100).toFixed(1) + '%');
            $('#statistic_bar_progress_total').css('width', (statistic_sale[4] / statistic_total[4] * 170).toFixed());
            $('#statistic_label_DM').html("DM發送量： [" + data['DM']['sale'] + ' / ' + data['DM']['total'] + '] ' + (data['DM']['sale'] / data['DM']['total'] * 100).toFixed(1) + '%');
            $('#statistic_bar_progress_DM').css('width', (data['DM']['sale'] / data['DM']['total'] * 950).toFixed());

            for(var i = 0; i < data['ticket'].length; i++){
                var seat_id = '#seat_' + data['ticket'][i]['floor'] + '_' + data['ticket'][i]['row'] + '_' + data['ticket'][i]['seat'];
                var seat_state = parseInt(data['ticket'][i]['state']);
                var seat_type = parseInt(data['ticket'][i]['type']);
                var seat_preserve = parseInt(data['ticket'][i]['preserve']);
                if(seat_preserve == 1 || seat_preserve == 4 || seat_preserve == 5)
                    $(seat_id).addClass('seat_type_6');
                else if(seat_state == 2)
                    $(seat_id).addClass('seat_type_5');
                else if(seat_state == 1)
                    $(seat_id).addClass('seat_type_4');
                else{
                    if(seat_type >= 4)
                        $(seat_id).addClass('seat_type_6');
                    else
                        $(seat_id).addClass('seat_type_' + seat_type);
                }
            }
            $('#message').show();
            $('#floor_4').show();
            $('#floor_3').show();
            $('#floor_2').show();
            $('#statistic').show();
        }
        else if(data["status"] == '1'){
            $('#requesting').html('目前非購票時段');
        }
        else{
            $('#requesting').html('讀取失敗，請稍候再試或聯絡管理員');
        }
    });
});
<commit_msg>fix map<commit_after>$(document).ready(function(){
    var dataset = {'id': 'guest'};
    connectServer('POST',
                  JSON.stringify(dataset),
                  'request',
                  function(data){
        if(data["status"] == "0"){
            $('#update_date').html('更新時間：' + data['message']['time'] + '　　　瀏覽次數：' + data['message']['counter']);
            $('#update_message').html(data['message']['message']);
            $('#requesting').hide();

            var statistic_sale = [0, 0, 0, 0, 0], statistic_total = [0, 0, 0, 0, 0], statistic_price = [400, 700, 1000, 1500];
            for(var i = 0; i < data['statistics'].length; i++){
                statistic_total[data['statistics'][i]['type']] += parseInt(data['statistics'][i]['num']);
                statistic_total[4] += parseInt(data['statistics'][i]['num']);
                if(parseInt(data['statistics'][i]['state']) == 2){
                    statistic_sale[data['statistics'][i]['type']] += parseInt(data['statistics'][i]['num']);
                    statistic_sale[4] += parseInt(data['statistics'][i]['num']);
                }
            }
            for(var i = 0; i < 4; i++){
                var rate = ((statistic_sale[i] / statistic_total[i]) * 100).toFixed(1);
                $('#statistic_label_' + i).html(statistic_price[i] + '元：' + rate + '%');
                $('#statistic_bar_progress_' + i).css('width', (rate * 1.7).toFixed());
            }

            $('#statistic_label_total').html("總計：" + (statistic_sale[4] / statistic_total[4] * 100).toFixed(1) + '%');
            $('#statistic_bar_progress_total').css('width', (statistic_sale[4] / statistic_total[4] * 170).toFixed());
            $('#statistic_label_DM').html("DM發送量： [" + data['DM']['sale'] + ' / ' + data['DM']['total'] + '] ' + (data['DM']['sale'] / data['DM']['total'] * 100).toFixed(1) + '%');
            $('#statistic_bar_progress_DM').css('width', (data['DM']['sale'] / data['DM']['total'] * 950).toFixed());

            for(var i = 0; i < data['ticket'].length; i++){
                var seat_id = '#seat_' + data['ticket'][i]['floor'] + '_' + data['ticket'][i]['row'] + '_' + data['ticket'][i]['seat'];
                var seat_state = parseInt(data['ticket'][i]['state']);
                var seat_type = parseInt(data['ticket'][i]['type']);
                var seat_preserve = parseInt(data['ticket'][i]['preserve']);
                if(seat_preserve > 0)
                    $(seat_id).addClass('seat_type_6');
                else if(seat_state == 2)
                    $(seat_id).addClass('seat_type_5');
                else if(seat_state == 1)
                    $(seat_id).addClass('seat_type_4');
                else{
                    if(seat_type >= 4)
                        $(seat_id).addClass('seat_type_6');
                    else
                        $(seat_id).addClass('seat_type_' + seat_type);
                }
            }
            $('#message').show();
            $('#floor_4').show();
            $('#floor_3').show();
            $('#floor_2').show();
            $('#statistic').show();
        }
        else if(data["status"] == '1'){
            $('#requesting').html('目前非購票時段');
        }
        else{
            $('#requesting').html('讀取失敗，請稍候再試或聯絡管理員');
        }
    });
});
<|endoftext|>


<commit_before>'use strict';

function Map(nodes, ui) {
	this.nodes = nodes;
	this.instructions = this.getThePath();
	ui.renderMap(this);
}

Map.prototype.getThePath = function() {
	var instructions = {};
	var prevCoord = null;
	var twoBack = null;
	var node = null;

	if(this.nodes.length == 0) {
		return instructions;
	}

	for (var i = 0; i <= this.nodes.length; i++) {
		node = i < this.nodes.length ? this.nodes[i] : node;
		var coord = transformY(node.coordinate);

		if (prevCoord) {

			if (isHorizontal(prevCoord, coord)
				&& (twoBack == null || isHorizontal(twoBack, prevCoord))) {
				pushInstruction(instructions, prevCoord, 'H');

			} else if (isVertical(prevCoord, coord)
				&& (twoBack == null || isVertical(twoBack, prevCoord))) {
				pushInstruction(instructions, prevCoord, 'V');

			// Handle turns.
			} else {
				if(isProgressive(twoBack.x, prevCoord.x)) {
					pushInstruction(instructions, prevCoord,
						nextPointAbove(prevCoord, coord) ? 'DL' : 'UL');
				}
				if(isProgressive(prevCoord.x, twoBack.x)) {
					pushInstruction(instructions, prevCoord,
						nextPointAbove(prevCoord, coord) ? 'DR' : 'UR');
				}
				if(isProgressive(twoBack.y, prevCoord.y)) {
					pushInstruction(instructions, prevCoord,
						nextPointFurther(prevCoord, coord) ? 'UR' : 'UL');
				}
				if(isProgressive(prevCoord.y, twoBack.y)) {
					pushInstruction(instructions, prevCoord,
						nextPointFurther(prevCoord, coord) ? 'DR' : 'DL');
				}
			}
			twoBack = prevCoord;
			prevCoord = coord;

		} else {
			prevCoord = coord;
		}
	}
	return instructions;

	// Helper methods for generating the path.
	function transformY(coord) {
	    return new Coordinate(coord.x, coord.y);
	}

	function pushInstruction(json, coord, instruction) {
		var x = coord.x.toString();
		var y = coord.y.toString();
		if (!json.hasOwnProperty(x)) {
			json[x] = {};
		}
		json[x][y] = instruction;
	}

	function isHorizontal(prev, next) {
		return prev.y == next.y;
	}

	function isVertical(prev, next) {
		return prev.x == next.x;
	}

	function checkTurn(prev, next) {
		return next.x + next.y - prev.x - prev.y;
	}

	function nextPointAbove(curr, next) {
		return curr.y < next.y;
	}

	function nextPointFurther(curr, next) {
		return curr.x < next.x;
	}

	function isProgressive(coord1, coord2) {
		return coord1 < coord2;
	}
};
<commit_msg>Pushed the hack for the legacy default level. Random road will exceed the limits of the paper for this reason.<commit_after>'use strict';

function Map(nodes, ui) {
	this.nodes = nodes;
	this.instructions = this.getThePath();
	ui.renderMap(this);
}

Map.prototype.getThePath = function() {
	var instructions = {};
	var prevCoord = null;
	var twoBack = null;
	var node = null;

	if(this.nodes.length == 0) {
		return instructions;
	}

	for (var i = 0; i <= this.nodes.length; i++) {
		node = i < this.nodes.length ? this.nodes[i] : node;
		var coord = transformY(node.coordinate);

		if (prevCoord) {

			if (isHorizontal(prevCoord, coord)
				&& (twoBack == null || isHorizontal(twoBack, prevCoord))) {
				pushInstruction(instructions, prevCoord, 'H');

			} else if (isVertical(prevCoord, coord)
				&& (twoBack == null || isVertical(twoBack, prevCoord))) {
				pushInstruction(instructions, prevCoord, 'V');

			// Handle turns.
			} else {
				if(isProgressive(twoBack.x, prevCoord.x)) {
					pushInstruction(instructions, prevCoord,
						nextPointAbove(prevCoord, coord) ? 'DL' : 'UL');
				}
				if(isProgressive(prevCoord.x, twoBack.x)) {
					pushInstruction(instructions, prevCoord,
						nextPointAbove(prevCoord, coord) ? 'DR' : 'UR');
				}
				if(isProgressive(twoBack.y, prevCoord.y)) {
					pushInstruction(instructions, prevCoord,
						nextPointFurther(prevCoord, coord) ? 'UR' : 'UL');
				}
				if(isProgressive(prevCoord.y, twoBack.y)) {
					pushInstruction(instructions, prevCoord,
						nextPointFurther(prevCoord, coord) ? 'DR' : 'DL');
				}
			}
			twoBack = prevCoord;
			prevCoord = coord;

		} else {
			prevCoord = coord;
		}
	}
	return instructions;

	// Helper methods for generating the path.
	function transformY(coord) {
	    return new Coordinate(coord.x, 4 - coord.y);
	}

	function pushInstruction(json, coord, instruction) {
		var x = coord.x.toString();
		var y = coord.y.toString();
		if (!json.hasOwnProperty(x)) {
			json[x] = {};
		}
		json[x][y] = instruction;
	}

	function isHorizontal(prev, next) {
		return prev.y == next.y;
	}

	function isVertical(prev, next) {
		return prev.x == next.x;
	}

	function checkTurn(prev, next) {
		return next.x + next.y - prev.x - prev.y;
	}

	function nextPointAbove(curr, next) {
		return curr.y < next.y;
	}

	function nextPointFurther(curr, next) {
		return curr.x < next.x;
	}

	function isProgressive(coord1, coord2) {
		return coord1 < coord2;
	}
};
<|endoftext|>


<commit_before>/* ============================================================
 * Bootstrap: rowlink.js v3.1.3
 * http://jasny.github.io/bootstrap/javascript/#rowlink
 * ============================================================
 * Copyright 2012-2014 Arnold Daniels
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============================================================ */

+function ($) { "use strict";

  var Rowlink = function (element, options) {
    this.$element = $(element)
    this.options = $.extend({}, Rowlink.DEFAULTS, options)

    this.$element.on('click.bs.rowlink mouseup.bs.rowlink', 'td:not(.rowlink-skip)', $.proxy(this.click, this))
  }

  Rowlink.DEFAULTS = {
    target: "a"
  }

  Rowlink.prototype.click = function(e, ctrlKey) {
    var target = $(e.currentTarget).closest('tr').find(this.options.target)[0]

    if ($(e.target)[0] === target) return
    if (e.type === 'mouseup' && e.which !== 2) return

    e.preventDefault();
    ctrlKey = ctrlKey || e.ctrlKey || (e.type === 'mouseup' && e.which === 2)

    if (!ctrlKey && target.click) {
      target.click()
    } else if (document.createEvent) {
      var evt = document.createEvent("MouseEvents");
      evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, ctrlKey, false, false, false, 0, null);
      target.dispatchEvent(evt);
    }
  }

  // ROWLINK PLUGIN DEFINITION
  // ===========================

  var old = $.fn.rowlink

  $.fn.rowlink = function (options) {
    return this.each(function () {
      var $this = $(this)
      var data = $this.data('bs.rowlink')
      if (!data) $this.data('bs.rowlink', (data = new Rowlink(this, options)))
    })
  }

  $.fn.rowlink.Constructor = Rowlink

  // ROWLINK NO CONFLICT
  // ====================

  $.fn.rowlink.noConflict = function () {
    $.fn.rowlink = old
    return this
  }

  // ROWLINK DATA-API
  // ==================

  $(document).on('click.bs.rowlink.data-api mouseup.bs.rowlink.data-api', '[data-link="row"]', function (e) {
    if (e.type === 'mouseup' && e.which !== 2) return
    if ($(e.target).closest('.rowlink-skip').length !== 0) return

    var $this = $(this)
    if ($this.data('bs.rowlink')) return
    $this.rowlink($this.data())

    var ctrlKey = e.ctrlKey || e.which === 2
    $(e.target).trigger('click.bs.rowlink', [ctrlKey])
  })

}(window.jQuery);
<commit_msg>Fix #366: Target is undefined on row whitout link (rowlink)<commit_after>/* ============================================================
 * Bootstrap: rowlink.js v3.1.3
 * http://jasny.github.io/bootstrap/javascript/#rowlink
 * ============================================================
 * Copyright 2012-2014 Arnold Daniels
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============================================================ */

+function ($) { "use strict";

  var Rowlink = function (element, options) {
    this.$element = $(element)
    this.options = $.extend({}, Rowlink.DEFAULTS, options)

    this.$element.on('click.bs.rowlink mouseup.bs.rowlink', 'td:not(.rowlink-skip)', $.proxy(this.click, this))
  }

  Rowlink.DEFAULTS = {
    target: "a"
  }

  Rowlink.prototype.click = function(e, ctrlKey) {
    var target = $(e.currentTarget).closest('tr').find(this.options.target)[0]

    if (typeof target == 'undefined' || $(e.target)[0] === target) return
    if (e.type === 'mouseup' && e.which !== 2) return

    e.preventDefault();
    ctrlKey = ctrlKey || e.ctrlKey || (e.type === 'mouseup' && e.which === 2)

    if (!ctrlKey && target.click) {
      target.click()
    } else if (document.createEvent) {
      var evt = document.createEvent("MouseEvents");
      evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, ctrlKey, false, false, false, 0, null);
      target.dispatchEvent(evt);
    }
  }

  // ROWLINK PLUGIN DEFINITION
  // ===========================

  var old = $.fn.rowlink

  $.fn.rowlink = function (options) {
    return this.each(function () {
      var $this = $(this)
      var data = $this.data('bs.rowlink')
      if (!data) $this.data('bs.rowlink', (data = new Rowlink(this, options)))
    })
  }

  $.fn.rowlink.Constructor = Rowlink

  // ROWLINK NO CONFLICT
  // ====================

  $.fn.rowlink.noConflict = function () {
    $.fn.rowlink = old
    return this
  }

  // ROWLINK DATA-API
  // ==================

  $(document).on('click.bs.rowlink.data-api mouseup.bs.rowlink.data-api', '[data-link="row"]', function (e) {
    if (e.type === 'mouseup' && e.which !== 2) return
    if ($(e.target).closest('.rowlink-skip').length !== 0) return

    var $this = $(this)
    if ($this.data('bs.rowlink')) return
    $this.rowlink($this.data())

    var ctrlKey = e.ctrlKey || e.which === 2
    $(e.target).trigger('click.bs.rowlink', [ctrlKey])
  })

}(window.jQuery);
<|endoftext|>


<commit_before>// JavaScript source code
$(document).ready(function () {
$('form').submit(function (evt) {
	evt.preventDefault();
	var searchTerm = $('#input').val();

	// AJAX Starts

	var flickrAPI = "https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
	var animal = searchTerm;
	var flickrOptions = {
		tags: animal,
		format: "json",

	};
	function displayPhotos(data) {
		var photoHTML = '
';
		$.each(data.items, function(i,photo) {
			photoHTML += '
';
			photoHTML += '';
			photoHTML += '
';
		});
		photoHTML += '
';
		$('#photos').html(photoHTML);
	}

		$.getJSON(flickrAPI, flickrOptions, displayPhotos);

}) //end submit

// Fire AJAX every time page reaches 70% of height
    $(document).scroll(function(e){

        if (processing)
            return false;

        if ( $(document).scrollTop() >= ( $(document).height() - $(window).height() ) {
	    console.log('reached');
            processing = true;
            $.getJSON(flickrAPI, flickrOptions, displayPhotos);
	    processing = false;
        }
    });

}); // end ready

<commit_msg>Update scripts.js<commit_after>// JavaScript source code
$(document).ready(function () {
$('form').submit(function (evt) {
	evt.preventDefault();
	var searchTerm = $('#input').val();

	// AJAX Starts

	var flickrAPI = "https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
	var animal = searchTerm;
	var flickrOptions = {
		tags: animal,
		format: "json",

	};
	function displayPhotos(data) {
		var photoHTML = '
';
		$.each(data.items, function(i,photo) {
			photoHTML += '
';
			photoHTML += '';
			photoHTML += '
';
		});
		photoHTML += '
';
		$('#photos').html(photoHTML);
	}

		$.getJSON(flickrAPI, flickrOptions, displayPhotos);

}) //end submit

// Fire AJAX every time page reaches 70% of height
     var processing;
    $(document).scroll(function(e){

        if (processing)
            return false;

        if ( $(document).scrollTop() >= ( $(document).height() - $(window).height() ) {
	    console.log('reached');
            processing = true;
            $.getJSON(flickrAPI, flickrOptions, displayPhotos);
	    processing = false;
        }
    });

}); // end ready

<|endoftext|>


<commit_before>//Funcoes especificas do Phonegap
var celular_modelo = "";
var celular_plataforma = "";
var celular_uuid = "";
var celular_versao = "";
var isPhoneGapReady = false;
var isConnected = false;
var isHighSpeed = false;
var pictureSource;   // picture source
var destinationType; // sets the format of returned value
var email_aplicativo;

function echeck(str) {
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){
	   //alert("Invalid E-mail ID")
	   return false
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   //alert("Invalid E-mail ID")
	   return false
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		//alert("Invalid E-mail ID")
		return false
	}

	 if (str.indexOf(at,(lat+1))!=-1){
		//alert("Invalid E-mail ID")
		return false
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		//alert("Invalid E-mail ID")
		return false
	 }

	 if (str.indexOf(dot,(lat+2))==-1){
		//alert("Invalid E-mail ID")
		return false
	 }

	 if (str.indexOf(" ")!=-1){
		//alert("Invalid E-mail ID")
		return false
	 }

	 return true
}

document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {
    pictureSource = navigator.camera.PictureSourceType;
    destinationType = navigator.camera.DestinationType;
	isPhoneGapReady = true;
	// detect for network access
	networkDetection();
	// attach events for online and offline detection
	document.addEventListener("online", onOnline, false);
	document.addEventListener("offline", onOffline, false);

	var conteudo = "";
	conteudo = conteudo + 'Modelo: '    + device.model    + '
';
	conteudo = conteudo + 'Plataforma: ' + device.platform + '
';
	conteudo = conteudo + 'UUID: '     + device.uuid     + '
';
	conteudo = conteudo + 'Verso: '  + device.version  + '
';
	conteudo = conteudo + 'Bateria: '  + status_bateria  + '
';

	celular_modelo = device.model;
	celular_plataforma = device.platform;
	celular_uuid = device.uuid;
	celular_versao = device.version;
	$("#deviceproperties").append(conteudo);

}

// alert dialog dismissed
function alertDismissed() {
	// do something
}

function AlertConfirmed(buttonIndex) {
	if (buttonIndex ==1){ //OK
		$.mobile.changePage("#foto");
	}
	if (buttonIndex ==2){ //Cancelar
		$.mobile.changePage("#pageone");
	}
}

function networkDetection() {
	if (isPhoneGapReady) {
		// as long as the connection type is not none,
		// the device should have Internet access
		if (navigator.network.connection.type != Connection.NONE) {
			isConnected = true;
		}
		// determine whether this connection is high-speed
		switch (navigator.network.connection.type) {
			case Connection.UNKNOWN:
			case Connection.CELL_2G:
				isHighSpeed = false;
				break;
			default:
				isHighSpeed = true;
				break;
		}
	}
}

function onOnline() {
	isConnected = true;
}

function onOffline() {
	isConnected = false;
}

function clearCache() {
	    navigator.camera.cleanup();
}

	var retries = 0;
	function onCapturePhoto(fileURI) {
	    var win = function (r) {
	        clearCache();
	        retries = 0;
	        //navigator.notification.alert('Concluido! A foto foi enviada para nosso servidor!', alertDismissed, 'Enviar Foto', 'OK');
			navigator.notification.confirm( 'Concluido! A foto foi enviada para nosso servidor! Deseja enviar outra foto?', AlertConfirmed, 'Enviar Foto', ['OK, CANCELAR']);
			//$.mobile.changePage("#main");
	    }

	    var fail = function (error) {
	        if (retries == 0) {
	            retries ++
	            setTimeout(function() {
	                onCapturePhoto(fileURI)
	            }, 1000)
	        } else {
	            retries = 0;
	            clearCache();
	            navigator.notification.alert('Ocorreu um problema!', alertDismissed, 'Enviar Foto', 'OK');
				$.mobile.changePage("#main");
	        }
	    }

		$('#content_news').text('Aguarde, a foto est sendo enviada para o nosso servidor!');

	    var options = new FileUploadOptions();
	    options.fileKey = "recFile";
	    options.fileName = fileURI.substr(fileURI.lastIndexOf('/') + 1);
	    options.mimeType = "image/jpeg";

		var params = new Object();
        params.email = email_aplicativo;

	    //options.params = {}; // if we need to send parameters to the server request
		options.params = params;

	    var ft = new FileTransfer();
	    ft.upload(fileURI, encodeURI("http://www.gotasdecidadania.com.br/novo/programado/upload_foto.php"), win, fail, options);
	}

	function capturePhoto() {
	    navigator.camera.getPicture(onCapturePhoto, onFail, {
	        quality: 100,
	        destinationType: destinationType.FILE_URI
	    });
	}

	function onFail(message) {
	    navigator.notification.alert('Ocorreu o seguinte erro: ' + message, alertDismissed, 'Enviar Foto', 'OK');
	}

	$(document).on('pageinit', '#pageone', function(){
		$(document).on('click', '#enviar_contato', function() { // catch the form's submit event

			var continuar = true;
			var mensagem ="Ocorreram os seguintes erros:\n";

			if ($('#email_contato').val() == "") {
				mensagem = mensagem +  'Digite o endereco de e-mail\n';
				continuar = false;
			} else {
				if (echeck($('#email_contato').val())==false){
				mensagem = mensagem + 'Preencha corretamente o endereco de e-mail\n';
				continuar = false;
				}
			}

			if (continuar){
				email_aplicativo = $('#email_contato').val();
				$.mobile.changePage("#foto");
			} else {
				alert(mensagem);
			}
			return false; // cancel original event to prevent form submitting

		});
	});

	$(document).on('pageinit', '#foto', function(){
		if (isPhoneGapReady){
			if (isConnected) {
				capturePhoto();
			} else {
				navigator.notification.alert('No existe conexo com a Internet', alertDismissed, 'Enviar Foto', 'OK');
				$.mobile.changePage("#main");
			}
		} else {
			navigator.notification.alert('O aplicativo no est pronto!', alertDismissed, 'Enviar Foto', 'OK');
			$.mobile.changePage("#main");
		}
	});<commit_msg>2015-12-31<commit_after>//Funcoes especificas do Phonegap
var celular_modelo = "";
var celular_plataforma = "";
var celular_uuid = "";
var celular_versao = "";
var isPhoneGapReady = false;
var isConnected = false;
var isHighSpeed = false;
var pictureSource;   // picture source
var destinationType; // sets the format of returned value
var email_aplicativo;

function echeck(str) {
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){
	   //alert("Invalid E-mail ID")
	   return false
	}

	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   //alert("Invalid E-mail ID")
	   return false
	}

	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		//alert("Invalid E-mail ID")
		return false
	}

	 if (str.indexOf(at,(lat+1))!=-1){
		//alert("Invalid E-mail ID")
		return false
	 }

	 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		//alert("Invalid E-mail ID")
		return false
	 }

	 if (str.indexOf(dot,(lat+2))==-1){
		//alert("Invalid E-mail ID")
		return false
	 }

	 if (str.indexOf(" ")!=-1){
		//alert("Invalid E-mail ID")
		return false
	 }

	 return true
}

document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {
    pictureSource = navigator.camera.PictureSourceType;
    destinationType = navigator.camera.DestinationType;
	isPhoneGapReady = true;
	// detect for network access
	networkDetection();
	// attach events for online and offline detection
	document.addEventListener("online", onOnline, false);
	document.addEventListener("offline", onOffline, false);

	var conteudo = "";
	conteudo = conteudo + 'Modelo: '    + device.model    + '
';
	conteudo = conteudo + 'Plataforma: ' + device.platform + '
';
	conteudo = conteudo + 'UUID: '     + device.uuid     + '
';
	conteudo = conteudo + 'Verso: '  + device.version  + '
';
	conteudo = conteudo + 'Bateria: '  + status_bateria  + '
';

	celular_modelo = device.model;
	celular_plataforma = device.platform;
	celular_uuid = device.uuid;
	celular_versao = device.version;
	$("#deviceproperties").append(conteudo);

}

// alert dialog dismissed
function alertDismissed() {
	// do something
}

function AlertConfirmed(buttonIndex) {
	if (buttonIndex ==1){ //OK
		$.mobile.changePage("#foto");
	}
	if (buttonIndex ==2){ //Cancelar
		$.mobile.changePage("#pageone");
	}
}

function networkDetection() {
	if (isPhoneGapReady) {
		// as long as the connection type is not none,
		// the device should have Internet access
		if (navigator.network.connection.type != Connection.NONE) {
			isConnected = true;
		}
		// determine whether this connection is high-speed
		switch (navigator.network.connection.type) {
			case Connection.UNKNOWN:
			case Connection.CELL_2G:
				isHighSpeed = false;
				break;
			default:
				isHighSpeed = true;
				break;
		}
	}
}

function onOnline() {
	isConnected = true;
}

function onOffline() {
	isConnected = false;
}

function clearCache() {
	    navigator.camera.cleanup();
}

	var retries = 0;
	function onCapturePhoto(fileURI) {
	    var win = function (r) {
	        clearCache();
	        retries = 0;
	        //navigator.notification.alert('Concluido! A foto foi enviada para nosso servidor!', alertDismissed, 'Enviar Foto', 'OK');
			navigator.notification.confirm( 'Concluido! A foto foi enviada para nosso servidor! Deseja enviar outra foto?', AlertConfirmed, 'Enviar Foto', ['OK', 'SAIR']);
			//$.mobile.changePage("#main");
	    }

	    var fail = function (error) {
	        if (retries == 0) {
	            retries ++
	            setTimeout(function() {
	                onCapturePhoto(fileURI)
	            }, 1000)
	        } else {
	            retries = 0;
	            clearCache();
	            navigator.notification.alert('Ocorreu um problema!', alertDismissed, 'Enviar Foto', 'OK');
				$.mobile.changePage("#main");
	        }
	    }

		$('#content_news').text('Aguarde, a foto est sendo enviada para o nosso servidor!');

	    var options = new FileUploadOptions();
	    options.fileKey = "recFile";
	    options.fileName = fileURI.substr(fileURI.lastIndexOf('/') + 1);
	    options.mimeType = "image/jpeg";

		var params = new Object();
        params.email = email_aplicativo;

	    //options.params = {}; // if we need to send parameters to the server request
		options.params = params;

	    var ft = new FileTransfer();
	    ft.upload(fileURI, encodeURI("http://www.gotasdecidadania.com.br/novo/programado/upload_foto.php"), win, fail, options);
	}

	function capturePhoto() {
	    navigator.camera.getPicture(onCapturePhoto, onFail, {
	        quality: 100,
	        destinationType: destinationType.FILE_URI
	    });
	}

	function onFail(message) {
	    navigator.notification.alert('Ocorreu o seguinte erro: ' + message, alertDismissed, 'Enviar Foto', 'OK');
	}

	$(document).on('pageinit', '#pageone', function(){
		$(document).on('click', '#enviar_contato', function() { // catch the form's submit event

			var continuar = true;
			var mensagem ="Ocorreram os seguintes erros:\n";

			if ($('#email_contato').val() == "") {
				mensagem = mensagem +  'Digite o endereco de e-mail\n';
				continuar = false;
			} else {
				if (echeck($('#email_contato').val())==false){
				mensagem = mensagem + 'Preencha corretamente o endereco de e-mail\n';
				continuar = false;
				}
			}

			if (continuar){
				email_aplicativo = $('#email_contato').val();
				$.mobile.changePage("#foto");
			} else {
				alert(mensagem);
			}
			return false; // cancel original event to prevent form submitting

		});
	});

	$(document).on('pageinit', '#foto', function(){
		if (isPhoneGapReady){
			if (isConnected) {
				capturePhoto();
			} else {
				navigator.notification.alert('No existe conexo com a Internet', alertDismissed, 'Enviar Foto', 'OK');
				$.mobile.changePage("#main");
			}
		} else {
			navigator.notification.alert('O aplicativo no est pronto!', alertDismissed, 'Enviar Foto', 'OK');
			$.mobile.changePage("#main");
		}
	});<|endoftext|>