/ Gists

Gists

On gists

From https://www.sitepoint.com/introduction-jquery-deferred-objects/

jQuery jQuery-plugins

deferred-timeout.js #

function timeout(milliseconds) {
  // Create a new Deferred object
  var deferred = $.Deferred();

  // Resolve the Deferred after the amount of time specified by milliseconds
  setTimeout(deferred.resolve, milliseconds);

  // Return the Deferred's Promise object
  return deferred.promise();
}

timeout(1000).then(function() {
  console.log('I waited for 1 second!');
});

On gists

google maps - multiple - ekospol (http://www.ekospol.cz/byty/prodej-bytu-praha)

Gmaps

google-maps-multiple-w-animation #

// Define your locations: HTML content for the info window, latitude, longitude
    var locations = [
      ['<div id="iw-container"><div class="iw-title">EKOCITY Hostivař</div><img src="http://www.ekospol.cz/assets/ekospol/ekocity_hostivar/vizualizace/4.jpg" alt="EKOCITY Hostivař" width="100%"><div class="iw-content"><a href="http://www.ekospol.cz/byty/prodej-bytu-praha/ekocity-hostivar/" class="button block-button primary" >Detail projektu</a></div></div>', 50.057417, 14.541753],
      ['<div id="iw-container"><div class="iw-title">Výhledy Barrandov</div><img src="http://www.ekospol.cz/assets/ekospol/vyhledy_barrandov/vyhledy-barrandov-viz.jpg" alt="Výhledy Barrandov" width="100%"><div class="iw-content"><a href="http://www.ekospol.cz/byty/prodej-bytu-praha/barrandov/" class="button block-button primary" >Detail projektu</a></div></div>', 50.031184, 14.362346],
      ['<div id="iw-container"><div class="iw-title">Panorama Kyje VIII</div><img src="http://www.ekospol.cz/assets/ekospol/panorama_kyje_viii/panorama-kyje-viii.jpg" alt="Panorama Kyje VIII" width="100%"><div class="iw-content"><a href="http://www.ekospol.cz/byty/prodej-bytu-praha/kyje-viii/" class="button block-button primary" >Detail projektu</a></div></div>', 50.115141, 14.567291],
      ['<div id="iw-container"><div class="iw-title">Viladomy Dubeč</div><img src="http://www.ekospol.cz/assets/ekospol/viladomy_dubec/viladomy-dubec.jpg" alt="Viladomy Dubeč" width="100%"><div class="iw-content"><a href="http://www.ekospol.cz/byty/prodej-bytu-praha/dubec/" class="button block-button primary" >Detail projektu</a></div></div>', 50.060931, 14.581599],
      ['<div id="iw-container"><div class="iw-title">EKOCITY Uhříněves I</div><img src="http://www.ekospol.cz/assets/ekospol/ekocity_uhrineves/ekocity-uhrineves.jpg" alt="EKOCITY Uhříněves I" width="100%"><div class="iw-content"><a href="http://www.ekospol.cz/byty/prodej-bytu-praha/ekocity-uhrineves/" class="button block-button primary" >Detail projektu</a></div></div>', 50.031954, 14.590639],
      ['<div id="iw-container"><div class="iw-title">Panorama Kyje VII</div><img src="http://www.ekospol.cz/assets/ekospol/panorama_kyje_vii/panorama-kyje-vii.jpg" alt="Panorama Kyje VII" width="100%"><div class="iw-content"><a href="http://www.ekospol.cz/byty/prodej-bytu-praha/kyje-vii/" class="button block-button primary" >Detail projektu</a></div></div>', 50.116056, 14.566058],
      ['<div id="iw-container"><div class="iw-title">Nové Měcholupy VI</div><img src="http://www.ekospol.cz/assets/ekospol/nove_mecholupy_vi/nove-mecholupy-vi.jpg" alt="Nové Měcholupy VI" width="100%"><div class="iw-content"><a href="http://www.ekospol.cz/byty/prodej-bytu-praha/mecholupy-vi/" class="button block-button primary" >Detail projektu</a></div></div>', 50.047834, 14.556056],
      ['<div id="iw-container"><div class="iw-title">Slunečné terasy</div><img src="http://www.ekospol.cz/assets/ekospol/slunecne_terasy/slunecne-terasy.jpg" alt="Slunečné terasy" width="100%"><div class="iw-content"><a href="http://www.ekospol.cz/byty/prodej-bytu-praha/slunecne-terasy/" class="button block-button primary" >Detail projektu</a></div></div>', 50.038257, 14.318665],
      ['<div id="iw-container"><div class="iw-title">Michelské zahrady</div><img src="http://www.ekospol.cz/assets/ekospol/michelske_zahrady/michelske-zahrady.jpg" alt="Michelské zahrady" width="100%"><div class="iw-content"><a href="http://www.ekospol.cz/byty/prodej-bytu-praha/michelske-zahrady/" class="button block-button primary" >Detail projektu</a></div></div>', 50.056753, 14.462231]
      ];   
    
    // When the window has finished loading create our google map below
            google.maps.event.addDomListener(window, 'load', init);  
    
 function init() {   
    // Setup the different icons and shadows
    var iconURLPrefix = 'http://www.ekospol.cz/assets/images/';
    
    var icons = [
      iconURLPrefix + 'home-green.png',
      iconURLPrefix + 'home-green.png',
      iconURLPrefix + 'home-green.png',
      iconURLPrefix + 'home-green.png',
      iconURLPrefix + 'home-green.png',
      iconURLPrefix + 'home-green.png',
      iconURLPrefix + 'home-green.png'
    ]
    var iconsLength = icons.length;

       var mapOptions = {
                    // How zoomed in you want the map to start at (always required)
                    zoom: 11,

                    // The latitude and longitude to center the map (always required)
                    center: new google.maps.LatLng(50.075452, 14.434719), // Prague
                    scrollwheel: false,
                    // How you would like to style the map. 
                    // This is where you would paste any style found on Snazzy Maps.
                    styles: [{"featureType":"landscape.man_made","elementType":"geometry","stylers":[{"color":"#f7f1df"}]},{"featureType":"landscape.natural","elementType":"geometry","stylers":[{"color":"#d0e3b4"}]},{"featureType":"landscape.natural.terrain","elementType":"geometry","stylers":[{"visibility":"off"}]},{"featureType":"poi","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"poi.business","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"poi.medical","elementType":"geometry","stylers":[{"color":"#fbd3da"}]},{"featureType":"poi.park","elementType":"geometry","stylers":[{"color":"#bde6ab"}]},{"featureType":"road","elementType":"geometry.stroke","stylers":[{"visibility":"off"}]},{"featureType":"road","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"road.highway","elementType":"geometry.fill","stylers":[{"color":"#ffe15f"}]},{"featureType":"road.highway","elementType":"geometry.stroke","stylers":[{"color":"#efd151"}]},{"featureType":"road.arterial","elementType":"geometry.fill","stylers":[{"color":"#ffffff"}]},{"featureType":"road.local","elementType":"geometry.fill","stylers":[{"color":"black"}]},{"featureType":"transit.station.airport","elementType":"geometry.fill","stylers":[{"color":"#cfb2db"}]},{"featureType":"water","elementType":"geometry","stylers":[{"color":"#a2daf2"}]}]
                };
// Get the HTML DOM element that will contain your map 
                // We are using a div with id="map" seen below in the <body>
                var mapElement = document.getElementById('map');

                // Create the Google Map using our element and options defined above
                var map = new google.maps.Map(mapElement, mapOptions);
    
                var infowindow = new google.maps.InfoWindow({
      //maxWidth: 172       
    });

    var markers = new Array();
    
    var iconCounter = 0;
    
    // Add the markers and infowindows to the map
    for (var i = 0; i < locations.length; i++) {  
      var marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        animation: google.maps.Animation.DROP,
        map: map,
        icon: icons[iconCounter]
      });

      markers.push(marker);

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(locations[i][0]);
          infowindow.open(map, marker);
        }
      })(marker, i));
      
     function stopAnimation(marker) {
    setTimeout(function () {
        marker.setAnimation(null);
    }, 740);
}
      
      iconCounter++;
      // We only have a limited number of possible icon colors, so we may have to restart the counter
      if(iconCounter >= iconsLength) {
      	iconCounter = 0;
      }
    }
    
    // *
  // START INFOWINDOW CUSTOMIZE.
  // The google.maps.event.addListener() event expects
  // the creation of the infowindow HTML structure 'domready'
  // and before the opening of the infowindow, defined styles are applied.
  // *
  google.maps.event.addListener(infowindow, 'domready', function() {

    // Reference to the DIV that wraps the bottom of infowindow
    var iwOuter = $('.gm-style-iw');

    //* Since this div is in a position prior to .gm-div style-iw.
    // * We use jQuery and create a iwBackground variable,
    // * and took advantage of the existing reference .gm-style-iw for the previous div with .prev().
   // */
    var iwBackground = iwOuter.prev();

    // Removes background shadow DIV
    iwBackground.children(':nth-child(2)').css({'display' : 'none'});

    // Removes white background DIV
    iwBackground.children(':nth-child(4)').css({'display' : 'none'});

    // Changes the desired tail shadow color.
    iwBackground.children(':nth-child(3)').find('div').children().css({'box-shadow': '#00673e 0px 1px 6px', 'z-index' : '1', 'background-color' : '#00673e'});

    // Reference to the div that groups the close button elements.
    var iwCloseBtn = iwOuter.next();

    // Apply the desired effect to the close button
    iwCloseBtn.css({opacity: '1', right: '38px', top: '3px', border: '7px solid #00673e', 'border-radius': '13px', 'box-shadow': '0 0 5px #000000'});

    // If the content of infowindow not exceed the set maximum height, then the gradient is removed.
    if($('.iw-content').height() < 140){
      $('.iw-bottom-gradient').css({display: 'none'});
    }

    // The API automatically applies 0.7 opacity to the button after the mouseout event. This function reverses this event to the desired value.
    iwCloseBtn.mouseout(function(){
      $(this).css({opacity: '1'});
    });
  });

    function autoCenter() {
      //  Create a new viewpoint bound
      var bounds = new google.maps.LatLngBounds();
      //  Go through each...
      for (var i = 0; i < markers.length; i++) {  
				bounds.extend(markers[i].position);
      }
      //  Fit these bounds to the map
      map.fitBounds(bounds);
    }
    autoCenter();
    }

