var currentMousePos = { x: -1, y: -1 };
var search_map = null;
var search_map_markers = new Array();
var search_default_list_html = '';

$(document).ready(function() {
   addDefaultValueBehaviour();
   
   $('#player_pic, #howto_video_link').fancybox({
                              openEffect  : 'none',
                              closeEffect : 'none',
                              height: 301,
                              width: 600,
                              helpers : {
                                 media : {}
                              }
	});
   
    $('.pick_btn, .pick_btn_special_offer').fancybox({'beforeLoad': function(){
                                     var place_id = $('#checkout_form').find('[name="place_id"]').val();

                                     if(place_id == 0 || ($(this.element).parent().data('placeid') != undefined && place_id != $(this.element).parent().data('placeid')))
                                     {
                                        $('#checkout_form').find('[name="place_id"]').val($(this.element).parent().data('placeid'));
                                     }
                                   }
    });
   
   if($('#packets_form').length > 0)
   {
      $('#packets_form').on('submit', validateSignupForm);
   }
   
   $('#packets .button, .get_start_btn, .btn_blue_medium, .btn_medium_pop').fancybox();

   if(typeof open_packet_form !== 'undefined' && open_packet_form !== null && open_packet_form === true)
   {
      $.fancybox.open('#exposure_packets_form');
   }

   if($('.search_area').length > 0)
   {
      // Init Select2 style selects
      if($('.search_area form select').length > 0)
      {
         $('.search_area form #region').select2({ width : '220', /* 350 */
                                       placeholder : 'Vælg landsdel',
                                       containerCssClass : 'search_select',
                                       minimumResultsForSearch : 100
                                    });

         $('.search_area form #seats').select2({ width : '220', /* 350 */
                                       placeholder: 'Vælg antal personer',
                                       containerCssClass : 'search_select',
                                       minimumResultsForSearch : 100
                                    });
         $('.search_area form #eventtype').select2({ width : '220', /* 350 */
                                       placeholder: 'Type af arrangement',
                                       containerCssClass : 'search_select',
                                       minimumResultsForSearch : 100
                                    });
      }
      
      if($('.search_area').length > 0)
      {
         if(typeof places_file !== 'undefined')
         {
            $( "#places_list" ).load( places_file, function() {
               var seats_interval = seats == undefined || seats == 0 ? 0 : seats.split('-');
               var minseats = seats_interval == 0 ? seats_interval : seats_interval[0];
               filterPlaces(event_type_id, region_id, minseats);

               if($('body.page-template-page-places-search-php').length > 0 || $('body.tax-event-type').length > 0 ||  $('body.page-template-page-places-landingpages-php').length > 0)
               {
                  initSearchMap();
               }
            });
         }
      }
   }
   
   if($('.sidebar.search').length > 0)
   {
      $('.sidebar.search .top_filters #filter_region').select2({  width : '250',
                                                                  placeholder : 'Vælg landsdel',
                                                                  containerCssClass : 'search_select',
                                                                  minimumResultsForSearch : 100
                                                               });

      $('.sidebar.search .top_filters #filter_seats').select2({   width : '250',
                                                                  placeholder: 'Vælg antal personer',
                                                                  containerCssClass : 'search_select',
                                                                  minimumResultsForSearch : 100
                                                               });
      $('.sidebar.search .top_filters #filter_type').select2({ width : '250',
                                                               placeholder: 'Type af arrangement',
                                                               containerCssClass : 'search_select',
                                                               minimumResultsForSearch : 100
                                                            });
   }

   if ($('#single_place_checkout').length > 0) {
      $('#save_info_checkmark_dummy').on('click', function(e) {
         var checked = $(this).data('checked');
         var checkmarkgreenurl = $(this).data('checkmarkgreenurl');
         var checkmarkgreyurl = $(this).data('checkmarkgreyurl');
         
         if(checked)
         {
            $(this).data('checked', 0);
            $(this).removeClass('checked');
            $('#save_info').prop('checked', false);
         } else
         {
            $(this).data('checked', 1);
            $(this).addClass('checked');
            $('#save_info').prop('checked', true);
         }
      });
   }
      
   if($('#big_picture').length > 0 && $('.images_line').length > 0)
   {
      $('.images_line').find('.place_thumbnail').on('click', function(e) {
         var url = $(this).data('url');
         
         $('#big_picture').attr('src', url);
      });
   }
   
   if($('.info_tooltip').length > 0)
   {
      $('.info_tooltip').tooltipster({
                                 position : 'left',
                                 maxWidth : 250,
                                 offsetY : 2,
                                 theme : 'place_info_tooltip'
      });
   }
   
   if($('.pack_tooltip').length > 0)
   {
      $('.pack_tooltip').tooltipster({
                                 position : 'left',
                                 maxWidth : 250,
                                 theme : 'place_info_tooltip'
      });
   }
   
   if($('#checkout_form').length > 0)
   {
      $('#checkout_form').on('submit', validateSignupForm);

      $('#checkout_form').find('#sleeping_checkmark_dummy').on('click', function(e) {
         var checked = $(this).data('checked');
         var checkmarkgreenurl = $(this).data('checkmarkgreenurl');
         var checkmarkgreyurl = $(this).data('checkmarkgreyurl');
         
         if(checked)
         {
            $(this).data('checked', 0);
            $(this).removeClass('checked');
            $('#sleeping').prop('checked', false);
         } else
         {
            $(this).data('checked', 1);
            $(this).addClass('checked');
            $('#sleeping').prop('checked', true);
         }
      });
   }
   
   
   if($('body.single-konferencested').length > 0)
   {
    
	tabs('tabs');
	tabs('tabs2');
	
	for (var i = 1; i < 30; i++) { 
			meetingroomInfo(i);
			}
	
	tooltip();
         function initialize() {
            var myLatlng = new google.maps.LatLng(place_lat,place_lng);
            var mapOptions = {
               zoom: 9,
               center: myLatlng,
               mapTypeId: google.maps.MapTypeId.ROADMAP
            }
            var map = new google.maps.Map(document.getElementById('gmap'), mapOptions);
			
			var tab = jQuery('ul#tabs li')[1]
			jQuery(tab).one('click', function(){
  			google.maps.event.trigger(map, 'resize');
			map.setCenter(myLatlng);	
			});

            var marker = new google.maps.Marker({
               position: myLatlng,
               map: map,
               clickable : true
            });

            var pinIcon = new google.maps.MarkerImage(
               "http://ateo.dk/wp-content/themes/ateo/img/pin_marker2.png",
               null, /* size is determined at runtime */
               null, /* origin is 0,0 */
               null, /* anchor is bottom center of the scaled image */
               new google.maps.Size(42, 68)
            ); 
            marker.setIcon(pinIcon);

            var content_string = '<div id="gmap_info">'+
                                    '<div id="siteNotice">'+
                                    '</div>'+
                                    '<h3 id="firstHeading" class="firstHeading">'+place_title+'</h3>'+
                                    '<div id="bodyContent">'+
                                    '<p>'+place_address+'<br />'+place_city_zip+'</div>'+
                                 '</div>';

            var infowindow = new google.maps.InfoWindow({
               content: content_string
            });

            google.maps.event.addListener(marker, 'click', function() {
               infowindow.open(map, marker);
            });
         }

         google.maps.event.addDomListener(window, 'load', initialize);

      $( '#showLoading' ).click(function() {
      $( '#loadingsymbol' ).removeClass('hide');
      });

   }
   
   if($('body.category-blog').length < 1)
   {
      if($('body.home').length > 0)
      {
         $('#non_featured_places .line').shuffle();
      } else
      {
         if($('#places_list .line.featured').length > 1)
         {
            $('#places_list .line.featured').shuffle();
         }

         if($('#places_list .line:not(.featured)').length > 1)
         {
            $('#places_list .line:not(.featured)').shuffle();
         }
      }
   }
   /*
	  *
	  ########## ÆNDRET ##########
	  *
	 */
	if($('body.page-template-page-places-search-php').length > 0) {
		
	  var minseats = $('#filter_seats').val();
      //var minseats = seats_interval == 0 ? seats_interval : seats_interval[0];
	  var event_type_id = $('#filter_type').val();
      var region_id = $('#filter_region').val();
      filterPlaces(event_type_id, region_id, minseats);

	  
	  $('#places_list').find('.line:not(.hide)').each(function(i) {
      var lat = $(this).data('lat');
	  var lng = $(this).data('lng');
      var title = $(this).data('title');
      var zip = $(this).data('zip');
      var city = $(this).data('city');
      var slug = $(this).data('slug');
      
      placeMapMarker(search_map, lat, lng, title, city, zip, slug);
      });
	  	   
	  initSearchMap();
	  
	  initFilters();
	  }
	 
	
   if($('body.tax-event-type').length > 0 || $('body.page-template-page-places-landingpages-php').length > 0)
   {
      initSearchMap();
	  
	  $( "#places_list" ).load( places_file, function() {
               var minseats = $('#filter_seats').val();
               //var minseats = seats_interval == 0 ? seats_interval : seats_interval[0];
			   var event_type_id = $('#filter_type').val();
			   var region_id = $('#filter_region').val();
               filterPlaces(event_type_id, region_id, minseats);
	  });
	  
	  $('#places_list').find('.line:not(.hide)').each(function(i) {
      var lat = $(this).data('lat');
	  var lng = $(this).data('lng');
      var title = $(this).data('title');
      var zip = $(this).data('zip');
      var city = $(this).data('city');
      var slug = $(this).data('slug');
      
      placeMapMarker(search_map, lat, lng, title, city, zip, slug);
      });
	  
	  initFilters();
   }
});

