﻿//****************************************************************
// TWITTER INTEGRATION
//****************************************************************
(function ($) {
	$.extend({
		jTwitter: function (username, numPosts, fnk) {
			var info = {};

			// If no arguments are sent or only username is set
			if (username == 'undefined' || numPosts == 'undefined') {
				return;
			} else if ($.isFunction(numPosts)) {
				// If only username and callback function is set
				fnk = numPosts;
				numPosts = 5;
			}

			var url = "http://twitter.com/status/user_timeline/"
				+ username + ".json?count=" + numPosts + "&callback=?";

			$.getJSON(url, function (data) {
				if ($.isFunction(fnk)) {
					fnk.call(this, data);
				}
			});
		}
	});
})(jQuery);

//****************************************************************
// SLIDER
//****************************************************************
(function ($) {
	$.fn.slider = function (options) {
		var defaults = {
			backButtonCss: 'slider-back-button',
			forwardButtonCss: 'slider-forward-button',
			buttonContainerCss: 'slider-button-container',
			pageButtonCss: 'slider-page-button',
			selectedPageButtonCss: 'slider-page-button-selected',
			itemCss: 'slider-item',
            autoScroll: false
		};

        // Merge the options with the defaults
		var opts = $.extend({}, defaults, options);

		return this.each(function() {

			var $this = $(this);

			// Create the back button
			var backButton = $(document.createElement("div"));
			backButton.addClass(opts.backButtonCss).hide();
			backButton.click(function (eventArgs) {
                eventArgs.preventDefault();
				eventArgs.stopPropagation();

				var state = $this.data("slider-state");
				if (state != null && state.displayIndex != 0)
					displayItem($this, state.displayIndex - 1);
			});

			// Create the forward button
			var forwardButton = $(document.createElement("div"));
			forwardButton.addClass(opts.forwardButtonCss).hide();
			forwardButton.click(function (eventArgs) {
				eventArgs.preventDefault();
				eventArgs.stopPropagation();

				var state = $this.data("slider-state");
				if (state != null && state.displayIndex < state.items.length - 1)
					displayItem($this, state.displayIndex + 1);
			});

			// Create the button container
			var buttonHolder = $(document.createElement("div"));
			buttonHolder.addClass(opts.buttonContainerCss);

			// Create our state information
			var state = {
				options: opts, 				// Options
				backButton: backButton, 		// Back button
				forwardButton: forwardButton, // Forward button
				buttonHolder: buttonHolder, 	// Button holder
				items: $this.children("div"), // List of child items
				displayedIndex: 0, 			// Currently displayed index
				inAnimation: false,				// Determines if the item is currently animating
                timer: null                 //handler for automatic scrolling
			};

			// Save the state information to the container
			$this.data("slider-state", state);

			// Create a button for each of the child items
			for (var index = 0; index < state.items.length; index++) {
				// Create a button to show the item
				buttonHolder.append(jQuery(document.createElement("a")).attr("href", "#")
							.addClass(index == 0 ? opts.selectedPageButtonCss : opts.pageButtonCss)
							.bind("click", index, function (eventArgs) {
								eventArgs.preventDefault();
								eventArgs.stopPropagation();
                                cancelAutoScroll($this);
								displayItem($this, eventArgs.data);
							}));

				// Add the item style to the child item
				$(state.items[index]).addClass(opts.itemCss).css("position", "absolute");
                //bind click event for box
				$(state.items[index]).css("cursor", "pointer");
				$(state.items[index]).attr("title", $(state.items[index]).find("h2 > a").text());
                $(state.items[index]).click(gotoLink);
				if (index == 0)
					$(state.items[index]).css("top", 0).css("left", 0);
				else
					$(state.items[index]).css("top", 0).css("left", $this.outerWidth());
			}

			// Add the slider elements to the container
			$this.append(forwardButton).append(backButton).append(buttonHolder);

            //install timer
            if (opts.autoScroll == true && state.timer == null){
                state.timer = self.setTimeout(function (){autoScroll($this)},10000);
            }
		});
        //go to link if not an anchor
        function gotoLink(){
            //fix for musem language about box error            
            var lnk = $(this).find("h2 > a").attr("href");
            if (lnk == null){
                document.location.href = ("/visiting/museum/about");
            }
            else{
                document.location.href = $(this).find("h2 > a").attr("href");
            } 
        }
        // do auto scroll
        function autoScroll(container){
			var state = container.data("slider-state");
			if (state != null && state.timer != null &&  state.items.length > 1  && !state.inAnimation){//check there at least a couple of items here
               //console.debug("auto scrolling:"+state.displayedIndex);
               if (state.displayedIndex < state.items.length - 1){
			         displayItem(container, state.displayedIndex + 1);
                  //   console.debug("auto scrolling - "+(state.displayedIndex + 1));
                   state.timer = self.setTimeout(function (){autoScroll(container)},5000); 
               }
            }
        };
        //cancels auto scroll
        function cancelAutoScroll(container){
          //  console.debug("cancelling");
            var state = container.data("slider-state");
            if (state.timer != null) {
                self.clearTimeout(state.timer);
                state.timer = null;
            }
        };
		// Shows the item with the specified index within the container
		function displayItem(container, index) {
			var animationPeriod = 1000;

			// Get the state for the control
			var state = container.data("slider-state");

			// Do not do anything if we are already showing the item
			if (index == state.displayedIndex || state.inAnimation)
				return;

			// If we are sliding to an item other than the next item, the slide speed should be increased
			if (state.displayedIndex < index - 1 || state.displayedIndex > index + 1)
				animationPeriod = 750;

			if (state.displayedIndex < index) {
				$(state.items[state.displayedIndex + 1]).css("top", 0).css("left", container.outerWidth());

				state.inAnimation = true;
				state.buttonHolder.children("." + state.options.selectedPageButtonCss).removeClass(state.options.selectedPageButtonCss).addClass(state.options.pageButtonCss);
				state.buttonHolder.children("a:nth-child(" + (state.displayedIndex + 2) + ")").addClass(state.options.selectedPageButtonCss);

				$(state.items[state.displayedIndex]).animate({ left: -container.outerWidth() }, animationPeriod);
				$(state.items[state.displayedIndex + 1]).animate({ left: 0 }, animationPeriod, function () {
					state.inAnimation = false;
					state.displayedIndex++;
					displayItem(container, index);
				});
			}
			else {
				$(state.items[state.displayedIndex + 1]).css("top", 0).css("left", -container.outerWidth());

				state.inAnimation = true;
				state.buttonHolder.children("." + state.options.selectedPageButtonCss).removeClass(state.options.selectedPageButtonCss).addClass(state.options.pageButtonCss);
				state.buttonHolder.children("a:nth-child(" + state.displayedIndex + ")").addClass(state.options.selectedPageButtonCss);

				$(state.items[state.displayedIndex]).animate({ left: container.outerWidth() }, animationPeriod);
				$(state.items[state.displayedIndex - 1]).animate({ left: 0 }, animationPeriod, function () {
					state.inAnimation = false;
					state.displayedIndex--;
					displayItem(container, index);
				});
			}
		}
	};
})(jQuery);

