$(document).ready(function() {
    $.ajaxSetup({ cache: false });
	createOverlay();
	var temp = document.getElementById('bgObj');
	if (temp != null){
		sObj.bgObj = temp;
	}
	temp = document.getElementById('videoObj');
	if (temp != null){
		sObj.videoObj = temp;
	}
	temp = '';
	var isMac = navigator.appVersion.indexOf("Mac");
	if (isMac){
		initSubBox();
		initMenu();
		killOverlay();
	}else{
		if (foundCookie(cookieName) || Silverlight.isInstalled('2.0.31005.0')) {
			initSubBox();
			initMenu();
			killOverlay();
		} else {
			displayOverlay();
		}
	}
});


// Global objects
cookieName = 'webharmony';
sObj = {};
moreLess = {content:['#subBoxLeft p','#subBoxRight'],moreStr:'More',moreClass:'more',lessStr:'Less',lessClass:'less'};
demoObj = { 'panel': '#switchPanel', 'frontView': '#frontView', 'sideView': '#sideView', 'frontVideo': 'http://mediadl.microsoft.com/mediadl/www/u/uk/expression/webharmony/videos/ball-straight-v3.wmv', 'sideVideo': 'http://mediadl.microsoft.com/mediadl/www/u/uk/expression/webharmony/videos/ball-side-v3.wmv', 'link': 'a.views', 'classname': 'selected' };
resourceObj = { 'container': '#downloadContainer', 'devContainer': '#developerContainer', 'designContainer': '#designerContainer', 'itemContainer': 'ul.downloads li', 'classname': 'downloadHilite','dev':'dev', 'design':'design', 'all':'all' };
resourceTrackingObj = {'dev1':{'eat':'Software Trial','evtid':'/uk/expression/:Web Harmony - VISUAL STUDIO TRIAL'},'designer1':{'eat':'Software Trial','evtid':'/uk/expression/:Web Harmony - EXPRESSION BLEND 2 TRIAL'},'other1':{'eat':'Product Offer (discount)','evtid':'/uk/expression/:Web Harmony - JOIN MICROSOFT PARTNER PROGRAMME FREE'},'other2':{'eat':'Other','evtid':'/uk/expression/:Web Harmony - INNOVATE ON - ON THE WEB'},'other3':{'eat':'Other','evtid':'/uk/expression/:Web Harmony - SILVERLIGHT.NET'},'other4':{'eat':'Virtual Lab/Hands-On Demo','evtid':'/uk/expression/:Web Harmony - LIVE LABS'}}
bubbleObj = { 'container': 'div.speechContent p', 'dev1': { 'bubble': 'dev', dev:{ 'text': 'This is sooooo cool. And it continues in the Microsoft tradition of development language innovation.'} }, 'designer1': { 'bubble': 'design', design: { 'text': 'If you\'re committed to great work, you need this.'} }, 'other1': { 'bubble': 'all', dev: { 'text': 'This Microsoft Partner Programme is a great way of finding out what\'s happening out there in Tech World.' }, design: { 'text': 'It\'s always there when I need it. Not that I need it, of course. I\'m a genius.'}}, 'other2': { 'bubble': 'all', dev:{'text':'It\'s great to get some support when you need it most.'},design:{'text': 'This is all too exciting. I\'m getting a nose bleed.'} }, 'other3': { 'bubble': 'all', dev:{'text': 'And remember, with Silverlight you can get bufferless video streaming.'}, design:{'text':'This portal has so many cool rich experience sites.'} }, 'other4': { 'bubble': 'all', dev:{'text': 'Whatever\'s new, hot and shiny, you\'ll find it here.'}, design:{'text':'The deep zoom technology is my favourite.'}} };