function initFilters()
{
   $('#filter_type, #filter_region, #filter_seats').on('change', function(e) {
      var event_type_id = $('#filter_type').val();
      var region_id = $('#filter_region').val();
      var seats = $('#filter_seats').val();
      var sleeping = $('#filter_sleeping').is(':checked') ? 1 : 0;
      var kitchen = $('#filter_kitchen').is(':checked') ? 1 : 0;
      var handicap = $('#filter_handicap').is(':checked') ? 1 : 0;
      
      var seats_interval = seats == undefined || seats == 0 ? 0 : seats.split('-');
      var minseats = seats_interval == 0 ? seats_interval : seats_interval[0];

      filterSearchPlaces(event_type_id, region_id, minseats, sleeping, kitchen, handicap);
	  
      showFilteredPlacesOnMap(search_map, true);
   });
      
    var event_id_2 = parseInt($('#filter_type').val(),10);
	var region_id_2 = parseInt($('#filter_region').val(),10);	
	
   $('#filter_type, #filter_region').on('change', function(e) {
	  var temp_region_id_2 = region_id_2;
      var temp_region_id = parseInt($('#filter_region').val(),10);
	   
	  var temp_event_id_2 = event_id_2;
      var temp_event_id = parseInt($('#filter_type').val(),10);
      ///parse it to integer
      filterEventRegId(temp_event_id, event_id_2, temp_region_id, region_id_2);
   });
   
   $('#filter_sleeping, #filter_kitchen, #filter_handicap').on('click', function(e) {
      var event_type_id = $('#filter_type').val();
      var region_id = $('#filter_region').val();
      var seats = $('#filter_seats').val();
      var sleeping = $('#filter_sleeping').is(':checked') ? 1 : 0;
      var kitchen = $('#filter_kitchen').is(':checked') ? 1 : 0;
      var handicap = $('#filter_handicap').is(':checked') ? 1 : 0;
      
      var seats_interval = seats == undefined || seats == 0 ? 0 : seats.split('-');
      var minseats = seats_interval == 0 ? seats_interval : seats_interval[0];

      filterSearchPlaces(event_type_id, region_id, minseats, sleeping, kitchen, handicap);
      
      showFilteredPlacesOnMap(search_map, true);
   });
   
   $('#filter_best_top').on('click', function(e) {
      if($(this).is(':checked'))
      {
         search_default_list_html = $('#places_list').html();
         $('#places_list').find('.line').sort(function (a, b) {
            return Number($(b).data('rating')) - Number($(a).data('rating'));
         }).each(function (_, container) {
            $(container).parent().append(container);
         });
      } else {
         $('#places_list').html(search_default_list_html);
      }

   });
}

