/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie = function (key, value, options) {

  // key and at least value given, set cookie...
  if (arguments.length > 1 && String(value) !== "[object Object]") {
    options = jQuery.extend({}, options);

    if (value === null || value === undefined) {
      options.expires = -1;
    }

    if (typeof options.expires === 'number') {
      var days = options.expires, t = options.expires = new Date();
      t.setDate(t.getDate() + days);
    }

    value = String(value);

    return (document.cookie = [
      encodeURIComponent(key), '=',
      options.raw ? value : encodeURIComponent(value),
      options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
      options.path ? '; path=' + options.path : '',
      options.domain ? '; domain=' + options.domain : '',
      options.secure ? '; secure' : ''
    ].join(''));
  }

  // key and possibly options given, get cookie...

  options = value || {};
  var result, decode = options.raw ? function (s) {
    return s;
  } : decodeURIComponent;
  return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

// REFERRER & COOKIE

var ref = document.referrer;

if (ref != "undefined") {
  if ($.cookie("referrer") == null) {
    $.cookie("referrer", ref);
  }
  var referrer = $.cookie("referrer");
}

// GOTOLINK FUNCTION

function gotoLink(htmlElement) {

  var destinationURL = "";
  var target = "";

  if (htmlElement.href) {
    destinationURL = htmlElement.href;
    target = htmlElement.getAttribute("target");
  }
  else {
    if (htmlElement.childNodes) {
      if (htmlElement.getElementsByTagName("a")) {
        destinationURL = htmlElement.getElementsByTagName("a")[0].href;
        target = htmlElement.getElementsByTagName("a")[0].getAttribute("target");
      }
    }
  }

  if (destinationURL.length > 0) {
    if (target == "_blank") {
      window.open(destinationURL);
    }
    else {
      location.href = destinationURL;
    }
  }
  return false;
}


$(window).load(function() {

  // METANAV

  if ($("#mainMenu").length) {
    var width = $("#mainMenu").width();
    var submenu = $(".submenu", "#mainMenu");
    submenu.width(width);
    $("#mainMenu > ul > li").hover(function() {
      $(this).toggleClass("hover");
    });
  }

});

// DISABLE RIGHT CLICK

/*$(document).bind("contextmenu",function(e){
  return false;
});*/

$(document).ready(function() {

  // INPUT VALUE SWAP

  if ($("form").length) {
    $('form input').each(function() {
      if ($(this).val() == '') {
        $(this).val($(this).attr('title'));
      }
    });

    var swap_val = [];

    $("input#address").each(function(i) {
      swap_val[i] = $(this).val();
      $(this).focusin(
          function() {
            if ($(this).val() == swap_val[i]) {
              $(this).val("");
            }
          }).focusout(function() {
        if ($.trim($(this).val()) == "") {
          $(this).val(swap_val[i]);
        }
      });
    });

    /* $('input.submit').bind('click', function(){
     $('form .body input').each(function(){
     if( $(this).val() == $(this).attr('title') ){
     $(this).val('');
     }
     });
     });*/
  }

  // ROOM SLIDER

  if ($("#room_slider").length) {

    var itemcount = $(".movingcontainer:first").children().length;
    var itemwidth = $(".item:first", ".movingcontainer:first").width();
    var movingcontainerlength = itemcount * itemwidth;
    $(".movingcontainer").width(movingcontainerlength);
    var plus = "-=";
    var pluswidth = plus.concat(itemwidth);
    var minus = "+=";
    var minuswidth = minus.concat(itemwidth);
    var speed = 200;
    var pos = 1;
    var maxpos = itemcount;


    $("a.leftarrow", "#room_slider").click(function() {
      $("a.rightarrow", "#room_slider").removeClass("isnone");
      if (pos > 1) {
        $(".movingcontainer").animate({
          left: minuswidth
        }, speed, "easeInOutQuad");
        pos--;
        if (pos == 1) {
          $(this).addClass("isnone");
        }
      }
      return false;
    });

    $("a.rightarrow", "#room_slider").click(function() {
      $("a.leftarrow", "#room_slider").removeClass("isnone");
      if (pos < itemcount) {
        $(".movingcontainer").animate({
          left: pluswidth
        }, speed, "easeInOutQuad");
        pos++;
        if (pos == ( itemcount )) {
          $(this).addClass("isnone");
        }
      }
      return false;
    });

    // Dateinput & Button

    var parsed;

    if ($("input.arrival").length > 0) {
      $("input.arrival").change(function(event, date) {
        var datum = $("input.arrival").val();
        var sdatum = datum.split(".");
        var tag = sdatum[0];
        var monat = sdatum[1];
        var jahr = sdatum[2];
        var date = Date.UTC(jahr, (monat - 1), tag, 0, 0, 00);
        parsed = date / 1000;
        $(this).blur();
      });
    }

    // Click on Button

    var itemsperrow = $(".nav .movingcontainer", "#room_slider").children().length;

    if ($("a#rooms_arrival_button").length > 0) {

      $("a#rooms_arrival_button").click(function() {

        $("#notinlist").show();

        var arraylength = price_seasons.length;

        for (i = 0; i < itemsperrow; i++) {

          if (price_seasons[i][0] < parsed && price_seasons[i][1] > parsed) {

            var topos = (i + 1);
            var difference = topos - pos;
            pos = pos + difference;
            var scrollamount = difference * itemwidth;

            $("#notinlist").hide();
            $(".movingcontainer", "#room_slider").animate({
              left:"-=" + scrollamount + "px"
            }, speed, "easeInOutQuad", function() {
            });

            if (pos == itemcount) {
              $("a.rightarrow", "#room_slider").addClass("isnone");
              $("a.leftarrow", "#room_slider").removeClass("isnone");
            }
            if (pos == 1) {
              $("a.leftarrow", "#room_slider").addClass("isnone");
              $("a.rightarrow", "#room_slider").removeClass("isnone");
            }
            if (pos > 1 && pos < itemcount) {
              $("a.leftarrow", "#room_slider").removeClass("isnone");
              $("a.rightarrow", "#room_slider").removeClass("isnone");
            }

          }
          else {

          }
        }


        return false;
      });
    }
  }

  // JQUERY UI DATEPICKER

  if ($("input.date").length) {
    //if (lang == "de") {
    $("input.date").datepicker({
      numberOfMonths: 1, regional: "de", dateFormat: 'dd.mm.yy', firstDay: 1,
      monthNames: ['Januar','Februar','M&auml;rz','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'],
      dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'],
      prevText: 'zur&uuml;ck', nextText: 'vor',
      minDate: 0
    });
    //}
  }


    // CHILDREN COUNT

    if ( $("input#count_children").length ) {

        $("input#count_children").blur(function() {
            var content = $(this).val();
            if ( content > 5 ) {
                $(".attention").show();
            }
            if ( content > 0 ) {
                $(".attention").hide();
                $(".fline.birthyears").show();
                for ( i=1; i<=content; i++ ) {
                    $("#by"+i).show();
                }
            }
        });



    }

  // LIGHTBOX (COLORBOX)

  if ($("a.lightbox").length) {

    if ($(".contentblock.gallery").length) {

      /*var random = "g" + Math.floor(Math.random() * 11);

      $(".contentblock.gallery .image").each(function() {
        var description = $("a", this).attr("title");
        var copyright = $("a", this).attr("alt");
        if ( copyright != "" ) {
          var newdesc = description + ", " + copyright;
        } else {
          var newdesc = description;
        }
        newdesc = $.trim(newdesc);
        $("a", $(this)).attr("title", newdesc);
        $("a", $(this)).attr("alt", newdesc);
        $("a", $(this)).attr("rel", random);
      });*/

    }

    $("a.lightbox").colorbox({
      current: function() {
      },
      opacity: 0.4
    });
  }

  // LIGHTBOX IFRAME

  if ($("a.lightboxiframe").length) {
    $("a.lightboxiframe").colorbox({
      iframe: true,
      width: "80%",
      height: "80%"
    });
  }


  // TABLE FORMATTING

  if ($(".contentblock table").length) {
    $(".contentblock table tbody tr:odd").addClass("odd");
  }

  // FAKESELECT

  if ($(".fakeselect").length) {

    $(".fakeselect").css("z-index", "100");
    $(".fakeselect .dropdown").hide();

    $(".fakeselect").click(function() {

      var thisfake = $(this);
      var thisfakec = thisfake.attr("class");
      var thisfakeclass = thisfakec.slice(11);

      if ($(this).css("z-index") < 120) {
        $(this).css("z-index", "120");
        $(".dropdown", this).fadeIn(0);
      } else {
        $(this).css("z-index", "100");
        $(".dropdown", this).hide();
      }

      $(".value", this).click(function() {

        var thisfakeselect = $(this).parent().parent();
        var thisval = $(this).html();
        var thisid = $(this).attr("dir");

        if (thisfakeselect.hasClass("newsletter")) {

          var hiddenselect = $("select.newsletter");
          $("option", hiddenselect).removeAttr("selected");

          var optionlength = $("option", hiddenselect).length;

          for (i = 0; i < optionlength; i++) {
            var currenttext = $("option:eq(" + i + ")", hiddenselect).text();
            var currentoption = $("option:eq(" + i + ")");
            if (currenttext == thisval) {
              currentoption.attr("selected", "");
            }
          }

        }
        else {
          var hiddeninput = $("input." + thisfakeclass + "");
          if (thisid != undefined) {
            hiddeninput.attr("value", thisval);
          }
          else {
            hiddeninput.attr("value", "");
          }
        }

        var thishead = $(this).parent().prev();
        thishead.html(thisval);
        var thisinput = $(this).parent().parent().prev();
        var thisdropdown = $(this).parent();
        thisdropdown.hide();
        $(thisinput).val(thisval);

      });
    });
  }

  // FAKECHECK

  if ($("a.fakecheck").length) {

    $("a.fakecheck").click(function() {

      $(this).toggleClass("clicked");
      var value = $(this).text();
      var parent = $(this).parent();
      var id = $(this).attr("id");
      if ( id == "newsletter" ) {
        var val = "ja";
      } else {
        var val = id;
      }
      if ( $(this).hasClass("clicked") ) {
        $("input#fc_"+id+"").attr("value",val);
      } else {
        $("input#fc_"+id+"").attr("value",val);
      }

      return false;
    });
  }

  // ELSLIDER ADDITION

  if ($(".contentblock.slider .elslider").length) {

    if ($(".contentblock.slider.special").length) {

      $(".contentblock.slider.special .elslider").elSlider({
        visibleitems  : 1,
        vertical    : false,
        continuous    : true,
        animationspeed  : 500,
        numbers     : true,
        thumbs      : true,
        fadingspeed   : 0
      });

    }

    $(".elslider").each(function() {

      var slider = $(this);

      var totalitems = $(".sl_movingcontainer", this).children();
      var totallength = totalitems.length;
      var pos = 1;
      var maxpos = totalitems;
      var ctotal = $(".total", this);
      var ccurrent = $(".current", this);
      var startappendage = "<div class='no'><div class='current'>1</div>/<div class='total'>" + totallength + "</div></div> </div>";
      $(".numbers", this).append(startappendage);

      var text = $(".text", slider);

      $(".sl_rightarrow a", this).click(function() {
        if (pos < totallength) {
          pos++;
        }
        else {
          pos = 1;
        }
        $(".current", slider).empty().text(pos);
        return false;
      });

      $(".sl_leftarrow a", this).click(function() {
        if (pos > 1) {
          pos--;
        }
        else {
          pos = totallength;
        }
        $(".current", slider).empty().text(pos);
        return false;
      });

    });

  }

  // MAP INIT

  if ($("#map_canvas").length) {
    initialize();
  }

  // DATEPICKER

  if ($("input.datepicker").length) {
    $("input.datepicker").datepicker({
      numberOfMonths: 1, regional: "de", dateFormat: 'dd.mm.yy', firstDay: 1,
      monthNames: ['Januar','Februar','M&auml;rz','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'],
      dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'],
      prevText: 'zur&uuml;ck', nextText: 'vor',
      minDate: 0
    });
  }

  // STANDARDCONTENTBLOCK ANPASSUNGEN

  if ($(".contentblock.videoteaserwide")) {
    var vrandom = "v" + Math.floor(Math.random() * 11);
    $(".contentblock.videoteaserwide .teaser").each(function() {
      var a = $("a", this);
      a.attr("rel", vrandom);
    });
  }

  if ($(".contentblock.wysiwyg_images_right")) {
    var wrandom = "w" + Math.floor(Math.random() * 11);
    $(".contentblock.wysiwyg_images_right a").each(function() {
      var a = $(this);
      a.attr("rel", wrandom);
    });
  }


  /*if ($(".contentblock.teaserwide").length) {
   $(".teaser",".contentblock.teaserwide").each(function() {
   if ( !$(".pimcore_block_buttons").length ) {
   $(this).attr("onclick","gotoLink(this);");
   $(".text",this).append("<span class='awrapper'></span>");
   }
   })
   }*/

  // Videoteaser Button

  if ($(".videoteaserwide").length) {
    $(".videoteaserwide .teaser").each(function() {
      if (lang == "de") {
        var txt = "Video abspielen";
      } else {
        var txt = "Play Video";
      }
      var xclass = $(".image a", this).attr("class");
      var href = $(".image a", this).attr("href");
      $(".text", this).append("<span class='button small'>" + txt + "</span>");
    });
  }

  // PREVENT FOOTER LINKS FROM BEING EXECUTED WHEN EMPTY

  if ($("ul.logos", "#footerMenu").length) {
    var logolink = $("ul.logos li a", "#footerMenu");
    var llength = logolink.length;
    for (i = 0; i < llength; i++) {
      var currentlink = $("ul.logos li a:eq(" + i + ")", "#footerMenu");
      var currid = currentlink.attr("id");
      if (currentlink.attr("href") == "#") {
        $("ul.logos li a#" + currid).click(function() {
          return false;
        })
      }
    }
  }

  if ($("ul", "#footerSocial").length) {
    var logolink = $("ul li a", "#footerSocial");
    var llength = logolink.length;
    for (i = 0; i < llength; i++) {
      var currentlink = $("ul li a:eq(" + i + ")", "#footerSocial");
      var currid = currentlink.attr("id");
      if (currentlink.attr("href") == "#") {
        $("ul li a#" + currid).click(function() {
          return false;
        })
      }
    }
  }


});

