/* Author: Bjoern Brauer

*/

/* ie-console hack to prevent js-errors in old browsers (for testing only) */
if (typeof window.console === 'undefined' || typeof console.log === 'undefined') {
  var console = {};
  console.log = function () {};
  window.console = console;
}


var sierra = {

  language: '',
  base_href: '',
  current_href: window.location.href || location.href,
  support_placeholder: false,
  _i18n: {
	de: {
		readmore: 'Mehr lesen',
		formerror: 'Bitte füllen Sie das Formular aus.',
		incart: 'Im Warenkorb',
                firstname: 'Vorname',
                lastname: 'Nachname',
                street: 'Straße',
                zip: 'Postleitzahl',
                city: 'Ort',
                email: 'E-mail Adresse',
                message: 'Nachricht'
	},
	en: {
		readmore: 'Mehr lesen',
		formerror: 'Bitte füllen Sie das Formular aus.',
		incart: 'Im Warenkorb',
                firstname: 'First name',
                lastname: 'Surname',
                street: 'Street',
                zip: 'Postcode',
                city: 'Town',
                email: 'Email address',
                message: 'Message'
	},
	es: {
		readmore: 'Mehr lesen',
		formerror: 'Bitte füllen Sie das Formular aus.',
		incart: 'Im Warenkorb',
                firstname: 'Nombre',
                lastname: 'Apellidos',
                street: 'Calle',
                zip: 'Código postal',
                city: 'Localidad',
                email: 'Dirección de correo electrónico',
                message: 'Mensaje'
	}
  },

  common: {
    init: function () {
      $('.page .nav-slider a.internal').live('mouseenter mouseleave', sierra.producthover.hover);
      $('.page .nav-slider a.internal').live('click', sierra.awardshover.hideTooltip);
      sierra.language = $('html').attr('lang');
      sierra.base_href = $('base[href]').attr('href');
	  
	  sierra.i18n = sierra._i18n[sierra.language];

      if (sierra.current_href.indexOf('#') >= 0) {
        sierra.current_href = sierra.current_href.substring(0, sierra.current_href.indexOf('#'));
      }

      sierra.navi.init($('#main-nav'), $('.subnav'));
      sierra.navigator.init();
      sierra.togglecontainers.init();
      sierra.awardshover.init();

      sierra.support_placeholder = sierra.helper.support_placeholder();

      sierra.support_placeholder = sierra.helper.support_placeholder();

      $('body').append('<div id="cache" style="display: none;"></div><div id="tooltip"><div class="tooltip-inner"></div></div>');

      $(window).bind('resize', sierra.helper.recalc_vig);
      
      $(window).resize();
      
    }
  },
  
  contactform: {
    init: function() {
      $.getScript('http://www.google.com/recaptcha/api/js/recaptcha_ajax.js', function(){
        $('#captcha').ready(function(){
          Recaptcha.create("6LcL18gSAAAAAP61LbRqQNlhS_lBR1VxbLjdpGZM",
            "captcha",
            {
              theme : 'blackglass',
              callback: Recaptcha.focus_response_field
            }
          );
        });
      });
      

      $('#contactformsubmit').bind('click', function() {
        var mandatoryFields = $('#contactform .required');
        for(var i = 0; i < mandatoryFields.length; i++ ) {
          if(mandatoryFields[i].value == '' || mandatoryFields[i].value == sierra._i18n[sierra.language][mandatoryFields[i].name]) {
            $(mandatoryFields[i]).addClass('error');
          }
        }
        
        if($('#contactform .required.error').length <= 0) {
          $('#contactform').submit();
        }
      });
    }
  },

  producthover: {
    active: null,
    init: function() {},
    hover: function(e) {
      var title = $(this).html(),
      offset = $(this).offset(),
      width = $(this).width(),
      height = $(this).height(),
      parent = $(this).parent();
      if (e.type === 'mouseenter') {
        $(this).removeAttr('title').removeAttr('alt').data('title', title);
       
        if(parent.hasClass('active')) {
          active = parent;
          parent.removeClass('active');
        }
        window.setTimeout(function () {
          sierra.awardshover.hideTooltip();
          sierra.awardshover.displayTooltip({ left: offset.left + width/2, top: offset.top + height }, title);
        }, 0);
         
      } else {
        sierra.awardshover.hideTooltip();
        if(!active.hasClass('active'))
          active.addClass('active');
      }
      return false;
    }
  },
  
  margaritas: {
    init: function() {
      $('.glass').live('click', function() {
        var glassLink = $(this).attr('href');
        var glass     = glassLink.replace(/.*\?.*product=([a-zA-Z0-9 ]*).*/, '$1');
        
        sierra.navigator.navigate_to_page('/' + sierra.language + '/shop?product='+glass, 'replace');
        
        GLASS = glass;
      });
    }
  },
  
  gallery: {
    init: function() {
      $('a.lightbox').live('click', sierra.gallery.showfullscreen);
    },
    showfullscreen: function (e) {
      e.preventDefault();
      var link = $(this);
      var picture = link.attr('href');
      var count = $('.lightbox').length;
      var currentCount = 0;
      var gotCurrent = false;
      $('.lightbox').each(function(i){
        if (!gotCurrent) {
         currentCount = i + 1; 
        }
        if($(this).attr('href') == picture) {
         gotCurrent = true; 
        }
      });
      $('body').append('<div id="overlay"></div><div class="product-full" style="background: none; height: 700px; width: 870px;"><img src="'+picture+'"><span style="float:right; padding-right: 50px;"><span id="current">'+currentCount+'</span>/'+count+'</span></div>');
      $('.product-full').append('<ul class="no-bullets prevnext"><li><a href="#" class="prev">prev</a></li><li><a href="#" class="closeproduct">close</a></li><li><a href="#" class="next">next</a></li></ul>');
      $('#overlay').css('height', sierra.helper.get_height()).show();
      $('.product-full').css({
        top: $('body').scrollTop() || $('html').scrollTop(),
        left: ($('html').width() / 2) - 435
      });
      
      $('.product-full').find('.closeproduct').bind('click', function (e) {
        e.preventDefault();
        $('.product-full').remove();
        $('#overlay').hide();
      });
      
      $('.product-full').find('.next').bind('click', function (e) {
        e.preventDefault();
        var current = $('.product-full img').attr('src');
        
        var nextItem = false;
        var newItem = '';
        $('.lightbox').each(function(){
          if(nextItem == true) {
            newItem = $(this).attr('href');
            nextItem = false;
          }
          
          if($(this).attr('href') == current) {
            nextItem = true;
          }

        });
        if(newItem != '') {
          $('.product-full img').attr('src', newItem);
          var current = parseInt($('#current').text());
          $('#current').text(current + 1);
        } else {
          newItem = $($('.lightbox')[0]).attr('href');
          $('.product-full img').attr('src', newItem);
          $('#current').text('1');
        }
        
      });
      
      $('.product-full').find('.prev').bind('click', function (e) {
        e.preventDefault();
        var current = $('.product-full img').attr('src');
        
        var lastItem = '';
        var newItem = '';
        $('.lightbox').each(function(){
          
          if($(this).attr('href') == current) {
            newItem = lastItem;
          }
          
          lastItem = $(this).attr('href');
        });
        if(newItem != '') {
          $('.product-full img').attr('src', newItem);
          var current = parseInt($('#current').text());
          $('#current').text(current - 1);
        } else {
          $('.product-full img').attr('src', lastItem);
          $('#current').text(1);
        }
        
      });
      
    }
  },
  
  awardshover: {
    init: function () {
      $('.awards img').live('mouseenter mouseleave', sierra.awardshover.hover);
    },
    hover: function (e) {
      e.preventDefault();
      e.stopPropagation();
      var title = $(this).attr('title') || $(this).data('title'),
          offset = $(this).offset(),
          width = $(this).width(),
          height = $(this).height();
      if (e.type === 'mouseenter') {
        $(this).removeAttr('title').removeAttr('alt').data('title', title);
        window.setTimeout(function () {
          sierra.awardshover.displayTooltip({ left: offset.left + width/2, top: offset.top + height }, title);
        }, 75);
      } else {
        sierra.awardshover.hideTooltip();
      }
      return false;
    },
    displayTooltip: function (coords, title) {
      $('#tooltip').show().css({ left: coords.left, top: coords.top }).find('.tooltip-inner').text(title);
    },
    hideTooltip: function () {
      $('#tooltip').hide().find('.tooltip-inner').text('');
    }
  },
  
  movie: {    
    init: function() {      
      
    },
    movie: function(){
      
      $('#movie video').bind('click', function() {
          $(this).trigger('play');
          $(this).unbind('click');
          delete UTIL.initialized['moviemovie'];
      });
    }
  },
  
  togglecontainers: {
    init: function () {
      $.getScript(sierra.base_href + 'js/libs/flowplayer-3.2.6.min.js');
      $('.showall, .close').live('click', sierra.togglecontainers.toggle);
    },
    toggle: function (e) {
      e.preventDefault();
      var link = $(this),
          target_id = link.attr('href'),
          open_blocks = $('[data-isopen="true"]:not("' + target_id + '")');
      if (target_id[0] !== '#') {
        target_id = target_id.substr(target_id.indexOf('#'));
      }
      open_blocks.hide().addClass('hidden').attr('data-isopen', false);
            
      if ($('.recipe-link a').length) {
        link = $('.recipe-link a');
      }
      $(target_id).toggle(function () {
        var $movie = $(this),
            comment;

        if ($movie.hasClass('hidden')) {
          $movie.removeClass('hidden').attr('data-isopen', true);
          if (link.hasClass('arrow-down')) {
            link.removeClass('arrow-down').addClass('arrow-up');
          }else if (link.hasClass('arrow-up')) { link.removeClass('arrow-up');
          }
          if (link.hasClass('arrow-left')) {
            link.removeClass('arrow-left').addClass('arrow-right');
          }
          
          if(link.parent().hasClass('recipe-link')) {
            link.addClass('arrow-down').addClass('activelink').parent().addClass('pink');
          }
          
          $movie.contents().filter(function () {
            return this.nodeType === 8;
          }).each(function (i, el) {
            comment = el;
            $movie.append(comment.nodeValue);
          });
          if (!sierra.helper.isElemInViewport($movie[0])) {
            sierra.helper.scrollPageTo($movie.offset().top);
          }
          
          try {
            //Movie nur starten, wenn auch #movie geklickt wurde
          if(target_id == '#movie' && $('video').length > 0)
            $('video')[0].play();
          
          if(target_id == '#description' && $('video').length > 0)
            $('video')[0].pause();
          } catch(e) {
            if(target_id == '#movie') {
                var moviename = $('#moviename').attr('value');
                if(!$f("player") || $f("player").getClip().url !== moviename) {
                    $f("player", "flowplayer-3.2.7.swf", {
                      clip : {
                        url: moviename,
                        autoPlay: true,
                        autoBuffering: true
                    },

                    plugins: {			
                        controls: {			
                            url: 'flowplayer.controls.swf',
                            playlist: true,		
                            tooltips: {		
                                buttons: true,
                                fullscreen: 'Enter Fullscreen mode'
                            }
                        }
                    }
                  });
                }
                
              $f().play();
            }
            
          }
          
        } else {
          $movie.addClass('hidden');
          try {
           if( $('video').length > 0 ) {
             $('video')[0].pause();
           }
          } catch(e) {
            $f("player").pause();
          }
          $movie.attr('data-isopen', false);
          if (link.hasClass('arrow-up')) {
            link.removeClass('arrow-up').addClass('arrow-down');
          }else if (link.hasClass('arrow-down')) {
            link.removeClass('arrow-down').addClass('arrow-up');
          }
          if (link.hasClass('arrow-right')) {
            link.removeClass('arrow-right').addClass('arrow-left');
          }
          
         
        }
      });
      window.setTimeout(sierra.helper.recalc_vig, 800);

    }
  },
  
  news: {
    init: function () {},
    fetch: function () {
      $.get('/fetch_blog.php', function(resp) {
        var html = '',
            article;
        for (article in resp) {
          article = resp[article];
          html += '<article class="'+ article.color +'">\
            <datetime>'+ article.date +'</datetime>\
            <h3><a href="'+ article.link +'">'+ article.title +'</a></h3>\
            <a href="'+ article.link +'" class="arrow">' + sierra.i18n.readmore + '</a>\
          </article>';
        }
        $('#news .loading').html(html);
        delete UTIL.initialized['newsfetch'];
      });
    }
  },
  
  home: {
    init: function () {
       
      $('.slides_container a img').bind('mouseenter mouseleave', function(e) {
          if('mouseenter' == e.type) {
            src = $(this).attr('src');
            src = src.replace(/\/img\/home-teaser-([0-9])([_a-z]*)\.(png|jpg)/, '/img/home-teaser-$1$2-rollover.$3');
            $(this).attr('src', src);
          } else {
            src = $(this).attr('src');
            src = src.replace(/\/img\/home-teaser-([0-9])([_a-z]*)-rollover.(png|jpg)/, '/img/home-teaser-$1$2.$3');
            $(this).attr('src', src);
          }
      });
    },
    initslider: function () {
      $.getScript(sierra.base_href + 'js/libs/slides.min.jquery.js', function () {
        $('#slider .slides_container a').show();
        $('#slider').slides({
          play: 5000,
          fadeSpeed: 500,
          effect: 'fade'
        });
        delete UTIL.initialized['homeinitslider'];
      });
    }
  },
  
  contact: {
    init: function() {
      $('#contact input, #contact textarea').live('focus', function(){
        var name = $(this).attr('name');

        if($(this).attr('value') == sierra._i18n[sierra.language][name]) {
          $(this).attr('value', '');
        }
      });
    }
  },

  shop: {
    init: function () {
      sierra.shop.cart = new sierra.shop.shoppingcart();
      sierra.shop.cart.fetch();
      $('.article .addtocart').live('click', sierra.shop.addtocart);
      $('#shop .removefromcart').live('click', sierra.shop.removefromcart);
      $('#shop .shopping-full').live('click', sierra.shop.showfullscreen);
      $('#shop .inputamount').live('change', sierra.shop.modifyamount);
      $('#cart-form').live('submit', sierra.shop.postsubmit);
      $('#country').live('change', sierra.shop.changeCountry);
      $('body').append('<div id="overlay"></div>');
    },
    initshop: function () {
      var dropzone = $('[dropzone]');
      dropzone.live('dragover', sierra.shop.canceldrag);
      dropzone.live('dragenter', sierra.shop.canceldrag);
      dropzone.live('drop', function (e) {
        var productid = e.originalEvent.dataTransfer.getData('Text');
        sierra.shop.addtocart.call($('#shop [data-productid="' + productid + '"] .addtocart'));
        $('[dropzone]').removeClass('dropzone');
      });
      $('[draggable]').live('dragstart', function (e) {
        dropzone.addClass('dropzone');
        e.originalEvent.dataTransfer.setData('Text', $(this).attr('data-productid'));
      });
      $('[draggable]').live('dragend', function (e) {
        dropzone.removeClass('dropzone');
      });
      delete UTIL.initialized['shopinitshop'];
    },
    orderform: function () {
      if (!sierra.support_placeholder) {
        sierra.helper.fixplaceholder();
      }
      $('#submitorder-form').live('submit', function (e) {
        if (e.preventDefault) {
          e.preventDefault();
        } else {
          if (e.stop) {
            e.stop();
            event.returnValue = false;
          }
        }
        e.stopPropagation();
        var errors = [];
        var params = {};
        $('form').find('.required').each(function (i, n) {
          var el = $(n),
            placeholder = el.data('placeholder') || el.attr('placeholder'),
            val = el.val();
          
          if (val === '' || val === placeholder) {
            errors.push(el);
          }
        });
        
        $('form').find('input, textarea').each(function(i, n) {
          var element = $(n);
          
          if(('radio' === element.attr('type') && element.attr('checked') === 'checked') || (!('radio' === element.attr('type')))) {
            params[element.attr('name')] = element.attr('value');
          }
          
        });
        
        $('form').find('select').each(function(i, n) {
          var element = $(n);

          params[element.attr('name')] = element.attr('value');      
        });
        
        if ($('.requiredcheck').attr('checked') !== 'checked') {
          errors.push($('requiredcheck'));
        }
        if (errors.length) {
          if (!$('p.error').length) {
           $('form p:last-child').before('<p class="error">' + sierra.i18n.formerror + '</p>');
           
          }
          
        } else if ($('p.error').length) {
          $('p.error').remove();
        }

        $.post($(this).attr('action') + '?return=json', params,function (resp) {
          if (resp && resp.error === false) {
            sierra.navigator.navigate_to_page('/' + sierra.language + '/shop/ordered', 'replace');
          }
        });
      });
    },
    canceldrag: function (e) {
      e.preventDefault();
      e.stopPropagation();
      return false;
    },
    removeborder: function (e) {
      sierra.shop.canceldrag(e);
      $('[dropzone]').removeClass('dropzone');
      return false;
    },
    shoppingcart: function () {
      this.products = {};
      this.amount = $('#shop .shopping-cart .amount').data('amount');
      this.add = function (product) {
        if (this.products[product.articleno] === undefined) {
          this.products[product.articleno] = product;
          this.amount++;
          $('#shop .shopping-cart .amount').text('(' + this.amount + ')').attr('data-amount', this.amount);
        }
      };
      this.remove = function (productid) {
        if (this.products[productid] !== undefined) {
          delete this.products[productid];
          this.amount--;
          $('#shop .shopping-cart .amount').text('(' + this.amount + ')').attr('data-amount', this.amount);
        }
      };
      this.fetch = function () {
        $.get(sierra.base_href + sierra.language + '/shop/show-cart?return=json', function (resp) {
          if (resp && resp.cart !== undefined) {
            sierra.shop.cart.products = resp.cart;
            sierra.shop.cart.amount = resp.amount;
          }
        });
      };
    },
    addtocart: function (e) {
      if (e) {
        e.preventDefault();
      }
      var article = $(this).parents('.article');
      var productid = article.data('productid');
      $.get($(this).attr('href') + '?return=json', function (resp) {
        if (resp && resp.cart && resp.cart[productid] !== undefined) {
          $('.article[data-productid="' + productid + '"] .addtocart').text(sierra.i18n.incart);
          $('.article[data-productid="' + productid + '"] .addtocart').addClass('incart');
          sierra.shop.cart.add(resp.cart[productid]);
          sierra.shop.clearshopcache();
          sierra.shop.updateshipping(resp.total);
          sierra.shop.updatetotal(resp.total);
        }
      });
    },
    removefromcart: function (e) {
      e.preventDefault();
      var productid = $(this).parents('[data-productid]').data('productid');
      var product = $(this).parents('.product');
      $.get($(this).attr('href') + '?return=json', function (resp) {
        if (resp && resp.cart) {
          sierra.shop.cart.remove(productid);
          product.remove();
          sierra.shop.clearshopcache();
          sierra.shop.updateshipping(resp.total);
          sierra.shop.updatetotal(resp.total);
        }
      });
    },
    changeCountry: function(e) {
      if ($(this).attr('value') == 'Deutschland') {
        $('#nachnahme').html('5.75');
      }  else {
        $('#nachnahme').html('13.75'); 
      }
      $.get(sierra.base_href + sierra.language + '/shop/get_info/?return=json', function(resp) {
        sierra.shop.updatetotal(resp.total);
        sierra.shop.clearshopcache();
      });
        
    },
    modifyamount: function (e) {
      var input = $(this);
      var product = input.parents('[data-productid]');
      var productid = product.data('productid');
      var amount = input.val();
      $.get(sierra.base_href + sierra.language + '/shop/modify-amount/' + productid + '?amount=' + amount + '&return=json', function (resp) {
        if (resp && resp.cart) {
          if (resp.cart[productid].amount === amount) {
            input.val(resp.cart[productid].amount);
            product.find('.price').text((resp.cart[productid].price * amount).toFixed(2));
            sierra.shop.updateshipping(resp.total);
            sierra.shop.updatetotal(resp.total);
          }
          sierra.shop.clearshopcache();
        }
      });
    },
    updatetotal: function (total) {
      sierra.shop.clearshopcache();
      var shipping = $('#shopping-cart .shipping .price').data('shipping');
      if($('#nachnahme').length > 0) {
        var nachnahme = parseInt($('#nachnahme').text());
      } else {
        nachnahme = 0;
      }
      $('#shopping-cart .total .price').text((total + shipping + nachnahme).toFixed(2));
    },
    updateshipping: function (total) {
      if(total > 50) {
        $('#shopping-cart .shipping .price').data('shipping', 0);
        $('#shopping-cart .shipping .price').html('0');
      } else {
        $('#shopping-cart .shipping .price').data('shipping', 4.65);
        $('#shopping-cart .shipping .price').html(4.65);
      }
    },
    postsubmit: function (e) {
      e.preventDefault();
      sierra.shop.clearshopcache();
      sierra.navigator.navigate_to_page($(this).attr('action'), true);
    },
    showfullscreen: function (e) {
      e.preventDefault();
      $('.product-full').remove();
      var product = $(this).parents('.article');
      var product_full = product.clone();
      product_full.addClass('product-full red').find('.product-name').wrap('<h2>');
      var image = product_full.find('img').remove();   
      var imgsrc = $(this).attr('href');
      image.attr('src', imgsrc).removeAttr('width').removeAttr('height');
      product_full.append(image).find('.shopping-full').addClass('pink').parent().remove();
      product_full.append('<ul class="no-bullets prevnext"><li><a href="#" class="prev">prev</a></li><li><a href="#" class="closeproduct">close</a></li><li><a href="#" class="next">next</a></li></ul>');
      product_full.find('.prev').bind('click', function (e) {
        e.preventDefault();
        var productid = product.data('productid');
        var prev = $('#shop').find('[data-productid="' + productid + '"]').prev();
        if (!prev.length) {
          prev = product.parents('.row').prev().find('.article:last');
        }
        if (!prev.length) {
          prev = $('#shop .row:last').find('.article:last');
        }
        sierra.shop.showfullscreen.call(prev.find('.shopping-full'), e);
      });
      product_full.find('.closeproduct').bind('click', function (e) {
        e.preventDefault();
        $('.product-full').remove();
        $('#overlay').hide();
      });
      product_full.find('.next').bind('click', function (e) {
        e.preventDefault();
        var productid = product.data('productid');
        var next = $('#shop').find('[data-productid="' + productid + '"]').next();
        if (!next.length) {
          next = product.parents('.row').next().find('.article:first');
        }
        if (!next.length) {
          next = $('#shop .row:first').find('.article:first');
        }
        sierra.shop.showfullscreen.call(next.find('.shopping-full'), e);
      });
      product_full.css({
        top: $('body').scrollTop() || $('html').scrollTop(),
        left: ($('html').width() / 2) - 270
      });
      $('body').append(product_full);
      $('#overlay').css('height', sierra.helper.get_height()).show();
    },
    clearshopcache: function () {
      var urls = [sierra.language + '/shop/index', sierra.language + '/shop/show-cart', sierra.language + '/shop/tos-and-shipping', sierra.language + '/shop/check-and-confirm'];
      $.each(urls, function (i, url) {
        sierra.navigator.page_cache(url, 'delete');
      });
    }
  },
  
  language_menu: {
    init: function () {
      $('#switch_language').live('click', function (e) {
        e.preventDefault();
        if ($(this).hasClass('open')) {
          $(this).removeClass('arrow-up').removeClass('open');
          $('.lang_popup').hide();
        } else {
          $(this).addClass('arrow-up').addClass('open');
          $('.lang_popup').show();
        }
      });
    }
  },


  helper: {
    recalc_vig: function () {
      
    },
    isHashChangeSupported: function () {
      if (!document.body) {
        return false;
      }
      // IE8 in IE7 compatibility mode doesn't fire onhashchange although it is reported as supported
      if ($.browser.msie && document.documentMode && document.documentMode < 8) {
        return false;
      }
      var element = document.body;
      var eventName = 'onhashchange';
      // When using `setAttribute`, IE skips "unload", WebKit skips "unload" and "resize"
      // `in` "catches" those
      var isSupported = (eventName in element);
      if (!isSupported && element.setAttribute) {
        element.setAttribute(eventName, 'return;');
        isSupported = typeof element[eventName] === 'function';
      }
      return isSupported;
    },
    support_localstorage: function () {
      try {
        return 'localStorage' in window && window['localStorage'] !== null;
      } catch (e) {
        return false;
      }
    },
    get_height: function () {
      var D = document;
      return Math.max(
        Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
        Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
        Math.max(D.body.clientHeight, D.documentElement.clientHeight)
      );
    },
    isElemInViewport: function (el) {
      var clientRect = el.getBoundingClientRect();
      return clientRect.top + 50 < window.innerHeight && clientRect.top > 0 && clientRect.bottom > 0;
    },
    scrollPageTo: function (pos) {
      $('html, body').animate({scrollTop: pos}, {ease: 'easeInOut'});
    },
    support_placeholder: function () {
      var i = document.createElement('input');
      return 'placeholder' in i;
    },
    fixplaceholder: function () {
      $('form').find('[placeholder]').each(function (i, n) {
        var el = $(n),
          placeholder = el.attr('placeholder');

        el.data('placeholder', placeholder)
          .val(placeholder)
          .bind('focus', function (e) {
            if ($(this).val() === placeholder) {
              $(this).val('');
            }
          })
          .bind('blur', function (e) {
            if ($(this).val() === '') {
              $(this).val(placeholder);
            }
          });
      });
    }
  }
};