function initSubBox() {
    var $subBoxToggle = $('#subBoxToggle');
    // Check to see if subToggleBox exists on page
    if ($subBoxToggle) {
        // Display More/Less link as javascript enabled
        $subBoxToggle.removeClass('hidden');
        // Click event that handles the displaying and hiding of the more /less content
        $('#subBoxToggle a').toggle(
            function() {
                $(this).removeClass(moreLess.lessClass).addClass(moreLess.moreClass).attr('title', moreLess.moreStr).text(moreLess.moreStr);
                for (var cc = 0; cc < moreLess.content.length; cc++) {
                    $(moreLess.content[cc]).hide();
                }
            },
            function() {
                $(this).removeClass(moreLess.moreClass).addClass(moreLess.lessClass).attr('title', moreLess.lessStr).text(moreLess.lessStr);
                for (var cc = 0; cc < moreLess.content.length; cc++) {
                    $(moreLess.content[cc]).show();
                }
            }
        );
        // Trigger onClick event to hide drop down
        $('#subBoxToggle a').trigger('click');
    }
}

function initMenu() {
    var $menuLinks = $('a.menu');
    var $menuContainer = $('#contentContainer');
    var $loadingWait = $('<div></div>').addClass('loading').append($('<img/>').attr({ 'src': 'images/ajax-loader.gif', 'alt': 'Loading. please wait', 'id': 'load-wait' }));
    if ($menuLinks) {
        $menuLinks.click(function(event) {
            stopBgAnim();
            $menuLinks.removeClass('selected');
            var filePath = 'includes/html/';
            var fileName = 'overview.aspx';
            switch ($(this).text().toLowerCase()) {
                case 'demo':
                    fileName = 'demo.aspx';
                    break;
                case 'case study':
                    fileName = 'case-study.aspx';
                    break;
                case 'resources':
                    fileName = 'resources.aspx';
                    break;
                default:
                    break;
            }
            $menuContainer.empty().before($loadingWait).load(filePath + fileName, { 'ts': Date.parse(Date()) }, function() {
                $loadingWait.remove();
                attachEvents();
                startBgAnim();
            })
			/*
			$menuContainer.fadeOut('normal',function(){
				$(this).before($loadingWait).empty().load(filePath + fileName, { 'ts': Date.parse(Date()) }, function(){
					$loadingWait.remove();
					attachEvents();
					$(this).fadeIn('normal');
					startBgAnim();
					
				})
			})
			*/
            $(this).addClass('selected');
            event.preventDefault();
        });
    }
    attachEvents();
}


// Handles the attaching of events depending on which divs are present
function attachEvents() {
    sObj.videoObj = document.getElementById('videoObj');
    if ($(demoObj.panel)) {
        demoEvents();
    }

    if ($(resourceObj.container)) {
        resourcesEvents();
    }
    
}

function demoEvents() {
    if ($(demoObj.panel)) {
        var $viewLinks = $(demoObj.link);
        $(demoObj.frontView).click(function() {
            sObj.videoURL = demoObj.frontVideo;
            sObj.currentPos = getVideoPosition()
            switchVideo();
            setVideoPosition();
            $viewLinks.removeClass(demoObj.classname);
            $(this).find(demoObj.link).addClass(demoObj.classname);
        });

        $(demoObj.sideView).click(function() {
            sObj.videoURL = demoObj.sideVideo;
            sObj.currentPos = getVideoPosition()
            switchVideo();
            setVideoPosition();
            $viewLinks.removeClass(demoObj.classname);
            $(this).find(demoObj.link).addClass(demoObj.classname);
        });
    }
}