//****************************************************************
// GOOGLE ANALYTICS
//****************************************************************
var googleId = 'UA-19984558-2';

//var _gaq = _gaq || [];
//_gaq.push(['_setAccount', googleId]);
//_gaq.push(['_trackPageview']);

//(function () {
//	var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
//	ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
//	var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
//})();

// Tracks an outbound link in analytics
function trackLink(link, category, action) {
	try {
		var pageTracker = _gat._getTracker(googleId);
		pageTracker._trackEvent(category, action);

		if (link.target != "" && link.target != "_self")
			window.open(link.href, "");
		else
			setTimeout('document.location = "' + link.href + '"', 100)
	}
	catch (err) { 
	} 
}

// Tracks a click
function trackClick(category, action) {
	try {
		var pageTracker = _gat._getTracker(googleId);
		pageTracker._trackEvent(category, action);
	}
	catch (err) { 
	}
}

/***********************ROLEX CLOCK*****************/
function updateWimbledonCountdown(){
  var dtsWimbledonStart = new Date('20 Jun 2011 12:00:00 +0100');
  var dtsNow = new Date();
  var sHours = '00' + (dtsNow.getHours() - dtsNow.getTimezoneOffset() / 60);
  var sMinutes = '00' + dtsNow.getMinutes();
  var londonTime = sHours.substring(sHours.length - 2) + ":" + sMinutes.substring(sMinutes.length - 2);

  $(".rolex-your-time").html(dtsNow.toTimeString().substring(0,5));
  $(".rolex-london-time").html(londonTime);
  var iSecondsTotal = parseInt((dtsWimbledonStart.getTime() - dtsNow.getTime())/1000);
 
  var sOutput = '000:00:00:00';
 
  if (iSecondsTotal > 0){
    var sDays = '000' + String(parseInt(iSecondsTotal/86400));
    iSecondsTotal = iSecondsTotal % 86400;
 
    sHours = '00' + String(parseInt(iSecondsTotal/3600));
    iSecondsTotal = iSecondsTotal % 3600;
    sMinutes = '00' + String(parseInt(iSecondsTotal/60));
    var sSeconds = '00' + String(iSecondsTotal % 60);
 
    sDays = sDays.substring(sDays.length - 3);
    if(sDays.substring(0,1)=='0')
      {
      sDays = sDays.substring(1);
    //  document.getElementById('countdownArea').style.fontSize = ".8em";
      }
    sHours = sHours.substring(sHours.length - 2);
    sMinutes = sMinutes.substring(sMinutes.length - 2);
    sSeconds = sSeconds.substring(sSeconds.length - 2);
    $(".rolex-countdown-days").html(sDays);
    $(".rolex-countdown-hours").html(sHours);
    $(".rolex-countdown-minutes").html(sMinutes);
    $(".rolex-countdown-seconds").html(sSeconds);
    
 }
 
//  document.getElementById('countdownArea').innerHTML = sOutput;
  setTimeout("javascript:updateWimbledonCountdown();",1000);
}
//Make boxes clickable if they contain the same link
var cmdClickable = function () {
    var firstLink = $(this).find("a:first");
    var link = $(firstLink).attr("href");
    //    var redirect = true;
    //    var linkCount = 0;
    //    $(this).find("a").each(function () {
    //        var uri = $(this).attr("href");
    //        //console.debug(link + " vs " + uri);
    //        linkCount++;
    //        if (uri != link) {
    //            redirect = false;
    //            return;
    //        }
    //    });
    //    if (redirect && linkCount > 0) {
    if ($(firstLink).attr("target") == "_blank")        
        //specify features to fix IE7 bug, previously null
        window.open(link, $(firstLink).attr("title"), "status=yes,toolbar=yes,menubar=yes,location=yes,resizable=yes,scrollbars=yes", true); 
    else window.location.href = link;
    //    }
    return false;
}