sierra.navigator = {

  $page: undefined,
  $cache: undefined,
  cache: {},
  localstorage: undefined,
  cache_func: undefined,
  push_state: undefined,
  replace_state: undefined,
  initial_state: {},
  current_hash: '',
  popped: ('state' in window.history),
  redirects_enabled: true,

  init: function () {
    sierra.navigator.$page = $('#page');
    sierra.navigator.$cache = $('#cache');

    sierra.navigator.initial_state = {
      title: document.title,
      content: sierra.navigator.$page.html(),
      url: location.href
    };
    
    if ($('[data-disableredirect]').length) {
      sierra.navigator.redirects_enabled = false;
    }

    sierra.navigator.current_hash = window.location.hash;

    $('a.internal').live('click', sierra.navigator.events.click);
    /*
    if (sierra.helper.support_localstorage()) {
      sierra.navigator.localstorage = window.localStorage;
      sierra.navigator.cache_func = sierra.navigator.localstorage_cache;
    }
    else {
      sierra.navigator.cache_func = sierra.navigator.js_cache;
    }
    */
    sierra.navigator.cache_func = sierra.navigator.js_cache;
    
    if (!!(window.history && history.pushState)) {
      sierra.navigator.push_state = sierra.navigator.html5_push_state;
      sierra.navigator.replace_state = sierra.navigator.html5_replace_state;
      $(window).bind('popstate', sierra.navigator.events.popstate);
      if (location.hash.length > 0) {
        sierra.navigator.navigate_to_page(location.hash, 'replace');
      }
    }
    else {
      $.getScript(sierra.base_href + 'js/libs/jquery.cookie.min.js', function () {
        if (sierra.current_href !== sierra.base_href && sierra.navigator.redirects_enabled) {
          $.cookie('redirect_to', window.location.href, {path: '/'});
          window.location.href = sierra.base_href;
        }
        if (!sierra.helper.isHashChangeSupported()) {
          if (!$.browser.msie) { // hashchange event isnt supported, if the browser is not ie, we have to load the jquery.history.js library
            $.getScript(sierra.base_href + 'js/libs/jquery.history.min.js');
          }
        }
        sierra.navigator.push_state = sierra.navigator.set_hash;
        sierra.navigator.replace_state = sierra.navigator.html4_replace_state;
        $(window).bind('hashchange', sierra.navigator.events.hashchange);

        if ($.cookie('redirect_to') !== null && sierra.navigator.redirects_enabled) {
          var redirect = $.cookie('redirect_to');
          sierra.navigator.navigate_to_page(redirect, 'replace');
          $.cookie('redirect_to', null);
        }
        if (sierra.navigator.current_hash !== '') {
          sierra.navigator.navigate_to_page(sierra.navigator.current_hash, 'replace');
        }
      });
    }
  },

  get_page: function (url, pop, animate) {
    $.ajax({
      url: url,
      method: 'GET',
      success:  function (data, status, jqxhr) {
        sierra.navigator.handle_ajax_response(data, status, jqxhr, url, pop, animate);
      },
      error: sierra.navigator.handle_ajax_response
    });
  },

  handle_ajax_response: function (data_or_jqxhr, status, error_or_jqxhr, url, pop, animate) {
    var jqxhr = typeof error_or_jqxhr === 'object' ? error_or_jqxhr : data_or_jqxhr;
    if (typeof error_or_jqxhr === 'object') {
      var data = data_or_jqxhr;
      var now = new Date();
      if (data && data[1] === '!') { // got a html comment at first position (probably we received the whole page), we need to wrap the entirely response with a div, to handle the textnodes
        data = '<div class="response">' + data + '</div>';
      }
      var $response = sierra.navigator.page_cache(url, data, now);
      sierra.navigator.set_page($response, url, pop, animate);
    }
    else {
      // error occured
      location.href = url;
    }
  },

  page_cache: function (url, html, tstamp) {
    if (!html) {
      return sierra.navigator.cache_func(url);
    }
    else if (html === 'delete') {
      return sierra.navigator.cache_func(url, 'delete');
    }
    else {
      return sierra.navigator.cache_func(url, html, tstamp);
    }
  },

  dom_cache: function (url, html, tstamp) {
    if (!html) {
      if (sierra.navigator.$cache.find('[data-url="' + url + '"]').length) {
        return sierra.navigator.$cache.find('[data-url="' + url + '"]');
      }
      else {
        return false;
      }
    }
    else if (html === 'delete') {
      sierra.navigator.$cache.find('[data-url="' + url + '"]').remove();
    }
    else {
      var $response = sierra.navigator.$cache.append(html).find('.response:last-child');
      $response.attr('data-time', tstamp.getTime()).attr('data-url', url);
      return $response;
    }
  },

  js_cache: function (url, html, tstamp) {
    if (!html) {
      if (sierra.navigator.cache[url] && sierra.navigator.cache[url].html) {
        return $(sierra.navigator.cache[url].html);
      }
      else {
        return false;
      }
    }
    else if (html === 'delete') {
      delete sierra.navigator.cache[url];
    }
    else {
      sierra.navigator.cache[url] = {
        html: html,
        time: tstamp
      };
      
      return $(sierra.navigator.cache[url].html);
    }
  },

  localstorage_cache: function (url, html, tstamp) {
    if (!html) {
      if (sierra.navigator.localstorage.getItem(url)) {
        return $(JSON.parse(sierra.navigator.localstorage.getItem(url)).html);
      }
      else {
        return false;
      }
    }
    else {
      var item = { html: html, time: tstamp };
      sierra.navigator.localstorage.setItem(url, JSON.stringify(item));
      return $(item.html);
    }
  },

  set_page_title: function (title) {
    document.title = title;
  },

  set_page_body: function (html, animate) {
    if (animate && (animate.left || animate.right)) {
      var old_stage_slide = sierra.navigator.$page.find('#stage .slide-part').addClass('oldslide');
      var slide_width = old_stage_slide.width();
    }
    sierra.navigator.$page.html('');
    sierra.navigator.$page.html(html);
    if (animate && (animate.left || animate.right)) {
      var prop = animate.left ? 'right' : 'left';
      sierra.navigator.$page.find('#stage .slide-part').css(prop, slide_width).before(old_stage_slide);
      sierra.navigator.$page.find('#stage .oldslide').css(prop, slide_width);
      sierra.navigator.$page.find('#stage .slide-part').each(function (i, n) {
        if (prop === 'left') {
          $(n).animate({left: parseInt($(n).css('left'), 10) - slide_width});
        } else {
          $(n).animate({right: parseInt($(n).css('right'), 10) - slide_width});
        }
       $('.oldslide').remove();
      });
    }
    $(window).resize();
    sierra.navigator.$page.find('[data-controller]').each(function (i, n) {
      var controller = $(this).data('controller');
      var action = $(this).data('action');
      if (UTIL.initialized[controller + action] === undefined) {
        if (UTIL.initialized[controller + 'init'] === undefined) {
          UTIL.exec(controller, 'init', $(this));
        }
        UTIL.exec(controller, action, $(this));
      }
    });
  },

  set_page: function ($response, url, pop, animate) { /* $response can be both - a $response-jquery object or a state object */
    if ($response === false) {
      window.location.href = url;
    }
    if(sierra.navigator.cache[url])
      test = sierra.navigator.cache[url].html;
    var title = $response.title || $response.find('.title').text();
    var content = $response.content || $response.find('.page').html();
    sierra.navigator.set_page_title(title);
    sierra.navigator.set_page_body(content, animate);
    var state = {
      url: url,
      title: title, 
      content: content
    };
    if (pop === 'replace') {
      sierra.navigator.push_state(state);
    } else if (pop === true) {
      sierra.navigator.push_state(state);
    }
    $(window).resize();
    $('.activenav').removeClass('activenav');
    $('.h-nav a[href="' + url + '"]').addClass('activenav');
    
    if(sierra.navigator.$page.find('[data-controller=shop]').length > 0) {
      $('.h-nav a[href="de/shop"]').addClass('activenav');
    }

    $('#main-nav li a.active').removeClass('active');
    var id = $('.h-nav a[href="' + url + '"]').parent().parent().attr('id');
    $('#main-nav .'+id+' a').addClass('active');
  },

  navigate_to_page: function (url, pop, animate) {

    if (url.indexOf(sierra.base_href) !== -1) {
      url = url.substring(sierra.base_href.length);
    }
    if (url.indexOf('#!') >= 0) {
      url = url.substring(url.indexOf('#!') + 2);
    }
    var cached_page = sierra.navigator.page_cache(url);
    if (cached_page) {
      sierra.navigator.set_page(cached_page, url, pop, animate);
    }
    else {
      sierra.navigator.get_page(url, pop, animate);
    }
  },

  html5_push_state: function (state) {
    history.pushState(state, state.title, state.url);
  },

  html5_replace_state: function (state) {
    history.replaceState(state, state.title, state.url);
  },

  html4_replace_state: function (state) {
    sierra.navigator.set_hash(state, true);
  },

  hashify: function (url) {
    if (url.indexOf('#') !== -1) {
      if (url.indexOf('#!') !== -1) {
        return url;
      }
      return '#!' + url.substring(url.indexOf('#') + 1);
    }
    return '#!' + url;
  },

  urlify: function (hash) {
    if (hash.indexOf('#!') !== -1) {
      return hash.substring(hash.indexOf('#!') + 2);
    }
    return hash;
  },

  set_hash: function (state, replace) {
    var hash = sierra.navigator.hashify(state.url);
    sierra.navigator.current_hash = hash;
    if (location.hash !== hash) {
      if (replace === true) {
        location.replace(sierra.base_href + hash);
      }
      else {
        location.hash = hash;
      }
    }
  },

  events: {

    click: function (e) {
      e.preventDefault();
      sierra.navi.hide();
      var url = $(this).attr('href');//.replace(/[a-z]{2}/, sierra.language);
      var animate = {};
      animate.left = $(this).hasClass('arrow-left') || $(this).hasClass('directlink-left');
      animate.right = $(this).hasClass('arrow-right') || $(this).hasClass('directlink-right');
      
      if ($(this).parents('.nav-slider').length) {
        if ($(this).parent().nextAll('.active').length) {
          animate.left = true;
        } else {
          animate.right = true;
        }
      }


      var open_blocks = $('[data-isopen="true"]');
      if (!open_blocks.length) {
        sierra.navigator.navigate_to_page(url, true, animate);
      }
      open_blocks.hide(function() {
        sierra.navigator.navigate_to_page(url, true, animate);
      }).addClass('hidden');
      open_blocks.attr('data-isopen', false);
      if (!$(this).parents('#shop').length && !$(this).hasClass('tos-link')) {
        $('html, body').animate({scrollTop: 0}, {ease: 'easeInOut'});
      } else {
        $('html, body').animate({scrollTop: $('#shop').offset().top}, {ease: 'easeInOut'});
      }
    },

    popstate: function (e) {
      var initialPop = !sierra.navigator.popped && location.href === sierra.navigator.initial_state.url;
      sierra.navigator.popped = true;
      if ( initialPop ) {
        return;
      }
      if (e.originalEvent && e.originalEvent.state && e.originalEvent.state.content && e.originalEvent.state.title) {
        var state = e.originalEvent.state;
      }
      else {
        var state = sierra.navigator.initial_state;
      }
      sierra.navigator.set_page(state, state.url, false);
    },

    hashchange: function (e) {
      if (window.location.hash !== sierra.navigator.current_hash) {
        sierra.navigator.navigate_to_page(sierra.navigator.urlify(window.location.hash));
      }
    }

  }

};