function placeMapMarker(search_map, lat, lng, title, city, zip, slug)
{
   var myLatlng = new google.maps.LatLng(lat, lng);

   var marker = new google.maps.Marker({
      position: myLatlng,
      map: search_map,
      clickable : true
   });
   
   var pinIcon = new google.maps.MarkerImage(
      "http://ateo.dk/wp-content/themes/ateo/img/pin_marker.png",
      null, /* size is determined at runtime */
      null, /* origin is 0,0 */
      null, /* anchor is bottom center of the scaled image */
      new google.maps.Size(15, 24)
   ); 
   marker.setIcon(pinIcon);
   
   search_map_markers.push(marker);

   var content_string = '<div id="gmap_info">'+
                           '<div id="siteNotice">'+
                           '</div>'+
                           '<h3 class="firstHeading">'+title+'</h3>'+
                           '<div id="bodyContent">'+
                           '<a href="http://ateo.dk/'+slug+'">Se sted</a>'+
                           '<p>'+zip+' '+city+'</p></div>'+
                        '</div>';

   var infowindow = new google.maps.InfoWindow({
      content: content_string
   });

   google.maps.event.addListener(marker, 'click', function() {
      infowindow.open(search_map, marker);
   });
}

function filterPlaces(event_type_id, region_id, min_seats)
{
   var $wrapper = $( "#places_list" );
   var $places = $wrapper.find('.place');
   var $mainCount = 0;
   
   for(var p = 0; p < $places.length; p++)
   {
      var featured = $($places.get(p)).data('featured');
      var place_regionid = $($places.get(p)).data('regionid');
      var place_regionids = null;
      if(place_regionid.toString().lastIndexOf(',') > -1)
      {
         var place_regionids = place_regionid.split(',');
      }

      var place_maxseats = $($places.get(p)).data('maxseats');
      var place_featured = $($places.get(p)).data('featured');

      var place_type_ids = new Array();
      if($($places.get(p)).data('types') !== '' && $($places.get(p)).data('types').toString().indexOf(',') > -1)
         place_type_ids = $($places.get(p)).data('types').split(',')
      else if ($($places.get(p)).data('types') !== '')
         place_type_ids.push($($places.get(p)).data('types').toString())

      if(($.inArray(event_type_id.toString(), place_type_ids) > -1 || event_type_id == 0) && (place_regionid == region_id || (place_regionids !== undefined && $.inArray(region_id.toString(), place_regionids) > -1) || region_id == 0) && (min_seats <= place_maxseats || min_seats == 0))
      {
         $($places.get(p)).removeClass('hide');
		 $mainCount ++;
      } else if($($places.get(p)).not('.hide'))
      {
         $($places.get(p)).addClass('hide');
      }
   }

   if ($mainCount > 0) {
	   var not_hide = document.getElementById("countingPlaces");
	   not_hide.className = not_hide.className - " countPlaceHide";
	   document.getElementById("countPlaces").innerHTML = $mainCount;
	   
	   var hide = document.getElementById("loadingCircle");
	   hide.className = hide.className + " countPlaceHide";

   $('#places_list').find('.line:not(.hide)').each(function(i) {
      var lat = $(this).data('lat');
	  var lng = $(this).data('lng');
      var title = $(this).data('title');
      var zip = $(this).data('zip');
      var city = $(this).data('city');
      var slug = $(this).data('slug');
      
      placeMapMarker(search_map, lat, lng, title, city, zip, slug);
	  });
	   
   }
   
//   $('#places_list').find('.line.hide').remove();
   
   $('#places_list .line.featured').shuffle();
   $('#places_list .line:not(.featured)').shuffle();
}