//competition countdown
var dtsDrawRemaining;


function updateCompetitionCountdown() {
        dtsDrawRemaining--;
        if (dtsDrawRemaining > 0){
            var remainder = secondsToTime(dtsDrawRemaining);
            
            if (remainder['d'] > 0) {
                $("span.hours").html("&nbsp;&nbsp;days")
                $("span.minutes").html("&nbsp;&nbsp;hours")
                $("span.seconds").html("minutes")
                $(".countdown-hours").html(remainder['d']);
                $(".countdown-minutes").html(remainder['h']);
                $(".countdown-seconds").html(remainder['m']);
            } else {
                $(".countdown-hours").html(remainder['h']);
                $(".countdown-minutes").html(remainder['m']);
                $(".countdown-seconds").html(remainder['s']);
            }
        }
    //  document.getElementById('countdownArea').innerHTML = sOutput;
    setTimeout("javascript:updateCompetitionCountdown();", 1000);
}
function secondsToTime(secs) {
    var hours = Math.floor(secs / (60 * 60));

    var divisor_for_minutes = secs % (60 * 60);
    var minutes = Math.floor(divisor_for_minutes / 60);

    var divisor_for_seconds = divisor_for_minutes % 60;
    var seconds = Math.ceil(divisor_for_seconds);
    var days = Math.floor(hours / 24);
    if (days > 0) hours = Math.ceil(hours % 24); 
    var obj = {
        "h": (hours>9) ? hours : "0"+hours,
        "m": (minutes>9) ? minutes : "0"+minutes,
        "s": (seconds > 9) ? seconds : "0" + seconds,
        "d": (days > 9) ? days : "0" + days
    };
    return obj;
}


$(document).ready(function () {
    updateWimbledonCountdown();
    $("div.box").each(fnClicableBox);
    $("div.box-1x2").each(fnClicableBox);

});

var fnClicableBox = function () {
    var firstLink = $(this).find("a:first");
    var link = $(firstLink).attr("href");
    var redirect = true;
    var linkCount = 0;
    $(this).find("a").each(function () {
        var uri = $(this).attr("href");
        //console.debug(link + " vs " + uri);
        linkCount++;
        if (uri != link) {
            redirect = false;
            return;
        }
    });
    if (linkCount > 0 && redirect) {
        $(this).click(cmdClickable);
        $(this).css("cursor", "pointer");
        $(this).attr("title", $(firstLink).text());
    }
};
