/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        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(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        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 { // only name given, get cookie
        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]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

/**
* 'jquery-tweets' Copyright (c) 2009 Andy Atkinson http://webandy.com
* jquery-tweets is a jquery plugin that fetches a user's tweets (must have public tweets enabled) 
* for display on a website.
* 
* MIT License, see LICENSE file
*/
var $ = jQuery.noConflict();
(function($) { 
  
var PROP_NAME = 'tweets';

function TweetsPlugin() {
  this._defaults = {
    username: 'ev',
    cycle: false,
    count: 5,
    animateDuration: 6000,
    singleRandomTweet: false,
    animate: true,
    showTimestamps: true
  };
}

$.extend(TweetsPlugin.prototype, {
  
  markerClassName: 'hasTweetsPlugin',
  baseUrl: 'http://twitter.com',
  api_method: 'http://twitter.com/statuses/user_timeline/',
  urlRegex: /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/,
  usernameRegex: /(@)(\w+)/g,
  requestUrl: "",
  responseData: null,
  
  setDefaults: function(settings) {
    $.extend(this._defaults, settings || {});
    return this;
  },
  
  /* Attach the tweets plugin functionality to an element.
    @param  target    (element) the html element on the page
    @param  settings  (object) the custom options for this instance */
  _attachTweetsPlugin: function(target, settings) {
    target = $(target);
    if (target.hasClass(this.markerClassName)) {
      // prevent attaching functionality to same element more than once
      return;
    }
    target.addClass(this.markerClassName);
    target.hide();
    var instance = {settings: $.extend({}, this._defaults)};
    $.data(target[0], PROP_NAME, instance);
    this._fetchTwitterData(target, settings);
  },
  
  /* Pull JSON from the twitter API for a user
	   @param  element    (element) the html element on the page
	   @param  settings  (object) the custom options for this instance */
  _fetchTwitterData: function(element, settings) {
    var instance = $.data(element[0], PROP_NAME);
    $.extend(instance.settings, settings);
    this.requestUrl = this.api_method + instance.settings.username + '.json?count=' + instance.settings.count + '&callback=?';
    var self = this;
    $.getJSON(this.requestUrl, function(data) {
        self.responseData = data; /* used by tests */
        self._buildMarkupFromData(element, data);
      }
    );
  },
  
  /* Convert JSON data returned from twitter API into markup to insert 
     into page
	   @param  element    (element) the html element on the page
	   @param  settings  (object) the custom options for this instance */
  _buildMarkupFromData: function(element, data) {
    var instance = $.data(element[0], PROP_NAME);
    var self = this;
    var tweetsHTML = '';
    if (instance.settings.singleRandomTweet) {
      var item = data[Math.floor(Math.random() * data.length)];
      var tweetHtml = '<li>' + self._buildTweetText(item) + '<span class="created_at">' + self._buildTweetTimestamp(element, item) + '</span></li>';
      tweetsHTML += tweetHtml;
    } else {
      $.each(data, function(i,item) {
        var tweetHtml = '<li><div>' + self._buildTweetText(item) + '<span class="created_at">' + self._buildTweetTimestamp(element, item) + '</span><ul class="tweet_links"><li><a href="#" class="twitter_link"><span class="ws" style="display:inline-block;float:left;clear:none;font-family: \'Web Symbols\', \'WebSymbolsRegular\'; text-indent:-9999px; width:20px; line-height:16px; background:transparent url(https://images.thomascookgroup.ca/belairtravel/includes/images/ws_replace/ws_twitter.png) no-repeat 0 0;">t</span>via <span>twitter</span></a></li><li><a href="#" class="read_more"><span class="ws" style="display:inline-block;float:left;clear:none;font-family: \'Web Symbols\', \'WebSymbolsRegular\'; text-indent:-9999px; width:20px; line-height:16px; background:transparent url(https://images.thomascookgroup.ca/belairtravel/includes/images/ws_replace/ws_retweet.png) no-repeat 0 0;">J</span>retweet</a></div></li></ul></li>';
        tweetsHTML += tweetHtml;
      });
    }

    $('<ul/>').html( tweetsHTML ).appendTo( element );
    this._displayTweets(element);
  },
  
  _buildTweetText: function(item) {
    var text = item.text;
    var self = this;
    text = self._autoLinkText(text);
    text = self._autoLinkUsernames(text);
    return text;
  },
  
  _buildTweetTimestamp: function(element, item) {
    var instance = $.data(element[0], PROP_NAME);
    var self = this;
    var timestamp = "";
    if (instance.settings.showTimestamps) {
      timestamp = self._autoLinkTimestamp(item.id_str, item.created_at, item.user.screen_name);
    }
    return timestamp;
  },
  
  /* Convert links to hyperlinked text
	   @param  text  (string) original plain text */
  _autoLinkText: function(text) {
    if (this.urlRegex.test(text)) {
      return text.replace(this.urlRegex, "<a href='$1' target='blank'>$1</a>");
    } else {
      return text;
    }
  },
  
  /* Convert twitter usernames to hyperlinked usernames
	   @param  text  (string) original plain text */
  _autoLinkUsernames: function(text) {
    if (this.usernameRegex.test(text)) {
      return text.replace(this.usernameRegex, "$1<a href='http://twitter.com/$2' target='blank'>$2</a>");
    } else {
      return text;
    }
  },
  
  /* Build link back to tweet permalink from parts
    @param  id_str       (string) twitter status ID string
    @param  date         (date) date when tweet was made
    @param  screen_name  (string) twitter username */
	
  _autoLinkTimestamp: function(id_str, date, screen_name) {
    var d = new Date(date),
    dateString = [
			  d.getUTCHours() + ':',
			  (Math.round(d.getMinutes() / 10) * 10) + ' ',
              d.getMonth() + 1 + '/',
              d.getDate()
            ].join('');
	
    var timestampUrl = [
                        this.baseUrl,
                        screen_name,
                        'status',
                        id_str
                        ].join('/');

    return "<a href='" + timestampUrl + "'>" + dateString + "</a>";
  },
  
  /* Decide to either cycle or display tweets markup
    @param  element  (element) element containing tweets */
  _displayTweets: function(element) {
    var instance = $.data(element[0], PROP_NAME);
    var self = this;
    if (instance.settings.animate && instance.settings.cycle) {
      self._cycleTweets(element);
    } else if (instance.settings.animate) {
      element.fadeIn();
    } else {
      element.show();
    }
  },
  
  /* Show one tweet for the animateDurection, then replace it with another
    @param  element  (element) element containing tweets */
  _cycleTweets: function(element) {
    var instance = $.data(element[0], PROP_NAME);
    element.show();
    element.find('ul > li').hide();
    element.find('ul > li:first').fadeIn();
    var i = 1;
    setInterval(function() {
      var items = element.find('li');
      items.hide();
      items.eq(i).fadeIn();
      if(i == items.length) {
        element.find('ul > li:first').fadeIn();
        i = 1;
      } else { i++; }
    }, instance.settings.animateDuration);
  }

});

// The list of commands that return values and don't permit chaining
var getters = ['settings'];
  
$.fn.tweets = function(options) {
  var otherArgs = Array.prototype.slice.call(arguments, 1);
  if ($.inArray(options, getters) > -1) {
    return $.tweets['_' + options + 'TweetsPlugin'].
      apply($.tweets, [this[0]].concat(otherArgs));
  }
  return this.each(function() {
    if (typeof options == 'string') {
      $.tweets['_' + options + 'TweetsPlugin'].
        apply($.tweets, [this].concat(otherArgs));
    }
    else {
      $.tweets._attachTweetsPlugin(this, options || {});
    }
  });
};

/* Initialize the tweets plugin */
$.tweets = new TweetsPlugin(); // singleton instance

})(jQuery);

;

    $.fn.betterTooltip = function(options){  
  
        /* Setup the options for the tooltip that can be 
           accessed from outside the plugin              */  
        var defaults = {  
            speed: 200,  
            delay: 400  
        };  
  
        var options = $.extend(defaults, options);  
  
        /* Create a function that builds the tooltip 
           markup. Then, prepend the tooltip to the body */  
        getTip = function() {  
            var tTip =  
            "<div class='tip'>" +  
                "<div class='tipMid'>"    +  
                "</div>" +  
                "<div class='tipBtm'></div>" +  
            "</div>";  
            return tTip;  
        }  
        $("body").append(getTip());  
  
        /* Give each item with the class associated with 
           the plugin the ability to call the tooltip    */  
        $(this).each(function(){  
  
            var $this = $(this);  
            var tip = $('.tip');  
            var tipInner = $('.tip .tipMid');  
  
            var tTitle = (this.title);  
            this.title = "";  
  
            var offset = $(this).offset();  
            var tLeft = offset.left;  
            var tTop = offset.top;  
            var tWidth = $this.width();  
            var tHeight = $this.height();  
  
            /* Mouse over and out functions*/  
            $this.hover(function() {  
                tipInner.html(tTitle);  
                setTip(tTop, tLeft);  
                setTimer();  
            },  
            function() {  
                stopTimer();  
                tip.hide();  
            }  
        );           
  
        /* Delay the fade-in animation of the tooltip */  
        setTimer = function() {  
            $this.showTipTimer = setInterval("showTip()", defaults.delay);  
        }  
  
        stopTimer = function() {  
            clearInterval($this.showTipTimer);  
        }  
  
        /* Position the tooltip relative to the class 
           associated with the tooltip                */  
        setTip = function(top, left){  
            var topOffset = tip.height();  
            var xTip = (left-10)+"px";  
            var yTip = (top-topOffset-35)+"px";  
            tip.css({'top' : yTip, 'left' : xTip});  
        }  
  
        /* This function stops the timer and creates the 
           fade-in animation                          */  
        showTip = function(){  
            stopTimer();  
            //tip.animate({/*"top": "+=20px", */"opacity": "toggle"}, defaults.speed);  
        }  
    });  
};  
;

$(document).ready(function() {
  
//Tooltips!
	
	//$('span[title]').betterTooltip();
	
	//alert(nh);
	if($('#lm_deals').length != 0){
		var h = document.getElementById('deal_feed').clientHeight;
		var nh = h - 10
		$('#lm_deals').css('min-height', nh + 'px');
	}
	;
	$('.deal_buckets > ul > li').hover(function(){
	 //$(this).children().find('dl').toggleClass('hidden');
	 if( $(this).children().find('dl.pricing_info').length != 0 ){
	 	$(this).children().find('img.hotel_img, div.hotel_info').slideToggle('fast');
	 }
    })
	 if ($.browser.webkit) {
    	$('#social h3').attr('style', 'margin-top:-20px;');
  	}
	//pdf viewer
		if(typeof myType != 'undefined'){  
		 $(galleryImage).fancybox({
				width: 800, 
				height: 600,
				padding: 10,
				centerOnScroll: false, 
				hideOnContentClick: false, 
				titlePosition	: 'inside',
				type: myType		
			  });
		}
	$('span.phone').attr('style', 'top:30px');
	$('div.top_links').attr('style', 'font-weight:bold;margin-right:20px;');
	$('div.address').attr('style', 'margin-right:20px;');
	$('#searchBox').attr('width', '288');
	$('.ie7 #searchOption').after('<br />');
	$('#header').css('width', '990px');
	$('#sub_menu').css('width', '986px');
	$('.logo').attr('id', 'bat_logo');
	$('.logo').html('<a href="http://www.belairtravel.com" title="Belair Travel home">\&nbsp\;</a>');
	$('span.phone').html('<a href="tel:18776757707" style="color:#f80;text-decoration:none">Call 1.877.675.7707</a>');
	$('.gate_btn > .ws').attr('style', 'font-family: "WebSymbolsRegular", "Web Symbol";text-indent: -9999px;display:inline-block;width: 20px;line-height: 16px;background: transparent url(https://images.thomascookgroup.ca/belairtravel/includes/images/ws_replace/ws_forward.png) no-repeat 0 0;');
	
	//var socialHeight = document.getElementById('social').clientHeight;
	//if(socialHeight < 300){
		//<a href="/christmas-new-years-vacation-packages.asp"> <img src="https://images.thomascookgroup.ca/belairtravel/images/homepage/banners/HolidaysSeason_unbelievable_300x180.jpg" width="300" height="180" alt="Christmas &amp; New Year's Vacation Deals" border="0"></a>
		//alert('socialHeight');
	//}
	
	//add tracking
	/*$('#hot_deals .deal_buckets > ul > li').find('a').each(function(){
		var myClick = $(this).attr('onclick') + "";
		//$(this).attr('data-click', myClick);
		$(this).click(function(){
			_gaq.push(['_trackEvent', 'HomepageDeals', 'HotDeals']);
			(new Function ($(this).attr('onclick') + ';onclick();'))();
		});
	});
	$('#recommended_deals .deal_buckets > ul > li').find('a').each(function(){
		var myClick = $(this).attr('onclick') + "";
		//$(this).attr('data-click', myClick);
		$(this).click(function(){
			_gaq.push(['_trackEvent', 'HomepageDeals', 'RecForYou']);
			(new Function ($(this).attr('onclick') + ';onclick();'))();
		});
	});
	
	$('#browse_top_deals').find('a').each(function(){
		var myClick = $(this).attr('onclick') + "";
		//$(this).attr('data-click', myClick);
		$(this).click(function(){
			_gaq.push(['_trackEvent', 'HomepageDeals', 'TopDeals']);
			(new Function ($(this).attr('onclick') + ';onclick();'))();
		});
	});
	
	$('#lm_deals').find('a').each(function(){
		var myClick = $(this).attr('onclick') + "";
		//$(this).attr('data-click', myClick);
		$(this).click(function(){
			_gaq.push(['_trackEvent', 'HomepageDeals', 'LastMinute']);
			(new Function ($(this).attr('onclick') + ';onclick();'))();
		});
	});*/
	
	//tweets
    $('#tweets').tweets({username: 'belairtravel', count: 3, cycle: false, showTimestamps: true});
	
	$('#booking_engine .search_type li input').click(function(){
		$(this).parent('li').addClass('active');
		$(this).parent().siblings('li').removeClass('active');
	});
	
	//show/hide options
	$('#options_button').click(function() {
	
	$('#additional_options').show();
	$('#options_button').hide();
  	return false;
	});
	
	$('#hide_options_button').click(function() {
	$('#options_button').show();
	$('#additional_options').hide();
  	return false;
	});
	

$(".slidetabs").tabs(".images > div", {

	// enable "cross-fading" effect
	effect: 'fade',
	fadeOutSpeed: "slow",

	// start from the beginning after the last tab
	rotate: true

// use the slideshow plugin. It accepts its own configuration
}).slideshow();
//tooltip
                                                $(".dealList_li > a").tooltip({ 
                                                                relative: true
                                                                // tweak the position
                                                });



});


;