On gists

czech sort in array

PHP Helpers-Filters-Plugins

czech-sort.php #

<?php

function SortCzechChars($a, $b){
    static $czechCharsS = array('Á', 'Č', 'Ď', 'É', 'Ě' , 'Ch' , 'Í', 'Ň', 'Ó', 'Ř', 'Š', 'Ť', 'Ú', 'Ů' , 'Ý', 'Ž', 'á', 'č', 'ď', 'é', 'ě' , 'ch' , 'í', 'ň', 'ó', 'ř', 'š', 'ť', 'ú', 'ů' , 'ý', 'ž');
    static $czechCharsR = array('AZ','CZ','DZ','EZ','EZZ','HZZZ','IZ','NZ','OZ','RZ','SZ','TZ','UZ','UZZ','YZ','ZZ','az','cz','dz','ez','ezz','hzzz','iz','nz','oz','rz','sz','tz','uz','uzz','yz','zz');
 
    $A = str_replace($czechCharsS, $czechCharsR, $a);
    $B = str_replace($czechCharsS, $czechCharsR, $b);
 
    return strnatcasecmp($A, $B);
}

On gists

Filter do Latte

Nette

predlozky.php #

<?php


	public static function predlozky($string) {
		/*

			$string = preg_replace('~ ([akosvzAKOSVZ]) ~', ' $1&nbsp;', $string);
			$string = preg_replace('~^([AKOSVZ]) ~', ' $1&nbsp;', $string);

			return $string;

		*/

		$string = preg_replace('~ ([akosvuzAKOSVZ]) ~', ' $1&nbsp;', $string);
        $string = preg_replace('~^([AKOSVZ]) ~', ' $1&nbsp;', $string);
        // predlozky, tituly, jednotky
        for($i = 1; $i <= 3; $i++)
            $string = preg_replace('~( |&nbsp;)(i|na|ve|pod|nad|od|do|před|ke|ku|ze|bez|ob|pro|při|po|skrz|za|Ing|MUDr|JUDr|Mgr|Bc|BcA|Ing. arch|MVDr|PhDr|RNDr|Pharmr|ThLic|ThDr|prof|doc|PaeDr|Dr|PhMr) ~', '$1$2&nbsp;', $string);

        $string = preg_replace('~(Na|Ve|Pod|Nad|Od|Do|Před|Ke|Ku|Ze|Bez|Ob|Pro|Při|Po|Skrz|Za) ~', '$1&nbsp;', $string);
        
        // en
        for($i = 1; $i <= 3; $i++)
            $string = preg_replace('~( |&nbsp;)(for|the|its|high-school|was|of|in|on|an|a|are|who|is|we|to|as|and|by|from|has|be|about|I) ~', '$1$2&nbsp;', $string);
        
        $string = preg_replace('~(For|The|Its|High-school|Was|Of|In|On|An|Are|Who|Is|We|To|As|And|By|From|Has|Be|About|I) ~', '$1&nbsp;', $string);
        // ru
        $string = preg_replace('~( |&nbsp;)(в|с|и|из|на|со) ~i', '$1$2&nbsp;', $string);
        
         // veliciny
        $string = preg_replace('~([0-9]{1,}) (m{1,2}|cm|dm|ml|l|dcl|dl|g|kg|%|dkg|kg|s|A|K|cd|mol|rad|sr|Hz|N|Pa|J|W|C|V|F|Ω|S|Wb|T|H|lm|lx|Bq|Gy|Sv|kat)( |\.|\,|$)~', '$1&nbsp;$2$3', $string);
        
        // procenta
        //$string = preg_replace('~([0-9]{1,}) %~', "$1&nbsp;%", $string);

        // kalendarni data
        $string = preg_replace('~(\d{1,})\. (\d{1,})\. (\d{1,})~', "$1.&nbsp;$2.&nbsp;$3", $string);

        //$string = preg_replace('^(([ ][a-zA-Z\&]{1,2})|([a-zA-Z0-9 ,\.\(][0-9]{1,5}))[ ]^','$1&nbsp;', $string);

        return $string;

	}