sierra.navi = {
  subnav: {
    $node: undefined,
    is_hover: false,
    is_open: false,
    close_interval: undefined,
    hide_timeout: undefined
  },
  last_mouse_move: new Date(),

  init: function ($nav, $subnav){
    $nav.find('a').bind('click', sierra.navi.events.click);
    $subnav.bind('mouseenter', sierra.navi.events.hover)
    .bind('mouseleave', sierra.navi.events.hover)
    .find('.close').bind('click', function (e) {
      sierra.navi.hide($(this).parents('.subnav'));
    });
    $(document).bind('keydown', sierra.navi.events.keydown)
    .bind('mousemove', sierra.navi.events.mousemove);
  },

  events: {
    click: function (e) {
      e.preventDefault();
      var href = $(this).attr('href');
      if (href.indexOf('#') > -1) {
        href = href.substring(href.indexOf('#'));
        sierra.navi.show($(href));
      }
      else {
        window.location.href = href;
      }
    },
    hover: function (e) {
      if (e.type === 'mouseenter') {
      sierra.navi.subnav.is_hover = true;
      }
      else {
        sierra.navi.subnav.is_hover = false;
      }
    },
    keydown: function (e) {
      if (e.which === '27') { // [ESC]
        sierra.navi.hide(sierra.navi.subnav.$node);
      }
    },
    mousemove: function (e) {
      if (sierra.navi.subnav.is_open) {
        sierra.navi.last_mouse_move = new Date();
      }
    }
  },

  show: function ($nav){
    sierra.navi.hide(sierra.navi.subnav.$node, function (){
      if (!$nav.is(':visible')) {
        $nav.slideDown('fast', function (){
          sierra.navi.subnav.$node = $nav;
          sierra.navi.subnav.is_hover = false;
          sierra.navi.subnav.is_open = true;
          sierra.navi.subnav.close_interval = window.setInterval(function (){
            if (!sierra.navi.subnav.is_hover) {
              if (!sierra.navi.subnav.hide_timeout) {
                sierra.navi.subnav.hide_timeout = window.setTimeout(function (){
                  sierra.navi.hide($nav);
                  window.clearInterval(sierra.navi.subnav.close_interval);
                  window.clearTimeout(sierra.navi.subnav.hide_timeout);
                  sierra.navi.subnav.hide_timeout = undefined;
                }, 3000);
              }
            }
            else {
              window.clearTimeout(sierra.navi.subnav.hide_timeout);
              sierra.navi.subnav.hide_timeout = undefined;
            }
            var now = new Date();
            if (now.getTime() - sierra.navi.last_mouse_move.getTime() >= 20000) {
              sierra.navi.hide($nav);
            }
          }, 700);
        });
      }
    });
  },

  hide: function ($nav, callback){
    $nav = $nav || sierra.navi.subnav.$node;
    callback = callback || function (){};
    if ($nav && $nav.length && $nav.is(':visible')) {
      $nav.slideUp('fast', function (){
        window.clearInterval(sierra.navi.subnav.close_interval);
        window.clearTimeout(sierra.navi.subnav.hide_timeout);
        sierra.navi.subnav = {
          $node: undefined,
          is_hover: false,
          is_open: false,
          close_interval: undefined,
          hide_timeout: undefined
        };
        if (callback) {
          callback();
          return;
        }
      });
    }
    callback();
    return;
  }
};





var UTIL = {
  initialized: {},
  exec: function (controller, action, arg) {
    var ns = sierra; // Namespace

    if (controller !== "" && ns[controller] && typeof ns[controller][action] === "function") {
      try {
        UTIL.initialized[controller + action] = true;
        ns[controller][action](arg);
      }
      catch (e) {
        console.log(e);
      }
    }
    else { console.log('UTIL.exec: controller or action are not declared (' + controller + '.' + action + ')'); }
  },
  init: function () {
    UTIL.exec('common', 'init');
    $.each($('[data-controller]'), function (i, node) {
      var controller = $(node).data('controller'),
          action = $(node).data('action');
      UTIL.exec(controller, 'init', node);
      if (!!action) {
        UTIL.exec(controller, action, node);
      }
    });
  }
};

$(document).ready(UTIL.init);
