/*
 * 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);

// cookie lib
function getCookie(c_name) {
  if (document.cookie.length>0) {
    c_start=document.cookie.indexOf(c_name + "=");
    if (c_start!=-1) { 
      c_start=c_start + c_name.length+1; 
      c_end=document.cookie.indexOf(";",c_start);
      if (c_end==-1) c_end=document.cookie.length;
      return unescape(document.cookie.substring(c_start,c_end));
    } 
  }
  return "";
}
function setCookie(c_name) {
  var referrer = document.referrer;
  if(referrer != '' && !referrer.match('norgesbooking.no')) {
    var today = new Date();
    var expiresDate = new Date(today.getTime() + (1000 * 60 * 60 * 24));
    document.cookie = c_name+ "=" +escape(document.referrer)+ ";path=/;expires=" + expiresDate.toGMTString();
  }
}
function checkCookie() {
  referrer = getCookie('nb_referrer');
  document.getElementById('referrer').value = referrer;
}


// function for updating images in search result
var updateImages = function updateImages() {
  $("img.missingSrc").each(function(){
	  $(this).attr("src", $(this).attr("rel"));
  }).show();
}

/********** UTIL FUNCTIONS *************/
function normalizeDate(date) {
  if( date == "1970-01-01T00:00:00" ) { 
    var d = new Date(),
        y = d.getFullYear(),
        month = d.getMonth(),
        m = month < 10 ? "0" + month : month,
        day = d.getDay(),
        d = day < 10 ? "0" + day : day;
    //normalize the date
    date = y + m + d;
  } else {
    date = date.substring(0, date.indexOf("T")).replace(/-/g, "");
  }
  return date;
}

/********** END UTIL FUNCTIONS *************/