function resourcesEvents() {
    var $devBubble = $(resourceObj.devContainer);
    var $designerBubble = $(resourceObj.designContainer);
    if ($(resourceObj.container)) {
        setupResourceClick();
		$('.extralink').hover(function(){
			$(resourceObj.itemContainer).unbind('click');
		},
		function(){
			setupResourceClick();
		});
		
        $(resourceObj.itemContainer).hover(function() {
            $(this).addClass(resourceObj.classname);
            var whichObj = $(this).attr('id');
            if (bubbleObj[whichObj]) {
                switch (bubbleObj[whichObj].bubble) {
                    case resourceObj.dev:
                        if (!bubbleObj.developer) {
                            bubbleObj.developer = $devBubble.find(bubbleObj.container).text();
                        }
						updateBubble($devBubble, bubbleObj[whichObj].dev.text);
                        break;
                    case resourceObj.design:
                        if (!bubbleObj.designer) {
                            bubbleObj.designer = $designerBubble.find(bubbleObj.container).text();
                        }
						updateBubble($designerBubble, bubbleObj[whichObj].design.text);
                        break;
                    case resourceObj.all:
                        if (!bubbleObj.developer) {
                            bubbleObj.developer = $devBubble.find(bubbleObj.container).text();
                        }
                        if (!bubbleObj.designer) {
                            bubbleObj.designer = $designerBubble.find(bubbleObj.container).text();
                        }
                        updateBubble($devBubble, bubbleObj[whichObj].dev.text);
                        updateBubble($designerBubble, bubbleObj[whichObj].design.text);
                        break;
                    default:
                        break;
                }
            }
        }, function() {
            $(this).removeClass(resourceObj.classname);
            var whichObj = $(this).attr('id');
            if (bubbleObj[whichObj]) {
                switch (bubbleObj[whichObj].bubble) {
                    case resourceObj.dev:
						updateBubble($devBubble, bubbleObj.developer);
                        break;
                    case resourceObj.design:
						updateBubble($designerBubble, bubbleObj.designer);
                        break;
                    case resourceObj.all:
                        updateBubble($devBubble, bubbleObj.developer);
						updateBubble($designerBubble, bubbleObj.designer);
                        break;
                    default:
                        break;
                }
            }
        });
    }
}

function setupResourceClick(){
	$(resourceObj.itemContainer).click(function(event) {
		var target = $(this).find('a').attr('target');
		var href = $(this).find('a').attr('href');
		var whichObj = $(this).attr('id');
		DCSext.mg_eat = resourceTrackingObj[whichObj].eat;
		DCSext.wt_evtid = resourceTrackingObj[whichObj].evtid;
		if (target) {
			var win = window.open(href, target);
		} else {
			document.loaction = href;
		}
		event.preventDefault();
	});
}

function updateBubble(which,text){
	which.find(bubbleObj.container).text(text);
}

function createOverlay() {
    var pageHeight = $(document).height()+'px';
    $('#pageOuterContainer').after('<div id="overlay"></div>');
    $('#overlay').css({ background: '#efefef', height: pageHeight, display: 'none' }).load('includes/html/which-version.aspx', function(){
		//attach events
		$('#enhancedSite a').click(function(event) {
			setCookie(cookieName, 'true');
			document.location = document.location;
			event.preventDefault();
		});

		$('#basicSite a').click(function(event) {
			setCookie(cookieName, 'false');
			document.location = document.location;
			event.preventDefault();
		});
	});
}

function displayOverlay(){
    stopBgAnim();
    $('#overlay').css({display:'block'});
}

function killOverlay(){
    $('#overlay').remove();
}


/* Silverlight Video and animation wrapper functions */
function getVideoPosition() {    
    if (sObj.videoObj) {
        return sObj.videoObj.Content.Page.PlayBackPosition();
    }
    return '';
}

function setVideoPosition() {
    if (sObj.videoObj && (sObj.currentPos != '' && sObj.currentPos != undefined)) {
        sObj.videoObj.Content.Page.SeekPlayback(sObj.currentPos);
    }
}

function switchVideo() {
    if (sObj.videoObj && sObj.videoURL) {
        sObj.videoObj.Content.Page.SetVideoSource(sObj.videoURL);
    }
}

function stopVideo() {
    if (sObj.videoObj) {
        sObj.videoObj.Content.Page.Stop();
    }
}

function startBgAnim() {
    if (sObj.bgObj) {
        sObj.bgObj.Content.Page.StartAnimation();
    }
}

function stopBgAnim() {
    if (sObj.bgObj) {
        sObj.bgObj.Content.Page.StopAnimation();
	}
    stopVideo();
}