On gists

From https://wrightshq.com/playground/placing-multiple-markers-on-a-google-map-using-api-3/

Gmaps

multiple-markers.js #

jQuery(function($) {
    // Asynchronously Load the map API 
    var script = document.createElement('script');
    script.src = "//maps.googleapis.com/maps/api/js?sensor=false&callback=initialize";
    document.body.appendChild(script);
});

function initialize() {
    var map;
    var bounds = new google.maps.LatLngBounds();
    var mapOptions = {
        mapTypeId: 'roadmap'
    };
                    
    // Display a map on the page
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    map.setTilt(45);
        
    // Multiple Markers
    var markers = [
        ['London Eye, London', 51.503454,-0.119562],
        ['Palace of Westminster, London', 51.499633,-0.124755]
    ];
                        
    // Info Window Content
    var infoWindowContent = [
        ['<div class="info_content">' +
        '<h3>London Eye</h3>' +
        '<p>The London Eye is a giant Ferris wheel situated on the banks of the River Thames. The entire structure is 135 metres (443 ft) tall and the wheel has a diameter of 120 metres (394 ft).</p>' +        '</div>'],
        ['<div class="info_content">' +
        '<h3>Palace of Westminster</h3>' +
        '<p>The Palace of Westminster is the meeting place of the House of Commons and the House of Lords, the two houses of the Parliament of the United Kingdom. Commonly known as the Houses of Parliament after its tenants.</p>' +
        '</div>']
    ];
        
    // Display multiple markers on a map
    var infoWindow = new google.maps.InfoWindow(), marker, i;
    
    // Loop through our array of markers & place each one on the map  
    for( i = 0; i < markers.length; i++ ) {
        var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
        bounds.extend(position);
        marker = new google.maps.Marker({
            position: position,
            map: map,
            title: markers[i][0]
        });
        
        // Allow each marker to have an info window    
        google.maps.event.addListener(marker, 'click', (function(marker, i) {
            return function() {
                infoWindow.setContent(infoWindowContent[i][0]);
                infoWindow.open(map, marker);
            }
        })(marker, i));

        // Automatically center the map fitting all markers on the screen
        map.fitBounds(bounds);
    }

    // Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
    var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
        this.setZoom(14);
        google.maps.event.removeListener(boundsListener);
    });
    
}

