$(document).ready(function() {

  // toggle default value
  $("#query").focus(function(){
    if ( $("#query").val() == "Enter keywords" ){
      $("#query").val("");
      $("#query").removeClass("light");
    }
  });

  $("#query").blur(function(){
    if ( $("#query").val() == "" ){
      $("#query").val("Enter keywords");
      $("#query").addClass("light");
    }
  });

	// purty sitemaps, UL needs an ID
	$("#sitemap > ul").attr("id", "sitemapUL");
													 
  // add a backgroud to packages content
  $('div.packages').html( '<div class="packagewrap">' +  $('div.packages').html() + '</div>');
	$('div.packages h2').each(function(){
		$(this).css("margin-top", "-165px").before('<div class="packagehead"></div>');
	});

  // formatting for left/right col pages
  $('.rightcol').after('<hr class="clr" />');

  // image captions
  $('.right, .left').each(function(){
    if ( $(this).attr("title") != "" ){
      $(this).wrap('<div class="'+$(this).attr("class")+'"></div>').removeClass();
      $(this).after('<div class="caption" style="max-width:'+$(this).attr("width")+'px">'+$(this).attr("title")+'</div>');
    }
  });

  // rounded corners on herobox images
  $('#herobox .mod_content:not(.hero-booking) img').each(function(){
    var parent = $(this).parent("a");
    parent.css("width", $(this).attr("width"))
      .css("height", $(this).attr("height"))
      .css("background-image", "url("+$(this).attr("src")+")")
      .css("display", "block");
    $(this).hide();
  });

  // herobox booking images
  $('#herobox .hero-booking img:gt(0)').each(function(){
    var parent = $(this).parent("a");
    parent.css("width", $(this).attr("width"))
      .css("height", $(this).attr("height")/2)
      .css("background-image", "url("+$(this).attr("src")+")")
      .css("display", "block");
    $(this).hide();
  });

  // lavalamp menu effect
  $("#nav ul").lavaLamp({
    fx: 'easeInOutExpo',
    speed: 700
  });
  
  /* Blockquotes */
  $("blockquote").each(function(){
    $(this).wrap('<div class="blockquote"></div>');
    $(this).after('<div class="blockquote-bottom"></div>');
  });
  
  $("#subnav").each(function(){
    $(this).wrap('<div class="subnav"></div>');
    $(this).after('<div class="subnav-bottom"></div>');
  });
  
  
  $(".ad-rotator").each(function(){
    $(this).wrap('<div class="ad-rotator-wrap"></div>');
  });

  // validate forms
  if ( $("#contact").length > 0 ) {
    $("#contact").validate();
  }
  if ( $("#enquiry").length > 0 ) {
    $("#enquiry").validate({
      errorPlacement: function(error, element) {
        error.appendTo( element.parent("li") );
      }
    });
  }
  
  // show/hide form fields
  $('#foundby').change(function(){
    if($(this).val()=="Other"){
      $('#otherdiv').show();
      $('#other').focus();
    } else {
      $('#otherdiv').hide();
    }
  });
  
  if ( $("#subnav").length > 0 ) {
    $("#subnav ul").superfish({ 
      animation: {opacity:'show',height:'show'}, 
      hoverClass:'sfHover', 
      delay : 700,
      speed: 'fast'
    });
  }
  
  // property detail page shennanigans
  if ($('#property-description').length > 0) {
    // If not logged in, start by hinding all tab panels. Only show those that have content
    if (typeof( window[ '_page_status' ] ) == "undefined"){
      $('#tab-container div[id$="-outer"]').hide();
    }
    $("#tab-container").prepend('<ul class="propdetailtablist">');
    if ($('#tab-specials .mod_content').children().size() > 0 || $('#tab-specials .specialitem').children().size() > 0) {
      $(".propdetailtablist").append('<li><a href="#tab-specials-outer">Specials</a></li>');
      $("#tab-specials-outer").show();
    }
    if ($('#tab-facilities .mod_content').children().size() > 0) {
      $(".propdetailtablist").append('<li><a href="#tab-facilities-outer">Facilities</a></li>');
      $('#tab-facilities .mod_content').append('<hr class="clr" />');
      $("#tab-facilities-outer").show();
    }
    if ($('#tab-rates .rate-data ').children().size() > 0) {
      $(".propdetailtablist").append('<li><a href="#tab-rates-outer">Rates</a></li>');
      if (typeof(window['pageid']) != "undefined" && pageid > 0) {
        $('#tab-rates').prepend('<a href="http://absolutealpine.amplify.com.au/rates/' + pageid + '" class="extlink">Link to this rate data</a>');
      }
      /*if ( $('#tab-rates h2').size() == 0 ) {
        $('#tab-rates').prepend("<h2>2010 Rates</h2>");
      }*/
      $("#tab-rates-outer").show();
    }
    
    if ($('#tab-gallery .mod_gallery').children().size() > 0) {
      $(".propdetailtablist").append('<li><a href="#tab-gallery-outer">Gallery</a></li>');
      $("#tab-gallery-outer").show();
    }
    if ($('#tab-map .gmap').children().size() > 0) {
      $(".propdetailtablist").append('<li><a href="#tab-map-outer">Map</a></li>');
      $("#tab-map-outer").show();
    }
    if ($('#tab-conditions .mod_content').children().size() > 0) {
      $(".propdetailtablist").append('<li><a href="#tab-conditions-outer">Conditions</a></li>');
      $("#tab-conditions-outer").show();
    }
  }
  
  // tabbed content
  if ( $("#tab-container").length > 0 ) {
    /*var status = "off";
    if (window.location.toString().indexOf('=')>-1)
      status = window.location.toString().substr(window.location.toString().indexOf('=') + 1);*/
    if (typeof( window[ '_page_status' ] ) == "undefined"){
      showTabbed();
    } else {
      /*$('.tabswitcher').live('click', function(){
        var url = window.location.toString();
        var anchor = location.hash;
        // if there is a hash we need to do some fernangling
        if (anchor.length>0){
          url = url.substr(0, url.indexOf('#'));
        }
        if (url.indexOf('=')>0) {
          // strip off the status and add the opposite
          url = url.substr(0, url.indexOf('=')+1);
          url += status=="on" ? "off":"on";
        } else {
          url = url + "?tab=on";
        }
        // add in the hash if there is one
        if (anchor.length>0){
          url = url + '#' + anchor;
        }
        location.href = url;
      });
      // add tab switcher link
      $('#tab-container').prepend('<div class="tabswitcher">Toggle tabbed content display</div>');*/
      // modify the styles of the tab containers to give them layout
      if ($('.propdetailtablist').length > 0 || $('#property-description').length > 0) {
        $("#tab-container > div > div").each(function(j){
          var tabname = $(this).attr('id');
          tabname = tabname.substring(4, tabname.length);
          $(this).addClass("shitbox").prepend('<p class="shitboxtop">' + tabname + '</p>');
        });
      }
      else {
        $("#tab-container > div[class!=tabswitcher]").each(function(j){
          // convert the tab id to text
          var tabname;
          var tabid = $(this).attr('id');
          switch(tabid){
            case 'tab1':
              tabname = 'Facts';
              break;
            case 'tab2':
              tabname = 'Facilites';
              break;
             case 'tab3':
              tabname = 'Activities';
              break;
             case 'tab4':
              tabname = 'Bars & Restaurants';
              break;
             case 'tab5':
              tabname = 'Gallery';
              break;
           }
          $(this).addClass("shitbox").prepend('<p class="shitboxtop">' + tabname + '</p>');
        });
      }
    }
  }
  
  // homepage hero content edit icons
  if ($("#herobox").length > 0 && typeof(window['pageid']) != "undefined" && pageid > 0) {
    $(window).load(function(){
        // modify the editor button positions
        var dividarr = [];
        $(".herobox-wrap div.herobox").each(function(j){
          dividarr[j] = $(this).attr("id");
        });
        // get the starting control position
        var off = $("#nav ul li").eq(1).offset();
        // loop through the divids and shift their offset
        var lplus = 100;
        var tplus = 40;
        for (var i = 0; i < dividarr.length; i++) {
          $("#" + dividarr[i] + "_ctrl").css({
            left: (off.left - 80 + ((i + 1) * lplus) + 'px'),
            top: (off.top + (1 * tplus) + 'px')
          });
        }
   });
  }
  
  // webcam gallery images
  if ($(".webcam-images-list").length > 0 && jQuery.trim($('.webcam-images-list').text()).length > 0 ) {
    var thetext = $('.webcam-images-list').text();
    if (thetext.indexOf("EMPTY WEBCAM IMAGES")== -1){
      $('.webcam-images-list a').lightBox({fixedNavigation:true});
    }
  }
  
  // property listing filters
  // hide the filters div on page load
  if($('.filters').length>0)
    $('.filters').hide();
  $('.proplisttabs > li').click(function(){
    $('.proplisttabs li, .filters li').removeClass('active');
    $('.filters').hide();
    $(this).addClass('active');
    var filter = $(this).attr('rel');
    if(filter=='all'){
      $('.listing > li').show('1000');
    } else {
      $('.listing > li').show().not('.'+filter).hide('1000');
      if(filter=="selfcontained")
        $('.filters').show();
    }
    
  });
  $('.filters li').click(function(){
    $('.filters li, .showall').removeClass('active');
    $(this).addClass('active');
    var filter = $(this).attr('rel');
    $('.listing > li').show().not('.'+filter+'.selfcontained').hide('1000');
  });
  
  $('.showall').click(function(){
    $('.filters li').removeClass('active');
    $(this).addClass('active');
    $('.listing > li.selfcontained').show('1000');
  });
  
  function showTabbed() {
    var anchor = document.location.hash;
      $("#tab-container").tabs();
      if (anchor.indexOf("#specialitem")>-1){
        $('#tab-container').tabs('select', $(anchor).parent().parent().attr("id"));
      }
        
      $('#tab-container').bind('tabsshow', function(event, ui) {
        if (ui.panel.id == "tab-map-outer") {
          google.maps.event.trigger(map, 'resize');
          map.setCenter(marker.getPosition());
        }
      });
      // hide empty tab links on resort pages
      var l = $("#tab-container").tabs('length');
      for(l;l>=0;l--){
        var t = "#tab" + (l+1);
        if($(t).length > 0 && ($(t + ' div ul').length == 0 || jQuery.trim($(t + ' div').html()).length == 0 )){
          $("#tab-container").tabs('remove',l);
        }
      }
      
      $('.extlink').hide();
      // line up the tabs edit icons
      $(window).load(function(){
        if (typeof(window['pageid']) != "undefined" && pageid > 0) {
          // modify the editor buttons so they don't show
          var dividarr = [];
          if ($('.propdetailtablist').length > 0 || $('#property-description').length > 0) {
            $("#tab-container div div div").each(function(j){
              dividarr[j] = $(this).attr("id");
            });
          }
          else {
            $("#tab-container div div").each(function(j){
              dividarr[j] = $(this).attr("id");
            });
          }
          // loop through the divids and shift their offset
          for (var i = 0; i < dividarr.length; i++) {
            $("#" + dividarr[i] + "_ctrl").css({
              display: "none"
            });
          }
        }
      });
  }

  // property listing filters
  $('.actionbuttons li a').click(function(){
    // hijack the parent forms action path and submit
    var action = $(this).attr('href');
    $(this).parents('form').attr('action', action).submit();
    return false;
  });
  
  if($('#datepicker').length > 0){
    $('#datepicker').datepicker({
      showOn: 'both',
      buttonImage: '/site/images/calendar.gif',
      buttonImageOnly: true,
      minDate: '+1', 
      maxDate: '+1Y +6M',
      dateFormat: 'dd/mm/yy'
    });
  }
  
  if($('.datepicker').length > 0){
    $('.datepicker').datepicker({
      showOn: 'both',
      buttonImage: '/site/images/calendar.gif',
      buttonImageOnly: true,
      dateFormat: 'yy-mm-dd'
    });
  }
  
  /* stripe those rows */
  $('.events-list li:even, .events-admin li:even').addClass('alt');
  $('.rate-data td').removeClass();
  
  $('.rate-data tr td:nth-child(odd)').addClass('odd');
  $('.rate-data tr td:nth-child(even)').addClass('even');
  
  /* convert all document links to new window and add relevant icon */
  $("a[href*=.pdf], a[href*=.doc]").each(function() {
    $(this).addClass("application-"+ $(this).attr('href').substr($(this).attr('href').length-3))
    .append("<span></span>");
  });
	
});

/* 

	Sitemap Styler v0.1
	written by Alen Grakalic, provided by Css Globe (cssglobe.com)
	visit http://cssglobe.com/lab/sitemap_styler/
	
*/
/* 

	Sitemap Styler v0.1
	written by Alen Grakalic, provided by Css Globe (cssglobe.com)
	visit http://cssglobe.com/lab/sitemap_styler/
	
*/

this.sitemapstyler = function(){
	var sitemap = document.getElementById("sitemapUL")
	if(sitemap){
		
		this.listItem = function(li){
			if(li.getElementsByTagName("ul").length > 0){
				var ul = li.getElementsByTagName("ul")[0];
				ul.style.display = "none";
				var span = document.createElement("span");
				span.className = "collapsed";
				span.onclick = function(){
					ul.style.display = (ul.style.display == "none") ? "block" : "none";
					this.className = (ul.style.display == "none") ? "collapsed" : "expanded";
				};
				li.appendChild(span);
			};
		};
		
		var items = sitemap.getElementsByTagName("li");
		for(var i=0;i<items.length;i++){
			listItem(items[i]);
		};
		
	};	
};

window.onload = sitemapstyler;
	