function filterSearchPlaces(event_type_id, region_id, min_seats, sleeping, kitchen, handicap)
{
   var $wrapper = $( "#places_list" );
   var $places = $wrapper.find('.place');
   var $mainCount = 0;
//   console.log(sleeping);
//   console.log(kitchen);
//   console.log(handicap);
   for(var p = 0; p < $places.length; p++)
   {
      var featured = $($places.get(p)).data('featured');
      var place_regionid = $($places.get(p)).data('regionid');
      var place_regionids = null;
      if(place_regionid.toString().lastIndexOf(',') > -1)
      {
         var place_regionids = place_regionid.split(',');
      }

      var place_maxseats = $($places.get(p)).data('maxseats');
      var place_featured = $($places.get(p)).data('featured');
      
      var place_sleeping = $($places.get(p)).data('sleeping');
      var place_kitchen = $($places.get(p)).data('kitchen');
      var place_handicap = $($places.get(p)).data('handicapfriendly');

      var place_type_ids = new Array();
      if($($places.get(p)).data('types') !== '' && $($places.get(p)).data('types').toString().indexOf(',') > -1)
         place_type_ids = $($places.get(p)).data('types').split(',')
      else if ($($places.get(p)).data('types') !== '')
         place_type_ids.push($($places.get(p)).data('types').toString())

      if((handicap == 0 || place_handicap == handicap) && (kitchen == 0 || place_kitchen == kitchen) && (sleeping == 0 || place_sleeping == sleeping) && ($.inArray(event_type_id.toString(), place_type_ids) > -1 || event_type_id == 0) && (place_regionid == region_id || (place_regionids !== undefined && $.inArray(region_id.toString(), place_regionids) > -1) || region_id == 0) && (min_seats <= place_maxseats || min_seats == 0))
      {
         $($places.get(p)).removeClass('hide');
		 $mainCount ++;
      } else if($($places.get(p)).not('.hide'))
      {
         $($places.get(p)).addClass('hide');
      }
   }
  
   document.getElementById("countPlaces").innerHTML = $mainCount;

//   $('#places_list').find('.line.hide').remove();
   
//   $('#places_list .line.featured').shuffle();
//   $('#places_list .line:not(.featured)').shuffle();

   if($('#places_list').find('.line:not(.hide)').length < 1)
   {
      $('.search_message').show();
      $('.places_list_view').hide();
   } else
   {
      $('.search_message').hide();
      $('.places_list_view').show();
   }
}

function filterEventRegId(temp_event_id, event_id_2, temp_region_id, region_id_2){
	
    if (temp_event_id == event_id_2 && temp_region_id == region_id_2)
       $('.showheadline').show();
    else
       $('.showheadline').hide();
}

function showFilteredPlacesOnMap(search_map, adjust)
{
   if(adjust)
   {
      for (var i = 0; i < search_map_markers.length; i++) {
         search_map_markers[i].setMap(null);
      }
   }
   
   $('#places_list').find('.line:not(.hide)').each(function(i) {
      var lat = $(this).data('lat');
	  var lng = $(this).data('lng');
      var title = $(this).data('title');
      var zip = $(this).data('zip');
      var city = $(this).data('city');
      var slug = $(this).data('slug');
      
      placeMapMarker(search_map, lat, lng, title, city, zip, slug);
   });

   if(adjust)
   {
      var myLatlng = new google.maps.LatLng($('#filter_region').find(':selected').data('lat'),$('#filter_region').find(':selected').data('lng'));
      
      var reg_id = $('#filter_region').find(':selected').val();
         
      zoomLevel = 6;

      switch(reg_id)
      {
         case '1':
         case '2':
         case '5':
            zoomLevel = 8;
         break;

         case '3':
         case '6':
         case '7':
         case '8':
         case '9':
            zoomLevel = 7;
         break;
      }
      
      search_map.setCenter(myLatlng);
      search_map.setZoom(zoomLevel);
   }
}

