/* =======================[- Initialization -]============================ */
// a more accessible "hover" function
jQuery.fn.extend({
  hover: function(fnOver, fnOut) {
    return this.bind('mouseenter mouseover focus',fnOver).bind('mouseleave mouseout blur', fnOut);
  }
});
 
$(document).ready(function(){
  // enable easySlider on homepage
  initEasySlider();
  // enables lightbox
  initLightbox();
  // make checkboxes look nice
  initCheckboxes();
  // make radiobuttons look nice
  initRadiobuttons();
  // enable ajax for dropdowns
  initKundenzentrum();
  // submit form data on change
  initKundenzentrumAdressen();
  // display input help on focus of textfields
  initInputHelp();
  // init Date input fields with datepicker
  initDatePickers();
  // make file upload fields look nice 
  initFileUploadFields();
  // get details via ajax call and show in jquery.ui.dialog 
  initAccountAngebotDetail();
  // clear input fields for login on focus
  initClearInputonFocus();
  // scolling for jumpmarks
  initJumpmarksScrolling();

  /* Text-cycle on homepage [S] */
  jQuery('div.animation .subheadline:first').show()  
  play();
    
  function play() {
        jQuery('div.animation .subheadline:first').show();
        setTimeout(function () {
            show();
        }, 4000);
  }
    
  function show() {
        jQuery('div.animation .subheadline:first').show().fadeOut(1000, function () {
            $(this).remove().appendTo(".animation ul");
            jQuery('div.animation .subheadline:first').fadeIn(1000);
            play();
        });
  }
  /* Text-cycle on homepage [E] */
   
}); 
 
/* =======================[- Functions -]============================ */
/*
 initClearInputonFocus
 --------------
 clear input fields on focus in login layer
*/
function initClearInputonFocus() {
  $("div#Password input[type='text'], div#Password input[type='password']").each(function() {
    $(this).focus(function() {
      if( $(this).val() == "Login" || $(this).val() == "Passwort") {
        $(this).val("");
      }
    });
  });
}
/* 
 initLightbox
 --------------
 enables lightbox for all anchors with rel="lightbox" 
*/
function initLightbox() {
  // apply lightbox to anchor with rel="lightbox"
  if ($("a[rel*='lightbox']").length > 0)
  {
    $("a[rel*='lightbox']").lightbox();
  }
  //if ($("a[rel*='exposeThumbnails']").length > 0) {
  //  $("a[rel*='exposeThumbnails']").lightBox({sourceAttribute:'rel',selectorMatches:'.exposeThumbnails > a'});
  //}
  if ($("a[rel*='exposeThumbnails']").length > 0) {
    $("a[rel*='exposeThumbnails']").lightbox();
  }
}
 
/* 
 initCheckboxes
 --------------
 makes all checkboxes clickable and sets the initial state 
*/ 
function initCheckboxes() {
  $("input[type='checkbox']").each(function() {
    // add event handler
    $(this).click(function () { 
      toggleCheckBox(this); 
    });
    // init checkboxes
    toggleCheckBox(this);        
  });
}
/* 
 initRadiobuttons
 --------------
 makes all radiobuttons clickable and sets the initial state 
*/ 
function initRadiobuttons() {
  $("input[type='radio']").each(function() {
    // add event handler
    $(this).click(function () { 
      toggleRadioButton(this); 
    });
    // init checkboxes
    toggleRadioButton(this);        
  });
}
            
/* 
 toggleCheckBox(elem)
 --------------------
 toggles the enhanced (nice looking) checkboxes by changing the css properties
 and classes 
*/ 
function toggleCheckBox(elem) {
  $(elem).parent().removeAttr("style");
  var cssObj = 
  {
    filter: "alpha(opacity=0)",
    opacity: "0.0",
    zIndex: "100"
  }
  $(elem).css(cssObj);
  var chk = elem;
  if (chk.checked) {
    $(elem).parent().removeClass("CheckBoxleer"); 
    $(elem).parent().addClass("CheckBox");
  } else {
    $(elem).parent().removeClass("CheckBox");
    $(elem).parent().addClass("CheckBoxleer");
  }
}
 
