﻿/// <reference path="jquery-1.3.2-vsdoc2.js"/>

Cufon.replace('.sub-navigation a', { fontFamily: 'Myriad Pro Light', hover: true });
Cufon.replace('#navigation a, h2.feature-txt, .feature-list li *', { fontFamily: 'Myriad Pro Light', hover: true });
Cufon.replace('h2:not(.feature-txt), h3:not(.no-cufon), h2.feature-txt strong', { fontFamily: 'Myriad Pro' });
Cufon.replace('.apply-now *', { fontFamily: 'Myriad Pro Light', hover: true });

document.createElement("abbr");

$(document).ready(function()
{
	$(document).externalLinks();

	$('.labeltovalue').labelToValue();

	$('.person').bigLink();

	$('#primary, #secondary').equaliseHeights();

	// IE6 + IE7 fix for incorrect clearing behaviour on DD
	if ($.browser.msie && $.browser.version <= 8)
	{
		$('#main dl:not(.steps):not(.vcard) dd').each(function(i)
		{
			$('<div class="clear"/>').insertAfter($(this));
		});
	}

	$('.vimeo-video').empty();
	$('.vimeo-list').vimeoList('2713112');
});


$.fn.vimeoList = function(userid)
{
	window.doctitle = document.title;

	this.each(function(i)
	{
		$.ajax({
			url: 'http://vimeo.com/api/v2/' + userid + '/videos.json',
			dataType: 'jsonp',
			success: onSuccess,
			context: this
		});
	});

	function onSuccess(data, textStatus, XMLHttpRequest)
	{
		if (!data.length) return;

		var list = $('<ul />');
		var link, thumb, overlay, video;

		var show = this.className.match(/\bshow-(\d)\b/);
		show = show && show[1] ? show[1] : 1;

		$.each(data.slice(0, show), function(i)
		{
			link = $('<a href="' + document.location.protocol + '//' + document.location.hostname + '/tv/#' + this.id + '" />').data('autoplay', 1).click(function(e)
			{
				var autoplay = $(this).data('autoplay');
				$(this).data('autoplay', 1);

				$('.vimeo-video').vimeoVideo($(this).attr('href').replace(/^.*?#/, ''), { autoplay: autoplay, color: '#71CDE5', portrait: 0, width: '535', title: 0, byline: 0 });

				autoplay = null;
				delete autoplay;
			});

			thumb = $('<img src="' + this.thumbnail_large + '" alt="' + this.title + '" />');

			overlay = $('<span class="overlay">' + this.title + '</span>');

			list.append($('<li />').append(link.append(thumb).append(overlay)));
		});

		$(this).append('<h3>TV</h3>').append(list);

		Cufon.refresh();

		// load first video into main
		video = list.find('a[href$=' + document.location.hash + ']:first');
		if (!video.length) video = list.find('a:eq(0)');
		video.data('autoplay', 0).click();

		link, thumb, overlay, video = null;
		delete link, thumb, overlay, video;
	}

	return this;
}

$.fn.vimeoVideo = function(url, options)
{
	this.each(function(i)
	{
		url = /^http/.test(url) ? url : 'http://vimeo.com/' + url;

		$.ajax({
			url: 'http://vimeo.com/api/oembed.json',
			dataType: 'jsonp',
			data: $.extend({ url: url }, options),
			success: onSuccess,
			context: $(this)
		});
	});

	function onSuccess(data)
	{
		this.html(data.html);

		this.prepend('<h2>' + data.title + '</h2>');
		this.append('<p>' + data.description.replace(/(\n|\r)/g, '<br />').replace(/<br\s*?\/?>\s*?<br\s*?\/>/g, '</p><p>') + '</p>');

		// update the addthis share url
		with ($('.addthis_button').get(0).share)
		{
			title = window.doctitle.replace(/^.+?-/, data.title + ' -');
			url = document.location.href.replace(/#.+$/, '') + '#' + data.video_id;
		}

		Cufon.refresh();

		if ($.browser.msie)
		{
			window.vimeoIEInterval = setInterval(function(e) { document.title = window.doctitle }, 10);

			setTimeout(function() { clearInterval(window.vimeoIEInterval); document.title = window.doctitle }, 5000);
		}

		var wmode = document.createElement('param');
		wmode.name = 'wmode';
		wmode.value = 'opaque';

		this.find('object').get(0).appendChild(wmode);
	}

	return this;
}

$.fn.equaliseHeights = function(val)
{
    var self = this;
    var height = 0;

    if (!val)
    {
        self.each(function(i)
        {
            height = Math.max($(this).height(), height);
        })
    }
    else
    {
        height = val / self.length;
    }

    self.css({ minHeight: height + 'px' });

    if ($.browser.msie && $.browser.version < 7)
    {
        self.css({ height: height + 'px' });
    }

    return self;
};

$.fn.delay = function(time, callback)
{
    jQuery.fx.step.delay = function() { };
    // Return meaningless animation, (will be added to queue)
    return this.animate({ delay: 1 }, time, callback);
};


$.fn.initAddThis = function()
{
    var self = $(this);
    var len = self.length - 1;
    
    self.each(function(i)
    {
        var addthis = $('<ul/>');

        var at_email = $('<li class="alpha email"><a class="addthis_button_email" href="#">Email</a></li>');
        var at_share = $('<li class="omega share"><a class="addthis_button" href="#">Share</a></li>');

        addthis.append(at_email).append(at_share);

        $(this).append($('<div class="social" />').append(addthis));

        if (i == len && $('head script[src*=addthis_widget.js]').length == 0)
        {
            $('head').append($('<script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js?pub=tallulahlove"><\/script>'));
        }
    });

    return self;
}

$.assetsRoot = function()
{
    var scr = $('script[src*="/global.js"]');
    return (scr.length) ? scr.attr('src').replace(/\/js\/global\.js.*?$/gi, '') : '';
}

$.fn.externalLinks = function()
{
    return this.find('a[href^=http]:not([href*=' + location.hostname + ']), a:[rel=external]').attr('target', '_blank')/*.append('<em class="ext"> [this link opens in a new window] </em>')*/.end();
};

$.fn.bigLink = function(/**String*/selector)
{
    var self = this;
    var selector = selector || 'a[@href]:eq(0)';

    self.each(function(i)
    {
        var link = $(this).find(selector);

        if (link.length)
        {
            $(this).click(function(e)
            {
                // the first link within the supplied element
                var prevent_default = false;

                //
                var target_is_link = (e.target.nodeName == 'A');

                // check through all click events for preventDefault command (so we know whether to redirect or not)
                var all_events = link.data('events');
                var click_events;

                if (all_events && all_events.click)
                {
                    click_events = all_events.click;

                    for (var k in click_events)
                    {
                        if (/\.preventDefault\(\)/.test(click_events[k].toString()))
                        {
                            prevent_default = true;
                        }
                    }
                }

                // trigger all jquery assigned events
                link.triggerHandler('click');

                // if preventDefault has never been assigned to this link then it is safe to do a standard redirect
                if (!prevent_default)
                {
                    //document.location = link.attr('href');
                    return !window.open(link.attr('href'), link.attr('target') || '_self');
                }
            })
	        .hover(function()
	        {
	            $(this).addClass('hover');
	        },
	        function()
	        {
	            $(this).removeClass('hover');
	        })
	        .css('cursor', 'pointer');
        }
    });

    return self;
}

$.fn.labelToValue = function()
{
    var self = this;

    self.focus(function()
    {
        var field = $(this);

        if (this.id)
        {
            var label = $.trim($('label[for="' + this.id + '"]:last').hide().text());
        }
        else
        {
            return;
        }

        if (field.val() == label)
        {
            field
			.val('')
			.removeClass('label');
        }
        else
        {
            field
			.removeClass('label');
        }
    })
	.blur(function()
	{
	    var field = $(this);

	    if (this.id)
	    {
	        var label = $.trim($('label[for="' + this.id + '"]:last').hide().text());
	    }
	    else
	    {
	        return;
	    }

	    if (field.val() == label || field.val() == '')
	    {
	        field
			.val(label)
			.addClass('label');
	    }
	})
	.blur()
	.parents('form').submit(function(e)
	{
	    var current = $(':focus');
	    var scrollY = $(document).scrollTop();

	    // trigger the focus event to remove label text from field
	    self.focus();
	    // remove all bound events
	    self.unbind();

	    current.get(0).focus();

	    $(document).scrollTop(scrollY);
	});

    return self;
}