﻿///////////////////////////////////////////////////
// Cookies
$.fn.createCookie = function(name,value,days) {
    if (days)
    {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
    
    //alert('Click-createCookie: '+name);
}

$.fn.readCookie = function(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) {
                //alert('Click-readCookie: '+c.substring(nameEQ.length,c.length));
                return c.substring(nameEQ.length,c.length);
        }
    }

    return null;
}

$.fn.eraseCookie = function(name) {
    $(this).createCookie(name,"",-1);
    //alert('Click-eraseCookie');
}

///////////////////////////////////////////////////
// Select2Div
/*
 * Ändert die gewöhnliche Selectbox in ein div konstrukt das Stylebar ist
 * @author Robert Agthe
 */
$.fn.select2div = function (after_select, after_show, after_remove) {
  // Variablen deklarieren
  var element = this;
  var optgroup_arr = element.find('optgroup');
  var options_arr = element.find('option');
  var selected_val = element.val();
  var selected_text = element.find('option:selected').text();
  var selected_flag = element.find('option:selected').attr('class');

  // Konstruiert das Dropdown 
  var dropdown_construct = function (e) {
    e.stopPropagation()
    e.preventDefault()

    $('.select2div_dropdown').each(function() {
      if($(this).parent().attr("id") != element.attr("id")) {
        $(this).parent().trigger("click");
      }
    });
    
    // Prüfen ob Dropdown layer schon vorhanden ist..
    if(element.find('.select2div_dropdown').length == 0) {
      // Sind Optgroups vorhanden? Wenn ja, dann erst diese
      // iterieren und unterliegeende Options dann übernehmen
      if(optgroup_arr.length > 0) {
        // Layer DIV einfügen
        $(this).after('\
          <div class="select2div_dropdown" style="display:none;">\
          </div>\
        ');

        // Ausgabe INIT
        var html ='';
       
        $.each(optgroup_arr, function(i,optgroup) {
          html = html+'<h4>'+$(optgroup).attr('label')+'</h4><ul>';
          // Optionen iterieren und anhängen
          $(optgroup_arr[i]).children('option').each(function(i,val) {
            html = html+'\
                <li>\
                  <a class="'+$(val).attr('class')+'" rel="'+val.value+'">\
                    '+val.text+'\
                  </a>\
                </li>';
          })
          html = html+'</ul>';
        })
        // Ausgabe in UL anhängen
        element.find('.select2div_dropdown').append(html);
      } else { // Keine Optgroups vorhanden!
        // Layer DIV einfügen
        $(this).after('\
          <div class="select2div_dropdown" style="display:none;">\
            <div class="Corners Border">\
              <div class="TopLeft"></div>\
              <div class="TopRight"></div>\
              <div class="BottomLeft"></div>\
              <div class="BottomRight"></div>\
            </div>\
            <span class="ui-icon"></span>\
            <ul>\
            \
            </ul>\
          </div>\
        ');

        // Optionen iterieren und anhängen
        $.each(options_arr, function(i,val) {
          element
            .find('.select2div_dropdown ul')
            .append('\
              <li>\
                <a class="'+$(options_arr[i]).attr('class')+'" rel="'+options_arr[i].value+'">\
                  '+options_arr[i].text+'\
                </a>\
              </li>'
            );
        })
      }
      
      element.find('.select2div_dropdown').show() // Dropdown anzeigen
      if(typeof(after_show) == 'function') {
        after_show.call(this);
      }
    } else {
    
      // Wird nichts ausgewählt, dann layer wieder schliessen
      element.find('.select2div_dropdown').remove();
      if(typeof(after_remove) == 'function') {
        after_remove.call(this);
      }
    }
  }

  // Aktionen nach einem Klick auf ein Item
  var accept_item = function() {
    selected_val = $(this).attr('rel');
    selected_text = $(this).text();
    selected_flag = $(this).attr('class');
    element.find('.select2div_select span')
      .text(selected_text) // Text übernehmen und anzeigen
      .removeClass() // alle CSS Klassen entfernen
      .addClass(selected_flag) // Flagge übernehmen

    element.find('.select2div_dropdown').remove(); // Dropdown löschen

    // Funktion ausführen um parameter weiterzuleiten
    if(typeof(after_select) == 'function') {
      after_select.call(this, selected_val);
    }
    
    if(typeof(after_remove) == 'function') {
      after_remove.call(this);
    }
    
  }

  // Selectbox löschen und DIV Container erstellen
  element
    .find('select')
    .replaceWith('\
      <div class="select2div_select">\
        <span class="'+selected_flag+'">'+selected_text+'</span>\
      </div>\
    ');

  // Klick ins Dokument -> Dropdown schliessen
  $("body").click(function(evt){
    element.find('.select2div_dropdown').remove();
    if(typeof(after_remove) == 'function') {
      after_remove.call(this, selected_val);
    }
  })

  // Event definieren, wenn DIV Konstrukt angeklickt wird
  element
    .find('.select2div_select')
    .click(dropdown_construct);

  // Event, wenn auf ein neues Listelement geklickt wird
  element
    .find('.select2div_dropdown ul li a')
    .live('click', accept_item);
}

