/**
 * jQuery Plugin: PLZ eingeben, in Cookie speichern, Anzeige der PLZ aus dem Cookie
 */
(function($){
  $.fn.extend({
    //pass the options variable to the function
    plz: function(opts) {
 
      //Set the default values, use comma to separate the settings, example:
      var defaults = {
          url: "http://localhost/plzgenerator/data/plz.json", 
          notfoundtext: "(nicht gefunden)", 
          notfoundurl: "http://localhost/plzgenerator", 
          redirect: false, 
          expires: 100, 
          minLength: 4, 
          plztariflabel: "Gewählter Ort:", 
          changeplzlabel: "ändern", 
          inputplzlabel: "Bitte PLZ eingeben:", 
          submitplzlabel: "->", 
          submitplzpic: ""
      };
      var options = $.extend(defaults, opts);
      var locations = new Array();
      var fetched = false;
      var submitplzlabel = "";
      if(options.submitplzpic!==""){
        submitplzlabel = '<input type="image" id="submitplz" class="submit" src="'+options.submitplzpic+'" alt="'+options.submitplzlabel+'" />';
      }else{
        submitplzlabel = '<input type="submit" id="submitplz" class="submit" value="'+options.submitplzlabel+'" />';
      }
      this.html('<div id="outputplzdiv">' + 
            '<div id="showplz">' + 
            '<p>'+options.plztariflabel+'</p>' + 
            '<div id="plzurl"></div>' + 
            '</div>' + 
            '<input type="submit" id="changeplz" value="'+options.changeplzlabel+'" />' + 
            '</div>' + 
            '<div id="inputplzdiv">' + 
            '<p>'+options.inputplzlabel+'</p>' + 
            '<input type="text" id="inputplz" class="acInput" size="5" maxlength="5" autocomplete="off" />' + 
            submitplzlabel + 
            '</div>'
      );
      return this.each(function() {
        
        // wenn keiner gesetzt ist (null), zählt es als false
        show(readCookie("plz"));
        
        $("#inputplz").keypress(function(evt) {
          if(!fetched){
            fetchData();
            fetched = true;
          }
          if((evt.keyCode || evt.which) == 13){
            $("#submitplz").click();
          }
        });
    
          $("#submitplz").click(function(){
            var input = parseInt($("#inputplz").val());
            if(input>999 && input<100000){
              createCookie("plz", input, options.expires);
              var notfound = true;
              for(i in locations){
                if(notfound && locations[i]["PLZ"]==readCookie("plz")){//BUG bei orten mit gleicher PLZ wird der erste genommen
                  createCookie("ort", locations[i]["Ort"], options.expires);
                  createCookie("seite", locations[i]["Seite"], options.expires);
                  notfound = false;
                  break;
                }
              }
              if(notfound){
                createCookie("ort", options.notfoundtext, options.expires);
                createCookie("seite", options.notfoundurl, options.expires);
              }
              show(true);
              if(options.redirect){
                window.location.href = readCookie("seite");
              }
            }
          });

        $("#changeplz").click(function(){
          eraseCookie("plz");
          eraseCookie("ort");
          eraseCookie("seite");
          eraseCookie("plzort");
          show(false);
        });
      });    

      /**
       * Eingegebene PLZ + Ort anzeigen und verlinken
       */
      function show(bool) {
        if(bool) {
          if(!readCookie("plzort")) {
            createCookie("plzort", readCookie("plz") + " " + readCookie("ort"), options.expires);
          }
          $("#plzurl").html('<a href="' + readCookie("seite") + '">' + readCookie("plzort") + "</a>");
          $("#outputplzdiv").show();
          $("#inputplzdiv").hide();
        } else {
          $("#outputplzdiv").hide();
          $("#inputplzdiv").show();
        }
      }
    
      /**
       * Daten für Autovervollständigen, Anzeige des Ortes und gezielte Weiterleitung holen
       */
      function fetchData() {
        data = null;
        $.ajax({
            url: options.url,
          dataType: "json",
          type: "GET",
          error: function (jqXHR, textStatus, errorThrown) {
            console.log("Textstatus: "+textStatus+", Error: "+errorThrown);
            },
            success: function (data) {
              // auch in settings?
              locations = data["W3MAN"]["MULTIPLE"]["Vertriebsgebiet"]["LOOP"];
              var plzs = new Array();
              for(i in locations){
                plzs.push({"value": locations[i]["PLZ"], "label": locations[i]["PLZ"] + " " + locations[i]["Ort"]});
              }
              $("#inputplz").autocomplete({
                source: plzs,
                delay: 0,
                minLength: 4,
                select: function(event, ui){
                  $("#inputplz").val(ui.item.value);
                  // WORKAROUND ansonsten wird bei Orten mit gleicher PLZ immer der erste Ort angezeigt
                  createCookie("plzort", ui.item.label, options.expires);
                  $("#submitplz").click();
                }
              });
            }
        });
      }
    
      /**
       * Cookie erstellen
       * @param name
       * @param value
       * @param days
       */
      function createCookie(name,value,days) {
        var expires = "";
        if(days){
          var date = new Date();
          date.setTime(date.getTime()+(days*24*60*60*1000));
          expires = "; expires="+date.toGMTString();
        }
        document.cookie = name+"="+value+expires+"; path=/";
      }
    
      /**
       * Cookie lesen
       * @param name
       * @returns
       */
      function readCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
          var c = ca[i];
          while(c.charAt(0)==' '){
            c = c.substring(1,c.length);
          }
          if(c.indexOf(nameEQ) == 0){
            return c.substring(nameEQ.length,c.length);
          }
        }
        return null;
      }
    
        /**
         * Cookie löschen
         * @param name
         */
        function eraseCookie(name) {
          createCookie(name,"",-1);
        }
    
    }
  });
})( jQuery );
