window.windalf = window.windalf || {};

windalf.toBool = function(str) {
  if(typeof str == "undefined") return false;
  str = str.toLowerCase();
  return (str == 'true' || str == 't' || str == 'yes' || str == 'y' || str == '1');
}
windalf.getMeta = function(key) {
  try {
    return $('meta[name="' + key + '"]').attr('content');
  }catch(e) {
    return undefined;
  }
};

windalf.externalHelper = function() {
  $('a[rel*=external]').live('click',function() {
    return !window.open(this.href);
  });
};
//var $buoop = {newwindow: true};
windalf.browserHelper = function() {
  if (!$.browser.msie && $.browser.opera) return;
  //$.getScript("http://browser-update.org/update.js");
};
windalf.gotoformHelper = function() {
  $('form.gotoform input[type=submit]').click(function() {
    var f = $(this).parents('form');
    location.href = f.attr('action') + ($('input[name=back_to]',f).size() > 0 ? '?back_to=' + $('input[name=back_to]',f).val() : '');
    return false;
  });
};

windalf.initPage = function(page) {
  var page = windalf.getMeta('page');
  logged_in = windalf.toBool(windalf.getMeta('user-loggedin'));
  csrf_token = windalf.getMeta('csrf-token');
  jQuery.ajaxSetup({data: { csrf_token: csrf_token }});
  
  if (page == 'index') {
	  if ($('.ie_warning').size()>0) {
	    $('.ie_warning').append(
	      $('<a href="#" id="ie_warning_close">&times;</a>').click(function() {
	        $('.ie_warning').hide(); return false;
	      })
	    );
	  }
	  $('#start_ProductSlider').addClass('loaded').nivoSlider({effect: 'boxRandom', pauseTime: 5000});
  }
  
  if (page == 'warenkorb') {
      $('input.product_qty').change(function() {
        if($('#cart_update').hasClass('hideme')) {
          $('#cart_update').removeClass('hideme').hide().fadeIn('slow');
        }
      });
  }
  
  if (page == 'warenkorb' && $('#warenkorb_table').hasClass('warenkorb_small')) {
      $('.placeholder_img_link').tipsy({ gravity: $.fn.tipsy.autoWE, html: true, title: function() {
         return "<img src='"+$(this).attr('href')+"'/>";
      }, opacity: 1 });
  }
  
  if (page == 'kasse_step' && $('#nachnahme-hinweis').size() > 0) {
      if (!$('#zahlung-nach').attr('checked')) $('#nachnahme-hinweis').hide();
      $('#kasse-zahlung input').change(function() {
         if ($('#zahlung-nach').attr('checked')) $('#nachnahme-hinweis').show();
         else $('#nachnahme-hinweis').hide();
      });
  }
  if (page == 'kasse_step' && $('#kasse_endform').size() > 0) {
      $('#kasse_endform').submit(function(e) {
          if (!$('#agb_accepted').attr('checked')) {
              $('#kasse_agbhinweis').css('border-left', '3px solid #FC8A00');
              windalf.flash.error('Sie müssen die AGB akzeptieren, um die Bestellung abschicken zu können.');
              e.preventDefault();
          }
      });
  }
  
  if (page == 'register') {
      if ($('#newuser-land option[selected]').val() != 'other') $('#newuser-land_other').hide();
      $('#newuser-land').change(function() {
          if ($('option[selected]', this).val() == 'other') $('#newuser-land_other').show();
          else $('#newuser-land_other').hide().val('');
      });
      
      $('#form-register').validate({
          //debug: true,
          rules: {
              "newuser[nick]": {
                  required: true,
                  minlength: 4,
                  maxlength: 15,
                  noSpaces: true,
                  noUmlauts: true,
                  noSpecialChars: true,
                  remote: "/register/usernickavail.bool"
              },
              "newuser[password]": {
                  required: true,
                  minlength: 5
              },
              "newuser[password2]": {
                  required: true,
                  minlength: 5,
                  equalTo: "#newuser-password"
              },
              "newuser[email]": {
                  required: true,
                  email: true
              },
              "newuser[telefon]": "required",
              "newuser[gender]": "required",
              "newuser[vorname]": "required",
              "newuser[nachname]": "required",
              "newuser[strasse]": "required",
              "newuser[hausnummer]": "required",
              "newuser[plz]": "required",
              "newuser[ort]": "required",
              "newuser[land]": "required",
              "newuser[land_other]": {
                  required: true,
                  minlength: 2,
                  notPlaceholder: true
              }
          },
          messages: { 
              "newuser[nick]": {
                  remote: jQuery.format("Dieser Name ist bereits vergeben")
              }
          },
          ignore: ".ignore"
      });
      jQuery.validator.messages.required = "Pflichtfeld"; // kurz!
      $('#newuser-email').change(function() {
          $('#form-register').valid(); //fixes visible error-msg
      });
      $('#newuser-land').change(function() {
        if ($('#newuser-use-other-land:selected').size() > 0) {
          $('#newuser-land_other').removeClass('ignore');
        } else {
          $('#newuser-land_other').addClass('ignore');
          $('#form-register').valid();
        }
      });
      $('#newuser-land_other').addClass('ignore');
      
      if ($.browser.msie) {
        // bwah! fu* you, ie6! *würg*
        $('#newuser-nick').rules('remove');
        $('#newuser-land').rules('remove');
        $('#newuser-land_other').rules('remove');
      }
      
  }
  
  if (page == 'kasse_step' && $('#form-liefer').size() > 0) {
      if ($('#liefer-land option[selected]').val() != 'other') $('#liefer-land_other').hide();
      $('#liefer-land').change(function() {
          if ($('option[selected]', this).val() == 'other') $('#liefer-land_other').show();
          else $('#liefer-land_other').hide().val('');
      });
      
      $('#form-liefer').validate({
          rules: {
              "liefer[name]": "required",
              "liefer[strasse]": "required",
              "liefer[hausnummer]": "required",
              "liefer[plz]": "required",
              "liefer[ort]": "required",
              "liefer[land]": "required",
              "liefer[land_other]": {
                  required: "#liefer-land option[value=other][selected]",
                  minlength: 2,
                  notPlaceholder: true
              }
          }
      });
      jQuery.validator.messages.required = "Pflichtfeld"; // kurz!
  }
  
  if (page == 'warenkorb') {
      $('input.product_qty').change(function() {
        if($('#cart_update').hasClass('hideme')) {
          $('#cart_update').removeClass('hideme').hide().fadeIn('slow');
        }
      });
  }
  
  if (page == 'contact') {
    if ($('#contact-ishuman-wrapper').size() < 1) return;
    var eq = $('#contact-ishuman-wrapper label span').text();
    if (eq.match(/^\d+[\+\-\/\*]\d+$/) === null) return;
    $('#contact-ishuman').val(eval(eq));
    $('#contact-ishuman-wrapper').hide();
  }
  
  if (page == 'konto_edit_passwort') {
    $('#new_password').chronoStrength({placeInto:'#passwordstrength',
    wrappingText: 'Ein normaler Rechner würde dieses Passwort innerhalb %s knacken. <a href="http://howsecureismypassword.net/faq/" rel="external">[?]</a>'});
  }
  
  //$('input:checkbox, input:radio').uniform();
  windalf.externalHelper();
  windalf.gotoformHelper();
  windalf.browserHelper();
  $('.flashWrapper .flash:not(.dynamic)').click(function(){ windalf.flash.removeFlash(this); });
  
  /* check for input[type=range] */
  var testi = document.createElement('input');
  testi.setAttribute('type', 'range');
  if (testi.type !== 'range') {
    $('body').addClass('no-range');
  }
  
  /* placeholder */
  var testi = document.createElement('input');
  if(!(!!(testi.placeholder === '') && !!(testi.placeholder !== undefined))) {
      $('input[placeholder]').placeholder();
  }
  
  /* check for background-size */
  var hasBackgroundSize = (function() {
      var m = document.createElement('bgtest'), bgTestProps = ['backgroundSize', 'WebkitBackgroundSize', 'MozBackgroundSize'];
      for ( var i in bgTestProps ) {
          if (m.style[ bgTestProps[i] ] !== undefined) {
              return true;
          }
      }
      return false;
  })();
  if (hasBackgroundSize) {
      $('body').addClass('backgroundsize');
  }
};

