(function ($) {
  $.fn.center = function (options) {
    var defaultOptions = {container:'window', vertical:false, horizontal:true};
    var config = $.extend(defaultOptions, options || {});

    return this.each(function () {
      var layer = $(this);

      var winContainer = config.container == "window";
      var container = winContainer ? $(window) : layer.parent();

      var parentHeight = container.actual("height");
      var parentWidth = container.actual("width");

      if (!winContainer) {
        parentHeight = container.actual("innerHeight");
        parentWidth = container.actual("innerWidth");
        layer.css({position:"absolute"});
      }

      var childHeight = layer.actual("outerHeight", { includeMargin:true });
      var childWidth = layer.actual("outerWidth", { includeMargin:true });

      if (config.vertical == true) {
        var layerTop = Math.ceil((parentHeight - childHeight) / 2);
        layer.css({top:String(layerTop) + "px"});
      }

      if (config.horizontal == true) {
        var layerLeft = Math.ceil((parentWidth - childWidth) / 2);
        layer.css({left:String(layerLeft) + "px"});
      }
    });
  };

  // Many thanks to: http://james.padolsey.com/javascript/jquery-delay-plugin/
  $.fn.delay = function (time, callback) {
    // Empty function:
    $.fx.step.delay = function () {
    };
    // Return meaningless animation, (will be added to queue)
    return this.animate({delay:1}, time, callback);
  }
})(jQuery);

$(function () {
  if ($(".ovl_video").length) {
    play_video();
  }

  menu_highlight();

  popupAdultChecker.init();
});

String.prototype.endsWith = function (text) {
  return (this.match(text + "$") == text);
};

function play_video() {
  $('.opn_video').click(function () {
    $('.ovl_video').show();
    $('#video').center();
    $('#video').show();
    return false;
  });
  $('a.close').click(function () {
    $('.ovl_video').hide();
    $('#video').hide();
    return false;
  });
}

var paths = {
  normalize:function (path) {
    return (path || "").replace(/(^\/+|\/+$)/g, "");
  },
  ancestors:function (path) {
    var ancestorPaths = [];

    var segments = this.normalize(path).split("/");
    var partial = "";
    for (var index = 0; index < segments.length; index++) {
      partial += "/" + segments[index];
      ancestorPaths.push(partial);
    }

    return ancestorPaths;
  },
  combine:function (right, left) {
    var path = right || "";
    if (!path.endsWith("/")) {
      path += "/";
    }
    path += this.normalize((left || ""));
    return path;
  }
}

function menu_highlight() {
  var pathname = location.pathname.replace(/(^\/+$)/g, "");
  var ancestors = paths.ancestors(pathname);

  $("#menu_top li a").each(function () {
    var href = $(this).attr("href") || "";
    var ancestor = (("" != pathname) && ("" != href) && ((pathname == href) || ($.inArray(href, ancestors) > 0)));
    if (ancestor) {
      $(this).parents("li").addClass("on");
    }
  });
}

var slideshow = {
  gallery:{},
  init:function (gallery) {
    var thisObject = this;

    this.gallery = gallery;

    var galSlideshow = $(".gal_slideshow");

    galSlideshow.unbind();

    var setCounter = function (count) {
      var index = isNaN(count) ? "" : String(count + 1);

      $('#index').html(String(index));
    };

    function onAfter(curr, next, opts) {
      setCounter(opts.currSlide);
    }

    galSlideshow.cycle({fx:'fade',
      timeout:5000,
      cleartype:true,
      after:onAfter
    });

    var galNav = $("#gallery_nav");

    galNav.find(".pause").click(function () {
      galSlideshow.cycle("pause");
      return false;
    });

    galNav.find(".play").click(function () {
      galSlideshow.cycle("resume");
      return false;
    });

    $("li.fullscreen a:first").click(function () {
      var index = $("#index");
      var counter = index.text() - 1;
      if (isNaN(counter)) {
        counter = -1;
      }
      thisObject.fullscreen.open(counter);
      return false;
    });

    setCounter(Number(gallery.index));
  },
  stop:function () {
    $('#gallery_nav .pause').click();
  },
  fullscreen:{
    open:function (index) {
      var galleryImage = slideshow.gallery.fullscreenPictures[index];
      if (!galleryImage) {
        return;
      }

      var thisObject = this;

      var newFullscreen = function () {
        $("body").addClass("fs");

        var container = $("<div></div>");
        var image = $("<img></img>");

        container.attr("id", "bkg");

        container.click(function () {
          thisObject.close();
          return false;
        });

        container.append(image);

        return container;
      };

      this.close();

      $("body").append(newFullscreen());

      var counter = $("#gallery_nav li.counter:first");

      var fullsizeImage = $("#bkg img");

      fullsizeImage.unbind();
      fullsizeImage.attr("src", galleryImage.url || "#");
      fullsizeImage.addClass("on");
      fullsizeImage.click(function () {
        fullsizeImage.removeClass("on");
      });
    },

    close:function () {
      $("body").removeClass("fs");
      $("#bkg").remove();
    }
  }
};