On gists

From http://stackoverflow.com/questions/3059044/google-maps-js-api-v3-simple-multiple-marker-example/3059129#3059129

Gmaps

multiple-marker2.js #

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>Multiple Markers Google Maps</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
        <script src="https://maps.googleapis.com/maps/api/js?v=3.11&sensor=false" type="text/javascript"></script>
        <script type="text/javascript">
        // check DOM Ready
        $(document).ready(function() {
            // execute
            (function() {
                // map options
                var options = {
                    zoom: 5,
                    center: new google.maps.LatLng(39.909736, -98.522109), // centered US
                    mapTypeId: google.maps.MapTypeId.TERRAIN,
                    mapTypeControl: false
                };

                // init map
                var map = new google.maps.Map(document.getElementById('map_canvas'), options);

                // NY and CA sample Lat / Lng
                var southWest = new google.maps.LatLng(40.744656, -74.005966);
                var northEast = new google.maps.LatLng(34.052234, -118.243685);
                var lngSpan = northEast.lng() - southWest.lng();
                var latSpan = northEast.lat() - southWest.lat();

                // set multiple marker
                for (var i = 0; i < 250; i++) {
                    // init markers
                    var marker = new google.maps.Marker({
                        position: new google.maps.LatLng(southWest.lat() + latSpan * Math.random(), southWest.lng() + lngSpan * Math.random()),
                        map: map,
                        title: 'Click Me ' + i
                    });

                    // process multiple info windows
                    (function(marker, i) {
                        // add click event
                        google.maps.event.addListener(marker, 'click', function() {
                            infowindow = new google.maps.InfoWindow({
                                content: 'Hello, World!!'
                            });
                            infowindow.open(map, marker);
                        });
                    })(marker, i);
                }
            })();
        });
        </script>
    </head>
    <body>
        <div id="map_canvas" style="width: 800px; height:500px;"></div>
    </body>