// Filter function for filtering and updating the search
function filterCabin(result) {
  // Function used to scramble search results
  function randomOrder() {
    return (Math.round(Math.random())-0.5);
  }

  // Sort on rooms
  function roomSortNumber(a, b) {
    return a[3] - b[3];
  }	

  // Build array for pure hits
  var cabinResults = [];
  var cabinPrices = result[0];

  var i = 0;
  while(i < cabinPrices.length) {
    jQuery.merge(cabinResults, [cabinPrices[i][0]]);
    i++;
  }
  var filteredCabins = jQuery.grep(extra.cabins, function(a, i) {
    if(jQuery.inArray(a[0], cabinResults) != - 1) {
      var price = jQuery.grep(cabinPrices, function(b, c) {
        if(jQuery.inArray(b[0], [a[0]]) != - 1) {
          a = jQuery.merge(a, [b[1], b[2]]);
          return true;
        } else {
          return false;
        }
      });
      return true;
    } else {
      return false;
    }
  });
  filteredCabins.sort(randomOrder);

  // If we have almost hits, add them to list
  var almostCabinResults = [];
  var almostCabinPrices = result[1];

  if(almostCabinPrices.length > 0) {
    i = 0;
    while(i < almostCabinPrices.length) {
      jQuery.merge(almostCabinResults, [almostCabinPrices[i][0]]);
      i++;
    }

    var almostfilteredCabins = jQuery.grep(extra.cabins, function(a, i) {
      if(jQuery.inArray(a[0], almostCabinResults) != - 1) {
        var price = jQuery.grep(almostCabinPrices, function(b, c) {
          if(jQuery.inArray(b[0], [a[0]]) != - 1) {
            a = jQuery.merge(a, [b[1], b[2]]);
            return true;
          } else {
            return false;
          }
        });
        return true;
      } else {
        return false;
      }
    });
    almostfilteredCabins.sort(randomOrder);
    
    // Merge the two arrays with hits
    if(almostfilteredCabins.length > 0) {
      jQuery.merge(filteredCabins, [["almosthits"]]);
    }
    jQuery.merge(filteredCabins, almostfilteredCabins);
  }
  filteredCabins.sort(roomSortNumber);
  // Build output
  var cabinResultsHTML = "<table cellspacing='1' id='cabinResultTable'><thead><tr><th> </th><th>" + lang.objectnumber + "</th><th>" + lang.destination + "</th><th>" + lang.beds + "</th><th>" + lang.price + "</th></tr></thead><tbody>";

  // Loop through all cabin hits/almost hits and build HTML
  var i = 0;
  while(i < filteredCabins.length) {
    if(filteredCabins[i][0] == "almosthits") {
    cabinResultsHTML += "<tr><td></td><td></td><td class='almosthits'><h3>" + lang.almosthits + "</h3></td><td></td><td></td>";
    } else {
    cabinResultsHTML += "<tr onclick='gotoCabin(\"" + filteredCabins[i][4] + "\")'><td class='img'>";
    // Image
    if(filteredCabins[i][2]) {
      cabinResultsHTML += "<img class='missingSrc' style='display:none;' rel=\"" + ips.system.urlroot + "filestore/" + filteredCabins[i][2] + "?size=110x0\">";
    }
    // Objectnumber
    cabinResultsHTML += "<td>" + filteredCabins[i][0] + "</td>";
    // Destination
    cabinResultsHTML += "<td>" + filteredCabins[i][5] + "</td>";
    // Beds
    cabinResultsHTML += "<td>" + filteredCabins[i][3] + "</td>";
    // Price
    cabinResultsHTML += "<td>";
    if(filteredCabins[i][6] != 'null') {
      cabinResultsHTML += filteredCabins[i][6];
      if(filteredCabins[i][7] != 'null' && filteredCabins[i][7] != filteredCabins[i][6]) {
        cabinResultsHTML += " - " + filteredCabins[i][7];
      }
      cabinResultsHTML += " NOK";
    }
    cabinResultsHTML += "</td></tr>";
    }
    i++;
  }
  cabinResultsHTML += "</tbody></table>";

  // Add filtered and processed result to page
  $('#cabins').html(cabinResultsHTML);

  // Create a sortable table
  dataTable = $('#cabinResultTable').dataTable({
    "aoColumns": [
      { "bSearchable": false, "bSortable": false },
      { "sWidth": "110px" },
      null,
      { "sWidth": "150px" },
      { "sWidth": "150px" }
    ],
    //"aaSorting": [ [3, "asc"] ],
    "bSort": false,
    "bAutoWidth": false,
    "bFilter": false,
    "bSortClasses": false,
    "bLengthChange": false,
    "sPaginationType": "full_numbers",
    "sDom": 'fiptp',
    "oLanguage": {
      "oPaginate": {
        "sPrevious": lang.previous,
        "sNext": lang.next,
        // Hack, to place a show all link
        "sFirst": lang.showall,
        "sLast": ""
      },
      "sZeroRecords": lang.nohits,
      "sInfoEmpty": lang.nohits,
      "sInfo": "_START_ " + lang.to + " _END_ (_TOTAL_ " + lang.hits + ")"
    },
    "fnInitComplete": function() {
      $("#cabinResultTable_first").trigger("click");
      $("#cabinResultTable_first").unbind("click").addClass("toggleAllResults");
      if($("span span.paginate_button").size() == 0){
        $(".dataTables_paginate").css("display", "none");
      }
    }
  });
  toggleResults(dataTable);
  updateImages();
}  // end filterCabin()

function toggleResults(dataTable) {
    $(".toggleAllResults").live("click", function() {
      if(dataTable.fnSettings()._iDisplayLength == -1) {
        dataTable.fnSettings()._iDisplayLength=10;
        dataTable.fnSettings()._iDisplayStart=0;
        dataTable.fnDraw();
        $(".paginate_button[id!=cabinResultTable_first]").css("display", "inline");
        $(this).html(lang.showall);
        $(".paginate_button[id!=cabinResultTable_first]").first().trigger("click");
      } else {
        dataTable.fnSettings()._iDisplayLength=-1;
        dataTable.fnDraw();
        $(".paginate_button[id!=cabinResultTable_first]").css("display", "none");
        $(this).html(lang.showlist);
      }
      updateImages();
      //$("#cabinResultTable_last").trigger("click");
    });
}


