﻿(function($) {
    var transitionIsHappening = false,
    dummyRepl = '<li class="tile tile-short tile-dummy"></li>',
	trackingTag = '<img id="atlasTracking" height="1" width="1" src=""/>',
    hasFeaturedTile = false,
    duration = $('#ie6').length == 0 ? 750 : 0,
    fullWidth = 656,
    fullHeight = 489,
    smallWidth = 155,
    smallHeight = 155,
    text_closeBtn = 'Close',
	text_shareBtn = 'Share',
    text_shareTitle = 'Bookmark &amp; Share',
    text_shareFavorite = 'Favorites',
    text_shareEmail = 'Email a friend',
    text_shareEmailTitle = 'Are you the New Busy?',
    text_shareEmailBody = 'Check out the New Busy headquarters at {0}. This is the place for people who are redefining busy. So take a look around, explore the world of the New Busy, and check out the new Hotmail features that will help you manage it all. Maybe you\'ll even discover some new ways to get busy.',
    text_errorFavoriteSupport = 'We\'re sorry, but your browser does not support this feature. You can press CTRL+D to manually add the bookmark.',
	atlasShareLink = 'http://view.atdmt.com/action/HM_Busy_Share?href=';
	
    function openModal() {
		// campaign tracking
        new OmniTrack('Module', [6], function(target) {
            this.LinkName = $(target).parents('li.tile:first').children('h2').text() + ':Step-by-Step';
        }).Track(this);
		trackAtlas($(this).parents('li.tile').data('atlasSeeHow'));
		
        var code = $(this).parents('.tutorial:first').children('div.tutorial-content'),
        title = code.find('h1').text(),
        content = code.find('div.content').html(),
        modal = $('<div id="modal" class="jqmID1 wlVideoModal tutorial" style="visibility:visible;z-index:9998;display:block;"><div aria-labelledby="modalLabel" role="dialog" class="modalWindow"><div class="modalShadow"></div><div class="modalShadowBottom" style="height: 353px;"></div><div class="modalDetail"><div class="header clr" id="modalLabel"><a role="button" class="closeModal">' + text_closeBtn + '</a><h1 class="seg30"></h1></div><div role="main" class="content"></div><div class="footer"></div></div></div></div>'),
        body = $('body'),
        center = function() {
            if (modal) {
                var deltas = { x: 0, y: 0 },
		            dialogH = modal.height(),
			        viewportH = window.innerHeight !== undefined ? window.innerHeight : document.documentElement.clientHeight,
			        dialogW = modal.width(),
			        viewportW = window.innerWidth !== undefined ? window.innerWidth : document.documentElement.clientWidth;
                deltas.y = viewportH - dialogH;
                deltas.x = viewportW - dialogW;
                offsetY = deltas.y > 0 ? deltas.y / 2 + document.documentElement.scrollTop : document.documentElement.scrollTop,
				    offsetX = deltas.x > 0 ? deltas.x / 2 + document.documentElement.scrollLeft : document.documentElement.scrollLeft,
				    css = {};
                if (deltas.y > 0) css.top = Math.floor(offsetY) + 'px';
                if (deltas.x > 0) css.left = Math.floor(offsetX) + 'px';
                modal.css(css);
            }
            else {
                $(window).unbind('scroll', center).unbind('resize', center);
            }
        };
        modal.find('h1').text(title);
        modal.find('div[role=main]').html(content);
        modal.find('a.closeModal').click(function() {
            $('#modalOverlay').add(modal).fadeOut(250, function() {
                $(this).remove();
            });
            delete modal;
            return false;
        });
        body.append('<div id="modalOverlay" class="jqmOverlay"></div>');
        body.append(modal.hide());
        center();
        modal.fadeIn(250);
        $(window).bind('scroll', center).bind('resize', center);
        return false;
    };

	function drawShareThis(host, title, url, emailSubj, emailBody) {
	    var urlSafe = encodeURIComponent(url),
	        titleSafe = encodeURIComponent(title),
	        emailSubjSafe = encodeURIComponent(emailSubj),
	        emailBodySafe = encodeURIComponent(emailBody),
	        html = '<div class="share-this-dlg hoverCont closed"><div class="tt2"> \
	                    <div class="tt1"> \
	                        <h3>' + text_shareTitle + '</h3> \
	                            <ul> \
	                                <li class="favorites"><a class="scShareThis atBookmark" href="' + url + '">' + text_shareFavorite + '</a></li> \
	                                <li class="delicious"><a target="sharethis" class="shareThis scShareThis" href="' + atlasShareLink + 'http://del.icio.us/post?url=' + urlSafe + '&amp;title=' + titleSafe + '">del.icio.us</a></li> \
	                                <li class="linkedin"><a target="sharethis" class="shareThis scShareThis" href="' + atlasShareLink + 'http://www.linkedin.com/shareArticle?mini=true&amp;url=' + urlSafe + '&amp;title=' + titleSafe + '&amp;summary=+&amp;source=+">LinkedIn</a></li> \
	                                <li class="newsvine"><a target="sharethis" class="shareThis scShareThis" href="' + atlasShareLink + 'http://www.newsvine.com/_tools/seed&amp;save?u=' + urlSafe + '&amp;h=' + titleSafe + '">Newsvine</a></li> \
	                            </ul> \
	                            <ul> \
	                                <li class="live"><a target="sharethis" class="shareThis scShareThis" href="' + atlasShareLink + 'https://favorites.live.com/quickadd.aspx?mkt=en-us&amp;url=' + urlSafe + '&amp;title=' + titleSafe + '&amp;top=0">Live</a></li> \
	                                <li class="digg"><a target="sharethis" class="shareThis scShareThis" href="' + atlasShareLink + 'http://digg.com/submit?phase=2&amp;url=' + urlSafe + '&amp;title=' + titleSafe + '">Digg</a></li> \
	                                <li class="facebook"><a target="sharethis" class="shareThis scShareThis" href="' + atlasShareLink + 'http://www.facebook.com/sharer.php?u=' + urlSafe + '&amp;t=' + titleSafe + '">Facebook</a></li> \
	                                <li class="myspace"><a target="sharethis" class="shareThis scShareThis" href="' + atlasShareLink + 'http://www.myspace.com/Modules/PostTo/Pages/?u=' + urlSafe + '&amp;t=' + titleSafe + '">MySpace</a></li> \
	                            </ul> \
	                            <div class="emailafriend"> \
	                                <a class="shareThis atEmail scShareThis" href="mailto:?subject=' + emailSubjSafe + '&amp;body=' + emailBodySafe + '">' + text_shareEmail + '</a>\
	                                <input type="hidden" value="' + url + '" id="pageURL"> \
	                            </div> \
		                    </div> \
		                </div> \
		                <div class="tt3"></div> \
	            	</div>';
	    $(html).insertAfter(host);
	};

    function grow(tile) {
        var tile = $(tile).find('div.bg-short');
		tile.css('background-color','transparent');
        if (transitionIsHappening || tile.data('expanded')) return;
        var css = { width: 216, height: 216, top: -31, left: -31 };
        if (duration > 0) {
            tile.stop().animate(css, 200);
        }
        else {
            tile.css(css);
        }
        tile.parent().css('z-index', 100);
    };

    function shrink(tile) {
        var tile = $(tile).find('div.bg-short');
        if (tile.data('expanded')) return;
        var css = { width: 155, height: 155, top: 0, left: 0 };
        if (duration > 0) {
            tile.stop().animate(css, 200);
        }
        else {
            tile.css(css);
        }
        tile.parent().css('z-index', 0);
    };

    function substitute(tile) {
        tile = $(tile);
        var pos = tile.offset(),
        repl = $(dummyRepl);
        tile.css({ position: 'absolute', top: pos.top, left: pos.left });
        repl.css({ width: tile.width(), height: tile.height() }).insertBefore(tile);
        return repl;
    };

    function restore(tile) {
        $(tile).css({ position: 'relative', top: 0, left: 0 });
    };

    function swap(next, skipRemove) {
        transitionIsHappening = true;
        var last = $('li.tile:first').stop(),
        	next = $(next).stop(),
			object = $(next).find('object').length > 0 ? $(next).find('object') : null;
        var scrollTop = document.documentElement.scrollTop !== undefined ? document.documentElement.scrollTop : document.body.scrollTop,
        lastRepl = skipRemove ? null : substitute(last),
        nextRepl = skipRemove ? null : substitute(next),
        lastOffset = last.offset(),
        nextOffset = next.offset(),
        finalize = function() {
            if (!skipRemove) {
                restore(last);
                last.data('expanded', false);
                nextRepl.replaceWith(last);
                lastRepl.replaceWith(next);
                initTile(last);
            }
            restore(next);
            next.data('expanded', true);
            next.css('z-index', 0);
			if(object) object.fadeIn();
            transitionIsHappening = false;
            finalize = place = last = next = lastRepl = nextRepl = nextOffset = null;
            hasFeaturedTile = true;
        },
        postPlace = function() {
            next.addClass('tile-feature').removeClass('tile-short');
            if (!skipRemove) {
                last.addClass('tile-short').removeClass('tile-feature').css({ width: smallWidth, height: smallHeight, top: nextOffset.top, left: nextOffset.left });
                last.children('div.bg-feature').hide();
				last.children('div.bg-featureMoreInfo').hide();
                last.children('div.bg-short').removeAttr('style');
                last.children('h2').removeAttr('style');
                if (duration > 0) {
					last.hide().fadeIn(duration, function() {
                        finalize();
                    });
                }
                else {
                    last.show();
                    finalize();
                }
            }
            else {
                finalize();
            }
        },
        place = function() {
            nextTitle = next.children('h2').hide();
            nextFeature = next.children('div.bg-feature').show();
            nextShort = next.children('div.bg-short').show().animate({ opacity: 0 }, duration);
            next.children('div.bg-featureMoreInfo').hide();
            if (duration > 0) {
                next.animate({ width: fullWidth, height: fullHeight }, duration, postPlace);
            }
            else {
                next.css({ width: fullWidth, height: fullHeight });
                postPlace();
            }
        };
        next.css('z-index', 200);
        if (skipRemove) {
            $('#tile-container').prepend(next);
            place();
        }
        else if (duration > 0) {
			if(object) object.hide();
			next.animate({ width: smallWidth, height: smallHeight, top: lastOffset.top, left: lastOffset.left }, duration, place);
        }
        else {
            place();
        }
        if (document.documentElement.scrollTop !== undefined) {
            document.documentElement.scrollTop = scrollTop;
        }
        else {
            document.body.scrollTop = scrollTop;
        }
        $('html, body').animate({ scrollTop: 0 }, duration);
    };

    function expand(tile) {

		var tileId = tile.attr('id').replace('tile-','');
		window.location.hash = '#tile='+tileId;

        new OmniTrack('Module', [5], function(target) {
            this.LinkName = $(target).children('h2').text();
        }).Track(tile);
		trackAtlas(tile.data('atlasMain'));
        swap(tile, !$('li.tile:first').data('expanded'));
    };

    function collapse(tile) {
        transitionIsHappening = true;
		var tile = $(tile);
        var finalize = function() {
            tile.removeClass('tile-feature').addClass('tile-short').data('expanded', false);
            tile.removeAttr('style');
            tile.find('div.bg-feature').hide();
            tile.find('div.bg-featureMoreInfo').hide();
            tile.find('h2').removeAttr('style');
            tile.find('div.bg-short:first').removeAttr('style').show();
			setTimeout(function(){
				transitionIsHappening = false;
			}, 200);
        };
        if (duration > 0) {
            tile.stop();
            tile.animate({ width: smallWidth, height: smallHeight }, duration, finalize);
        }
        else {
			finalize();
        }
    };

    function closeFeature(feature) {
        if (transitionIsHappening) return false;
        collapse($(feature).parents('li.tile:first'));
    }

    function moreInfo(feature) {
        if (transitionIsHappening) return false;

        transitionIsHappening = true;

        var tile = $(feature).parents('li.tile:first'),
		silverlight = tile.children('div.bg-feature:first'),
        moreInfo = $(feature).parents('li.tile:first').children('div.bg-featureMoreInfo:first'),
        featured = silverlight,
        hidden = moreInfo;

		new OmniTrack('Module', [5], function(target) {
					var feature = (silverlight.is(':hidden')) ? ': Feature' : ''; 
		            this.LinkName = tile.children('h2').text() + feature;
				}).Track(tile);
		var actionName = (silverlight.is(':hidden')) ? 'atlasMain' : 'atlasSilverlightFeature' ;
		trackAtlas(tile.data(actionName));

        finalize = function() {
            featured.hide();
            hidden.show();
            moreInfo.children(".feature-img:first").css({ position: 'absolute', width: fullWidth, height: fullHeight });
			moreInfo.blur();
            transitionIsHappening = false;
        };

        showNext = function() {
            featured.hide();
            hidden.show();
            hidden.animate({ width: fullWidth, height: fullHeight }, duration / 2, finalize);
        };

        if (silverlight.is(":hidden")) {
            hidden = silverlight;
            featured = moreInfo;
        }
        else {
            featured = silverlight;
            hidden = moreInfo;
        }

        if (duration > 0) {
            moreInfo.children(".feature-img:first").css({ position: 'static' });
            hidden.css({ width: 1, height: 1 });
            featured.animate({ width: 1, height: 1, top: 0, left: 0 }, duration / 2, showNext);
        }
        else {
            finalize();
        }

        return false;
    }

    function initTile(node) {
        if ($(node).hasClass('has-feature') || $(node).hasClass('has-silverlight') || $(node).hasClass('has-overlay') || $(node).hasClass('has-linkout')) {

			// tracking data
			var tileName = $(node).attr('id').split('-').pop();
				$(node).data('atlasMain','HM_Busy_'+tileName+'_View');
				$(node).data('atlasSeeHow','HM_Busy_'+tileName+'_SeeHow_View');
				if($(node).hasClass('has-silverlight')) {
					$(node).data('atlasSilverlightFeature','HM_Busy_'+tileName+'_Feature_View');
				}

            $(node).mouseover(function() {
                grow(this);
            }).mouseout(function() {
                shrink(this);
            }).click(function() {
				// Special has overlay
                var tile = $(this);
				if ($(node).hasClass('has-overlay')){
					// should we close up
					openCelticModal.call($(this));
					return true;
				}
				else if ($(node).hasClass('has-linkout'))
				{
					$('a',node).click(function(e){
						// do omniture here
						e.stopPropagation();
					}).trigger('click');
					return true;
				}

				if ($(node).hasClass('has-silverlight') && tile.data('expanded')) return true;
                if (transitionIsHappening || !tile.hasClass('has-feature') && !$(node).hasClass('has-silverlight') || tile.data('expanded')) return false;
                expand(tile);
            });

            $('a.tutorial-link', node).click(openModal);

            $('a.collapse-tile-link', node).click(function(e) {
				e.preventDefault();
                closeFeature($(this));
            });

			$('a.swap-silverlight', node).click(function() {
				$(this).parents('li.tile').find('object[id^="silverlight"]').trigger('moreInfo');
            });
			
			if (!$(node).hasClass('has-silverlight') && !$(node).hasClass('has-overlay')  && !$(node).hasClass('has-linkout'))
			{
				$('a.share-this').mouseenter(function() {
					$(this).next('div.hoverCont').removeClass('closed').show(250);
				}).next('div.hoverCont').mouseleave(function() {
					$(this).hide(250, function() { $(this).addClass('closed'); });
				}).find('a').click(function(e) {
					e.preventDefault();
					e.stopImmediatePropagation();
					// Omniture tracking
					new OmniTrack('Module', [4], function(target) {
						this.LinkName = $(target).parents('li.tile:first').children('h2').text() + ':Share ' + $(target).text();
					}, 'e').Track(this);
					// Atlas tracking for email/bookmark links (other links handled by Atlas re-directs)
					if ($(this).hasClass('atEmail') || $(this).hasClass('atBookmark')) {
						var actionName = ($(this).hasClass('atEmail')) ? 'HM_Busy_Share_Email' : 'HM_Busy_Share_Bookmark';
						trackAtlas(actionName);
					}
					
					$(this).parents('div.hoverCont:first').hide(250, function() { $(this).addClass('closed') });
					if (this.href.indexOf('mailto:') == 0) {
						window.location.href = this.href;
					}
					else if ($(this).parent().hasClass('favorites')) {
						if (window.sidebar && window.sidebar.addPanel) {
							window.sidebar.addPanel(document.title, this.href, '');
						}
						else if (window.external && typeof window.external.AddFavorite == 'unknown') {
							window.external.AddFavorite(this.href, document.title);
						}
						else {
							alert(text_errorFavoriteSupport);
						}
					}
					else {
						window.open(this.href);
					}
					return false;
				});
			} 

        }
        else {
            return;
        }
    };

    function addFeatureElements(node) {
        node = $(node);
        var container = node.find('div.fg-feature'),
        share = $('<a href="#" class="share-this"><span class="social-icons"></span><span class="share-word">' + text_shareBtn + '</span><span class="share-arrow"></span></a>').appendTo(container),
		id = node.attr('id').replace('tile-', ''),
        title = document.title,
		url = window.location.toString().split('?')[0] + '?tile=' + encodeURIComponent(id);
        
		$('<a href="#" class="collapse-tile-link">' + text_closeBtn + '</a>').prependTo(container);
		drawShareThis(share, title, url, text_shareEmailTitle, text_shareEmailBody.replace('{0}', url));
		
		if(node.hasClass('has-silverlight')){
			$('<a href="#" class="swap-silverlight">&lt;&lt; return</a>').prependTo(container);
		}
    };

	function trackAtlas(actionName){
		// create tracking url and place an img on the page to trigger Atlas tracking
		var atlas = 'http://view.atdmt.com/action/'+actionName;
		$('#atlasTracking').attr('src',atlas);	
	};
	
	function setupTiles() {
		$('li.tile').each(function() {
            addFeatureElements(this);
            initTile(this);
        });
		
		$('object[id^="silverlight"]').bind('close', function(e) {
            closeFeature(this);
        });

        $('object[id^="silverlight"]').bind('moreInfo', function(e) {
            moreInfo(this);
        });
	}

    function forceShow(tile) {
		var tile;
        if (tile.length < 1) { tile = $('#tile-intro'); }
		else { tile = $(tile); }
				
        tile.stop().removeClass('tile-short').addClass('tile-feature');
		
        if ($('li.tile:first').get(0) != tile.get(0)) {
            tile.remove().prependTo('#tile-container');
        }
		
        tile.data('expanded', true);
        $('html, body').animate({ scrollTop: 0 }, duration);
        hasFeaturedTile = true;
    };

    function openCelticModal() {
		// campaign tracking
		/* Change tracking */
        new OmniTrack('Module', [5], function(target) {
            this.LinkName = $(target).children('h2').text();
        }).Track(this);
		trackAtlas($(this).data('atlasMain'));
		
        var content = $(this).find('.bg-feature').html(),
        modal = $('<div id="modal" class="jqmID1 wlVideoModal tutorial" style="visibility:visible;z-index:9998;display:block;"> \
						<div aria-labelledby="modalLabel" role="dialog" class="celticModal"> \
							<div class="celticDetail"> \
								<div role="main" class="content"> \
										<a class="closeModal">x</a>\
										<object id="Object1" data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="880" height="672">	\
										  <param name="source" value="ClientBin/Celtic.xap"/>		\
										  <param name="onError" value="onSilverlightError" />		\
										  <param name="background" value="transparent" />			\
										  <param name="windowless" value="true" />					\
										  <param name="minRuntimeVersion" value="3.0.40624.0" />	\
										  <param name="autoUpgrade" value="true" />					\
											<a class="closeModal nosl-close">close</a> \
										  <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=3.0.40624.0" class="no-sl-link" style="text-decoration:none">			\
											  <img src="img/InstallSilverlightBanner.jpg" alt="Get Microsoft Silverlight" style="border-style:none"/>		\
										  </a>																	\
										</object><iframe id="Iframe1" style="visibility:hidden;height:0px;width:0px;border:0px"></iframe>			\
									</div> \
								<div class="footer"></div> \
							</div> \
						</div>	\
					</div>'),
        body = $('body'),
        center = function() {
            if (modal) {
                var deltas = { x: 0, y: 0 },
		            dialogH = modal.height(),
			        viewportH = window.innerHeight !== undefined ? window.innerHeight : document.documentElement.clientHeight,
			        dialogW = modal.width(),
			        viewportW = window.innerWidth !== undefined ? window.innerWidth : document.documentElement.clientWidth;
                deltas.y = viewportH - dialogH;
                deltas.x = viewportW - dialogW;
                offsetY = deltas.y > 0 ? deltas.y / 2 + document.documentElement.scrollTop : document.documentElement.scrollTop,
				    offsetX = deltas.x > 0 ? deltas.x / 2 + document.documentElement.scrollLeft : document.documentElement.scrollLeft,
				    css = {};
                if (deltas.y > 0) css.top = Math.floor(offsetY) + 'px';
                if (deltas.x > 0) css.left = Math.floor(offsetX) + 'px';
                modal.css(css);
            }
            else {
                $(window).unbind('scroll', center).unbind('resize', center);
            }
        };
		
        //modal.find('div[role=main]').html(content);
		
		var object = modal.find('object').length > 0 ? modal.find('object') : null;
        modal.find('a.closeModal').live('click',function() {
            $('#modalOverlay').add(modal).fadeOut(250, function() {
                $(this).remove();
            });
            delete modal;
            return false;
        });
		if(object) object.hide();
		
        body.append('<div id="modalOverlay" class="jqmOverlay"></div>');
        body.append(modal.hide());
		center();

        //modal.fadeIn(250);
        modal.show();
        $(window).bind('scroll', center).bind('resize', center);
		
		if(object) object.fadeIn();

        return false;
    };

	(function() {
        setTimeout(function(){
			var query = window.location.search;
			var hash = window.location.hash;
			var index = query ? query.toLowerCase().indexOf('tile=') : -1;
			var initId = 'intro';

			if ( index < 0 && hash) { // direct link using hash 
				index = hash.toLowerCase().indexOf('tile=');
				query = hash;
			}

			if (index > -1) {
				query = query.toLowerCase();
				var end = query.indexOf('&', index);
				initId = query.slice(index, end > -1 ? end : query.length).split('=')[1];
			}
			if (initId == 'fourleafs') {
				initId = 'intro';
				openCelticModal();
			}
			

			forceShow('#tile-' + initId);

			//$('body').append('<script language="javascript" src="http://core.insightexpressai.com/adServer/adServerESI.aspx?bannerID=162471"></script>');
			setupTiles();
			
			

		},300);
    })();
	
    $(document).ready(function() {
		if($('#atlasTracking').length == 0){
			$(trackingTag).appendTo('body');
		}

		var query = window.location.search,
			index = query ? query.toLowerCase().indexOf('tile=') : -1,
			initId = 'intro';

		if (index > -1) {
			query = query.toLowerCase();
			var end = query.indexOf('&', index);
			initId = query.slice(index, end > -1 ? end : query.length).split('=')[1];
		}

		var tileName = $('#tile-' + initId).attr('id').split('-').pop();
		trackAtlas('HM_Busy_' + tileName + '_IndexView');
		
		$('.scWLLink').click(function(e) {
            new OmniTrack('TN', [2], null , 'e').Track(this);
        });
		
		$('.scGetHM').click(function(e) {
            new OmniTrack('TN', [3], null, 'e').Track(this);
        });

		// add facebook tracking
		$('#tile-facebook a.collapse-tile-link').live('click',function(){
			try{ $('#silverlight-facebook')[0].Content.MediaPlayer.Stop();} catch(e){}
		})
		// Add no Silverlight Link Tracking
		$('a.no-sl-link').live('click',function(){
			s.linkTrackVars='prop3,eVar3,events';
			s.linkTrackEvents='event16';
			s.eVar3=s.prop3='Click on Install Silverlight';
			s.events='event16';
			s.tl(this,'o',s.prop3);
			s.linkTrackVars='';
			s.eVar3=s.prop3= undefined;
			s.events = s.linkTrackEvents = undefined;
		});
		
    });

})(jQuery);

//Closes the active Silverlight Feature

function closeFeature(id) {
	if (id == 'celtic'){
		$('a.closeModal').trigger('click');
	} else {
		$('#silverlight-' + id).trigger('close');
	}
	
}

//Shows the moreInfo tile for the Silverlight Feature
function moreInfo(id) { 
	if (id == 'celtic'){
		$('a.closeModal').trigger('click');
	} else {
		$('#silverlight-' + id).trigger('moreInfo'); 
	}
	
}
