/*
 * jQuery BBQ: Back Button & Query Library - v1.1.1 - 1/22/2010
 * http://benalman.com/projects/jquery-bbq-plugin/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($,n){var g,o=n.location,k=Array.prototype.slice,q=decodeURIComponent,a=$.param,c,j,u,b=$.bbq=$.bbq||{},p,t,h,e=$.event.special,d="hashchange",z="querystring",C="fragment",x="elemUrlAttr",i="href",s="src",w=/^.*\?|#.*$/g,v=/^.*\#/,B={};function D(E){return typeof E==="string"}function A(F){var E=k.call(arguments,1);return function(){return F.apply(this,E.concat(k.call(arguments)))}}function l(E){return E.replace(/^[^#]*#?(.*)$/,"$1")}function m(E){return E.replace(/(?:^[^?#]*\?([^#]*).*$)?.*/,"$1")}function f(G,L,E,H,F){var N,K,J,M,I;if(H!==g){J=E.match(G?/^([^#]*)\#?(.*)$/:/^([^#?]*)\??([^#]*)(#?.*)/);I=J[3]||"";if(F===2&&D(H)){K=H.replace(G?v:w,"")}else{M=j(J[2]);H=D(H)?j[G?C:z](H):H;K=F===2?H:F===1?$.extend({},H,M):$.extend({},M,H);K=a(K)}N=J[1]+(G?"#":K||!J[1]?"?":"")+K+I}else{N=L(E!==g?E:o[i])}return N}a[z]=A(f,0,m);a[C]=c=A(f,1,l);$.deparam=j=function(H,E){var G={},F={"true":!0,"false":!1,"null":null};$.each(H.replace(/\+/g," ").split("&"),function(K,P){var J=P.split("="),O=q(J[0]),I,N=G,L=0,Q=O.split("]["),M=Q.length-1;if(/\[/.test(Q[0])&&/\]$/.test(Q[M])){Q[M]=Q[M].replace(/\]$/,"");Q=Q.shift().split("[").concat(Q);M=Q.length-1}else{M=0}if(J.length===2){I=q(J[1]);if(E){I=I&&!isNaN(I)?+I:I==="undefined"?g:F[I]!==g?F[I]:I}if(M){for(;L<=M;L++){O=Q[L]===""?N.length:Q[L];N=N[O]=L<M?N[O]||(Q[L+1]&&isNaN(Q[L+1])?{}:[]):I}}else{if($.isArray(G[O])){G[O].push(I)}else{if(G[O]!==g){G[O]=[G[O],I]}else{G[O]=I}}}}else{if(O){G[O]=E?g:""}}});return G};function y(G,E,F){if(E===g||typeof E==="boolean"){F=E;E=a[G?C:z]()}else{E=D(E)?E.replace(G?v:w,""):E}return j(E,F)}j[z]=A(y,0);j[C]=u=A(y,1);$[x]||($[x]=function(E){return $.extend(B,E)})({a:i,base:i,iframe:s,img:s,input:s,form:"action",link:i,script:s});h=$[x];function r(H,F,G,E){if(!D(G)&&typeof G!=="object"){E=G;G=F;F=g}return this.each(function(){var K=$(this),I=F||h()[(this.nodeName||"").toLowerCase()]||"",J=I&&K.attr(I)||"";K.attr(I,a[H](J,G,E))})}$.fn[z]=A(r,z);$.fn[C]=A(r,C);b.pushState=p=function(H,E){if(D(H)&&/^#/.test(H)&&E===g){E=2}var G=H!==g,F=c(o[i],G?H:{},G?E:2);o[i]=F+(/#/.test(F)?"":"#")};b.getState=t=function(E,F){return E===g||typeof E==="boolean"?u(E):u(F)[E]};b.removeState=function(E){var F={};if(E!==g){F=t();$.each($.isArray(E)?E:arguments,function(H,G){delete F[G]})}p(F,2)};e[d]=$.extend(e[d],{add:function(E,G,F){return function(I){var H=I[C]=c();I.getState=function(J,K){return J===g||typeof J==="boolean"?j(H,J):j(H,K)[J]};E.apply(this,arguments)}}})})(jQuery,this);
/*
 * jQuery hashchange event - v1.1 - 1/21/2010
 * http://benalman.com/projects/jquery-hashchange-plugin/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($,i,b){var h=i.location,j,k=$.event.special,c="hashchange",e=$.browser,f=document.documentMode,g=e.msie&&(f===b||f<8),d="on"+c in i&&!g;function a(l){l=l||h.href;return l.replace(/^[^#]*#?(.*)$/,"$1")}$[c+"Delay"]=100;k[c]=$.extend(k[c],{setup:function(){if(d){return false}j.start()},teardown:function(){if(d){return false}j.stop()}});j=(function(){var l={},q,m,n,p;function o(){n=p=function(r){return r};if(g){m=$('<iframe src="javascript:0"/>').hide().appendTo("body")[0].contentWindow;p=function(){return a(m.document.location.href)};n=function(t,r){if(t!==r){var s=m.document;s.open().close();s.location.hash="#"+t}};n(a())}}l.start=function(){if(q){return}var s=a();n||o();(function r(){var u=a(),t=p(s);if(u!==s){n(s=u,t);$(i).trigger(c)}else{if(t!==s){h.href=h.href.replace(/#.*/,"")+"#"+t}}q=setTimeout(r,$[c+"Delay"])})()};l.stop=function(){if(!m){q&&clearTimeout(q);q=0}};return l})()})(jQuery,this);