var eventGallery = {
  galleries:[],
  bind:function (galleries) {
    this.galleries = galleries || [];

    this.initNavBars();
  },
  initNavBars:function () {
    var navEntries = $("#entry_wrapper .entry_nav");
    var thisObject = this;
    navEntries.each(function () {
      var navEntry = $(this);
      var navIndex = navEntries.index(this);
      var hideBar = true;
      var item = thisObject.galleries.items[navIndex];

      var lnkNavLeft = navEntry.find(".nav_sx a");
      var lnkNavCount = navEntry.find(".nav_tot a");
      var lnkNavRight = navEntry.find(".nav_dx a");
      var imgPicture = navEntry.parents(".entry_img").find("img:first");

      if (item) {
        var pictureCount = item.pictures.length;

        var setCounter = function (count) {
          var index = isNaN(count) ? "" : String(count + 1);

          lnkNavCount.html(index + "&nbsp;[ " + pictureCount + " ]");
        };

        var nextIndex = function () {
          item.index = (item.index + 1) % pictureCount;
          return item.index;
        };

        var prevIndex = function () {
          item.index = ((item.index > 0 ? item.index : pictureCount) - 1) % pictureCount;
          return item.index;
        };

        var loadPicture = function (newIndex) {
          setCounter(newIndex);
          var newPicture = item.pictures[newIndex];
          var newUrl = newPicture ? newPicture.url : "#";
          imgPicture.attr("src", newUrl);
        };

        if (pictureCount > 1) {
          lnkNavLeft.click(function () {
            loadPicture(prevIndex());
            return false;
          });
          lnkNavRight.click(function () {
            loadPicture(nextIndex());
            return false;
          });
        }

        hideBar = (pictureCount <= 1);

        setCounter(Number(item.index));
      }

      if (hideBar) {
        navEntry.hide();
      }
    });
  }
};

var chefSpecial = {
  MAX_COURSES:25,
  MAX_PICTURES:10,
  specials:[],
  index:0,
  bind:function (specials) {
    this.specials = specials;

    this.initSlider();
  },
  open:function (animation) {
    $('#main_dx_nav').hide();
    if (animation) {
      $("#slider_box").slideDown(animation);
    } else {
      $("#slider_box").show();
    }
    $('#slider_menu p.open').addClass('on');
    $("#open").html(this.specials.slider.labels["hide"]);
  },
  close:function (animation) {
    if (animation) {
      $("#slider_box").slideToggle(animation);
    } else {
      $("#slider_box").hide();
    }
    $('#main_dx_nav').show();
    $('#slider_menu p.open').removeClass('on');
    $("#open").html(this.specials.slider.labels["show"]);
  },
  initSlider:function () {
    var thisObject = this;
    var ulSlider = $("#slider_box ul");
    var mainNav = $("#main_dx_nav");
    var courseCount = 0;

    $.each(this.specials.items, function (index, value) {
      var course = value;

      var thumbnailUrl = course.thumbnail.url || "";

      if (("" == thumbnailUrl) || (courseCount++ >= thisObject.MAX_COURSES)) return;

      var newThumbnailImg = $("<img></img>");
      var newThumbnailLnk = $("<a></a>");
      var newWrapper = $("<li></li>");

      newThumbnailImg.attr("src", course.thumbnail.url);
      newThumbnailLnk.attr("href", "#");

      newThumbnailLnk.click(function () {
        thisObject.loadCourse(course);
        thisObject.index = index;
        $("#slider_box").smoothDivScroll("moveToElement", "number", index + 1);
        return false;
      });

      var ovlLayer = $("<div></div>");
      var courseTitle = $("<p></p>");

      ovlLayer.addClass("ovl_sld");
      courseTitle.html(course.title || "");

      newThumbnailLnk.append(ovlLayer.append(courseTitle));
      ulSlider.append(newWrapper.append(newThumbnailLnk.append(newThumbnailImg)));

      newThumbnailImg.load(function () {
        courseTitle.center({container:"parent", horizontal:true, vertical:true});
      });
    });

    var hideMainNav = this.specials.items.length <= 1;
    if (hideMainNav) {
      mainNav.hide();
      $("#open").click(function () {
        mainNav.hide();
        return false;
      });
    }

    var navPrev = $("#main_dx_nav a:eq(0)");
    var navNext = $("#main_dx_nav a:eq(1)");

    if (courseCount > 0) {
      var clickAt = function (newIndex) {
        ulSlider.find("li:eq(" + newIndex + ") a").click();
      };

      navPrev.click(function () {
        var newIndex = ((thisObject.index <= 0 ? courseCount : thisObject.index) - 1) % courseCount;
        clickAt(newIndex);
        return false;
      });

      navNext.click(function () {
        var newIndex = (thisObject.index + 1) % courseCount;
        clickAt(newIndex);
        return false;
      });
    }


    $('#open').click(function () {
      if ($("#slider_box").is(":hidden")) {
        thisObject.open("slow");
      } else {
        thisObject.close("slow");
      }

      return false;
    });

    this.index = this.courseIndexByUrl();

    $("#slider_box").smoothDivScroll({
      scrollStep:5,
      visibleHotSpots:"always",
      scrollableArea:"ul.scrollableArea",
      scrollWrapper:"div.scrollWrapper"
    });

    this.close();
    ulSlider.find("li:eq(" + this.index + ") a").click();
  },
  courseIndexByUrl:function () {
    var path = location.pathname || "";
    if ("" == path) {
      return 0;
    }

    var courseIndex = 0;
    $.each(this.specials.items, function (index, value) {
      var course = value;
      if (course.url == path) {
        courseIndex = index;
      }
    });

    return courseIndex;
  },
  loadCourse:function (course) {
    // console.log("course->%o", course);

    var picture = $("#course_picture");
    var video = $("#main_watch");
    var title = $("#course_title");
    var subtitle = $("#course_subtitle");
    var description = $("#menu_txt_box");
    var navButtons = $(".s_nav_btn");
    var shareBox = $("#menu_txt_share .addthis_toolbox:first");

    navButtons.empty();

    var picturesCount = Math.min(course.gallery.pictures.length, this.MAX_PICTURES);
    // console.log("picturesCount->%s", picturesCount);

    $.each(course.gallery.pictures, function (index, value) {
      if (index >= this.MAX_PICTURES) return;

      var link = $("<a></a>");
      link.attr("href", "#");

      link.click(function () {
        var pictureUrl = value.url || "#";
        // console.log("pictureUrl->%s", pictureUrl);
        picture.attr("src", pictureUrl);
        return false;
      });

      navButtons.append(link);
    });

    var videoId = course.videoId || "";
    var videoPlayer = $(".wrap_video iframe");

    if (videoId != "") {
      videoPlayer.attr("src", "http://www.youtube.com/embed/" + videoId)
      video.show();
    } else {
      video.hide();
    }

    var wrapperNav = navButtons.parent();
    if (picturesCount > 1) {
      wrapperNav.show();
    } else {
      wrapperNav.hide();
    }

    title.html(course.title || "");
    subtitle.html(course.subtitle || "");
    description.html(course.description || "");
    picture.attr("src", course.picture.url || "#");

    description.unbind();
    description.data("jsp", null);
    description.jScrollPane();

    if (addthis) {
      addthis.update("share", "url", paths.combine(appSettings.baseUrl, course.url));
    }
  }
};