// Function building and handling the submit to webservice
function searchCabin(form) {
  // Removes visibility to hide selects in IE6
  $("#cabinSearch select").css("visibility","hidden");
  $("#cabinSearchLoader").height( $("#cabinSearch").height() );

  // Fades the loading screen in while processing
  $("#cabinSearchLoader").fadeIn("slow");

  var loc = window.location.href;
  if(loc.indexOf("\#") != -1) {
    window.location.href = ips.system.urlroot + ips.system.searchfolder + loc.substring(loc.indexOf("#"), loc.length);
  } else {
    window.location.href = ips.system.urlroot + ips.system.searchfolder + "#all=all";
  }

  // Loops through checkboxes and creates string with values
  var facilities = $("#cabinSearchForm input[type=checkbox]:checked");
  var facilitiesStr = "";
  var separator = ",";
  for (i=0; i < facilities.length; i++) {
    if(i == facilities.length) {
      separator = ";";
    }
    facilitiesStr += facilities[i].value + separator;
  }

  // Builds up the proper query
  var query = "";
  query = $("#cabinSearchForm :input[type='hidden']").serialize();
  query = query + "&" + $("#extraFields select:not(:[name='region'])").serialize();

  var destinations = "";
  if($("#destinations option:selected").size() > 0 ) {
    $("#destinations option:selected").each(function(i) {
      destinations += $(this).val() + ",";
    });
    query = query + "&destinations=" + destinations.substring(0,destinations.length - 1);
  } else if ($("select[name='region']").val() != 0) {
    $("#destinations option").each(function(i) {
      destinations += $(this).val() + ",";
    });
    query = query + "&destinations=" + destinations.substring(0,destinations.length - 1);
  }

  query = query + "&" + $("fieldset.actions select").serialize();
  query = query + "&facilities=" + facilitiesStr;
  //turn string into a obj for manipulation

  query = jQuery.deparam(query);
  var state = $.bbq.getState(); 
  if (state.moredestinations && state.destinations) {
    query.destinations = state.destinations + "," + state.moredestinations;	
  } else if (state.destinations) {
    query.destinations = state.destinations;
  }
  if (state.morecounty && state.county) {
    query.county = state.county + "," + state.morecounty;
  } else if (state.county) {
    query.county = state.county;
  }
  //turn obj backinto a string
  query = jQuery.param(query);

  // Post the information to the groovy for further processing
  $.ajax({ 
    type: 'GET',
    url: './scripts/bookingActions.groovy',
    data: query,
    // When response, either output error or redirect to search result
    success: function(response) {
      if(response == 'ERROR - HTTP:500') {
        $("#cabinSearch select").css("visibility","visible");
        $("#cabinSearchLoader").fadeOut("slow");
      } else {
        if($("#cabinSearchResults").size() === 0) {
          $('#cabinSearchForm').attr("action", ips.system.urlroot + ips.system.searchfolder);
          $("#ws_result").attr("value", response);
          $("#cabinSearchForm").unbind("submit");
          form.submit();
        } else {
          var result = eval(response.replace(/\'/g, "\""));
          filterCabin(result);
          $("#cabinSearch select").css("visibility","visible");
          $("#cabinSearchLoader").fadeOut("slow", function(){
            searchComplete = true;
            toggleSlideAdvanced('slideWrapper', document.getElementById('hideButton'));
          });
        }
      }
    }
  });
} //end searchCabin()

// Function handling the slide down showing more choices
// used inline?
function toggleSlide(toggleObject, referingObject) {
  $("#" + toggleObject).slideToggle("slow", function() {
    if($("#" + toggleObject).css("display") == "none") {
      $(referingObject).html("<span>" + lang.moreoptions + "</span><span id='toggleButton' class='down'></span>");
      $("#imageMapWrapper").height(366);
    } else {
      $(referingObject).html("<span>" + lang.lessoptions + "</span><span id='toggleButton' class='up'></span>");
      $("#imageMapWrapper").animate({ 
        height: "562px"
      }, 500 );
    }
  });
}

// Function handling the slide down showing more choices
function toggleSlideAdvanced(toggleObject,referingObject) {
  $("#" + toggleObject).slideToggle("slow", function() {
    if($("#" + toggleObject).css("display") == "none" || searchComplete === true) {
      $(referingObject).html("<span>" + lang.moreoptions2 + "</span><span id='toggleButton' class='down'></span>");
      $("fieldset.actions .button").fadeOut();
      searchComplete = false;
    } else {
      $(referingObject).html("<span>" + lang.lessoptions2 + "</span><span id='toggleButton' class='up'></span>");
      $("fieldset.actions .button").fadeIn();
      searchComplete = false;
    }
  });
}

// Function used to update select
$("select[name=region]").change(function(e, trigger) {
  if($(this).find("option:selected").val() != 0) {
    var countyId = $("select[name=region] :selected").attr("id");
    countyId = countyId.substring(7);
    $("#destinations").html("<option value='1'>" + lang.loading + "</option>");
    $("#destinations").attr("disabled","disabled");
    $.ajax({ 
      type: 'GET',
      url: ips.system.urlroot + '?root=' + lang.regionroot + ';template=optionsDestination;selected=' + countyId,
      success: function(response) {
	    $("#destinations option[value!=0]").remove();
	    $("#destinations").html(response);
            $("#destinations").removeAttr("disabled");
        if (typeof trigger === "function") {trigger();}
      }
    });
  } else {
    $.ajax({ 
      type: 'GET',
      url: ips.system.urlroot + '?root=' + lang.regionroot + ';template=optionsDestination',
      success: function(response) {
        $("#destinations option[value!=0]").remove();
	$("#destinations").append(response);
      }
    });
  }
});
$("select[name=region]").trigger("change");

// Function used to create popup windows
function showInformation(id) {
  childWindow = open(ips.system.urlroot + "?Module=Articles&Action=Article.publicOpen;id=" + id + ";template=information","information" + id,"status=1,toolbar=0,width=500,height=500");
  if (childWindow.opener === null) { childWindow.opener = self; }
}

// Function used to go from search to cabin
function gotoCabin(cabinUrl) {
  window.location = ips.system.urlroot + cabinUrl + "?template=cabinView;arrival=" + $("#date_from").val() + ";departure=" + $("#date_to").val();
}

function carouselDisplay(id) {
  if($("carouselImage_" + id).className != "carouselImage active") {
    $("img.carouselImage").removeClass("active");
    $("img.carouselImage").css("display", "none");
    $("li.carouselArticle").removeClass("active");
    $("img.carouselImage").stop({clearQueue: "true"}).css("opacity", "");
    $("#carouselImage_" + id).fadeIn("slow");
    $("#carouselImage_" + id + ",#carouselArticle_" + id).addClass("active");
  }
}

// Freetext / Article search.
function search(index,pagesize) {
	// searchQuery is a global/window object emitted by the XSLT template
  $("#searchResults").load(searchQuery + index + "&pagesize=" + ( pagesize || "10" ) + "&lang=" + ips.system.lang);
}

// After document is ready, do this:
jQuery(document).ready(function($) {

/********** ARTICLE SEARCH *************/

  // If search, perform search
  if( $("#searchResults").size() > 0 ) search("1");

  // Function to hide/show proper links on search result pagination
  $(".paginate_button").live("click", function() {
    var $active = $("span.paginate_active");
    if( $active.html() == "1" && $active.next("span").size() == 0 ) {
      $("span.previous").css("display","none");
      $("span.next").css("display","none");
    } else if( $active.html() == "1" ) {
      $("span.previous").css("display","none");
    } else if ( $active.next("span").size() == 0 ) {
      $("span.next").css("display","none");
    } else {
      $("span.previous").css("display","inline");
      $("span.next").css("display","inline");
    }
  });
/********** END SEARCH *************/

/********** PARTNERWEB(EXTRANET) *************/


  $("a.gotocabin").bind("click", function(e) {
    e.preventDefault();
    if($("#objectnumber option:selected").val() == "0") {
      alert("Velg hytte f" + unescape("%F8") + "rst");
    } else {
      window.location = ips.system.urlroot + "scripts/object.groovy?objectnumber=" + $("#objectnumber").val() + "&lang=" + ips.system.lang;
    }
  });


  if( $("#partnerobjects").size() > 0 ) {
    selectPastDates = true;

    $("#partnerobjects input.button").bind("click", function() {
      // Show loading while processing
      $("#report").html("<img src='" + ips.system.urlroot + "filestore/dev/GFX/search_loader.gif' style='margin: 40px auto;'/>");

      var start = $("#date_from").val()
      var stop = $("#date_to").val()
      if(start == "1970-01-01T00:00:00" ) {
        var month = "" + (d.getMonth() + 1);
        if(month.length == 1) { month = "0" + month; }
        start = d.getFullYear() + "-" + month + "-01T00:00:00";
        stop = (d.getFullYear() + 2) + "-" + month + "-01T00:00:00";
      }
      if(stop == "1970-01-01T00:00:00" ) {
        stop = (Number($("#date_from").val().substring(0,4)) + 2) + $("#date_from").val().substring(4)
      }

      // Load the report
      $("#report").load(ips.system.urlroot + "?template=getReport&nocache=true&lang=" + ips.system.lang + "&objectNumber=" + $("#objectnumber").val() + "&contractFromDate=" + start + "&contractToDate=" + stop);
    });
  }

  // Reload calendar on object change
  if( $("#partnerbooking").size() > 0 ) {
    var year = d.getFullYear();
    var month = d.getMonth();

    // Reload calenders for choosen cabin
    $("#objectnumber").bind("change", function() {
      // Set new objectnumber and override
      ips.booking.objectnumber = $(this).val();
      blankCalender = false;
      baceurl = ips.system.urlroot + "scripts/bookingActions.groovy?mainAction=availability;nocache=true;objectNumber=" + ips.booking.objectnumber + ";";
      // Reset calendar data cache
      calenderData = {};
      selectedFrom = [3000, 0, 0];
      selectedTo = [3000, 0, 0];
      calFrom = [year, month];
      calTo = [year, month];
      getAvailabillety(year,month);
      $("#date_from").val("1970-01-01T00:00:00");
      $("#date_to").val("1970-01-01T00:00:00");
    });

    if($("#objectnumber").val() != "0") {
      $("#objectnumber").trigger("change");
    }

    // Perform booking
    $("#partnerbooking .submit").bind("click", function() {
      if($("#objectnumber option:selected").val() == "0" || selectedFrom[0] == 3000 || selectedTo[0] == 3000) {
        if(ips.system.lang == 'ger') {
          alert("Bitte wahlen Sie Hutte und gultige An- und Abreise Daten ");
        }
        else if(ips.system.lang == 'eng') {
           alert("Choose cabin and valid arrival- and departuredate");
        }
        else {
          alert("Velg hytte og gyldige ankomst- og avreisedatoer");
        }
        return false;
      }
      var $this = $(this);
      $this.attr("disabled","disabled");
      $("#bookingstatus").html("<img src='" + ips.system.urlroot + "filestore/dev/GFX/search_loader.gif' style='margin: 40px auto;'/>");

      // Post the information to the groovy for further processing
      $.ajax({ 
        type: 'GET',
        url: './scripts/bookingActions.groovy?mainAction=partnerBooking',
        data: $("#partnerbooking input, #partnerbooking select").serialize(),
        success: function(response) {
          $this.removeAttr("disabled");
          if(response.match(/SUCCESS/).length > 0) {
            var myobject = $("#objectnumber option:selected").html();
            if(myobject == null) {
              myobject = $(".singleobject").val();
            }
            $this.closest(".article").html("<p><strong>Booking av " + myobject + " er registrert for perioden " + $("#date_from").val().substring(0,10) + " - " + $("#date_to").val().substring(0,10) + "</strong></p>");
          } else {
            $("#bookingstatus").html("<p class='mandatory2'><strong>Feil, bookingen blev ikke registrert</strong></p>");
          }
        }
      });
    });
  }

/********** END PARTNERWEB(EXTRANET) *************/


/********** BOOKING/ADV SEARCH *************/

  //
  var arrival = ips.confirm.arrival.length > 0 ? ips.confirm.arrival : ips.system.arrival, 
      departure = ips.confirm.departure.length > 0 ? ips.confirm.departure : ips.system.departure;

  if(arrival.length == 0) {
    arrival = "1970-01-01T00:00:00";
    departure = "1970-01-01T00:00:00";
  }

  //
  $(".objectPricesContainer").load(ips.system.urlroot + "?module=ExternalSources&action=ExternalSource.publicShowContents&id=11&longlang=" + ips.system.longlang + "&objectId=" + ips.system.objectnumber + "&arrival=" + normalizeDate(arrival) + "&departure=" + normalizeDate(departure) + "&lang=" + ips.system.lang + "&template=objectPrices");

  //
  $("a.togglePricesButton").live("click", function(e){
    e.preventDefault();
    if( $("dl.togglePrices").css("display") == "none" ) {
      $(this).text(lang.onlycurrentperiod);
    } else {
      $(this).text(lang.showallprices);
    }
    $("dl.togglePrices").slideToggle();    
  });

  //
  $("a.updatePricesButton").live("click", function(e){
    e.preventDefault();

    if($("#date_to").val() == 0) {
      $("#date_to").val("1970-01-01T00:00:00");
      $("#date_from").val("1970-01-01T00:00:00");
    }

    $(".objectPricesContainer").load(ips.system.urlroot + "?module=ExternalSources&action=ExternalSource.publicShowContents&id=11&longlang=" + ips.system.longlang + "&objectId=" + ips.system.objectnumber + "&arrival=" + normalizeDate($("#date_from").val()) + "&departure=" + normalizeDate($("#date_to").val()) + "&template=objectPrices&lang=" + ips.system.lang);
  });

  // If search comes from frontpage, slide up
  if(ips.system.fromfrontpage) {
    searchComplete = true;
    toggleSlideAdvanced('slideWrapper', document.getElementById('hideButton'));
  }

  // Validate search form on submit
  var searchComplete = false;

  // Reset search
  $("#cabinSearchForm input.reset").bind("click", function() {
    selectedFrom = [3000,0,0];
    selectedTo = [3000,0,0];
    renderCalenders();

    $("#cabinSearchForm")[0].reset();
    $("#date_from").attr("value", "1970-01-01T00:00:00");
    $("#date_to").attr("value", "1970-01-01T00:00:00");
    $("select[name=region]").trigger("change");
  });

  // Check hash, to see if search is defined
  var state = $.bbq.getState();
  if( !jQuery.isEmptyObject(state) ) {
    $.each(state, function(index, value) { 
      //console.log("debug" + index + ":" + value);
      var input = $(".hashable[name=" + index + "]");
      if(input.attr("type") == "checkbox" ) {
        input.attr("checked","checked");
      } else if ( input.attr("name") == "region" ) {
        input.val(value);
        $("select[name=region]").trigger("change", function() {
          if(state.destinations != undefined) {
            $("#destinations").val(state.destinations);
          }
        });
      } else {
        input.val(value);
     }
    });
    searchCabin( $("#cabinSearchForm") );
  }
  // searchresult/edit search / deep-linkingn support?
  $(".hashable").live("change", function() {
    var hash = $(".hashable").filter(function() {
      var value = $(this).val();
      if(value != 0 && value != "1970-01-01T00:00:00" && $(this).attr("name") != "destinations") {
        return $(this);
      }
    }).serialize();
    var destinations = "";
    $("#destinations option:selected").each(function(i) {
      destinations += $(this).val() + ",";
    });
    if(destinations.length > 0) {
      hash = hash + "&destinations=" + destinations.substring(0,destinations.length - 1);
    }
    //console.log(jQuery.param(jQuery.bbq.getState()) !== hash);
    if (jQuery.param(jQuery.bbq.getState()) !== hash) {
      $.bbq.pushState("#" + hash);		
    }
   
  });
  // Frontpage, partner login, adv search - > Update month from dropdown
  $("#cabinSearch,#bookingCalendars,#partnerobjects,#partnerbooking").delegate(".bookingMonth","change", function() {
    var month = ($(this).val() * 1),
        year = d.getFullYear(),
        nextMonth;
    if(selectPastDates) {
      year = 2 + year;
      nextMonth = (d.getMonth() + 1) - month;
      if( nextMonth < 0 ) {
        years = Math.floor(nextMonth / -12);
        year = year - years;
        nextMonth = nextMonth + (years * 12);
      }
    } else {
      nextMonth = (month + d.getMonth() - 1);
      if( nextMonth > 11 ) {
        years = Math.floor(month / 12);
        year = year + years;
        nextMonth = nextMonth - (years * 12);
      }
    }
    if(nextMonth > 11) {
      nextMonth = nextMonth - 12;
      year++;
    } else if (nextMonth < 0) {
      nextMonth = nextMonth + 12;
      year--;
    }
    if( $(this).closest("td[valign=top]").attr("id") == 'cal_from' ) {
      calFrom = [year, nextMonth];
      calTo = [year, nextMonth];
    } else {
      calTo = [year, nextMonth];
    }
    //renderCalenders();
    getAvailabillety(year, nextMonth);
  });

  //SEARCHRESULT
  // 2 events for capturing updates
  $("#cabinResultTable_paginate .paginate_button").live("mouseleave",function(){
    setTimeout(function(){
	  // downloads images
	  updateImages();}
	,400);
  });
  $("#cabinResultTable_paginate").live("click",function(){
    setTimeout(function(){
	  // downloads images
	  updateImages();
	},400);
  });


  // init adv search
 // If search response have a value (search have been made from frontpage), do search.
  if( $("#cabinSearchResults").size() > 0 && typeof extra !== "undefined" && extra.cabinResponse.length > 0 ) {
      filterCabin(extra.cabinResponse[0]);
  }

  // Override cabin search and animate search while loading
  $("#cabinSearchForm").bind("submit", function(event) {
    event.preventDefault();
    searchCabin($(this));
  });

  // Search after a object with specific objectnumber
  $("#objectSearchForm").submit(function(event) {
    event.preventDefault();
    var query = "template=ajaxObjectIdSearch;module=Search;action=publicSearch;qtype=Articles.Article;qroot=" + ips.system.langtopfolderid;
    query = query + ";query=attribobjectnumber:" + $("#objectId").val();
      $.ajax({ 
        type: 'GET', 
        url: ips.system.urlroot,
        data: query,
        success: function(response) {
          if(response == 'ERROR') {
            alert(lang.nohits);
          } else {
            window.location = ips.system.urlroot + response + "?template=cabinView";
          }
        }
      });
  });

  // Loads the calendars if inputs are on page
  if( $("#cal_from").length > 0 ) {
    if(ips.booking.objectnumber == "") {
      ips.booking.objectnumber = "1000000";
    } else {
      blankCalender = false;
    }
    // overriding global var from rangecalendar.js
    baceurl = ips.system.urlroot + "scripts/bookingActions.groovy?mainAction=availability;nocache=true;objectNumber=" + ips.booking.objectnumber + ";";
    // Setting globals defined in rangecalendar.js
    if(ips.booking.arrival.length > 0) {
      selectedFrom = ips.booking.arrival;
      selectedTo = ips.booking.departure;
      calFrom = [ips.booking.arrival[0],ips.booking.arrival[1]];
      calTo = [ips.booking.departure[0],ips.booking.departure[1]];
    }
    renderCalenders();
  }

/********** END BOOKING SEARCH *************/

/********** GENERAL INIT STUFF *************/
  //
  function fancyGoogleMap() {
    $("#mapCanvas").fancybox({
      'overlayColor' : '#fff',
      'overlayOpacity' : '0.4',
      'type' : 'inline',
      'content' : $("#mapCanvas"),
      'padding' : 10,
      'onStart' : function() {
        $("#mapCanvas").unbind("click");
        var center = map.getCenter();
        $("#mapCanvas").css("width", "500px").css("height", "450px");
        map.checkResize()
        map.setCenter(center);
        $("a.google").hide();
      },
      'onClosed' : function() {
        fancyGoogleMap();
        var center = map.getCenter();
        $("#mapCanvas").css("width", "272px").css("height", "200px");
        map.checkResize()
        map.setCenter(center);
        $("a.google").show();
      }
    });
  }
  // init
  fancyGoogleMap();

  $(".gotocalendars input").bind("click", function(e) {
    e.preventDefault();
    // Scroll down to calendars
    var target_offset = $("#footer").offset();
    var target_top = target_offset.top;
    $('html, body').animate({scrollTop:target_top}, 500);
  });

  $("a.google").bind("click", function(e) {
    e.preventDefault();
    $("#mapCanvas").trigger("click");
  });

  // Validation for all forms
  $("form").validate({
      errorClass: "mandatory2",
      errorPlacement: function(error, element) {
      },
      highlight: function(element, errorClass) {
        $(element).addClass("mandatory");
        $(element.form).find("label[for=" + element.name + "]").addClass("mandatory");
        if($(".cabinView").find("#cabinBookingForm").length) {
          $("#cabinBookingForm").before("<p class='mandatory'>" + lang.pickdate + "</p>");
        }
      },
      unhighlight: function(element, errorClass) {
        $(element).removeClass("mandatory");
        $(element.form).find("label[for=" + element.name + "]").removeClass("mandatory");
      }
    }
  );

  
  $("textarea[name='comments']").bind("keyup", function() {
    var $val = $(this).val();
    var $max = $(this).attr("maxlength");
    if($val.length > $max) {
      $(this).val($val.substring(0,$max));
    }
  });  

  // Apply lightbox to all images with the class lightbox
  $("a.lightbox").fancybox({
    'overlayColor' : '#fff',
    'overlayOpacity' : '0.4'
  });

  // Set the cookie to referrer, will be submitted in booking
  setCookie('nb_referrer');

  // On confirm page, set referrer
  if($("#referrer").size() > 0) {
    checkCookie();
  }

  // Validate and submit if valid email.
  $("#newsletterSignupForm").validate({
    rules: { email: { required: true, email: true } },
    messages: {  email: lang.novalidemail },
    submitHandler: function() {
      $.ajax({ 
        type: 'GET', 
        url: './',
        data: ( "template=" + ips.system.lang + "NewsletterSignup;" + $("#newsletterSignupForm").serialize() ),
        success: function(response) {
          alert(lang.newsletterconfirmtext);
          return false;
        }
      });
    }
  });

/********** END GENERAL INIT STUFF *************/


/********** FRONTPAGE *************/

  // Frontpage imagemap -= > shortcuts to "Opplevelser i Norge"
  var $mapWrap = $("#imageMapWrapper");
  if($mapWrap.length) {
    $mapWrap.find("area").hover(function(){
      if($(this).attr("alt") == "hvorvildureise_sor") {
        $mapWrap.find(".sor").show();
      }
      if($(this).attr("alt") == "hvorvildureise_vest") {
        $mapWrap.find(".vest").show();
      }
      if($(this).attr("alt") == "hvorvildureise_ost") {
        $mapWrap.find(".ost").show();
      }
      if($(this).attr("alt") == "hvorvildureise_midt") {
        $mapWrap.find(".midt").show();
      }
      if($(this).attr("alt") == "hvorvildureise_nord") {
        $mapWrap.find(".nord").show();
      }
    },
    function(){
      if($(this).attr("alt") == "hvorvildureise_sor") {
        $mapWrap.find(".sor").hide();
      }
      if($(this).attr("alt") == "hvorvildureise_vest") {
        $mapWrap.find(".vest").hide();
      }
      if($(this).attr("alt") == "hvorvildureise_ost") {
        $mapWrap.find(".ost").hide();
      }
      if($(this).attr("alt") == "hvorvildureise_midt") {
        $mapWrap.find(".midt").hide();
      }
      if($(this).attr("alt") == "hvorvildureise_nord") {
        $mapWrap.find(".nord").hide();
      }
    });
  }
  // IMAGEMAP SETUP FOR HOVER EFFECT
  var orgSrc = $mapWrap.find("img").attr("src"); // Set normal src when mouseleave wrapper
  $mapWrap.find("area").mouseenter(function(e){
    var alt2src = ips.system.urlroot + "filestore/dev/GFX/imageMap/" + $(this).attr("alt") + ".gif";
    $mapWrap.find("img").attr("src", alt2src);
  });
  $mapWrap.mouseleave(function(){
    $mapWrap.find("img").attr("src", orgSrc);
  }); // END IMAGEMAP

  // Initiate carousel on frontpage
  if( $("#carousel").length > 0 ) {
    var autoscroll = "true";
    setInterval(function () {
      if(autoscroll == "true") {
        if($(".carouselArticle.active").attr("id") != $(".carouselArticle:last").attr("id")) {
          $(".carouselArticle.active").next().trigger('onmouseover');
        } else {
          $(".carouselArticle:first").trigger('onmouseover');
        }
      }
    }, 5000);
    $("#carousel").mouseover(function(){
      autoscroll = "false";
    }).mouseout(function(){
      autoscroll = "true";  
    });
  }

/********** END FRONTPAGE *************/

}); // END DOC RDY