$(document).ready(function () {

  // VARIABLES
  var urlroot = ips.system.urlroot;

  // CALENDAR QROOTS
  var calendarExhibitions = 1;
  var calendarEvents = 2;
  if (ips.system.lang == 'en') {
    calendarExhibitions = 4;
  }

  // SLIDESHOW QROOTS
  var slideCalendarExhibitions = "1+OR+2";
  if (ips.system.lang == 'en') {
    slideCalendarExhibitions = 4;
  }

  // CALENDAR DATES
  var fulldate = getDate();
  var futureDate = getFutureDate();

  // CACHE SELECTOR FOR PRELOADER
  var $eventsList = $(".eventlist");
  
  var userDate = false;

  // DATEPICKER DEFAULT SETTINGS
  $.datepicker.setDefaults({
    dateFormat: 'yymmdd',
    firstDay: 1
  });

  // ----------------- FUNCTIONS ---------------------
  // RETURNS TODAYS DATE

  function getDate() {
    var time = new Date();
    var month = time.getMonth() + 1;
    var realmonth = month < 10 ? "0" + month : month;
    var date = time.getDate();
    var realdate = "" + date;
    if (realdate.length == 1) {
      realdate = "0" + realdate;
    }
    var year = time.getYear();
    if (year < 2000) {
      year = year + 1900;
    }
    return "" + year + realmonth + realdate;
  }
  
  function getTomorrowsDate() {
    var time = new Date();
    var month = time.getMonth() + 1;
    var realmonth = month < 10 ? "0" + month : month;
    var date = time.getDate() + 1; 
    var realdate = "" + date;
    if (realdate.length == 1) {
      realdate = "0" + realdate;
    }
    var year = time.getYear();
    if (year < 2000) {
      year = year + 1900;
    }
    return "" + year + realmonth + realdate;
  }

  // RETURNS TODAYS DATE + 6 DAYS

  function getFutureDate() {
    var time = new Date();
    time.setDate(time.getDate() + 10);
    var month = time.getMonth() + 1;
    var realmonth = month < 10 ? "0" + month : month;
    var date = time.getDate();
    var realdate = "" + date;
    if (realdate.length == 1) {
      realdate = "0" + realdate;
    }
    var year = time.getYear();
    if (year < 2000) {
      year = year + 1900;
    }
    var newfutureDate = "" + year + realmonth + realdate;

    return newfutureDate;
  }

  // RETURNS TODAYS DATE + 30 DAYS

  function getNextThirtyDays() {
    var time = new Date();
    time.setDate(time.getDate() + 30);
    var month = time.getMonth() + 1;
    var realmonth = month < 10 ? "0" + month : month;
    var date = time.getDate();
    var realdate = "" + date;
    if (realdate.length == 1) {
      realdate = "0" + realdate;
    }
    var year = time.getYear();
    if (year < 2000) {
      year = year + 1900;
    }
    var newfutureDate = "" + year + realmonth + realdate;

    return newfutureDate;
  }

  // RETURNS TODAYS DATE - 1 DAY

  function getPreviousDate() {
    var time = new Date();
    var month = time.getMonth() + 1;
    var realmonth = month < 10 ? "0" + month : month;
    var date = time.getDate() - 1;
    var realdate = "" + date;
    if (realdate.length == 1) {
      realdate = "0" + realdate;
    }
    var year = time.getYear();
    if (year < 2000) {
      year = year + 1900;
    }
    var newfulldate = "" + year + realmonth + realdate;

    return newfulldate;
  }

  // RETURNS TODAYS DATE + 1 DAY

  function getNextDate() {
    var time = new Date();
    var month = time.getMonth() + 1;
    var realmonth = month < 10 ? "0" + month : month;
    var date = time.getDate() + 1;
    var realdate = "" + date;
    if (realdate.length == 1) {
      realdate = "0" + realdate;
    }
    var year = time.getYear();
    if (year < 2000) {
      year = year + 1900;
    }
    var newfulldate = "" + year + realmonth + realdate;

    return newfulldate;
  }

  // RETURNS TODAYS DATE + 10 YEARS

  function getFutureYear() {
    var time = new Date();
    var month = time.getMonth() + 1;
    var realmonth = month < 10 ? "0" + month : month;
    var date = time.getDate();
    var realdate = "" + date;
    if (realdate.length == 1) {
      realdate = "0" + realdate;
    }
    var year = time.getYear();
    if (year < 2000) {
      year = year + 1900;
    }
    var futureYear = year + 10;
    var newfutureDate = "" + futureYear + realmonth + realdate;

    return newfutureDate;
  }

  function getMonthName(month) {
    var months = ['januar', 'februar', 'mars', 'april', 'mai', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'desember'];
    return months[month - 1];
  }

  // UPDATES CALENDAR HEADER WITH CORRECT DATES

  function showFriendlyDate(startDate, endDate) {
    var startYear = startDate.substr(0, 4);
    var startMonth = startDate.substr(4, 2);
    var startMonthName = getMonthName(startMonth);
    var startDay = startDate.substr(6, 2);

    var endYear = endDate.substr(0, 4);
    var endMonth = endDate.substr(4, 2);
    var endMonthName = getMonthName(endMonth);
    var endDay = endDate.substr(6, 2);

    $(".dateHeader").html(startDay + ". " + startMonthName + (startYear == endYear ? "" : " " + startYear) + "&ndash;" + endDay + ". " + endMonthName + " " + endYear);

  }

  function transformUIDateToIPSDate(uidate, addDays) {
    addDays = addDays || 0;
    uidate = uidate.replace("/", "");
    var year = uidate.substring(0, 4);
    var month = uidate.substring(4, 6);
    var day = uidate.substring(6, 8);

    myDate = new Date();
    myDate.setFullYear(year, month, day);
    myDate.setDate(myDate.getDate() + addDays);
    day = myDate.getDate();
    var realdateChosen = "" + day;
    if (realdateChosen.length == 1) {
      realdateChosen = "0" + realdateChosen;
    }

    month = myDate.getMonth();
    var realmonthChosen = month < 10 ? "0" + month : month;

    year = myDate.getYear();
    if (year < 2000) {
      year = year + 1900;
    }

    return ("" + year + realmonthChosen + realdateChosen);
    //$("#endDate").val(futureDateChosen);	
  }

  function transformIPSDateToUIDate(ipsdate) {
    ipsdate = "" + ipsdate;
    var year = ipsdate.substring(0, 4);
    var month = ipsdate.substring(4, 6);
    var day = ipsdate.substring(6, 8);

    myDate = new Date();
    myDate.setFullYear(year, month - 1, day);

    return myDate;
  }

  function normalizeIndex(index, pagesize) {
    pagesize = pagesize || (jQuery.bbq.getState("selectedPagesize") || 20);
    if (index < pagesize) {
      return 1;
    }
    if (normalizeIndex[index] != null) {
      return normalizeIndex[index];
    }
    for (var i = 0; i < 200; i++) {
      if (index <= (pagesize * (i + 1))) {
        index = (pagesize * i) + 1;
        break;
      }
    }
    return normalizeIndex[index] = index;
  }


  /*************************** 
   # FRONTPAGE SIDEMAL
   ***************************/

  // SLIDESHOW FRONTPAGE
  if ($("#slideshow").length) {
    $("#slideshow").load(urlroot + "?module=Search;action=Search.publicSearch;qtype=EventCalendar.Event&qroot=" + slideCalendarExhibitions + ";query=attribslideshow:true;lang=" + ips.system.lang + ";template=slideshow", function () {
      $("ul.tabs").tabs(".images > .slide", {
        effect: "fade",
        fadeOutSpeed: "slow",
        rotate: true
      }).slideshow({
        autoplay: true,
        interval: '8000'
      });
      $(this).find(".images .slide").click(function () {
        if(slideCalendarExhibitions == 4) {
          window.location = (urlroot + $(this).attr('rel') + "&template=exhibitionView_en");
        }
        else {
          window.location = (urlroot + $(this).attr('rel') + "&template=exhibitionView");
        }
      });
    });

    $("#pickStartdate").click(function () {
      $("#startDate").focus();
    });
    $("#startDate").datepicker({
      beforeShow: function () {
        $("#startDate").datepicker("option", "minDate", fulldate);
      },
      onSelect: function (selectedDate) {
        var instance = $(this).data("datepicker");
        var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
        window.location = (urlroot + "?template=calendar_" + ips.system.lang + ";#startDate=" + transformUIDateToIPSDate(selectedDate) + "&endDate=" + transformUIDateToIPSDate(selectedDate, 6) + "&view=calendar");
      }
    });
  }

  /*------------GALLERY SIDEMAL -----------------------------*/

  var folderId = $("#gallery").attr("rel");
  var objectId;
  var selectedPagesize = 20;
  var selectedIndex = 1;
  var $gallery = $("#gallery");

  $gallery.bind("gallery", function (e) {
    var state = $.bbq.getState();
    category = state.cat ? ("attribgalleryCategory:" + ips.data.params.cat) : "public:true";
    //ips.system.lang = state.lang || ips.system.lang;
    selectedPagesize = state.selectedPagesize || selectedPagesize;
    selectedIndex = state.selectedIndex || selectedIndex;

    $("#gallery").load(urlroot + "?module=Search&action=Search.publicSearch&qtype=Articles.Article&qroot=" + folderId + "&query=" + category + "&lang=" + ips.system.lang + "&pagesize=" + selectedPagesize + "&index=" + selectedIndex + "&template=galleryresults", function () {
      if ($(".galleryItem").length == 1 && selectedPagesize == 1) {
        $(".galleryItem").load($(".galleryItem").find("a").attr("href") + "?template=galleryresults");
        $("#showPage").hide();
      }

      $(this).find("#showPage li a").each(function () {
        if ($(this).attr("rel") == selectedPagesize) {
          $(this).addClass("current");
        }
      });
    });
  });

  if ($gallery.length) {
    $gallery.trigger("gallery");
    $gallery.delegate(".galleryItem", "click", function (e) {
      e.preventDefault();
      jQuery.bbq.pushState({
        "selectedPagesize": 1,
        "selectedIndex": ((selectedIndex * 1) + $(this).prevAll(".galleryItem").length)
      });
    });
    $gallery.delegate(".updateGallery", 'click', function (e) {
      e.preventDefault();
      jQuery.bbq.pushState({
        "selectedIndex": normalizeIndex($(this).attr("rel"))
      });
    });
    $gallery.delegate(".galleryItem", "mouseenter", function () {
      $(this).find(".switch").toggleClass('hover');
      $(this).find(".switch .galleryContent").toggleClass("display");
    });
    $gallery.delegate(".galleryItem", "mouseleave", function () {
      $(this).find(".switch").toggleClass('hover');
      $(this).find(".switch .galleryContent").toggleClass("display");
    });
    $gallery.delegate(".galleryItem", "click", function () {
      if ($(this).hasClass('single')) {
        $gallery.removeClass('single');
        $gallery.addClass('thumbs');
      }
      else {
        $gallery.removeClass('thumbs');
        $gallery.addClass('single');
      }
    });
    $gallery.delegate("#showPage li a", 'click', function (e) {
      e.preventDefault();
      jQuery.bbq.pushState({
        "selectedPagesize": $(this).attr("rel")
      });
      jQuery.bbq.pushState({
        "selectedIndex": normalizeIndex($(this).attr("rel"))
      });
    });
    $gallery.delegate("#showCat li a", 'click', function (e) {
	  console.log("OK");
      e.preventDefault();
      jQuery.bbq.pushState({
        "cat": $(this).attr("rel")
      });
    });
    $(".gallery").delegate("#showType li a", 'click', function (e) {
      e.preventDefault();
      jQuery.bbq.pushState({
        "selectedPagesize": $(this).attr("rel")
      });
      jQuery.bbq.pushState({
        "selectedIndex": normalizeIndex($(this).attr("rel"))
      });
      if ($gallery.hasClass('single')) {
        $gallery.removeClass('single');
        $gallery.addClass('thumbs');
      }
      else {
        $gallery.removeClass('thumbs');
        $gallery.addClass('single');
      }
    });

    //General listnener for hash #
    $(window).bind('hashchange', function (e) {
      $gallery.trigger("gallery");
    }).trigger("hashchange"); //init
  }

  /*------------CALENDAR SIDEMAL -----------------------------*/


  // PRELOADER
  if ($eventsList.length) {
    $eventsList.ajaxStart(function () {
      $(this).addClass("loading");
    }).ajaxStop(function () {
      $(this).removeClass("loading");
    });
  } // END if
  var isCalendar = $("body.calendar").length > 0 ? true : false;
  var isExhibitionList = $("body.exhibitionList").length > 0 ? true : false;
  if (isExhibitionList || isCalendar) {
    // VISNINGSTED
    $(".locationMenu a").live("click", function (e) {
      e.preventDefault();
      $.bbq.pushState({
        "cat": $.deparam($(this).attr("href")).cat || "all",
        "view": isCalendar ? "calendar" : "exhibition"
      });
      $(this).parent().siblings().removeClass("selected");
      $(this).parent().addClass("selected");
    });
    var $timeNav = $(".timeNav a");
    $timeNav.live("click", function (e) {
      e.preventDefault();
      $.bbq.pushState($.deparam($.param.fragment($(this).attr("href"))));
    });
    $(window).bind('hashchange', function (e) {
      var state = $.bbq.getState();
      var _location = state.cat && state.cat !== "undefined" && state.cat !== "all" ? "attribeventLocation:" + (state.cat || ips.data.params.cat || "") + "+AND+" : "";
      if (state.cat) {
        $("#showCat li").removeClass("selected").filter(function () {
          var _href = $(this).find("a").attr("href") + "";
          return ($.deparam(_href).cat == state.cat);
        }).addClass("selected");
      }
      //select show and show2 
      $(".timeNav li").removeClass("selected").each(function () {
        if (new RegExp("(show\=" + (state.show || "current") + ")|(show2\=" + (state.show2 || "current") + ")").test($(this).find("a").attr("href"))) {
          $(this).addClass("selected");
        }
      });

      if (isExhibitionList) {
        var _startDate1 = 0,
          _endDate1 = getDate(),
          _startDate2 = getDate(),
          _endDate2 = getFutureYear();
        if (state.show == "upcoming") {
          _startDate1 = getNextDate();
          _endDate1 = getFutureYear();
          _startDate2 = getNextDate();
          _endDate2 = getFutureYear();
        }
        else if (state.show == "previous") {
          _startDate2 = 0;
          _endDate2 = getDate();
        }
        var urlObj = {
          "module": "Search",
          "action": "Search.publicSearch",
          "qtype": "EventCalendar.Event",
          "qroot": calendarExhibitions,
          "lang": ips.system.lang,
          "pagesize": "50",
          "sort" : state.show == "previous" ? "descending" : "ascending",
          "template": "exhibitionResults",
          "query": _location + "((attribfromDate:[" + _startDate1 + "+TO+" + _endDate1 + "])+AND+(attribtoDate:[" + _startDate2 + "+TO+" + _endDate2 + "]))" // previous = second startdate = 0, upcoming = 0 = today
        }
        // LEFT SIDE
        $("#tempExhibitions").load(urlroot + "?" + $.param(urlObj).replace(/%2B/ig, '+') + "+NOT+attribexhibitionType:true");

        // RIGHT SIDE
        _startDate1 = 0;
        _endDate1 = getDate();
        _startDate2 = getDate();
        _endDate2 = getFutureYear();
        if (state.show2 == "previous") {
          _startDate2 = 0;
          _endDate2 = getDate();
        }
        urlObj.query = _location + "((attribfromDate:[" + _startDate1 + "+TO+" + _endDate1 + "])+AND+(attribtoDate:[" + _startDate2 + "+TO+" + _endDate2 + "]))";

        $("#reoccuringExhibitions").load(urlroot + "?" + $.param(urlObj).replace(/%2B/ig, '+') + "+AND+attribexhibitionType:true");
      }

    });
  }

  if (isCalendar) {
	
	$(".datepickerMenu li a").click(function(){
	  $(this).parent().siblings().find("a").removeClass("selected");
	  $(this).addClass("selected");	
	});
    // VISER ALLE HENDELSER DE 10 NESTE DAGENE
    if ($("a#nextten").length) {
      $("a#nextten").click(function (e) {
        e.preventDefault();
        $.bbq.pushState({
          "startDate": fulldate,
          "endDate": getFutureDate(),
          "view": "calendar"
        });
      });
    } // END if

    // VISER ALLE HENDELSER DE 30 NESTE DAGENE
    if ($("a#nextthirty").length) {
      $("a#nextthirty").click(function (e) {
        e.preventDefault();
        $.bbq.pushState({
          "startDate": fulldate,
          "endDate": getNextThirtyDays(),
          "view": "calendar"
        });
      });
    } // END if

    // VISER ALLE NÅVÆRENDE OG FREMTIDIGE HENDELSER
    if ($("a#showAll").length) {
      $("a#showAll").click(function (e) {
        e.preventDefault();
        $.bbq.pushState({
          "startDate": fulldate,
          "endDate": getFutureYear(),
          "view": "calendarAll"
        });
      });
    } // END if
    // DATOVELGER STARTDATO    
    $("#startDateImage").click(function () {
      $("#startDate").focus();
    });
    $("#startDate").datepicker({
      onSelect: function (selectedDate) {
        //var selectedDate = parseInt(selectedDate) - 1;
        userDate = true;
        $.bbq.pushState({
          "startDate": selectedDate,
          "endDate": selectedDate > $("#endDate").val() ? selectedDate : $("#endDate").val(),
          "view": "calendar"
        });
        $(".datepickerMenu li a").removeClass("selected");
      }
    }); // END datepicker
    // DATOVELGER SLUTTDATO
    $("#endDateImage").click(function () {
      $("#endDate").focus();
    });
    $("#endDate").datepicker({
      beforeShow: function () {
        if ($.bbq.getState().view == "calendarAll") { //check if in far future 
          $(this).datepicker("option", "changeYear", true);
        }
        else {
          $(this).datepicker("option", "changeYear", false);
        }
      },
      onSelect: function (selectedDate) {
        $.bbq.pushState({
          "endDate": selectedDate,
          "view": "calendar"
        });
        $(".datepickerMenu li a").removeClass("selected");
      }
    }); // END datepicker

    //General listnener for hash #
    $(window).bind('hashchange', function (e) {
      var state = $.bbq.getState();
      //toggle share elements
/*if (state.toggle) {
        var $elem = $("#" + state.toggle)
        if (!$elem.parent().find(".toggleContent").is(":visible")) {
          $elem.click();
        }
      }*/
      
      if (state.view && state.view == "calendarAll") {
        $(this).trigger("loadCalendar");
        $(".eventColumnOne").find(".dateHeader").html("Viser alle arrangementer");
        $(".eventColumnTwo").find(".dateHeader").html("Viser alle utstillinger");
      }

      else if ((state.view && state.view == "calendar") || isCalendar) {
        $(this).trigger("loadCalendar");
      }

    }).bind("loadCalendar", function () {
      /*var _startDate;
      if(userDate == true) {
        _startDate = (state.startDate - 1) || getDate();
        console.log("OK" + _startDate);
      } else {
        //_startDate = state.startDate || getDate();
        //console.log("Not" + _startDate);
      }*/
      var state = $.bbq.getState(),
        _startDate = state.startDate || getDate(),
        _endDate = state.endDate || getFutureDate(),
        _location = state.cat && state.cat !== "undefined" && state.cat !== "all" ? "attribeventLocation:" + (state.cat || ips.data.params.cat || "") + "+AND+" : "";
      var urlObj = {
        "module": "Search",
        "action": "Search.publicSearch",
        "qtype": "EventCalendar.Event",
        "qroot": 2,
        "query": _location + "(attribfromDate:[0+TO+" + _endDate + "]+NOT+attribtoDate:[0+TO+" + _startDate  +"])",
        "lang": ips.system.lang,
        "pagesize": "50",
        "template": "eventResults"
      }

      $("#events").load(urlroot + "?" + $.param(urlObj).replace(/%2B/ig, '+'), function () {
        $('.toggleContent,.shareWrapper,.tipsForm').hide();
      });
      urlObj.qroot = calendarExhibitions;
      urlObj.query = _location + "(attribfromDate:[0+TO+" + _endDate + "]+NOT+attribtoDate:[0+TO+" + _startDate + "])";
      urlObj.template = "exhibitionResults";
      // LOAD EXHIBITIONS WITH SELECTED DATE AND LOCATION
      $("#exhibitions").load(urlroot + "?" + $.param(urlObj).replace(/%2B/ig, '+'), function () {
        $('.toggleContent,.shareWrapper,.tipsForm').hide();
      });

      $("#startDate").val(_startDate);
      $("#endDate").val(_endDate);
      showFriendlyDate(_startDate, _endDate);
      $("#endDate").datepicker("option", "minDate", transformIPSDateToUIDate(_startDate));



    });

  } // END if

  /*-------------- EXHIBITIONVIEW SIDEMAL -----------------------*/

  var $exViewMeta = $("#exhibitionViewMeta");

  // SLIDESHOW EXHIBITION VIEW
  var isExhibitionView = $("body.exhibitionView").length > 0 ? true : false;
  if (isExhibitionView) {
    $("#multimediaMenu a").live("click", function (e) {
      e.preventDefault();
      //new RegExp("(tab\="+(state.tab||"loadImages")+")").test($(this).find("a").attr("href"))
      $.bbq.pushState({
        "tab": $(this).attr("id"),
        "id": $(this).attr("rel")
      });
    });
    $(window).bind("hashchange", function () {
      var state = $.bbq.getState();
      // check for tab state, or load id any tab
      if (state.tab) {	  
       $exViewMeta.trigger(state.tab, state.id)
      }
      else if ($("#multimediaMenu li").length > 0) {
        //find if tab
        $exViewMeta.trigger($("#multimediaMenu li:first a").attr("id"), $("#multimediaMenu li:first a").attr("rel"));
        if($("#multimediaMenu li").length == 1) {
		      $("#multimediaMenu").hide();
	      }
      }
    });
  }

  // IMAGES
  if ($exViewMeta.length) { // START MEDIA BINDS
    // IMAGES BIND
    $exViewMeta.bind("loadImages", function (e, folderid) {
      $exViewMeta.find("#exhibitionViewImages").load(urlroot + "?module=Files;action=FileFolder.publicDisplay;ID=" + folderid + ";template=slideshowExhibitionView", function () {
        $exViewMeta.find("ul.tabs").tabs(".images > div", {
          effect: 'fade',
          fadeOutSpeed: "slow",
          rotate: true
        }).slideshow();
        var $names = $(".imagesNameContainer p").eq(0).show().end();
        $(".tabs li a").click(function () {
          $names.hide().eq(1 * $(this).text() - 1).show();
        });
      });
    });

    // LINKS BIND
    $exViewMeta.bind("loadLinks", function (e, folderid) {
      $exViewMeta.find("#exhibitionViewImages").load(urlroot + "?module=Articles;action=Article.publicOpen;ID=" + folderid + ";template=ajaxLinks");
    });

    // VIDEOS BIND
    $exViewMeta.bind("loadVideos", function (e, folderid) {
      $exViewMeta.find("#exhibitionViewImages").load(urlroot + "?module=Files;action=FileFolder.publicDisplay;ID=" + folderid + ";template=multimedia", function (e) {
        $(this).find("div.scrollable").scrollable({
          items: ".items",
          item: ".item",
          prev: ".prev",
          next: ".next",
          size: 3
        });
        $(this).find("a.thumbLink").live("click", function (e) {
          e.preventDefault();
          var videoSrc = $(this).attr('rel');
          $("#exhibitionViewImages").find("#video").html("<embed src='" + videoSrc + "' type='application/x-shockwave-flash' width='316' height='208' allowscriptaccess='always' allowfullscreen='true'></embed>");
        });
      });
    });
    //$("#multimediaMenu li a").eq(0).click();
  } // END MEDIA BINDS
  

  // ----------------- SEARCH RESULT SIDEMAL ---------------------
  var query = ips.data.params.query || "public:true";
  var lang = ips.data.params.lang;

  $(".updateresult").live("click", function (event) {
    event.preventDefault();
    $(this).closest("div.searchresult").load(urlroot + "?module=Search&action=Search.publicSearch&qtype=EventCalendar.Event&qroot=1&pagesize=" + ips.system.pagesize + "&query=" + query + "&lang=" + lang + "&template=searchResults&index=" + $(this).attr("rel"));
  });


  if ($("#searchExhibitions").length) {
    $("#searchExhibitions").load(urlroot + "?module=Search&action=Search.publicSearch&qtype=EventCalendar.Event&qroot=1&pagesize=" + ips.system.pagesize + "&query=" + query + "&lang=" + lang + "&template=searchResults");
  }

  if ($("#searchArticles").length) {
    $("#searchArticles").load(urlroot + "?module=Search&action=Search.publicSearch&qtype=Articles.Article&qroot=39&pagesize=" + ips.system.pagesize + "&query=" + query + "&lang=" + lang + "&template=searchResults");
  }

  if ($("#searchEvents").length) {
    $("#searchEvents").load(urlroot + "?module=Search&action=Search.publicSearch&qtype=EventCalendar.Event&qroot=2&pagesize=" + ips.system.pagesize + "&query=" + query + "+NOT+attribtoDate:[0+TO+" + getDate() +"]&lang=" + lang + "&template=searchResults");
  }

  // ----------------- TIP A FRIEND ---------------------
  $("#triggerTipform").live("click", function () {
    $('.tipsForm').slideToggle('slow');
  });

  // TIP  A FRIEND AJAX SETUP AND VALIDATION
  var $tipsform = $(".tipsForm");
  var emailpattern = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  $tipsform.hide().live("submit", function (e) {
    e.preventDefault();
    var $this = $(this),
    //cache
    $response = $this.find("h3"),
      $sender = $this.find("#senderEmail"),
      $recipient = $this.find("#recipientEmail");

    if (!emailpattern.test($sender.val())) {
      $response.addClass("error").text("Vennligst sjekk e-post");
      $sender.addClass("error").focus();
      return false;
    }
    else if (!emailpattern.test($recipient.val())) {
      $response.addClass("error").text("Vennligst sjekk e-post");
      $recipient.addClass("error").focus();
      return false;
    }
    $response.text("Sender tips....");
    $(".tipsForm:visible input[name=ipsfm_url]").val(window.location.toString().replace(/\s+/igm, '+'));
    $.ajax({
      type: 'POST',
      url: './',
      data: $this.serialize(),
      success: function () {
        $response.text("Tipset ble sendt!");
        $this.find("input[type=text]").val("");
        $tipsform.delay(5000).slideUp("slow");
      }
    });
  }); // END TIP A FRIEND
  //TEXTSIZE
  var getTextSize = function () {
    var textsize = $.cookie('textsize'),
      $body = $("body").removeClass("default").removeClass("small").removeClass("medium").removeClass("large").addClass(textsize);
  };
  getTextSize();
  $("#sizeSelector a").click(function (event) {
    var $target = $(event.target);
    $.cookie('textsize', $target.attr("class"), {
      expires: 29,
      path: '/'
    });
    getTextSize();
    return false;
  }); // END TEXTSIZE
  $(".shareWrapper ul li a img[title]").tooltip('#hovertip');

  // SEARCH RESULT
  var $searchresult = $(".searchresult");
  if ($searchresult.length) {
    $searchresult.ajaxStart(function () {
      $(this).addClass("loading");
    }).ajaxStop(function () {
      $(this).removeClass("loading");
    });
  }

  // TOGGLE CONTENT
  // hides the slickbox as soon as the DOM is ready
  $('.toggleContent').hide();

  // toggles the content on clicking the noted link
  $('a.toggleButton').live("click", function (e) {
    e.preventDefault();
    var $this = $(this);
    $this.toggleClass("open");
    if ($this.parent().find('.toggleContent').is(":visible")) {
      $this.parent().find('.toggleContent').slideUp(400);
    }
    else {
      $this.parent().find('.toggleContent').slideDown(400);
      $this.parent().find('.ajaxRelations').each(function () {
        var $this = $(this);
        $.get($this.attr('href') + ';template=ajaxRelations', function (data) {
          $this.replaceWith(data);
        });
      });
    }
  });


  // SHARELINE
  // hides the slickbox as soon as the DOM is ready
  $('.shareWrapper').hide();

  // toggles the content on clicking the noted link
  $('a.share').live("click", function () {
    if (!$(this).hasClass("expanded")) {
      $("body").live("click", function (e) {
        if (!$(e.target).closest(".shareWrapper").length > 0) {
          $(".shareWrapper").slideUp();
          $("body").die("click");
          $("a.share:visible").removeClass("expanded");
        }
      });
    }
    else {
      $("body").die("click");
    }
    $(this).toggleClass("expanded").parent().find('.shareWrapper').slideToggle(400);


    return false;
  });



  if (isCalendar || isExhibitionList || isExhibitionView) {
    $(window).trigger("hashchange"); //init
  }

  /* ******************
  Twitter
  ********************/

  if( $("#twitter").length ) {
    new TWTR.Widget({
      version: 2,
      type: 'search',
      search: 'nasjonalmuseet OR from:nasjonalmuseet OR vestbanen -Kaffebrenneriet -tog -SMS',
      interval: 8000,
      title: 'Om Nasjonalmuseet p&aring; Twitter',
      id: 'twitter',
      subject: '',
      width: 280,
      height: 162,
      theme: {
        shell: {
          background: '#e4e4e9',
          color: '#333333'
        },
        tweets: {
          background: '#ffffff',
          color: '#444444',
          links: '#1985b5'
        }
      },
      features: {
        scrollbar: false,
        loop: true,
        live: true,
        hashtags: true,
        timestamp: true,
        avatars: true,
        behavior: 'default'
      }
    }).render().start();
  } // END Twitter

}); // END JavaScript Document