</html>

On gists

From http://stackoverflow.com/questions/3059044/google-maps-js-api-v3-simple-multiple-marker-example/3059129#3059129

Gmaps

simple-multiple-marker-google-ma #

<!DOCTYPE html>
<html> 
<head> 
  <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> 
  <title>Google Maps Multiple Markers</title> 
  <script src="http://maps.google.com/maps/api/js?sensor=false" 
          type="text/javascript"></script>
</head> 
<body>
  <div id="map" style="width: 500px; height: 400px;"></div>

  <script type="text/javascript">
    var locations = [
      ['Bondi Beach', -33.890542, 151.274856, 4],
      ['Coogee Beach', -33.923036, 151.259052, 5],
      ['Cronulla Beach', -34.028249, 151.157507, 3],
      ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
      ['Maroubra Beach', -33.950198, 151.259302, 1]
    ];

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 10,
      center: new google.maps.LatLng(-33.92, 151.25),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var infowindow = new google.maps.InfoWindow();

    var marker, i;

    for (i = 0; i < locations.length; i++) {  
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map
      });

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(locations[i][0]);
          infowindow.open(map, marker);
        }
      })(marker, i));
    }
  </script>
</body>
</html>

On gists

jQuery e-mail plugin validation

jQuery jQuery-plugins

