// * Cookie plugin Copyright (c) 2006 Klaus Hartl (stilbuero.de)
jQuery.cookie=function(name,value,options){if(typeof value!='undefined'){options=options||{};if(value===null){value='';options.expires=-1;}
var expires='';if(options.expires&&(typeof options.expires=='number'||options.expires.toUTCString)){var date;if(typeof options.expires=='number'){date=new Date();date.setTime(date.getTime()+(options.expires*24*60*60*1000));}else{date=options.expires;}
expires='; expires='+date.toUTCString();}
var path=options.path?'; path='+(options.path):'';var domain=options.domain?'; domain='+(options.domain):'';var secure=options.secure?'; secure':'';document.cookie=[name,'=',encodeURIComponent(value),expires,path,domain,secure].join('');}else{var cookieValue=null;if(document.cookie&&document.cookie!=''){var cookies=document.cookie.split(';');for(var i=0;i<cookies.length;i++){var cookie=jQuery.trim(cookies[i]);if(cookie.substring(0,name.length+1)==(name+'=')){cookieValue=decodeURIComponent(cookie.substring(name.length+1));break;}}}
return cookieValue;}};

/*
  JQuery stickySelect

  Maintains select options between page loads using client-side cookie.
  * Requires the above cookie plugin
  * select.id used as the cookie key

*/

function attachPageEventsAffectedByAjax($) {


  // modify lists with more than X item with "and X more"
  $("#secondary ul#facet_place").each(function(){
    var $list = $(this);
    var $children = $list.find("li");
    var numChildren = $children.length;

    if (numChildren > 10) {
      var numExtra = numChildren - 10;
      var $extra = $("<ul/>").attr("class", "showMore");
      $extra.append("<p>And " + numExtra.toString() + " more. <a href='#'>Show All</a></p>");
      $extra.insertAfter($(this));
      for (item = 10; item < numChildren; item++ ) {
        $($children[item]).addClass("extra")
        $extra.append($children[item] );
      }
      $extra.find("p a").click(function(){
        $("#facet_place").append($(this).closest("ul").find("li"));
        $("#facet_place li.extra").slideToggle();
        $(this).closest("ul").remove();
        return false;
      });
      $extra.find("li").hide();
    }    
  });

  
  $('#metaTrigger').click(function() {
    $("#metaeditor").slideToggle("normal");
    return false;
  });
  
  $('h4 a.facet_trigger').click(function(){
    var facet_container_id = this.id.replace('_trigger_','_');
    $("#"+facet_container_id).slideToggle("normal");
    $.cookie(facet_container_id,$('#'+facet_container_id).is(':hidden').length > 0);
    var images = this.getElementsByTagName('img');
    for (var i=0; i < images.length; i++) {
      if (images[i].src.match('arrow_expanded')) {
        images[i].src = images[i].src.replace('arrow_expanded','arrow_collapsed');
      } else {
        images[i].src = images[i].src.replace('arrow_collapsed','arrow_expanded');
      }
      return false;
    }
  });

  $('#facet_trigger_region').click(function(){
    var facet_container_id = this.id.replace('_trigger_','_');
    if ($('#'+facet_container_id).children('li.other').length) {
      $('#'+facet_container_id).children('li.other').slideToggle("normal");
      $.cookie(facet_container_id,$('#'+facet_container_id).is(':hidden').length > 0);
      var images = this.getElementsByTagName('img');
      for (var i=0; i < images.length; i++) {
        if (images[i].src.match('arrow_expanded')) {
          images[i].src = images[i].src.replace('arrow_expanded','arrow_collapsed');
        } else {
          images[i].src = images[i].src.replace('arrow_collapsed','arrow_expanded');
        }
      }
      return false;
    }
  });

  $('h4 a.begin_closed').each(function(){
    var facet_container_id = this.id.replace('_trigger_','_');
    if ($('#'+facet_container_id).children('li.other').length) {
      $('#'+facet_container_id).children('li.other').css("display","none");
      var images = this.getElementsByTagName('img');
      for (var i=0; i < images.length; i++) {
        if (images[i].src.match('arrow_expanded')) {
          images[i].src = images[i].src.replace('arrow_expanded','arrow_collapsed');
        } else {
          images[i].src = images[i].src.replace('arrow_collapsed','arrow_expanded');
        }
      }
    }
  });

  $('#region_facet').children('li.other').hide();

  // Maps & Tabs
  if (typeof($('.ui_tabs').tabs) == 'function') {
    var opts = {
      show: function(ui) {
        $.cookie('selected_tab', LINE.ui_tabs.data('selected.tabs'));
        if (LINE.maps && document.getElementById('map_tab')) {
          LINE.maps.setup();
        }
      }
    }
    var selected_tab = $.cookie('selected_tab')
    if (selected_tab != null) {
      opts.selected = selected_tab;
    }
    opts.selected = window.defaultTab || 0;
    //console.log("tab options: ", opts)
    LINE.ui_tabs = $('.ui_tabs').tabs(opts);
    // Change pagination when tab selected
    $(".ui_tabs").bind("tabsselect", function(event, ui) {
        var tabElement = ui.tab;
        var tabName = tabElement.toString().split('#').pop();
        changePaginationFragment("#" + tabName);
        setDefaultTab(tabName);
    });
  }

  // Check page's URL fragment part, change pagination links if needed
  var pageUrlSegments = window.location.href.split("#");
  if (pageUrlSegments.length > 1) {
      var newFragment = "#" + pageUrlSegments.pop();
      changePaginationFragment(newFragment);
  }

  if (LINE.maps && document.getElementById('map_tab')) {
    LINE.maps.setup();
  }

  // tabs - only show once page loaded

  $('.ui_tabs').show();

  // IF THE MAP TAB EXISTS
  if (LINE.maps && document.getElementById('map_tab')) {
    // GET THE CENTER
    var center = LINE.maps.map.getCenter();
    // ZOOM AND CENTER WHEN MAP TAB IS SELECTED
    $('.ui_tabs').bind('tabsshow', function(event, ui) {
      if(ui.panel.id == 'map_tab') {
        LINE.maps.map.checkResize();
        var zoomlevel = LINE.maps.map.getBoundsZoomLevel(LINE.maps.bounds);
        if (zoomlevel > LINE.maps.constants.maxZoomLevel) {
            zoomlevel = LINE.maps.constants.maxZoomLevel;
        }
        LINE.maps.map.setCenter(center, zoomlevel);
      }
    });
  }


  applyStats();
}