/* type of video/flat content */
function setLevel(dataObj){
	dataObj.useDownLevel = navigator.appVersion.indexOf('PPC')?false:true;
	if (dataObj.useDownLevel || dataObj.debug==true){
		downLevel(dataObj);
	}else{
		var isSilverlightInstalled = Silverlight.isInstalled(dataObj.minVersion);
		if (isSilverlightInstalled || getCookie(dataObj.cookieName) == 'true') {
			upLevel(dataObj);
		} else {
			downLevel(dataObj);
		}
	}
}

function upLevel(dataObj){
	Silverlight.createObject(
		"ClientBin/VideoPlayerM.xap",
		document.getElementById(dataObj.videoElement),
		"videoObj",
		{ width:dataObj.silverSettings.width, height:dataObj.silverSettings.height, background:'transparent', minruntimeversion: dataObj.minVersion, Windowless: 'true' },
		"",
		dataObj.silverParams,
		""
	);
}

function downLevel(dataObj){
	if(foundCookie(dataObj.cookieName) && navigator.appVersion.indexOf('MSIE')){
		var mediaPlayerLocation = document.getElementById(dataObj.videoElement);
		mediaPlayerLocation.innerHTML = createMediaPlayerControl(wm);
	}else{
		$('<a></a>').attr({'href':dataObj.wm.URL,'class':'video'}).text('Watch the video in your default media player').prependTo(validjQueryID(dataObj.videoElement));
	}
}

function validjQueryID(oldID){
	if (oldID.indexOf('#') >= 0){
		return oldID;
	}else{
		return '#'+oldID;
	}
}

/* Media Player fallback video */
function createMediaPlayerControl(mpProperties) {
    var htmlBuilder = [];
	var embedBuilder = '<EMBED type="video/x-ms-wmp"';
    htmlBuilder.push('<object classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6"');
    if (mpProperties.id != null) {
        htmlBuilder.push(' id="' + mpProperties.id + '"');
		embedBuilder += ' id="' + mpProperties.id + '"';
    }
    if (mpProperties.width != null) {
        htmlBuilder.push(' width="' + mpProperties.width + '"');
		embedBuilder += ' width="' + mpProperties.width + '"';
    }
    if (mpProperties.height != null) {
        htmlBuilder.push(' height="' + mpProperties.height + '"');
		embedBuilder += ' height="' + mpProperties.height + '"';
    }
    htmlBuilder.push(' >');

    delete mpProperties.id;
    delete mpProperties.width;
    delete mpProperties.height;

    for (var name in mpProperties) {
        if (mpProperties[name]) {
            htmlBuilder.push('<param name="' + htmlAttributeEncode(name) + '" value="' + htmlAttributeEncode(mpProperties[name]) + '" />');
			embedBuilder += ' ' + htmlAttributeEncode(name.toLowerCase()) + '="' + htmlAttributeEncode(mpProperties[name]) + '"';
        }
    }
	embedBuilder += ' />';
	htmlBuilder.push(embedBuilder);
    htmlBuilder.push('<\/object>');
    return htmlBuilder.join('');
}

function htmlAttributeEncode(strInput) {
    var c; var retVal = '';
    if (strInput == null) {
        return null;
    }
    for (var cnt = 0; cnt < strInput.length; cnt++) {
        c = strInput.charCodeAt(cnt);
        if (((c > 96) && (c < 123)) ||
                  ((c > 64) && (c < 91)) ||
                  ((c > 43) && (c < 58) && (c != 47)) ||
                  (c == 95)) {
            retVal = retVal + String.fromCharCode(c);
        }
        else {
            retVal = retVal + '&#' + c + ';';
        }
    }
    return retVal;
}


//Cookie handling routines
function foundCookie(cookieName)
{
	var cookie = getCookie(cookieName);
	
	if (cookie != ""){
		return true;
	}
	else
	{
	    return false;
	}
}
		
function setCookie(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}
	
function getCookie(c_name)
{
	if (document.cookie.length>0)
	{
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1)
		{ 
			c_start=c_start + c_name.length+1; 
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		} 
	}
	return "";
}