function initSearchMap()
{
   function initialize() {
      if($('#filter_region').find(':selected').length > 0)
      {
         var myLatlng = new google.maps.LatLng($('#filter_region').find(':selected').data('lat'),$('#filter_region').find(':selected').data('lng'));
         
         var reg_id = $('#filter_region').find(':selected').val();
         
         zoomLevel = 6;
         
         switch(reg_id)
         {
            case '1':
            case '2':
            case '5':
               zoomLevel = 8;
            break;
               
            case '3':
            case '6':
            case '7':
            case '8':
            case '9':
               zoomLevel = 7;
            break;
         }
      } else
      {
         var myLatlng = new google.maps.LatLng($('#filter_region').find('[value="0"]').data('lat'),$('#filter_region').find('[value="0"]').data('lng'));
         var zoomLevel = 6;
      }

      var mapOptions = {
         zoom: zoomLevel,
         center: myLatlng,
         mapTypeId: google.maps.MapTypeId.ROADMAP,
         mapTypeControl: false,
         zoomControl: true,
         zoomControlOptions: {
           style: google.maps.ZoomControlStyle.SMALL
         },
         streetViewControl: false
      };
      search_map = new google.maps.Map(document.getElementById('gmap'), mapOptions);

      showFilteredPlacesOnMap(search_map);
   }

   google.maps.event.addDomListener(window, 'load', initialize);
}

// Tabs til partner siden

    var tabLinks = new Array();
    var contentDivs = new Array();

function tabs(tabId) {
	
     // Grab the tab links and content divs from the page
      var tabListItems = document.getElementById(tabId).childNodes;
      var j = 0;
      for ( var i = 0; i < tabListItems.length; i++ ) {
        if ( tabListItems[i].nodeName == "LI" ) {
          var tabLink = getFirstChildWithTagName( tabListItems[i], 'A' );
          var id = getHash( tabLink.getAttribute('href') );
          
          tabLinks[id] = tabLink;
          contentDivs[id] = document.getElementById( id );
            
          tabLinks[id].onclick = showTab;
          tabLinks[id].onfocus = function() { this.blur() };
          
            if( j == 0){
              tabLinks[id].className = 'selected';
              contentDivs[id].className = 'tabContent';
          } else {
             contentDivs[id].className = 'tabContent hide';
          }
          j++;
        }
      }
    }
	
	function showTab() {
		
      var parentDiv = this.parentNode.parentNode.parentNode;
      var selectedId = getHash( this.getAttribute('href') );
	  
	  // Highlight the selected tab, and dim all others.
      // Also show the selected content div, and hide all others.
     
 
      for ( var i = 0; i < parentDiv.childNodes.length; i++ ) {
        if ( parentDiv.childNodes[i].nodeName == "DIV" ) {
              var id = parentDiv.childNodes[i].getAttribute('id');
              if ( id == selectedId ) {
                  tabLinks[id].className = 'selected';
                  contentDivs[id].className = 'tabContent';
              } else {
                  tabLinks[id].className = '';
                  contentDivs[id].className = 'tabContent hide';
              }
        }
      }

      // Stop the browser following the link
      return false;
    }

	function getFirstChildWithTagName( element, tagName ) {
      for ( var i = 0; i < element.childNodes.length; i++ ) {
        if ( element.childNodes[i].nodeName == tagName ) return element.childNodes[i];
      }
    }
	
	function getHash( url ) {
      var hashPos = url.lastIndexOf ( '#' );
      return url.substring( hashPos + 1 );
    }

function meetingroomInfo(roomId) {
	
	var i = true;
	
	$('#show_more' + roomId).click(function(){
		
		$('#more_room_info' + roomId).stop().slideToggle('slow');
		
		/* if (i == true) {
		   var not_hide = document.getElementById("trMeetingRoom");
		   not_hide.className = not_hide.className - "hide";
		   i = false;
		}
		else {
		   var not_hide = document.getElementById("trMeetingRoom");
		   not_hide.className = not_hide.className + "hide";
			
			i = true;			
		} */
		
		return false;
		
	});
}
	
function tooltip() {
	$(document).ready(function() {
// Tooltip only Text
$('.masterTooltip').hover(function(){
        // Hover over code
        var title = $(this).attr('title');
        $(this).data('tipText', title).removeAttr('title');
        $('<p class="tooltip"></p>')
        .text(title)
        .appendTo('body')
        .fadeIn('slow');
}, function() {
        // Hover out code
        $(this).attr('title', $(this).data('tipText'));
        $('.tooltip').remove();
}).mousemove(function(e) {
        var mousex = e.pageX + 20; //Get X coordinates
        var mousey = e.pageY + 10; //Get Y coordinates
        $('.tooltip')
        .css({ top: mousey, left: mousex })
});
});
}

function removeFromBasket(e)
{
   var trash_icon = $(e.target);
   var placeid = $(trash_icon).parent('.item').data('placeid');
   var item = $(trash_icon).parent('.item');

   // Add to session data
   var data = {
      action: 'removeItemFromBasket',
      placeid: placeid
   };

   $.ajax({
      type: 'post',
      url: MyAjax.ajaxurl,
      data: data,
      dataType: 'html',
      success: function (response, textStatus, jqXHR) {
         $(item).remove();
         $('#basket').find('input[type="hidden"][value="'+placeid+'"]').remove();

         if($('#basket').find('.item').length < 1)
         {
            $('#basket').find('.goto_checkout').hide();
            
            if($('.page-template-page-checkout-php').length < 1)
            {
               $('#basket').find('.basket_intro').show(); 
               $('.basket_info').hide();
            } else
            {
               $('#basket').find('.basket_intro').show(); 
               $('.basket_info').hide();
            }
         }
                  
         if($('.pick_btn.single_place').length > 0)
         {
            $('.pick_btn.single_place').removeClass('place_is_picked');
            $('.pick_btn.single_place').html('Få tilbud fra<span>'+$('.pick_btn.single_place').data('title')+'</span>');
         }
      },
      error: function (jqXHR, textStatus, errorThrown) {
      },
      complete: function(jqXHR, textStatus) {

      }
   });
}