var restaurantMenu = {
  MAX_MENUS:10,
  menus:[],
  courseTypes:[],
  bind:function (menus, courseTypes) {
    this.menus = menus;
    this.courseTypes = courseTypes;

    this.initMenuLinks();
  },
  loadMenu:function (menu) {
    var menuDescription = $("#menu_nav h3");

    menuDescription.html(menu.description || "");

    this.loadCourses(menu);
  },
  initMenuLinks:function () {
    var linksWrapper = $("#link_ovl");
    var thisObject = this;

    var addMenuLink = function (menu) {
      var link = $("<a></a>");

      link.attr("href", "#");
      link.addClass("opn_menu");
      link.html(menu.description || "");

      link.click(function () {
        thisObject.loadMenu(menu);
        return false;
      });

      linksWrapper.append(link);
    };

    $.each(this.menus.items, function (index, value) {
      addMenuLink(value);
    });

    var menuLayers = $(".ovl_menu,#restaurant_menu");
    $('.opn_menu').click(function (event) {
      $("#restaurant_menu").center();
      menuLayers.show();
      //TODO: WORKAROUND per ottenere il focus in cima alla pagina (event.isDefaultPrevented()=true)
      location.href = "#";
      return false;
    });
    $('a.close').click(function () {
      menuLayers.hide();
      return false;
    });
  },
  newCourseWrapper:function (showCourseType) {
    return {
      hiddenCourseTypes:["beverage", "champagne"],
      courses:[],
      label:function (courseType) {
        return restaurantMenu.label(restaurantMenu.courseTypes.items, courseType);
      },
      draw:function (menuWrapper) {
        if (this.courses.length <= 0) {
          return;
        }

        var courseWrapper = $("<div></div>");
        var listWrapper = $("<div></div>");
        var listContent = $("<ul></ul>");

        courseWrapper.addClass("menu_el");
        listWrapper.addClass("el_list");

        courseWrapper.append(listWrapper.append(listContent));

        var thisObject = this;
        var prevCourseType = "";
        $.each(this.courses, function (index, value) {
          var content = $("<li></li>");
          var left = $("<p></p>");
          var right = $("<p></p>");

          left.addClass("plate");
          right.addClass("price");

          var price = value.price || "";
          left.html(value.description);
          if (showCourseType) {
            var hidden = $.inArray(value.courseType, thisObject.hiddenCourseTypes) > -1;
            // console.log("%s %s", value.courseType, hidden);
            var canShow = (value.courseType != prevCourseType) && (!hidden);

            if (canShow) {
              var courseTypeLabel = thisObject.label(value.courseType);
              left.prepend($("<h3/>").html(courseTypeLabel.i18n));
            }
          }
          prevCourseType = value.courseType;
          right.html("" != price ? "&euro;&nbsp;" + price : "");

          content.append(left);
          content.append(right);

          listContent.append(content);
        });

        menuWrapper.append(courseWrapper);

        this.courses = [];
      }
    };
  },
  loadCourses:function (menu) {
    // console.log("menu: %o", menu);

    var menuContainer = $("#restaurant_menu");
    var menuNav = $("#menu_nav");
    var courseTypeWrapper = $("#menu_nav ul");

    var menuType = menu.menuType || "";
    var allInclusive = ("allinclusive" == menuType);
    var noCourseTypeLinks = !menuNav.is("div");
    var tinyMenu = allInclusive || noCourseTypeLinks;

    courseTypeWrapper.empty();

    if (tinyMenu) {
      menuNav.hide();
      menuContainer.addClass("tiny_menu").removeClass("full_menu");
    } else {
      menuNav.show();
      menuContainer.addClass("full_menu").removeClass("tiny_menu");
    }

    var thisObject = this;
    var menuWrapper = $("#menu_courses");

    menuWrapper.empty();

    var showCourses = function (coursesTitle, courses) {
      menuWrapper.empty();

      var menuTitle = $("<h2></h2>");
      menuWrapper.append(menuTitle);

      menuTitle.html(coursesTitle);

      var courseWrapper = thisObject.newCourseWrapper(allInclusive);

      $.each(courses, function (index, value) {
        // console.log("value->%o", value);
        courseWrapper.courses.push(value);

        if (value.courseSplitter) {
          courseWrapper.draw(menuWrapper);
        }
      });

      courseWrapper.draw(menuWrapper);
    };

    var addCourseTypeLink = function (courseType) {
      var wrapper = $("<li></li>");
      var link = $("<a></a>");
      var coursesTitle = courseType.label.i18n || "";

      var courses = thisObject.filterCourses(menu, courseType.key);

      link.attr("href", "#");
      link.html(coursesTitle);
      link.click(function () {
        // console.log("courseType->%o clicked !", courseType);
        showCourses(coursesTitle, courses);
        return false;
      });

      if (courses.length > 0) {
        courseTypeWrapper.append(wrapper.append(link));
      } else {
        link.hide();
      }
    };

    $.each(this.courseTypes.items, function (index, value) {
      addCourseTypeLink(value);
    });

    // no course type links
    if (tinyMenu) {
      showCourses(menu.description || "", menu.courses);

      if (allInclusive) {
        var price = menu.price || "";
        var menuPrice = $("#menu_courses .menu_el:last .price");
        menuPrice.html("" != price ? "&euro;&nbsp;" + price : "");
      }
    } else {
      courseTypeWrapper.find("li:first a").click();
    }
  },
  label:function (values, key) {
    var matchedLabel = {"orig":"", "i18n":""};
    $.each(values, function (index, value) {
      if (value.key == key) {
        matchedLabel = value.label;
      }
    });

    return matchedLabel;
  },
  filterCourses:function (menu, courseType) {
    var courses = [];

    $.each(menu.courses, function (courseIndex, course) {
      if (courseType != course.courseType) {
        return;
      }
      courses.push(course);
    });

    // console.log("courses->%o", courses);
    return courses;
  }
};