windalf.flash = {};
windalf.flash._getFlashWrapper = function () {
  if ($('.flashWrapper').length < 1) {
    $('#pageTop').after('<div class="flashWrapper"></div>');
  }
  return $('.flashWrapper');
};
windalf.flash.addFlash = function(type, content) {
  var flash = $('<div class="flash ' + type + ' dynamic">' + content + ' <span class="flashclose">&times;</span></div>');
  flash.click(function(){ windalf.flash.removeFlash(flash); });
  return flash.appendTo(windalf.flash._getFlashWrapper());
};
windalf.flash.removeFlash = function(flash) {
  var flash = $(flash);
  if (windalf.flash._getFlashWrapper().children().size() - 1 < 1) {
      windalf.flash._getFlashWrapper().hide('blind',{ direction: "vertical" }, 400, function(){
          $(this).remove();
      });
  }else{
      flash.hide('blind',{ direction: "vertical" }, 400, function() {
          flash.remove();
      });
  }
}
windalf.flash.error = function(c){ return windalf.flash.addFlash('error', c); };
windalf.flash.fail = function(c){ return windalf.flash.addFlash('fail', c); };
windalf.flash.info = function(c){ return windalf.flash.addFlash('info', c); };
windalf.flash.notice = function(c){ return windalf.flash.addFlash('notice', c); };
windalf.flash.ok = function(c){ return windalf.flash.addFlash('ok', c); };
windalf.flash.success = function(c){ return windalf.flash.addFlash('success', c); };