/* 
 toggleRadiobutton(elem)
 --------------------
 toggles the enhanced (nice looking) radiobuttons by changing the css properties
 and classes 
*/ 
function toggleRadioButton(elem) {
  $(elem).parent().removeAttr("style");
  var cssObj = 
  {
    filter: "alpha(opacity=0)",
    opacity: "0.0",
    zIndex: "100"
  }
  $(elem).css(cssObj);
  var chk = elem;
  if (chk.checked) {
    $(elem).parent().removeClass("Radioleer"); 
    $(elem).parent().addClass("Radio");
    
  } else {
    $(elem).parent().removeClass("Radio");
    $(elem).parent().addClass("Radioleer");
  }
  
  // uncheck all in same group (with same name)
  var name = $(elem).attr("name");
  $("input[type='radio'][name='"+name+"']").each(function() {
      var chk2 = this;
      if (chk2.checked) {
          $(this).parent().removeClass("Radioleer"); 
          $(this).parent().addClass("Radio");
      } else {
          $(this).parent().removeClass("Radio");
          $(this).parent().addClass("Radioleer");
      }
  });
} 
 
 
/* 
 initKundenzentrum
 ----------------- 
 initializes form data for kundenzentrum selection and binds needed events
*/
function initKundenzentrum() {
  $("#kundenzentrum select").each(function() {
    // add event handler
    $(this).change(function () { 
      if ($(this).parent().hasClass("borderSelect")) {
          $(this).parent().removeClass("borderSelect");
      }
      kundenzentrumGetAjaxData(this);
    });
  });
  // init BundeslÃ¤nder
  options = '';
  options += $('#kundenzentrum select[name=bundesland]').html();
  $('#kundenzentrum select[name=bundesland]').html(options);
  
}
/* 
 kundenzentrumGetAjaxData
 ------------------------
 retrieves a JSON object with data for kundenzentrum form
*/ 
function kundenzentrumGetAjaxData(inputElem) {
      var elementvalue = $(inputElem).val();
      var elementname = $(inputElem).attr("name");
      
      if (elementname == "bundesland") {
          $("#kundenzentrum select[name='ort'],#kundenzentrum select[name='strasse'],#kundenzentrum select[name='hausnummer']").each(function() {
                  $(this).parent().parent().parent().fadeOut();
          });
          ajaxUrl = "/service/service/kundenzentrum/ajax/" + encodeURIComponent(elementvalue) + "?reset=true";
            elemOutput = $("#kundenzentrum select[name='ort']");
      } else if (elementname == "ort") {
          $("#kundenzentrum select[name='strasse'],#kundenzentrum select[name='hausnummer']").each(function() {
                  $(this).parent().parent().parent().fadeOut();
          });
          bundesland = $("#kundenzentrum select[name='bundesland']").val();
          ajaxUrl = "/service/service/kundenzentrum/ajax/" + encodeURIComponent(bundesland) + "/" + encodeURIComponent(elementvalue);
          elemOutput = $("#kundenzentrum select[name='strasse']");
      } else if (elementname == "strasse"){
           $("#kundenzentrum select[name='hausnummer']").each(function() {
                  $(this).parent().parent().parent().fadeOut();
           });
           bundesland = $("#kundenzentrum select[name='bundesland']").val();
           ort = $("#kundenzentrum select[name='ort']").val();
           ajaxUrl = "/service/service/kundenzentrum/ajax/" + encodeURIComponent(bundesland) + "/" + encodeURIComponent(ort) + "/" + encodeURIComponent(elementvalue);
           elemOutput = $("#kundenzentrum select[name='hausnummer']");
      } else {
           elemOutput = null;
      }
      
      if (elementname != "hausnummer") {
          $("#kundenzentrum input[name='senden']").fadeOut();
      }
      
      if (elemOutput != null) {
        $.getJSON(ajaxUrl, function(data){
          var options = '';
          for (var i in data) {
              options += '<option value="' + i + '">' + data[i] + '</option>';
          }
          $(elemOutput).html(options);
          $(elemOutput).parent().parent().parent().fadeIn();
          $(elemOutput).parent().addClass("borderSelect");
        });
      }
      
      if (elementname == "hausnummer" && $("#kundenzentrum select[name='hausnummer']").val() && $("#kundenzentrum select[name='hausnummer']").val() != -1) {
        $("#kundenzentrum input[name='senden']").fadeIn();
      }
}
/* 
 initKundenzentrumAdressen
 ------------------------- 
 initializes form data for kundenzentrum/adressen (bundesland selection) 
 and binds needed events
*/
function initKundenzentrumAdressen() {
  var init = true;
  $("div#kundenzentrumAdressenResults").hide(); // hide div with results
  
  $("#kundenzentrumAdressen select").each(function() {
    // add event handler
    $(this).change(function () { 
      $("div#kundenzentrumAdressenResults").slideUp("normal", function()
         {
              /* is executed after effect has completed */
              $("form#kundenzentrumAdressen").submit();
         }
       ); /* end slideup */
       
    });
  });
  if ( $("#kundenzentrumAdressen select").val() != "-1" )
  $("div#kundenzentrumAdressenResults").slideDown("normal"); // on startup
}
 