var goldGallery = {
  galleries:[],
  bind:function (galleries, galleryTypes) {
    this.galleries = galleries;

    this.initGalleryLinks();
  },
  initGalleryLinks:function () {
    var galleryLinks = $("#gallery_menu ul");
    var thisObject = this;

    $.each(this.galleries.items, function (index, value) {
      var wrapper = $("<li></li>");
      var link = $("<a></a>");

      link.attr("href", "#");
      link.html(value.title);
      link.click(function () {
        // console.log("galleryLink->%o clicked !", value);
        thisObject.loadGallery(value);
        return false;
      });

      galleryLinks.append(wrapper.append(link));
    });

    galleryLinks.find("li:first a").click();
  },
  loadGallery:function (gallery) {
    var imageWrapper = $("#gallery_img ul");

    imageWrapper.empty();

    $.each(gallery.galleryPictures, function (index, value) {
      var item = $("<li></li>");
      var image = $("<img></img>");

      image.attr("src", value.url || "#");

      imageWrapper.append(item.append(image));
    });

    var galleryNav = $("#gallery_nav")
    var galleryCounter = galleryNav.find("#count");

    galleryCounter.html("&nbsp;[ " + String(gallery.galleryPictures.length) + " ]");

    var hideGalleryNav = gallery.galleryPictures.length <= 0;
    if (hideGalleryNav) {
      galleryNav.hide();
    } else {
      galleryNav.show();
    }

    slideshow.init(gallery);
  }
};

var findUsMap = {
  container:function () {
    return $("#map iframe")
  },
  baseUrl:"http://maps.google.it/maps",
  markers:{
    "gold":{
      urlParams:{
        "f":"q",
        "source":"s_q",
        "hl":appSettings.locale || "it",
        "geocode":"",
        "q":"Dolce & Gabbana Gold  Piazza Risorgimento",
        "sll":"41.442726,12.392578",
        "sspn":"26.71628,67.631836",
        "ie":"UTF8",
        "hq":"Dolce & Gabbana Gold  Piazza Risorgimento",
        "hnear":"",
        "cid":"18216590049271703718",
        "ll":"45.468538,9.210703",
        "spn":"0.037318,0.049696",
        "z":"15",
        "iwloc":"A",
        "output":"embed"
      }
    },
    "martini":{
      urlParams:{
        "f":"q",
        "source":"s_q",
        "hl":appSettings.locale || "it",
        "geocode":"",
        "q":"Bar Martini",
        "sll":"41.442726,12.392578",
        "sspn":"26.781686,67.631836",
        "ie":"UTF8",
        "hq":"Bar Martini",
        "hnear":"",
        "ll":"45.467746,9.198389",
        "spn":"0.01866,0.024848",
        "z":"15",
        "iwloc":"A",
        "output":"embed"
      }
    }
  },
  draw:function (markerId) {
    var marker = this.markers[markerId];
    if (!marker) {
      return;
    }

    var mapUrl = this.baseUrl + "?" + $.param(marker.urlParams);
    this.container().attr("src", mapUrl);
  }
};

var captchaImage = {
  captchaUrl:"",
  image:function () {
    return $("#captcha_image");
  },
  init:function (captchaUrl) {
    this.captchaUrl = captchaUrl;

    var thisObject = this;
    var captcha = this.image();

    captcha.unbind();
    captcha.click(function () {
      thisObject.redraw(true);
    });
  },
  renewUrl:function (renew) {
    return this.captchaUrl + '?v=' + Math.random() + "&renew=" + String(renew);
  },
  redraw:function (renew) {
    var captcha = this.image();
    if (!captcha.is("img")) {
      return;
    }

    captcha.attr("src", this.renewUrl(renew));
  }
};

