$(document).ready(function() {

   // callback function for fancybox
   // maphighlight refuses to show the image in IE7-9 if the container is initially hidden as it is with fancybox. So activate the maphighlifht AFTER fancybox is activated (shown).
   function activateMapHilight() {
      $('#hoverMap').maphilight({fillColor: 'cfff00', fillOpacity: '1', strokeWidth: '2', strokeOpacity: '.5', strokeColor: '666666'});
   }


   $('#mainPageMapNav').slideDown(2000).prependTo('#bodyInnerWrap');

   if( $('.mapNavTrigger').length)
      $('.mapNavTrigger').fancybox({
         'padding' : 10,
         'overlayOpacity' : .8,
         'overlayColor' : '#ccc',
         'centerOnScroll' : 'yes',
         'scrolling' : 'no',
         'autoDimensions' : false,
         'width' : 650,
         'height' : 381,
         'transitionIn' : 'fade',
         'speedIn' : 500,
         'onComplete' : activateMapHilight,
         'transitionOut' : 'fade'
      }); 



   if($('a.galleryItem').length)
      $("a.galleryItem").fancybox();


   $('.listingDesc').hide();

   $('.uploadImage').click(function() {
      $("form:first").submit();
      $('.indicator').show();
   });


   // remove "New Zealand" from B&Bs list on homepage
   var spanItem = $('.regionContainer>p>a>span');
   spanItem.each(function() {
      var spanText = $(this).text().replace(/New Zealand /g, '');
      $(this).text(spanText);
   });

   
   // character counter setup
   if($('#listingDescriptionsForm').length)
   {
      $( '[name="description"]' ).charCount({
         allowed: 1500,
         warning: 100,
         counterElement: 'span class="charCounter"',
         counterText: 'Remaining characters: '
      });

      $( '[name="short_description"]' ).charCount({
         allowed: 300,
         warning: 50,
         counterElement: 'span class="charCounter"',
         counterText: 'Remaining characters: '
      });

      $( '[name="location"]' ).charCount({
         allowed: 60,
         warning: 20,
         counterElement: 'span class="charCounter"',
         counterText: 'Remaining characters: '
      });
      $( '[name="directions"]' ).charCount({
         allowed: 150,
         warning: 30,
         counterElement: 'span class="charCounter"',
         counterText: 'Remaining characters: '
      });
   };
   





   if($('.tipTip').length )
   {
      $(function(){
         $(".tipTip").tipTip({activation:"focus",maxWidth:"280px",defaultPosition:"top",delay:100});
      });   
   }

   



   if($('#listingNames').length )
   {
      $('#listingNames').change(function() {
          $(this).closest("form").submit();
      });      
   }
   
   
   
   
   
   // main page hover maps
   if($('#hoverMap').length )
      $('#hoverMap').maphilight({fillColor: 'cfff00', fillOpacity: '1', strokeWidth: '2', strokeOpacity: '.5', strokeColor: '666666'});
      
   
   if($('#wantToExplore').length )
      $(function() {
         $('area').mouseover(function(e) {
            var thisarea = $(this).attr('class');
            $('#regionInfo div').css('display', 'none');
            $('#regionInfo div.info'+thisarea).css('display', 'block');
            $('#wantToGo li a.'+thisarea).css('background-color', '#cfff00');
         }).mouseout(function(e) {
            var thisarea = $(this).attr('class');
            $('#regionInfo div').css('display', 'none');
            $('#regionInfo div.infoNewZealand').css('display', 'block');
            $('#wantToGo li a.'+thisarea).css('background', 'none');
         });
      });

   if($('#wantToGo').length )
      $(function() {
         $('#wantToGo ul li a').mouseover(function(e) {
            var thisarea = $(this).attr('class');
            $('area.'+thisarea).mouseover();
            $('#regionInfo div').css('display', 'none');
            $('#regionInfo div.info'+thisarea).css('display', 'block');
         }).mouseout(function(e) {
            var thisarea = $(this).attr('class');
            $('area.'+thisarea).mouseout();
            $('#regionInfo div').css('display', 'none');
            $('#regionInfo div.infoNewZealand').css('display', 'block');
         });
      });
   
   
   
   
   
   if($('#datepicker').length )
      $(function() {
         $("#datepicker").datepicker();
      });
  
  
  

/*
     if($('#placepicker').length )
      $( function () {
        // Initialize Google Map
        var map = new google.maps.Map( $( '#map-canvas' )[0], {
          zoom: 4,
          center: new google.maps.LatLng( -41.2924945, 174.7732353 ),
          mapTypeId: google.maps.MapTypeId.ROADMAP
        } );
        
        var pp = $( '#placepicker' ).placepicker( {
          map: map,
          
          // Form parameter is a jQuery object that has named fields for the
          // location info to be saved in (normally hidden)
          form: $( 'form' ),
         
         // Clickable lets you click places on the map
         clickable: true
        } );
      } );
*/




   $("#imageUploadForm :submit").css("display", "none");
   $('#imageFile').change(function(){
      $("#imageUploadForm :submit").css("display", "block");
   });



   $('.regionContainer').addClass('shrunk');
   $('.regionContainer').removeClass('zoomed');

   $('.regionContainer > p' ).hide();
   $('.regionHeading span').hide();
   $('.regionContainer .regionHeading div').mouseover().css( "cursor", "pointer" );

   $('.regionContainer .regionHeading div').mousedown( function() {
      var thisParent = $(this).parent();
      var thisGrParent = $(this).parent().parent();

      if( $(thisGrParent).hasClass('zoomed') ) // already expanded, so retract
      {
         $('span', thisParent).hide();
         $('> p', thisGrParent).hide('slow');
         $(thisGrParent).removeClass('zoomed');
         $(thisGrParent).addClass('shrunk');
      }
      else // not already expanded, so retract all and expand this
      {
         $('.regionContainer > p').hide('slow');
         $('.regionContainer').removeClass('zoomed');
         $('.regionContainer').addClass('shrunk');

         $('p>a>span', thisGrParent).css('display', 'inline');
         $('p', thisGrParent).show('slow');
         $(thisGrParent).removeClass('shrunk');
         $(thisGrParent).addClass('zoomed');
      }
   });






   $("#mapForm :submit").css("display", "none");
   
   function watchGpsInputBoxes() {
      if ($('#lat').val() != $originalLat || $('#lng').val() != $originalLng) {
          $('#mapForm').submit();
      }
    }
    
   $originalLat = $('#lat').val();
   $originalLng = $('#lng').val();
   setInterval(watchGpsInputBoxes, 100);





   // hover for .bigMenu
   // on mouseover
   $(function() {
      $(".bigMenu li a").css("opacity","1.0");
      $(".bigMenu li a").hover(function () {
         $(this).stop().animate({
            opacity: 0.7
         }, "fast");
      },
      // on mouseout
      function () {
         $(this).stop().animate({
            opacity: 1.0
         }, "fast");
      });
   });






   $(".flashNotice").show("fast")
/*
   $(function() {
       // setTimeout() function will be fired after page is loaded
       // it will wait for 5 sec. and then will fire
       // $("#successMessage").hide() function
       setTimeout(function() {
           $(".flashNotice").hide("slow")
       }, 10000);
   });
*/




   // get GET params
   function getQueryParams(qs) {
       qs = qs.split("+").join(" ");
       var params = {},
           tokens,
           re = /[?&]?([^=]+)=([^&]*)/g;
       while (tokens = re.exec(qs)) {
           params[decodeURIComponent(tokens[1])]
               = decodeURIComponent(tokens[2]);
       }
       return params;
   }

   




   $(function() {
      if($('#sortableImageList').length ) {
         var $_GET = getQueryParams(document.location.search);
         var lid = $_GET["lid"];
         $( "#sortableImageList" ).sortable({
            update : function () {
               serial = "image[]=" + lid + "&" + $('#sortableImageList').sortable('serialize')  // add listing id number as first image
               $.ajax({
                  url: "index.php?id=1073",
                  type: "post",
                  data: serial,
                  error: function(){
                     alert("theres an error with AJAX");
                  }
               });
            }
         });
      }
   });

   

/*
   if ( $('.mapcontent').length )
      $(".mapcontent").fancybox({ 
         'frameWidth': 600, 'frameHeight': 360,
         'hideOnContentClick': false,
         'callbackOnClose': function() {
            $("#fancy_content").empty();
         } 
     });





   
   if ( $("a#inline").length )
      $("a#inline").fancybox({
      'hideOnContentClick': true,
      'overlayOpacity'    : "0.9",
      'overlayColor'      : "#2f3d14",
      'autoDimensions'    : false,
      'width'             : '600'  
   });

*/


   if($('#map_1').length)
   {
      var mapOptions = {
         mapTypeId: google.maps.MapTypeId.ROADMAP,
         scrollwheel: false
      };
      $("#map_1").mosne_map({
         map_opt:mapOptions,
         elements:'#map_1_list .maplocation',
         marker_icon: 'assets/img/icons/gmapBB.png',
         infowindows: false,
         infobox: true,       
         cluster_styles: {
            zoomOnClick: true,
            maxZoom: 12,
            gridSize: 20
         }
       });
   };


});