/* 
 initInputHelp()
 ---------------
 makes textfields on focus to display a help message
 (see symfony template: registration.php)
*/ 
function initInputHelp() {
    
    /* divs must be named <input field id>_help*/
    $("input[type='text'],input[type='password']").each(function() {
        $(this).focus(function () { 
            $("#" + $(this).attr("id") + "_help").fadeIn();
        });
        
        $(this).blur(function () { 
            $("#" + $(this).attr("id") + "_help").fadeOut();
        });
    });
    
    // attach password-strength-meter
    if ($("input[id='passwort']").length > 0) {
      $("input[id='passwort']").attachPassMeter(null,'#bar');
    }
}
/* 
 initDatePickers()
 ---------------
 attach datepickers to textfields with class="datefield".
*/ 
function initDatePickers() {
    $("input.datefield").each(function() {
        $(this).datepicker(
            {
                showOn: 'button',
                buttonImageOnly: true, 
                buttonImage: '/images/layout/cal_icon.gif',
                buttonText: 'Datum wÃ¤hlen',
                minDate: new Date()
            }
        )
     if( $(this).attr("name") == "geburtstag" ) {
         $(this).datepicker("change", {minDate: null, yearRange: '-120:+1'});
     }
    });
}

/* 
 initFileUploadFields()
 ---------------
 make fileupload fields look nice
*/
function initFileUploadFields() {
    $("input[type='file']").each(function() {
        $(this).parent().addClass("uploadFile");
        $(this).parent().next().show();
        $(this).change(function () { 
               $(this).parent().next().val($(this).val());
        });
    });
}

/* 
 initAccountAngebotDetail()
 --------------------------
 Get details via ajax call and show in jquery.ui.dialog
*/
function initAccountAngebotDetail() {
    $("a[rel='dialog']").each(function () {
        $(this).click(function () { 
            var id = $(this).attr('id');
            id = id.replace("angebot_","");
            getAjaxAccountAngebotDetail(id);
            return false;
        });
    
    });   
}
 
/* 
 getAjaxAccountAngebotDetail()
 -----------------------------
 Get details via ajax call and show in jquery.ui.dialog
*/    
function getAjaxAccountAngebotDetail(id) {
    // make ajax call and insert resulting html into DOM
    $("#floater").dialog("destroy");
    $("#floater").remove();
    $.get("/service/account/bieteSucheAjaxDetails/id/"+id, function(data){
          $("body").prepend(data);
          // show dialog
        $("#floater").dialog({
              width: '540px', 
              height: 'auto',
              title: '<p class="floaterline"><a href="#" class="link" id="closebtn">Fenster schlieÃŸen</a></p>',
              maxWidth: '650',
              maxHeight: '600',
              minWidth: '540',
              minHeight: '300',
              close: function(ev, ui) { $("#floater").remove(); }
          });
      
          $("#closebtn").click(function(){
              $("#floater").dialog("close");
              return false;
          });
      
        $(".ui-resizable-se").attr("title", "GrÃ¶ÃŸe Ã¤ndern");
        $(".ui-resizable-sw").attr("title", "GrÃ¶ÃŸe Ã¤ndern");
        $(".ui-resizable-s").attr("title", "GrÃ¶ÃŸe Ã¤ndern");
        $(".ui-resizable-w").attr("title", "GrÃ¶ÃŸe Ã¤ndern");
        $(".ui-resizable-e").attr("title", "GrÃ¶ÃŸe Ã¤ndern");
    });
}
/* 
 initJumpmarksScrolling()
 -----------------------------
 activate smooth scrolling for jumpmarks
*/  
function initJumpmarksScrolling() {
    $.localScroll({duration: 500});
}


/*
initEasySlider()
----------------
*/
function initEasySlider() {
  if ($('#slider').length > 0) {
    $('#slider').easySlider({auto: true, continuous: true, controlsShow: false, pause: 6000});
  }
}