jquery-email-validation.js #

(function ($) {

    $.fn.validateEmail = function () {
        return this.each(function () {
            var $this = $(this);
            $this.change(function () {
                var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
                if ($this.val() == "") {
                    $this.removeClass("badEmail").removeClass("goodEmail")
                }else if(reg.test($this.val()) == false) {
                    $this.removeClass("goodEmail");
                    $this.addClass("badEmail");
                }else{
                    $this.removeClass("badEmail");
                    $this.addClass("goodEmail");
                }
            });
        });
    };
})(jQuery);

On gists

Capslock.js - example how to write js native plugin

JavaScript-OOP JavaScript Helpers-Filters-Plugins

capslock.js #

/*

CapsLock.js

An object allowing the status of the caps lock key to be determined

Created by Stephen Morley - http://code.stephenmorley.org/ - and released under
the terms of the CC0 1.0 Universal legal code:

http://creativecommons.org/publicdomain/zero/1.0/legalcode

*/

// create the CapsLock object
var CapsLock = (function(){

  // initialise the status of the caps lock key
  var capsLock = false;

  // initialise the list of listeners
  var listeners = [];

  // store whether we are running on a Mac
  var isMac = /Mac/.test(navigator.platform);

  // Returns whether caps lock currently appears to be on.
  function isOn(){
    return capsLock;
  }

  /* Adds a listener. When a change is detected in the status of the caps lock
   * key the listener will be called, with a parameter of true if caps lock is
   * now on and false if caps lock is now off. The parameter is:
   *
   * listener - the listener
   */
  function addListener(listener){

    // add the listener to the list
    listeners.push(listener);

  }

  /* Handles a key press event. The parameter is:
   *
   * e - the event
   */
  function handleKeyPress(e){

    // ensure the event object is defined
    if (!e) e = window.event;

    // store the prior status of the caps lock key
    var priorCapsLock = capsLock;

    // determine the character code
    var charCode = (e.charCode ? e.charCode : e.keyCode);

    // store whether the caps lock key is down
    if (charCode >= 97 && charCode <= 122){
      capsLock = e.shiftKey;
    }else if (charCode >= 65 && charCode <= 90 && !(e.shiftKey && isMac)){
      capsLock = !e.shiftKey;
    }

    // call the listeners if the caps lock key status has changed
    if (capsLock != priorCapsLock){
      for (var index = 0; index < listeners.length; index ++){
        listeners[index](capsLock);
      }
    }

  }

  // listen for key press events
  if (window.addEventListener){
    window.addEventListener('keypress', handleKeyPress, false);
  }else{
    document.documentElement.attachEvent('onkeypress', handleKeyPress);
  }

  // return the public API
  return {
    isOn        : isOn,
    addListener : addListener
  };

})();

On gists

From http://code.stephenmorley.org/php/creating-downloadable-csv-files/

PHP Helpers-Filters-Plugins

csv-on-the-fly.php #

// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');

// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');

// output the column headings
fputcsv($output, array('Column 1', 'Column 2', 'Column 3'));

// fetch the data
mysql_connect('localhost', 'username', 'password');
mysql_select_db('database');
$rows = mysql_query('SELECT field1,field2,field3 FROM table');

// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);