///////////////////////////////////////////////////
// ScrollTo
$.fn.scrollTo = function(event) {
  event.preventDefault();
  var full_url = $(this).attr("href");
  var parts = full_url.split("#");
  
  if(parts.length > 1) {
    var trgt = parts[1];
    var target_offset = $("#"+trgt).offset();
    var target_top = target_offset.top;
  } else {
    var target_top = 0;
  }
  $('html, body').animate({scrollTop:target_top}, 500);
}

///////////////////////////////////////////////////
// Quicksearch
$.fn.quicksearch = function(options) {
  var elem = $(this);
  var isActive = false;
  elem.options = options;
/*
  if(jsPrefix != null && jsPrefix != '') {
    elem.options.elemInput.attr('value', 'Search is disabled in preview');
    elem.options.elemForm.submit(function(){return false;});
    elem.options.elemInput.focus(function(){
      elem.options.elemLayer.show();
    });
    elem.options.elemInput.blur(function(){
      elem.options.elemLayer.hide();
    });
    return;
  }
*/
  // Tagcloud reinladen
  elem.options.elemTagCloud.tagcloud(elem.options.tagCloudUrl, elem.options.searchUrl);

  // Eingabefeld mit Label der aktuellen Sprache versehen
  //elemInput.val(labelText[language]);

  elem.options.elemSubmit.click(function() {
    if(elem.options.elemInput.attr('value').length > 3 && elem.options.elemInput.attr('value') != elem.options.elemInputDefaultVal) {
      location.href= elem.options.searchUrl+'?wm=sub&q='+elem.options.elemInput.attr('value');
    }
  });
  
  
  // Event definieren
  // Wenn das Eingabefeld Focus bekommt
  elem.options.elemInput.live('focus',function () {
      // Label löschen, falls es eins gibt
    if ($(this).attr('value') === elem.options.elemInputDefaultVal) {
      $(this).attr('value', '');
    }

    // Layer einblenden
    elem.options.elemFancy.show();
    elem.options.elemLayer.show();
    elem.isActive = true;
  });

  // Event definieren
  // Wenn jemand etwas in das Suchfeld eingibt
  elem.options.elemInput.keyup(function() {
    var self = elem.options.elemInput;
    if (self.attr('value').length > 3) {
      // get by ajax the suggestions
      var query = self.attr('value');

      // Nur wenn es einen PHP Callback gibt und dieser definiert wurde
      if (typeof(elem.options.suggestUrl) != "undefined") {
        var output = '';
        $.ajax({
          url: elem.options.suggestUrl + '&q=' + query,
          context: elem.options.elemContent,
          dataType: "json",
          error: function(data){
            //alert('error' + data.responseText);
            $('#qsLayer_suggest li').hide();
            $("#suggestNoResult").show();
          },
          success: function (data, txtStatus, xhr) {
            if(data == null || data.length == 0) {
              $('#qsLayer_suggest li').hide();
              $("#suggestNoResult").show();
            }
            else
            {
              // Alle Daten durchgehen und Liste bauen
              $.each(data, function(i,val){
                var ltrick = 'href="'+val.url+'"';
                output = output + '<li><a '+ltrick+'>'+val.title+'</a></li>'
              })

              // Liste um Span Tag, der die Treffer kennzeichnet erweitern!
              elem.options.elemContent.html(output.replace(
                  (
                    new RegExp(
                      '(href="[^"]*">)([^<]*)(' + query + ')([^<]*<)',
                      "gim"
                    )
                  ),'$1$2<span>$3</span>$4'
                )
              );
              $("#suggestShowAll").show();
            }

          }
        });
      }
    }

    if(self.attr('value').length < 4) {
      $('#qsLayer_suggest li').hide();
      $("#suggestNotEnough").show();
    }
  });

 
  elem.disable = function() {
    var self = elem.options.elemInput;
    if (self.attr('value') === "") {
      self.attr('value', elem.options.elemInputDefaultVal);
    }
    // Layer ausblenden
    elem.options.elemFancy.hide();
    elem.options.elemLayer.hide();
    elem.isActive = false;
  };
 
  // Wenn man das Eingabefeld den Focus verliert,
  // Layer wieder ausblenden
  elem.options.elemInput.live('blur', function(){
    var self = elem.options.elemInput;
    window.setTimeout(function () {
      elem.disable();
    },200);
  })
  /*
  // Klick ins Dokument -> Dropdown schliessen
  $("body").click(function(evt){
    if(elem.isActive && $(evt.target).parentsUntil("div.StageBanner", "div.QuickSearch").length == 0) {
      elem.options.elemInput.attr('value', '');
      elem.disable();
    }
  });
  */
}

$.fn.tagcloud = function(tagCloudUrl, searchUrl) {
  var output = '';
  $.ajax({
    url: tagCloudUrl,
    context: this,
    dataType: "json",
    success: function (data, txtStatus, xhr) {
      $.each(data,function(i, val){
        var ltrick = 'href="'+searchUrl+val.url+'"';
        if(val.int > 250) {
          var fsize = 250;
        } else {
          var fsize = val.int;
        }
        //output = output+'<li><a '+ltrick+' style="font-size:'+fsize+'%">'+val.title+'</a></li>'
        output = output+'<a '+ltrick+' style="font-size:'+fsize+'%">'+val.title+'</a> ';
      })
      $(this).html(output);
    }
  });
}