var errors = 0;
function validateSignupForm(e)
{
   var $form = e.target ? $(e.target) : $(e.srcElement);

   /* VALIDATE ATTENDEE */
   var name = $form.find('[name="personname"]').val();
   if(!isName(name))
   {
      $form.find('[name="personname"]').addClass('error');
      $form.find('[name="personname"]').next('.error_msg').slideDown();
      errors++;
   } else if ($form.find('[name="personname"]').next('.error_msg').is(':visible'))
   {
      $form.find('[name="personname"]').next('.error_msg').slideUp();
   }

   var mail = $form.find('[name="mail"]').val();
   if(!isMail(mail) || mail === '')
   {
      $form.find('[name="mail"]').addClass('error');
      $form.find('[name="mail"]').next('.error_msg').slideDown();
      errors++;
   } else if ($form.find('[name="mail"]').next('.error_msg').is(':visible'))
   {
      $form.find('[name="mail"]').next('.error_msg').slideUp();
   }

//   var mobile = $form.find('[name="mobile"]').val();
//   if(!isPhone(mobile))
//   {
//      $form.find('[name="mobile"]').addClass('error');
//      $form.find('[name="mobile"]').next('.error_msg').css('visibility', 'visible');
//      errors++;
//   }

   // TODO: Validate values
   // TODO: Send ajax request
   if(errors < 1)
   {
      // No errors - submit form
      
   } else
   {
      // Errors, do nothing - error messages already visible to user
      e.preventDefault ? e.preventDefault() : e.returnValue = false;
   }
}

function addDefaultValueBehaviour()
{
   $('input[type="text"], textarea').each(function(i) {
      if($.trim($(this).val()) == '')
      {
         var defaultvalue = $(this).data('defaultvalue');
         $(this).val(defaultvalue);
      }
   });
   
   $('input[type="text"], textarea').off('focus', onInputFocus);
   $('input[type="text"], textarea').on('focus', onInputFocus);

   $('input[type="text"], textarea').off('blur', onInputBlur);
   $('input[type="text"], textarea').on('blur', onInputBlur);
}

function onInputFocus(e)
{
   var targetElm = e.target !== undefined ? $(e.target) : $(e.srcElement);
   var defaultvalue = $(targetElm).data('defaultvalue');
      
   if($.trim($(targetElm).val()) == defaultvalue)
   {
      $(targetElm).val('');
   }
}

function onInputBlur(e)
{
   var targetElm = e.target !== undefined ? $(e.target) : $(e.srcElement);

   if($.trim($(targetElm).val()) == '')
   {
      var defaultvalue = $(targetElm).data('defaultvalue');
      $(targetElm).val(defaultvalue);
   }
}

function isName(name)
{
   return /^[A-Za-zæøåÆØÅ\-\s]+$/.test(name);
}

function isMail(email)
{
   return /^[a-zA-ZæøåÆØÅ0-9\.\-\_]+@[a-zA-ZæøåÆØÅ0-9\-]+\.[a-zA-ZæøåÆØÅ0-9\-\.]+((\.[a-zA-ZæøåÆØÅ0-9\-\.])+)?$/.test(email);
}

function isPhone(phone)
{
   return /^\+?[0-9\-\s]+$/.test(phone);
}

function makeid()
{
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for( var i=0; i < 15; i++ )
        text += possible.charAt(Math.floor(Math.random() * possible.length));

    return text;
}

(function($){
 
    $.fn.shuffle = function() {
 
        var allElems = this.get(),
            getRandom = function(max) {
                return Math.floor(Math.random() * max);
            },
            shuffled = $.map(allElems, function(){
                var random = getRandom(allElems.length),
                    randEl = $(allElems[random]).clone(true)[0];
                allElems.splice(random, 1);
                return randEl;
           });
 
        this.each(function(i){
            $(this).replaceWith($(shuffled[i]));
        });
 
        return $(shuffled);
 
    };
 
})(jQuery);








/*!
 * jQuery Cookie Plugin v1.4.0
 * https://github.com/carhartl/jquery-cookie
 *
 * Copyright 2013 Klaus Hartl
 * Released under the MIT license
 */