var reservationProxy = {
  dialogs:{
    init:function () {
      var thisObject = this;

      $('.opn_dtl').click(function () {
        if (!thisObject.validateSubmit()) {
          $('.ovl_confirm').hide();
          $('#confirm').hide();
          $('.ovl_dtl').show();
          $('#dtl').show();

          captchaImage.redraw(false);
        }

        return false;
      });
      $('.close_dtl a').click(function () {
        $('.ovl_dtl').hide();
        $('#dtl').hide();
        return false;
      });

      $('.close_confirm a').click(function () {
        $('.ovl_confirm').hide();
        $('#confirm').hide();
        $("#confirm_wrap").empty();
        return false;
      });

      this.confirm.bookingDate.init();

      this.confirm.phone.init();

      $("#dtl,#confirm").center();
    },
    validateSubmit:function () {
      var error = false;
      $('.field').removeClass("borderError");
      $(".resError").hide();

      if (null == this.confirm.bookingDate.get()) {
        error = true;
        showReservationError("#bookingDate");
      }
      if ($("#bookingTime").val() == "") {
        error = true;
        showReservationError("#bookingTime");
      }
      if ($("#partySize").val() == "") {
        error = true;
        showReservationError("#partySize");
      }
      return error;
    },
    confirm:{
      phone:{
        init:function () {
          this.reset();
        },
        formatPhone:function () {
          return "(" + $("#prefix").val() + ") " + $("#phone").val();
        },
        reset:function () {
          $("#prefix").val("00");
          $("#phone").val("");
        }
      },
      bookingDate:{
        emptyDate:"",
        init:function () {
          var thisObject = this;

          var regionalSettings = $.datepicker.regional[appSettings.language] || $.datepicker.regional[appSettings.locale];
          if (regionalSettings) {
            //fix colonne dei giorni sono primo carattere
            $.each(regionalSettings.dayNamesMin, function (index, value) {
              regionalSettings.dayNamesMin[index] = value.charAt(0);
            });

            $.datepicker.setDefaults(regionalSettings);
            this.emptyDate = regionalSettings.dateFormat;
          }

          var dateEquals = function (date1, date2) {
            if ((date1 instanceof Date) && (date2 instanceof Date)) {
              return(date1 > date2) ? false : (date1 < date2) ? false : true;
            } else {
              return false;
            }
          }


          var dateRange = function (since, days) {
            var dates = [];

            if (!(since instanceof Date)) {
              return [];
            }

            for (var i = 0; i < days; ++i) {
              var date = new Date(since);
              date.setDate(date.getDate() + i);
              dates.push(date);
            }

            return dates;
          }

          var skipSundayDates = function (date) {
            var December = 11;
            var January = 0;

            var day = date.getDay(), Sunday = 0, Monday = 1, Tuesday = 2, Wednesday = 3, Thursday = 4, Friday = 5, Saturday = 6;

            var openingDates = [
              new Date(2011, December, 4),
              new Date(2011, December, 11),
              new Date(2011, December, 18) ];

            var closingDates = [];

            $.each(dateRange(new Date(2011, December, 24), 12), function (index, value) {
              closingDates.push(value);
            });

            var openingDate = false;
            var closingDate = false;

            $.each(openingDates, function (index, value) {
              if (dateEquals(value, date)) {
                openingDate = true;
                return false;
              }
            });

            $.each(closingDates, function (index, value) {
              if (dateEquals(value, date)) {
                closingDate = true;
                return false;
              }
            });

            if (openingDate) {
              return [ true ];
            } else if (closingDate) {
              return [ false ];
            }

            return [ (Sunday != day) ];
          };

          var today = new Date();

          $("#bookingDate").keydown(function (e) {
            var code = e.keyCode ? e.keyCode : w.which;
            switch (code) {
              case $.ui.keyCode.DELETE:
              case $.ui.keyCode.BACKSPACE:
                e.preventDefault();
                thisObject.reset();
                break;
            }
          });

          $("#bookingDate").datepicker({
            beforeShowDay:skipSundayDates,
            numberOfMonths:1,
            minDate:today,
            maxDate:'+12M',
            firstDay:1
          });

          this.reset();
        },
        get:function () {
          var value = $("#bookingDate").val();
          return value == this.emptyDate ? null : $("#bookingDate").datepicker("getDate");
        },
        set:function (date) {
          $("#bookingDate").datepicker("setDate", date);
        },
        formatDate:function () {
          return $.datepicker.formatDate("dd/mm/yy", this.get());
        },
        reset:function () {
          this.set(null);
          $("#bookingDate").val(this.emptyDate);
        }
      },
      show:function (message) {
        $('.ovl_dtl').hide();
        $('#dtl').hide();
        $('.ovl_confirm').show();
        $('#confirm').show();
        $("#confirm_wrap").html(message);
      },
      reset:function () {
        this.bookingDate.reset();
        this.phone.reset();

        $("#bookingTime").val("");
        $("#partySize").val("");
        $("#name").val("");
        $("#lastname").val("");
        $("#email").val("");
        $("#prefix").val("00");
        $("#captcha_code").val("");
        $("#privacy").attr("checked", false);
      },
      validate:function () {
        var error = false;
        $(".formError").hide();
        if ($("#name").val().trim() == "") {
          error = true;
          showConfirmError("#name");
        }
        if ($("#lastname").val().trim() == "") {
          error = true;
          showConfirmError("#lastname");
        }
        if ($("#email").val().trim() == "" || !isValidMail($("#email").val())) {
          error = true;
          showConfirmError("#email");
        }
        if ($("#prefix").val().trim().replace(/0+/g, "") == "") {
          error = true;
          showConfirmError("#phone");
        }
        if ($("#phone").val().trim() == "") {
          error = true;
          showConfirmError("#phone");
        }
        if (!$("#privacy").is(':checked')) {
          error = true;
          showConfirmError("#privacy");
        }
        return error;
      },
      back:{
        visible:function (show) {
          var backConfirm = $("#confirm .back_confirm");
          if (show) {
            backConfirm.show();
          } else {
            backConfirm.hide();
          }

        }
      }
    },
    reset:function () {
      this.confirm.reset();
    }
  },
  reservationUrl:"",
  init:function (reservationUrl) {
    var thisObject = this;

    this.reservationUrl = reservationUrl;
    this.dialogs.init();

    $("#confirm_details").click(function () {
      if (!thisObject.dialogs.confirm.validate()) {
        thisObject.reserveSeat();
      }
      return false;
    });

    var privacyLink = $("#privacy_link");
    if (privacyLink.is("a")) {
      var privacyHref = privacyLink.attr("href") || "";
      if ("" != privacyHref) {
        $("#privacy_reservation").attr("href", privacyHref);
      }
    }

  },
  reserveSeat:function () {
    var thisObject = this;

    $.ajax({
      beforeSend:function () {
        $("#confirm_ajax").show();
      },
      type:"POST",
      url:thisObject.reservationUrl || "",
      data:{
        bookingDate:thisObject.dialogs.confirm.bookingDate.formatDate(),
        bookingTime:$("#bookingTime").val(),
        partySize:$("#partySize").val(),
        name:$("#name").val(),
        lastname:$("#lastname").val(),
        phone:thisObject.dialogs.confirm.phone.formatPhone(),
        email:$("#email").val(),
        captcha:$("#captcha_code").val(),
        privacy:$("#privacy").val(),
        locale:appSettings.locale || ""
      },
      dataType:"json",
      success:function (data) {
        captchaImage.redraw(false);
        var success = data.status == "success";

        // console.log("reserveSeat: %o", data);
        if (success) {
          thisObject.dialogs.reset();
        }

        var wrongCaptha = "reservation.wrong.captcha" == (data.cause.code || "");

        $("#captcha_code").val("");

        if (wrongCaptha) {
          showConfirmError("#captcha_code");
        } else {
          thisObject.dialogs.confirm.back.visible(!success);
          thisObject.dialogs.confirm.show(data.cause.message);
        }
      },
      complete:function () {
        $("#confirm_ajax").hide();
      },
      error:function () {
        captchaImage.redraw(false);
      }
    });
  }
};