;(function($) {
	$.fn.stickySelect = function() {
    if (typeof($.cookie == 'function')) {
      this.each(function() {
        if (this.id) {
          var cookie = $.cookie('stickySelect_'+this.id);
          if (cookie != null) {
            var options = this.getElementsByTagName('option');
            for (var i=0; i < options.length; i++) {
              if (options[i].value == cookie) {
                this.selectedIndex = i;
              }
            }
          }
          $(this).change(function(ev) {
            $.cookie('stickySelect_'+ev.target.id,ev.target.value);
          });
        }
      });
    } else {
      console.log("Requires Cookie plugin");
    }
  }
})(jQuery);

if (LINE == null) {
  var LINE = {};
}

$(document).ready(function(){

  attachPageEventsAffectedByAjax($);

  // Favourites
  $('#favouritesTrigger').click(function() {
    $("#favourites").slideToggle("normal");
  });
  if ($('#favouritesTrigger').css('display') != 'none') {
    window.setTimeout("$('#favourites').hide('normal')",2000);
  }
 
      
      // favorites tooltip
      // dont show in ie<=6
      if ($.browser.msie && $.browser.version.substr(0,1)<7) {} else {

        $("button#faves_add, button#faves_rem").qtip({
          position: {
            corner: {
              target: 'bottomMiddle',
              tooltip: 'topLeft'
            }
          },
          content: 'Save your favourite places and send a copy of the links by email to share with friends. Click on the \'My Favourites\' tab at the top of every page to quickly view them again or to send them by email',
          style: { 
              width: 200,
              padding: 10,
              background: '#ffffff',
              color: '#394A75',
              textAlign: 'left',
              border: {
                 width: 1,
                 radius: 5,
                 color: '#394A75'
              },
              tip: {
                corner:'topLeft'
              }
             //name: 'light' // Inherit the rest of the attributes from the preset light style
           }
      });
        
      }

      
    

  // Image Maps
  if (swfobject == null || !swfobject.hasFlashPlayerVersion("9.0.0")) {
    $('#imagemap area').mouseover(function() {
      if (this.overlay == null) {
        this.overlay = document.getElementById('imagemap_image_overlay');
      }
      if (this.image == null) {
        this.image = document.createElement('img');
        this.image.src = '/images/map/'+this.id+'.gif';
      }
      this.overlay.src = this.image.src;
    });
    $('#imagemap area').mouseout(function() {
      if (this.overlay == null) {
        this.overlay = document.getElementById('imagemap_image_overlay');
      }
      this.overlay.src = this.overlay.original_src;
    });
    $('#imagemap area').each(function() {
      this.overlay = document.getElementById('imagemap_image_overlay');
      this.overlay.original_src = this.overlay.src;
      this.image = document.createElement('img');
      this.image.src = '/images/map/'+this.id+'.gif';
    });
    // Image Maps Pre-load
    $('#imagemap_image').mouseout(function() {
      this.image.src = '/images/map/blank.gif';
    });
  } else {
    $('#imagemap_image').css('display','none');
    $('#imagemap_image_overlay').css('display','none');
  }

  $('#rgn_select').change(function(){
    window.location = this.value;
    // console.log(this.value);
  });

  $('#favourites .check_remove').click(function(){
    var checkbox = document.getElementById(this.id.replace('link_','remove_'));
    checkbox.checked = true;
    checkbox.form.submit();
  });

  
  // $('h4 a.facet_trigger').each(function(){
  //   var facet_container_id = this.id.replace('_trigger_','_');
  //   var cookie;
  //   if (cookie = $.cookie(facet_container_id)) {
  //     $("#"+facet_container_id).hide();
  //   }
  // });

  

  // Carousel
  if (typeof($('.carousel').jCarouselLite) == 'function') {
    $(".carousel").jCarouselLite({
        btnNext: ".carousel_next",
        btnPrev: ".carousel_prev",
        scroll: 3,
        speed: 600,
        visible: 4
    });
  }

  // Sticky Selects
  if (typeof($("select.sticky").stickySelect) == 'function') {
    $("select.sticky").stickySelect();
  }

  

  $('A[rel="popup"]').click( function() {
	  window.open( $(this).attr('href') + "?popup=1", "popup", "status=0,toolbar=0,width=600,height=400,scrollbars=1" );
	  return false;
	   
  });
  
  $('A.useofferbtn').click( function() {
	  window.open( $(this).attr('href'), "Use Offer", "status=0,toolbar=0,width=1000,height=600,scrollbars=1" );
	  return false;
  });


  $('A[rel="submit"]').click( function() {
	  $(this).parents("form")[0].submit(); 
	  return false;
  });

  $('li.headlink').hover(
			function() { $('ul', this).css('display', 'block'); },
			function() { $('ul', this).css('display', 'none'); }
  );

	var hostname = window.location.hostname;
	
	hostname = hostname.replace('www.', '').toLowerCase();

	var hostnames = [hostname, 'welcometoscotland.com', 'willkommeninschottland.com', 'bienvenueenecosse.com'];

	$('a').each(function() {
		
		var obj = $(this);
		if (obj.attr('href')) {
			var href = obj.attr('href').toLowerCase();
			if (href.indexOf('http://')!= -1) {
				var valid = false;
				for (i in hostnames) {
					if (href.indexOf(hostnames[i]) != -1) {
						valid = true;
					}
				}
				if (!valid) obj.attr('target', '_blank');
			}
		}
	});

  
  $('.datetime').each(function() {
    $(this).datetimepicker({
      dateFormat: 'yyyy-mm-dd HH:MM'
    });
  });
});



function setDefaultTab(tabName) {
  window.defaultTab = tabName === 'map_tab' ? 1 : 0;
  // console.log("changed default tab to: ", window.defaultTab)  
}


function changePaginationFragment(tabFragment) {
    $(".pagination > li > a").each(function(){
        // Remove previous fragment if it exists
        var url = $(this).attr('href');
        if (url.indexOf('#thumb') === -1 || url.indexOf('#map') === -1) {            
          // Add new fragment
          url = url.concat(tabFragment);
          $(this).attr('href', url);
        }
    });
}


// listing rating bar equal height of parent
(function($){
  $(function(){
    $("ul.ratings").each(function(i,el){
      var parentHeight = $(this).parent().css("height");
      console.log(parentHeight, " --> ", $(this).parent())
      $(this).css("height", parentHeight)
    })
  })
})(jQuery);