(function (factory) {
	if (typeof define === 'function' && define.amd) {
		// AMD. Register as anonymous module.
		define(['jquery'], factory);
	} else {
		// Browser globals.
		factory(jQuery);
	}
}(function ($) {

	var pluses = /\+/g;

	function encode(s) {
		return config.raw ? s : encodeURIComponent(s);
	}

	function decode(s) {
		return config.raw ? s : decodeURIComponent(s);
	}

	function stringifyCookieValue(value) {
		return encode(config.json ? JSON.stringify(value) : String(value));
	}

	function parseCookieValue(s) {
		if (s.indexOf('"') === 0) {
			// This is a quoted cookie as according to RFC2068, unescape...
			s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\');
		}

		try {
			// Replace server-side written pluses with spaces.
			// If we can't decode the cookie, ignore it, it's unusable.
			s = decodeURIComponent(s.replace(pluses, ' '));
		} catch(e) {
			return;
		}

		try {
			// If we can't parse the cookie, ignore it, it's unusable.
			return config.json ? JSON.parse(s) : s;
		} catch(e) {}
	}

	function read(s, converter) {
		var value = config.raw ? s : parseCookieValue(s);
		return $.isFunction(converter) ? converter(value) : value;
	}

	var config = $.cookie = function (key, value, options) {

		// Write
		if (value !== undefined && !$.isFunction(value)) {
			options = $.extend({}, config.defaults, options);

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

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

		// Read

		var result = key ? undefined : {};

		// To prevent the for loop in the first place assign an empty array
		// in case there are no cookies at all. Also prevents odd result when
		// calling $.cookie().
		var cookies = document.cookie ? document.cookie.split('; ') : [];

		for (var i = 0, l = cookies.length; i < l; i++) {
			var parts = cookies[i].split('=');
			var name = decode(parts.shift());
			var cookie = parts.join('=');

			if (key && key === name) {
				// If second argument (value) is a function it's a converter...
				result = read(cookie, value);
				break;
			}

			// Prevent storing a cookie that we couldn't decode.
			if (!key && (cookie = read(cookie)) !== undefined) {
				result[name] = cookie;
			}
		}

		return result;
	};

	config.defaults = {};

	$.removeCookie = function (key, options) {
		if ($.cookie(key) === undefined) {
			return false;
		}

		// Must not alter options, thus extending a fresh object...
		$.cookie(key, '', $.extend({}, options, { expires: -1 }));
		return !$.cookie(key);
	};

}));

/**
 * Review Javascrip
 */
(function ($) {
    "use strict";
    $(function() {

      var facilities,catering,service,sleeping,location,valueformoney,total;

      function showTotal ( total ) {
         $('.total .star').removeClass('active').eq( Math.round( total ) - 1 ).prevAll().andSelf().addClass('active');
         $('.total .review-sum').html( total );
      }

      function updateTotal () {
         facilities = $('.facilities .active').length;
         catering = $('.catering .active').length;
         service = $('.service .active').length;
         sleeping = $('.sleeping .active').length;
         location = $('.location .active').length;
         valueformoney = $('.valueformoney .active').length;

         var divider = 0;
         total = 0;

         if ( facilities > 0 ) {
            total += facilities;
            divider++;
         };

         if ( catering > 0 ) {
            total += catering;
            divider++;
         };

         if ( service > 0 ) {
            total += service;
            divider++;
         };
         
         if ( sleeping > 0 ) {
            total += sleeping;
            divider++;
         };
         
         if ( location > 0 ) {
            total += location;
            divider++;
         };
         
         if ( valueformoney > 0 ) {
            total += valueformoney;
            divider++;
         };

         total = Math.round( ( total / divider ) * 2 ) / 2;
         $('.total input[name="total"]').val( total );
         showTotal( total );
      }
       

      $('.active-stars .star').on('mouseenter', function(e) {
         $(this).prevAll().andSelf().addClass('over');
      });

      $('.active-stars .star').on('mouseleave', function(e) {
         $(this).prevAll().andSelf().removeClass('over');
      });

      $('.active-stars .star').on('click', function(e) {
         $(this).prevAll().andSelf().removeClass('over').addClass('active');
         $(this).nextAll().removeClass('active');
         $(this).parent().next().val( $(this).index() + 1 );
         updateTotal();
      });

      $('#review-form').on('submit', function(e) {
         var proceed = true;

         var nameInput = $('input[name="name"]');
         nameInput.removeClass('error');
         if( nameInput.val() == '' || !isName( nameInput.val() ) ) {
            nameInput.addClass('error');
            proceed = false;
         }

         var emailInput = $('input[name="email"]');
         emailInput.removeClass('error');
         if( emailInput.val() == '' || !isMail( emailInput.val() ) ) {
            emailInput.addClass('error');
            proceed = false;
         }

         var textArea = $('textarea[name="comment"]');
         textArea.removeClass('error');
         if( textArea.val() == '' ) {
            textArea.addClass('error');
            proceed = false;
         }

         var totalInput = $('input[name="total"]');
         if( totalInput.val() == '' || totalInput == 0 ) {
            alert('Du skal afgive en vurdering i mindst 1 af de 6 muligheder');
            proceed = false;
         }



         if ( !proceed ) {
            e.preventDefault();
         };
      });

    });
}(jQuery));

/*! http://mths.be/placeholder v2.0.7 by @mathias */
;(function(window, document, $) {

   var isInputSupported = 'placeholder' in document.createElement('input');
   var isTextareaSupported = 'placeholder' in document.createElement('textarea');
   var prototype = $.fn;
   var valHooks = $.valHooks;
   var propHooks = $.propHooks;
   var hooks;
   var placeholder;

   if (isInputSupported && isTextareaSupported) {

      placeholder = prototype.placeholder = function() {
         return this;
      };

      placeholder.input = placeholder.textarea = true;

   } else {

      placeholder = prototype.placeholder = function() {
         var $this = this;
         $this
            .filter((isInputSupported ? 'textarea' : ':input') + '[placeholder]')
            .not('.placeholder')
            .bind({
               'focus.placeholder': clearPlaceholder,
               'blur.placeholder': setPlaceholder
            })
            .data('placeholder-enabled', true)
            .trigger('blur.placeholder');
         return $this;
      };

      placeholder.input = isInputSupported;
      placeholder.textarea = isTextareaSupported;

      hooks = {
         'get': function(element) {
            var $element = $(element);

            var $passwordInput = $element.data('placeholder-password');
            if ($passwordInput) {
               return $passwordInput[0].value;
            }

            return $element.data('placeholder-enabled') && $element.hasClass('placeholder') ? '' : element.value;
         },
         'set': function(element, value) {
            var $element = $(element);

            var $passwordInput = $element.data('placeholder-password');
            if ($passwordInput) {
               return $passwordInput[0].value = value;
            }

            if (!$element.data('placeholder-enabled')) {
               return element.value = value;
            }
            if (value == '') {
               element.value = value;
               // Issue #56: Setting the placeholder causes problems if the element continues to have focus.
               if (element != safeActiveElement()) {
                  // We can't use `triggerHandler` here because of dummy text/password inputs :(
                  setPlaceholder.call(element);
               }
            } else if ($element.hasClass('placeholder')) {
               clearPlaceholder.call(element, true, value) || (element.value = value);
            } else {
               element.value = value;
            }
            // `set` can not return `undefined`; see http://jsapi.info/jquery/1.7.1/val#L2363
            return $element;
         }
      };

      if (!isInputSupported) {
         valHooks.input = hooks;
         propHooks.value = hooks;
      }
      if (!isTextareaSupported) {
         valHooks.textarea = hooks;
         propHooks.value = hooks;
      }

      $(function() {
         // Look for forms
         $(document).delegate('form', 'submit.placeholder', function() {
            // Clear the placeholder values so they don't get submitted
            var $inputs = $('.placeholder', this).each(clearPlaceholder);
            setTimeout(function() {
               $inputs.each(setPlaceholder);
            }, 10);
         });
      });

      // Clear placeholder values upon page reload
      $(window).bind('beforeunload.placeholder', function() {
         $('.placeholder').each(function() {
            this.value = '';
         });
      });

   }

   function args(elem) {
      // Return an object of element attributes
      var newAttrs = {};
      var rinlinejQuery = /^jQuery\d+$/;
      $.each(elem.attributes, function(i, attr) {
         if (attr.specified && !rinlinejQuery.test(attr.name)) {
            newAttrs[attr.name] = attr.value;
         }
      });
      return newAttrs;
   }

   function clearPlaceholder(event, value) {
      var input = this;
      var $input = $(input);
      if (input.value == $input.attr('placeholder') && $input.hasClass('placeholder')) {
         if ($input.data('placeholder-password')) {
            $input = $input.hide().next().show().attr('id', $input.removeAttr('id').data('placeholder-id'));
            // If `clearPlaceholder` was called from `$.valHooks.input.set`
            if (event === true) {
               return $input[0].value = value;
            }
            $input.focus();
         } else {
            input.value = '';
            $input.removeClass('placeholder');
            input == safeActiveElement() && input.select();
         }
      }
   }

   function setPlaceholder() {
      var $replacement;
      var input = this;
      var $input = $(input);
      var id = this.id;
      if (input.value == '') {
         if (input.type == 'password') {
            if (!$input.data('placeholder-textinput')) {
               try {
                  $replacement = $input.clone().attr({ 'type': 'text' });
               } catch(e) {
                  $replacement = $('<input>').attr($.extend(args(this), { 'type': 'text' }));
               }
               $replacement
                  .removeAttr('name')
                  .data({
                     'placeholder-password': $input,
                     'placeholder-id': id
                  })
                  .bind('focus.placeholder', clearPlaceholder);
               $input
                  .data({
                     'placeholder-textinput': $replacement,
                     'placeholder-id': id
                  })
                  .before($replacement);
            }
            $input = $input.removeAttr('id').hide().prev().attr('id', id).show();
            // Note: `$input[0] != input` now!
         }
         $input.addClass('placeholder');
         $input[0].value = $input.attr('placeholder');
      } else {
         $input.removeClass('placeholder');
      }
   }

   function safeActiveElement() {
      // Avoid IE9 `document.activeElement` of death
      // https://github.com/mathiasbynens/jquery-placeholder/pull/99
      try {
         return document.activeElement;
      } catch (err) {}
   }

}(this, document, jQuery));
jQuery('input, textarea').placeholder();