var section = {
  siteSection:{},
  bind:function () {
    this.siteSection = siteSection;
    this.fill();
  },
  fill:function () {
    var pictureUrl = this.siteSection.picture.url || "";
    $("#section_title").html(this.siteSection.title || "");
    $("#section_subtitle").html(this.siteSection.subtitle || "");
    $("#section_description").html(this.siteSection.description || "");
    $("#section_picture").attr("src", pictureUrl);

    if ("" == pictureUrl) {
      $("#section_picture").parent("p.img").hide();
      $("#section_description").parent("div.art_img_cont").removeClass("art_img_cont").addClass("art_txt");
    }
  }
};

function showReservationError(field) {
  $(field).addClass("borderError");
  $(".resError").show();
}

function showConfirmError(field) {
  //console.log($(field).parent().find(".formError"));
  $(field).parent().find(".formError").show();
  //$(".formError").show();
}

function isValidMail(email) {
  var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  return filter.test(email);
}

var popupAdultChecker = {
  form:{},
  countries:{
    get:function (code) {
      for (var index in this.data) {
        var object = this.data[index];
        if (code == object.value) {
          return object;
        }
      }

      return null;
    },
    data:[
      { years:18, value:"NL-BE", text:"Belgium - Flemish" },
      { years:18, value:"FR-BE", text:"Belgium - French" },
      { years:18, value:"DE-DE", text:"Germany" },
      { years:18, value:"IT-IT", text:"Italy" },
      { years:18, value:"RU-RU", text:"Russia" },
      { years:18, value:"ES-ES", text:"Spain" },
      { years:18, value:"EN-GB", text:"United Kingdom" },
      { years:18, value:"EN-AL", text:"Albania" },
      { years:18, value:"ES-AR", text:"Argentina" },
      { years:18, value:"EN-AM", text:"Armenia" },
      { years:18, value:"EN-AU", text:"Australia" },
      { years:18, value:"EN-AT", text:"Austria" },
      { years:18, value:"EN-AZ", text:"Azerbaijan" },
      { years:18, value:"EN-BS", text:"Bahamas" },
      { years:18, value:"EN-BH", text:"Bahrain" },
      { years:18, value:"EN-BY", text:"Belarus" },
      { years:18, value:"EN-BL", text:"Belize" },
      { years:18, value:"EN-BM", text:"Bermuda" },
      { years:18, value:"ES-BO", text:"Bolivia" },
      { years:18, value:"EN-BA", text:"Bosnia" },
      { years:18, value:"PT-BR", text:"Brazil" },
      { years:18, value:"EN-BG", text:"Bulgaria" },
      { years:18, value:"EN-CM", text:"Cameroon" },
      { years:18, value:"EN-CA", text:"Canada" },
      { years:18, value:"EN-AB", text:"Canada - Alberta" },
      { years:18, value:"EN-BC", text:"Canada - British Columbia" },
      { years:18, value:"EN-MB", text:"Canada - Manitoba" },
      { years:18, value:"EN-NB", text:"Canada - New Brunswick" },
      { years:18, value:"EN-ND", text:"Canada - Newfoundland" },
      { years:18, value:"EN-NW", text:"Canada - Northwest Territories" },
      { years:18, value:"EN-NS", text:"Canada - Nova Scotia" },
      { years:18, value:"EN-NT", text:"Canada - Nunavut" },
      { years:18, value:"EN-ON", text:"Canada - Ontario" },
      { years:18, value:"EN-PE", text:"Canada - Prince Edward Island" },
      { years:18, value:"EN-QC", text:"Canada - Quebec" },
      { years:18, value:"FR-QC", text:"Canada - Quebec" },
      { years:18, value:"EN-SK", text:"Canada - Saskatchewan" },
      { years:18, value:"EN-YN", text:"Canada - Yukon" },
      { years:18, value:"ES-CL", text:"Chile" },
      { years:18, value:"EN-CN", text:"China" },
      { years:18, value:"ES-CO", text:"Colombia" },
      { years:18, value:"ES-CR", text:"Costa Rica" },
      { years:18, value:"EN-HR", text:"Croatia" },
      { years:18, value:"EN-CZ", text:"Czech Republic" },
      { years:18, value:"EN-DK", text:"Denmark" },
      { years:18, value:"ES-DR", text:"Dominican Republic" },
      { years:18, value:"ES-EC", text:"Ecuador" },
      { years:18, value:"EN-EG", text:"Egypt" },
      { years:18, value:"ES-ER", text:"El Salvador" },
      { years:18, value:"EN-EE", text:"Estonia" },
      { years:18, value:"EN-FJ", text:"Fiji" },
      { years:18, value:"EN-FI", text:"Finland" },
      { years:18, value:"FR-FR", text:"France" },
      { years:18, value:"EN-GE", text:"Georgia" },
      { years:18, value:"EN-GR", text:"Greece" },
      { years:18, value:"ES-GT", text:"Guatemala" },
      { years:18, value:"EN-HN", text:"Honduras" },
      { years:18, value:"EN-HK", text:"Hong Kong" },
      { years:18, value:"EN-HU", text:"Hungary" },
      { years:18, value:"EN-IS", text:"Iceland" },
      { years:18, value:"EN-IN", text:"India" },
      { years:18, value:"EN-ID", text:"Indonesia" },
      { years:18, value:"EN-IE", text:"Ireland" },
      { years:18, value:"EN-IL", text:"Israel" },
      { years:18, value:"EN-JM", text:"Jamaica" },
      { years:18, value:"EN-JP", text:"Japan" },
      { years:18, value:"EN-KZ", text:"Kazakhstan" },
      { years:18, value:"EN-KE", text:"Kenya" },
      { years:18, value:"LV-LV", text:"Latvia" },
      { years:18, value:"EN-LB", text:"Lebanon" },
      { years:18, value:"EN-LS", text:"Lesotho" },
      { years:18, value:"EN-LI", text:"Liechtenstein" },
      { years:18, value:"EN-LT", text:"Lithuania" },
      { years:18, value:"EN-LU", text:"Luxembourg" },
      { years:18, value:"EN-MK", text:"Macedonia" },
      { years:18, value:"EN-MY", text:"Malaysia" },
      { years:18, value:"EN-MT", text:"Malta" },
      { years:18, value:"EN-MU", text:"Mauritius" },
      { years:18, value:"EN-MX", text:"Mexico" },
      { years:18, value:"EN-MD", text:"Moldova" },
      { years:18, value:"EN-MO", text:"Mongolia" },
      { years:18, value:"EN-ME", text:"Montenegro" },
      { years:18, value:"EN-NP", text:"Nepal" },
      { years:18, value:"EN-NL", text:"Netherlands" },
      { years:18, value:"EN-NZ", text:"New Zealand" },
      { years:18, value:"ES-NC", text:"Nicaragua" },
      { years:18, value:"EN-NO", text:"Norway" },
      { years:18, value:"EN-OT", text:"Other" },
      { years:18, value:"EN-PW", text:"Palau" },
      { years:18, value:"EN-PA", text:"Panama" },
      { years:18, value:"EN-PG", text:"Papua New Guinea" },
      { years:18, value:"EN-PY", text:"Paraguay" },
      { years:18, value:"ES-PE", text:"Peru" },
      { years:18, value:"EN-PH", text:"Philippines" },
      { years:18, value:"EN-PL", text:"Poland" },
      { years:18, value:"EN-PT", text:"Portugal" },
      { years:18, value:"EN-PR", text:"Puerto Rico" },
      { years:18, value:"EN-RO", text:"Romania" },
      { years:18, value:"EN-WS", text:"Samoa" },
      { years:18, value:"EN-RS", text:"Serbia" },
      { years:18, value:"EN-SG", text:"Singapore" },
      { years:18, value:"EN-SK", text:"Slovakia" },
      { years:18, value:"EN-SI", text:"Slovenia" },
      { years:18, value:"EN-SB", text:"Solomon Islands" },
      { years:18, value:"EN-ZA", text:"South Africa" },
      { years:18, value:"EN-KR", text:"South Korea" },
      { years:18, value:"EN-LK", text:"Sri Lanka" },
      { years:18, value:"EN-SZ", text:"Swaziland" },
      { years:18, value:"EN-SE", text:"Sweden" },
      { years:18, value:"EN-CH", text:"Switzerland" },
      { years:18, value:"EN-TW", text:"Taiwan" },
      { years:18, value:"EN-TZ", text:"Tanzania" },
      { years:18, value:"EN-TH", text:"Thailand" },
      { years:18, value:"EN-TO", text:"Tonga" },
      { years:18, value:"EN-TT", text:"Trinidad &amp; Tobago" },
      { years:18, value:"EN-TR", text:"Turkey" },
      { years:18, value:"EN-UA", text:"Ukraine" },
      { years:21, value:"EN-US", text:"United States" },
      { years:18, value:"EN-UY", text:"Uruguay" },
      { years:18, value:"EN-UZ", text:"Uzbekistan" },
      { years:18, value:"EN-VE", text:"Venezuela" },
      { years:18, value:"EN-ZW", text:"Zimbabwe" }
    ]
  },
  visible:function (show) {
    if (show) {
      $("#data_wrap,.ovl_data").show();
    } else {
      $("#data_wrap,.ovl_data").hide();
    }
  },
  cookie:{
    name:"it.killnine.dg.martini.isAdult",
    options:{ expires:7, path:"/" },
    reset:function () {
      $.cookie(this.name, "", this.options);
    },
    set:function (value) {
      $.cookie(this.name, value, this.options);
    },
    get:function () {
      return $.cookie(this.name) == "true";
    }
  },
  buildOptions:function (object, values) {
    var element = object;

    element.find("option[value != '']").remove();

    $.each(values, function (index, value) {
      var option = $("<option></option>");
      option.attr("value", value.value);
      option.html(value.text);

      element.append(option);
    });
  },
  buildYears:function () {
    var nowYear = (new Date()).getFullYear();
    var values = [];

    for (var i = 0; i < 118; ++i) {
      var year = nowYear - i;
      values.push({value:year, text:year});
    }

    this.buildOptions(this.year(), values);
  },
  buildMonths:function () {
    var values = [];

    for (var i = 0; i < 12; ++i) {
      var month = i + 1;
      values.push({value:month, text:month});
    }

    this.buildOptions(this.month(), values);
  },
  buildDays:function () {
    var values = [];

    for (var i = 0; i < 31; ++i) {
      var day = i + 1;
      values.push({value:day, text:day});
    }

    this.buildOptions(this.day(), values);
  },
  buildCountries:function () {
    this.buildOptions(this.country.object(), this.countries.data);
  },
  year:function () {
    return this.form.find("select#year");
  },
  month:function () {
    return this.form.find("select#month");
  },
  day:function () {
    return this.form.find("select#day");
  },
  country:{
    parent:{},
    object:function () {
      return this.parent.form.find("select#country");
    },
    val:function () {
      return this.object().val();
    },
    info:function () {
      return this.parent.countries.get(this.val());
    }
  },
  birthDate:{
    parent:{},
    val:function () {
      return this.empty() ? null : new Date(this.parent.year().val(), this.parent.month().val() - 1, this.parent.day().val());
    },
    empty:function () {
      var parts = [this.parent.year().val(), this.parent.month().val(), this.parent.day().val()];

      for (var index in parts) {
        var part = parts[index];
        if (part == "") {
          return true;
        }
      }

      return false;
    }
  },
  isAdult:function () {
    if (this.birthDate.empty()) {
      return false;
    }

    var adultInfo = this.country.info();
    if (!adultInfo) {
      return false;
    }

    var years = adultInfo.years;

    var today = new Date();
    var birthDate = this.birthDate.val();
    var adultDate = new Date(birthDate.getFullYear() + years, birthDate.getMonth(), birthDate.getDate());

    // console.log("birthDate: %s, adultDate: %s", birthDate, adultDate);
    return today.getTime() >= adultDate.getTime();
  },
  alert:{
    hide:function () {
      $('.alert').hide();
      $('#alert_data').hide();
      $('#alert_country').hide();
      $('#alert_notlegalage').hide();
    },
    show:function (messageId) {
      this.hide();

      var alertId = "";
      switch (messageId) {
        case "empty_date":
          alertId = "#alert_data";
          break;

        case "empty_country":
          alertId = "#alert_country";
          break;

        case "not_adult":
          alertId = "#alert_notlegalage";
          break;
      }

      if ("" != alertId) {
        $(".alert").show();
        $(alertId).show();
      }
    }
  },
  validate:function () {
    var statusId = "success";

    if (this.birthDate.empty()) {
      statusId = "empty_date";
    } else if (!this.country.info()) {
      statusId = "empty_country";
    } else {
      var adult = this.isAdult();
      if (!adult) {
        statusId = "not_adult";
      }
    }

    return statusId;
  },
  exit:function (opts) {
    var waitMillis = 0;

    if ((opts.showMessage || false)) {
      this.alert.show("not_adult");
      waitMillis = 7000;
    }

    $("#exit_data").delay(waitMillis, function () {
      location.href = "http://www.dolcegabbana.com";
    });
  },
  init:function () {
    var thisObject = this;

    this.birthDate.parent = this;
    this.country.parent = this;

    var wrapper = $("#data_wrap");
    if (!wrapper.is("div")) {
      return;
    }

    wrapper.center({vertical:true, horizontal:true});

    this.form = $('#enterdata_form');

    this.buildYears();
    this.buildMonths();
    this.buildDays();
    this.buildCountries();

    var adult = this.cookie.get();
    this.visible(!adult);

    $("#exit_data").click(function () {
      thisObject.exit({showMessage:false});
      return false;
    });

    $("#submit_data").click(function () {
      var status = thisObject.validate();

      if ("success" == status) {
        thisObject.cookie.set("true");
        thisObject.visible(false);
      } else {
        thisObject.cookie.reset();

        if ("not_adult" == status) {
          thisObject.exit({showMessage:true});
        } else {
          thisObject.alert.show(status);
        }
      }
    });
  }
};

