var Plugin = null;
var Root = null;
var _IsStartup = true;
var _LanguageList = ['English', 'Deutsch'];
var _PageList = ['Highlight', 'Specs', 'Testimonials', 'Features', 'News'];
var _SiteList = ['Intro', 'w700', 'w700ds', 'Sony'];
var _CurrentSite = _SiteList[0];
var _CurrentPage = _PageList[0];
var _CurrentLanguage = _LanguageList[0];
var _InAnimation = false;
var _RegisteredTimerList = [];
var _HighlightedLaptop = '';
var _IsDownloading = false;
var _DoNotSetSource = ['images/precache/loading.screen.png', 'images/precache/loading.bar.png', 'images/precache/ajax_50.png', 'images/precache/loading.progress.bg.png', 'images/precache/loading.text.png', ];

if (!window.Product) Product = {};

Product.Page = function() { }

Silverlight.createDelegate = function(instance, method) {
    return function() {
        return method.apply(instance, arguments);
    }
}

function Page_Loaded(sender, events) {
	Plugin = sender.getHost();
}

function CreateSilverlight(page) {
    var scene = new Product.Page();
    Silverlight.createObjectEx(
        {
            source: page,
            parentElement: document.getElementById("silverlightControlHost"),
            id: "SilverlightControl",
            properties: { width: "100%", height: "100%", version: "1.0", isWindowless: "true", background: "Transparent" },
            events: {
                onLoad: Silverlight.createDelegate(scene, scene.handleLoad),
                onError: function(sender, args) {
                    var errorDiv = document.getElementById("errorLocation");
                    if (errorDiv != null) {
                        var errorText = args.errorType + "- " + args.errorMessage;

                        if (args.ErrorType == "ParserError") {
                            errorText += "<br>File: " + args.xamlFile;
                            errorText += ", line " + args.lineNumber;
                            errorText += " character " + args.charPosition;
                        } else if (args.ErrorType == "RuntimeError") {
                            errorText += "<br>line " + args.lineNumber;
                            errorText += " character " + args.charPosition;
                        }
                        errorDiv.innerHTML = errorText;
                        //alert(errorText);
                    }
                }
            }
        }
    );
}

Product.Page.prototype =
{
    handleLoad: function(control, userContext, rootElement) {
        this.control = control;
        Control = control;
        UserContext = userContext;
        Root = rootElement;

        UpdateSizeOfSilverlightControlHost();
        AddHandler(window, 'resize', 'UpdateSizeOfSilverlightControlHost');

        AjaxAnimation();

        LoadXAML(0);
        SetFooterClickEvents();
        _IsStartup = false;
    }
}

function UpdateSizeOfSilverlightControlHost() {
    var obj = document.getElementById("silverlightControlHost");
    var html = document.getElementsByTagName('HTML')[0];
    var width = 940;
    var height = 630;

    if (width < html.clientWidth) width = html.clientWidth;
    if (height < html.clientHeight) height = html.clientHeight;

    obj.style.width = width + 'px';
    obj.style.height = height + 'px';
}

function AjaxAnimation() {
	var icon = GetObject("AjaxAnimation")
	var margin = 0;
	setInterval(
		function() {
			if (GetObject("Testimonials_SequenceLoadingAjaxAnimation")) GetObject("Testimonials_SequenceLoadingAjaxAnimation")["Canvas.Left"] = margin;
			icon["Canvas.Left"] = margin;
			if (margin - 50 > icon.Width * -1) {
				margin -= 50;
			} else {
				margin = 0;
			}
		}
	, 100);
}


function LoadXAML(siteListIndex) {

	GetObject("LoadingBar").Width = 1;

	GetObject("sb_LoadingFadeIn").stop();
	GetObject("sb_LoadingFadeIn").begin();

	setTimeout(
		function() {
			_CurrentSite = _SiteList[siteListIndex];
			_CurrentPage = _PageList[0];

			SetLanguageIcon(false);

			setTimeout(
				function() {
					var downloader = Control.createObject('downloader');

					GetObject("SiteBG_Lenovo").Opacity = 0;
					GetObject("SiteBG_Sony").Opacity = 0;

					switch (_CurrentSite) {
						case _SiteList[0]:
						case _SiteList[1]:
						case _SiteList[2]:
							GetObject("SiteBG_Lenovo").Opacity = 1;
							break;
						case _SiteList[3]:
							GetObject("SiteBG_Sony").Opacity = 1;
							break;
					}

					downloader.open('GET', 'xaml/' + _CurrentSite + '.xaml');
					downloader.addEventListener('DownloadProgressChanged', 'DownloadXAMLProgressChanged');
					downloader.addEventListener('Completed', 'DownloadXAMLCompleted');
					downloader.send();
				}
			, 100);
		}
	, 1000);			
}

function DownloadXAMLProgressChanged(sender, args) {
	var done = Math.floor(sender.downloadProgress * 100);
	var progress = GetObject("LoadingBar");
    progress.Width = (done / 100) * 300;
}
function DownloadImageProgressChanged(sender, args) {
	var done = Math.floor(sender.downloadProgress * 100);
	var progress = GetObject("LoadingBar");
	progress.Width = (done / 100) * 300;
}

function DownloadImageCompleted(sender, args) {
	_IsDownloading = false;
	SetSource(sender, Root);
}

function DownloadImageProgressError(sender, args) {
	_IsDownloading = false;
}

function DownloadXAMLCompleted(sender, args) {
    if (sender.status != 200) {
		alert("download failed");
		return;
    }
    var theXaml = sender.getResponseText('');
	var theContent = sender.getHost().content.createFromXaml(theXaml);
	var myRoot = GetObject("Content");

	ClearTimers();
	myRoot.children.Clear();
	myRoot.children.Insert(0, theContent);
       
    _IsDownloading = true;

    var image = Control.createObject('downloader');
    image.open('GET', 'images/' + _CurrentSite + '.zip');
    image.addEventListener('DownloadProgressChanged', 'DownloadImageProgressChanged');
    image.addEventListener('DownloadFailed', 'DownloadImageProgressError');
    image.addEventListener('Completed', 'DownloadImageCompleted');
    image.send();

    var loop = setInterval(
		function() {
			if (_IsDownloading) return;

			switch (_CurrentSite) {
				case _SiteList[0]:
					SetIntroPageItems();
					break;
				case _SiteList[1]:
					Setw700PageItems();
					break;
				case _SiteList[2]:
					Setw700dsPageItems();
					break;
				case _SiteList[3]:
					SetSonyPageItems();
					break;
			}

			GetObject("LoadingBar").Width = 1;

			GetObject("sb_LoadingFadeIn").stop();
			GetObject("sb_LoadingFadeOut").begin();

			clearInterval(loop);
		}
    , 250);
}

function IsSafeToSetSource(value) {
	if (value == '') return false;
	var list = _DoNotSetSource;
	for (var i = 0; i < list.length; i++) {
		if (value == list[i]) return false;
	}
	return true;
}

function SetSource(sender, root) {
	switch (root.toString()) {
		case 'Canvas':
		case 'Grid':
		case 'StackPanel':
		case 'Panel':
			for (var i = 0; i < root.children.count; i++) {
				SetSource(sender, root.children.getItem(i));
			}
			break;
		case 'Image':
			try {
				var value = root.source;
				if (IsSafeToSetSource(value)) root.setSource(sender, value);
			} catch (e) { }
	}
}

function GetObject(element) {
    try {
        return Root.findName(element);
    } catch (e) {
        return null;
    }
}

function ApplyStoryboard(name, target, objCompletedEvent) {
    var obj = GetObject(name);
    if (objCompletedEvent == null) {
        objCompletedEvent = function() { };
    }
    obj.stop();
    obj["Storyboard.TargetName"] = target;
    obj.addEventListener("Completed", objCompletedEvent);
    obj.begin();
}

function RegisterTimer(id) {
    _RegisteredTimerList.push(id);
}

function ClearTimers() {
    for (var i = 0; i < _RegisteredTimerList.length; i++) {
        clearInterval(_RegisteredTimerList[i]);
    }
}

function ValidateAndToggleVideoStartup() {
    if (_CurrentSite == _SiteList[1]) {
        pTestimonials.StopVideo();
        pFeatures.StopVideo();
        if (_CurrentPage == _PageList[2]) {
        	pTestimonials.PlayVideo();
        } else if (_CurrentPage == _PageList[3]) {
			pFeatures.PlayVideo();
        }
    } else if (_CurrentSite == _SiteList[2]) {
		if (pTestimonials.IsSquenceDownloadCompleted()) pTestimonials.StopVideo();
        if (_CurrentPage == _PageList[2]) {
        	if (pTestimonials.IsSquenceDownloadCompleted()) pTestimonials.PlayVideo();
        }
    }
}

function WireUpNavigationEvents() {
    var home = GetObject("Btn_Home");
    var highlight = GetObject("Btn_Highlight");
    var specs = GetObject("Btn_Specs");
    var testimonials = GetObject("Btn_Testimonials");
    var features = GetObject("Btn_Features");
    var news = GetObject("Btn_News");
    var shopnow = GetObject("Btn_ShopNow");

    if (home) {
        home.addEventListener("MouseLeftButtonDown", function() { LoadXAML(0); ValidateAndToggleVideoStartup(); });
        home.addEventListener("MouseEnter", function() { ApplyStoryboard("sb_QuickFadeIn", "Btn_Home_Over"); });
        home.addEventListener("MouseLeave", function() { ApplyStoryboard("sb_QuickFadeOut", "Btn_Home_Over"); });
    }
    if (highlight) {
        highlight.addEventListener("MouseLeftButtonDown", function() { if (_CurrentPage != _PageList[0]) { SelectPage(_PageList[0]); ValidateAndToggleVideoStartup(); } });
        highlight.addEventListener("MouseEnter", function() { if (_CurrentPage != _PageList[0]) ApplyStoryboard("sb_QuickFadeIn_Highlight", "Btn_Highlight_Over"); });
        highlight.addEventListener("MouseLeave", function() { if (_CurrentPage != _PageList[0]) ApplyStoryboard("sb_QuickFadeOut_Highlight", "Btn_Highlight_Over"); });
    }
    if (specs) {
        specs.addEventListener("MouseLeftButtonDown", function() { SetSpecsContent(_LanguageList[0]); if (_CurrentPage != _PageList[1]) { SelectPage(_PageList[1]); ValidateAndToggleVideoStartup(); } });
        specs.addEventListener("MouseEnter", function() { if (_CurrentPage != _PageList[1]) ApplyStoryboard("sb_QuickFadeIn_Specs", "Btn_Specs_Over"); });
        specs.addEventListener("MouseLeave", function() { if (_CurrentPage != _PageList[1]) ApplyStoryboard("sb_QuickFadeOut_Specs", "Btn_Specs_Over"); });
    }
    if (testimonials) {
        testimonials.addEventListener("MouseLeftButtonDown", function() { if (_CurrentPage != _PageList[2]) { SelectPage(_PageList[2]); ValidateAndToggleVideoStartup(); } });
        testimonials.addEventListener("MouseEnter", function() { if (_CurrentPage != _PageList[2]) ApplyStoryboard("sb_QuickFadeIn_Testimonials", "Btn_Testimonials_Over"); });
        testimonials.addEventListener("MouseLeave", function() { if (_CurrentPage != _PageList[2]) ApplyStoryboard("sb_QuickFadeOut_Testimonials", "Btn_Testimonials_Over"); });
    }
    if (features) {
        features.addEventListener("MouseLeftButtonDown", function() { if (_CurrentPage != _PageList[3]) { SelectPage(_PageList[3]); ValidateAndToggleVideoStartup(); } });
        features.addEventListener("MouseEnter", function() { if (_CurrentPage != _PageList[3]) ApplyStoryboard("sb_QuickFadeIn_Features", "Btn_Features_Over"); });
        features.addEventListener("MouseLeave", function() { if (_CurrentPage != _PageList[3]) ApplyStoryboard("sb_QuickFadeOut_Features", "Btn_Features_Over"); });
    }
    if (news) {
        news.addEventListener("MouseLeftButtonDown", function() { if (_CurrentPage != _PageList[4]) { SelectPage(_PageList[4]); ValidateAndToggleVideoStartup(); } });
        news.addEventListener("MouseEnter", function() { if (_CurrentPage != _PageList[4]) ApplyStoryboard("sb_QuickFadeIn_News", "Btn_News_Over"); });
        news.addEventListener("MouseLeave", function() { if (_CurrentPage != _PageList[4]) ApplyStoryboard("sb_QuickFadeOut_News", "Btn_News_Over"); });
    }
    if (shopnow) {
        var url = '';
        switch (_CurrentSite) {
            case _SiteList[1]:
                url = 'http://shop.lenovo.com/SEUILibrary/controller/e/web/LenovoPortal/en_US/catalog.workflow:category.details?current-catalog-id=12F0696583E04D86B9B79B0FEC01C087&current-category-id=469B22CBBD044D2CB149286D6891D3E6cid=USPMSFTW700&';
                break;
            case _SiteList[2]:
                url = 'http://shop.lenovo.com/SEUILibrary/controller/e/web/LenovoPortal/en_US/catalog.workflow:category.details?current-catalog-id=12F0696583E04D86B9B79B0FEC01C087&current-category-id=469B22CBBD044D2CB149286D6891D3E6cid=USPMSFTW700&';
                break;
            case _SiteList[3]:
                url = 'http://www.sonystyle.com/webapp/wcs/stores/servlet/CategoryDisplay?catalogId=10551&storeId=10151&langId=-1&categoryId=8198552921644588896&parentCategoryId=16154';
                break;
        }
        shopnow.addEventListener("MouseLeftButtonDown", function() { window.open(url); });
        shopnow.addEventListener("MouseEnter", function() { ApplyStoryboard("sb_QuickFadeIn", "Btn_ShopNow_Over"); });
        shopnow.addEventListener("MouseLeave", function() { ApplyStoryboard("sb_QuickFadeOut", "Btn_ShopNow_Over"); });
    }
    
    SelectPage(_CurrentPage);
}

function SelectPage(which) {
    var highlight = GetObject("Btn_Highlight_Over");
    var specs = GetObject("Btn_Specs_Over");
    var testimonials = GetObject("Btn_Testimonials_Over");
    var features = GetObject("Btn_Features_Over");
    var news = GetObject("Btn_News_Over");

    if (highlight && _CurrentPage == _PageList[0] && parseInt(highlight["Opacity"]) == 1) {
        ApplyStoryboard("sb_QuickFadeOut_Highlight", "Btn_Highlight_Over");
        ApplyStoryboard("sb_FadeOutPanel", "Panel_Highlight", function() { if (GetObject("Panel_Highlight")) GetObject("Panel_Highlight")["Visibility"] = "Collapsed"; });
    }
    if (specs && _CurrentPage == _PageList[1] && parseInt(specs["Opacity"]) == 1) {
        ApplyStoryboard("sb_QuickFadeOut_Specs", "Btn_Specs_Over");
        ApplyStoryboard("sb_FadeOutPanel", "Panel_Specs", function() { if (GetObject("Panel_Specs")) GetObject("Panel_Specs")["Visibility"] = "Collapsed"; });
    }
    if (testimonials && _CurrentPage == _PageList[2] && parseInt(testimonials["Opacity"]) == 1) {
        ApplyStoryboard("sb_QuickFadeOut_Testimonials", "Btn_Testimonials_Over");
        ApplyStoryboard("sb_FadeOutPanel", "Panel_Testimonials", function() { if (GetObject("Panel_Testimonials")) GetObject("Panel_Testimonials")["Visibility"] = "Collapsed"; });
    }
    if (features && _CurrentPage == _PageList[3] && parseInt(features["Opacity"]) == 1) {
        ApplyStoryboard("sb_QuickFadeOut_Features", "Btn_Features_Over");
        ApplyStoryboard("sb_FadeOutPanel", "Panel_Features", function() { if (GetObject("Panel_Features")) GetObject("Panel_Features")["Visibility"] = "Collapsed"; });
    }
    if (news && _CurrentPage == _PageList[4] && parseInt(news["Opacity"]) == 1) {
        ApplyStoryboard("sb_QuickFadeOut_News", "Btn_News_Over");
        ApplyStoryboard("sb_FadeOutPanel", "Panel_News", function() { if (GetObject("Panel_News")) GetObject("Panel_News")["Visibility"] = "Collapsed"; });
    }

    _CurrentPage = which;

    setTimeout(
		function() {
		    TransitionToPage(which);
		}
	, 300);
    
}

function EnsurePanelVisibility(name) {
    setTimeout(function() { GetObject(name)["Visibility"] = "Visible"; }, 200);
}

function TransitionToPage(which) {
    var highlight = GetObject("Btn_Highlight_Over");
    var specs = GetObject("Btn_Specs_Over");
    var testimonials = GetObject("Btn_Testimonials_Over");
    var features = GetObject("Btn_Features_Over");
    var news = GetObject("Btn_News_Over");

    switch (which) {
        case _PageList[0]:
            highlight["Opacity"] = 1;
            GetObject("Panel_Highlight")["Visibility"] = "Visible";
            ApplyStoryboard("sb_FadeInPanel", "Panel_Highlight");
            SetLanguageIcon(false);
            EnsurePanelVisibility('Panel_Highlight');
            break;
        case _PageList[1]:
            specs["Opacity"] = 1;
            GetObject("Panel_Specs")["Visibility"] = "Visible";
            ApplyStoryboard("sb_FadeInPanel", "Panel_Specs");
            SetLanguageIcon(true);
            EnsurePanelVisibility('Panel_Specs');
            break;
        case _PageList[2]:
            testimonials["Opacity"] = 1;
            GetObject("Panel_Testimonials")["Visibility"] = "Visible";
            ApplyStoryboard("sb_FadeInPanel", "Panel_Testimonials");
            SetLanguageIcon(false);
            EnsurePanelVisibility('Panel_Testimonials');
            break;
        case _PageList[3]:
            features["Opacity"] = 1;
            GetObject("Panel_Features")["Visibility"] = "Visible";
            ApplyStoryboard("sb_FadeInPanel", "Panel_Features");
            SetLanguageIcon(false);
            EnsurePanelVisibility('Panel_Features');
            break;
        case _PageList[4]:
            news["Opacity"] = 1;
            GetObject("Panel_News")["Visibility"] = "Visible";
            ApplyStoryboard("sb_FadeInPanel", "Panel_News");
            SetLanguageIcon(false);
            EnsurePanelVisibility('Panel_News');
            break;
    }
}

function SetLanguageIcon(isEnabled) {
    if (isEnabled) {
        if (_CurrentSite == _SiteList[1]) {
            ApplyStoryboard("sb_FadeIn_Deutch", "Logo_Deutsch");
            GetObject("Logo_Deutsch")["Cursor"] = 'Hand';
        }
    } else {
        ApplyStoryboard("sb_FadeOut_Deutch", "Logo_Deutsch");
        GetObject("Logo_Deutsch")["Cursor"] = 'Default';
    }
}

function SetSpecsContent(language) {
    if (_CurrentPage == _PageList[1] && _CurrentSite == _SiteList[1]) {
        for (var i = 0; i < _LanguageList.length; i++) {
            var title = GetObject("Spec_TitleText_" + _LanguageList[i]);
            var body = GetObject("Spec_Text_" + _LanguageList[i]);
            if (title) title["Opacity"] = 0;
            if (body) body["Opacity"] = 0;
        }
        GetObject("Spec_TitleText_" + language)["Opacity"] = 1;
        GetObject("Spec_Text_" + language)["Opacity"] = 1;
        _CurrentLanguage = language;
    } else {
        _CurrentLanguage = _LanguageList[0];
    }
    
}

function SetFooterClickEvents() {
    GetObject("Logo_Deutsch").addEventListener("MouseLeftButtonDown", function() {
        if (_CurrentLanguage == _LanguageList[0]) {
            SetSpecsContent(_LanguageList[1]);
        } else {
            SetSpecsContent(_LanguageList[0]);
        }
    });
    GetObject("Logo_Icons").addEventListener("MouseLeftButtonDown", function() { window.open('http://www.microsoft.com/prophoto/icons/default.aspx'); });
    GetObject("Link_Privacy_Statement").addEventListener("MouseLeftButtonDown", function() { window.open('http://www.microsoft.com/info/privacy/default.mspx'); });
    GetObject("Link_Terms_Of_Use").addEventListener("MouseLeftButtonDown", function() { window.open('http://www.microsoft.com/info/cpyright.mspx'); });
    GetObject("Logo_Microsoft").addEventListener("MouseLeftButtonDown", function() { window.open('http://www.microsoft.com/prophoto/'); });
}

function ScrollBar() {
   	var _this = this;
   	var _track, _notch, _content, _canvas, _offSet = 0;
   	var _initialY, _dragX = 0, _dragY = 0;
   	var _isMouseDown = false;
	
   	this.SetTrack = function(name) {
   		_track = GetObject(name);
   	};
   	this.SetNotch = function(name) {
   		_notch = GetObject(name);
   		_notch.addEventListener("MouseLeftButtonDown", _this.DragStart);
   		_notch.addEventListener("MouseMove", _this.MouseMove);
   		_notch.addEventListener("MouseLeftButtonUp", _this.DragStop);
   	};
   	this.SetContent = function(name) {
   		_content = GetObject(name);
   	};
   	this.SetCanvas = function(name) {
   		_canvas = GetObject(name);
   	};
   	this.SetScrollOffset = function(height) {
   		_offSet = height;
   	};
   	this.MouseMove = function(s, e) {
   		var thisTrackHeight = _track["Height"];
   		var thisTrackTop = _track["Canvas.Top"];
   		var thisThumbHeight = _notch["Height"];
   		var thisTrackEnd = thisTrackTop + thisTrackHeight - thisThumbHeight - 3;
   		var thisTrackStart = thisTrackTop + 3;
   		var slideItemMaxScroll = _content["Height"] - _offSet;
   		var maxScroll = thisTrackEnd - thisTrackStart;
   		var slideItem = _canvas;

   		if (_isMouseDown) {
   			var currX = e.getPosition(null).x;
   			var currY = e.getPosition(null).y;
   			if (s["Canvas.Top"] + currY - _dragY < thisTrackEnd && s["Canvas.Top"] + currY - _dragY > thisTrackStart) {
   				s["Canvas.Top"] += currY - _dragY;
   			} else {
   				if (s["Canvas.Top"] + currY - _dragY <= thisTrackStart) {
   					s["Canvas.Top"] = thisTrackStart;
   				} else if (s["Canvas.Top"] + currY - _dragY >= thisTrackEnd) {
   					s["Canvas.Top"] = thisTrackEnd;
   				}
   			}
   			if (currY > thisTrackTop + _initialY && currY < thisTrackTop + thisTrackHeight - thisThumbHeight + _initialY) {
   				_dragX = currX;
   				_dragY = currY;
   			}
   			thisScrollPercent = (s["Canvas.Top"] - thisTrackStart) / maxScroll;
   			slideItem["Canvas.Top"] = -(slideItemMaxScroll * thisScrollPercent);
   		}
   	};
   	this.DragStart = function(s, e) {
   		s.captureMouse();
   		_dragX = e.getPosition(null).x;
   		_dragY = e.getPosition(null).y;
   		_initialY = e.getPosition(null).y - s["Canvas.Top"];
   		_isMouseDown = true;
   	};
   	this.DragStop = function(s, e) {
   		_isMouseDown = false;
   		s.releaseMouseCapture();
   	};
}

function SetAnimatedLink(rootName, animatedName, storyboardOver, storyboardOut, urlOrObj) {
    var item = GetObject(rootName);
    if (typeof (urlOrObj) == 'string') {
        item.addEventListener("MouseLeftButtonDown", function() { window.open(urlOrObj); });
    } else if (urlOrObj) {
    item.addEventListener("MouseLeftButtonDown", urlOrObj);
    }
    item.addEventListener("MouseEnter", function() { ApplyStoryboard(storyboardOver, animatedName); ApplyStoryboard(storyboardOut, rootName); });
   	item.addEventListener("MouseLeave", function() { ApplyStoryboard(storyboardOut, animatedName); ApplyStoryboard(storyboardOver, rootName); });
}

function SelectedHighlightedLaptop(which) {
    if (_HighlightedLaptop == which) return;
    if (_HighlightedLaptop != '') {
        ApplyStoryboard("sb_QuickFadeOut_Highlight", "Laptop_" + _HighlightedLaptop);
        ApplyStoryboard("sb_FadeOutLaptopIcon", "Laptop_" + _HighlightedLaptop + '_Icon');

        for (var i = 0; i < 3; i++) {
            var item = GetObject("HighLight_Crosshair_" + _HighlightedLaptop + "_" + i);
            if (item) {
                item["IsHitTestVisible"] = false;
                ApplyStoryboard("sb_FadeOut_CrossHeir_" + i, "HighLight_Crosshair_" + _HighlightedLaptop + "_" + i);
            }
        }

        for (var i = 0; i < 1; i++) {
            var award = GetObject("HighLight_Award_" + _HighlightedLaptop + "_" + i);
            if (award) {
                ApplyStoryboard("sb_FadeOut_Award_" + i, "HighLight_Award_" + _HighlightedLaptop + "_" + i);
            }
        }
         
    }

    _HighlightedLaptop = which;
    ApplyStoryboard("sb_AnimateIn_Laptop" + which, "Laptop_" + which);
    ApplyStoryboard("sb_FadeInLaptopIcon", "Laptop_" + which + '_Icon');

    GetObject("sb_SlideCarrot_" + which).begin();

    for (var i = 0; i < 3; i++) {
        var item = GetObject("HighLight_Crosshair_" + which + "_" + i);
        if (item) {
            item["IsHitTestVisible"] = true;
            ApplyStoryboard("sb_FadeIn_CrossHeir_" + i, "HighLight_Crosshair_" + which + "_" + i);
        }
    }

    for (var i = 0; i < 1; i++) {
        var award = GetObject("HighLight_Award_" + which + "_" + i);
        if (award) {
            ApplyStoryboard("sb_FadeIn_Award_" + i, "HighLight_Award_" + which + "_" + i);
        }
    }
    
}

function DisplayHighlightText(direction, which, index) {
    if (_HighlightedLaptop != which) return;

    var item = GetObject("HighLight_Crosshair_" + which + "_" + index);

    if (direction == 'in') {
        if (item) item["Cursor"] = "Hand";
        ApplyStoryboard("sb_FadeOut_HighlightText", "HighLight_ToolTip_Intro");
        ApplyStoryboard("sb_FadeIn_HighlightText", "HighLight_ToolTip_" + which + "_" + index);
    } else {
        if (item) item["Cursor"] = "Arrow";
        ApplyStoryboard("sb_FadeOut_HighlightText", "HighLight_ToolTip_" + which + "_" + index);
        ApplyStoryboard("sb_FadeIn_HighlightText", "HighLight_ToolTip_Intro");
    }
}

function AddHandler(target,eventName,handlerName)
{
   if(target.addEventListener)
   {
      target.addEventListener(eventName, function(e){ target[handlerName](e); }, false);
   }
   else if(target.attachEvent)
   {
      target.attachEvent('on' + eventName, function(e){ target[handlerName](e); });
   }
   else
   {
      var handler = target['on' + eventName];
      if(handler){
         target['on' + eventName] = function(e){ handler(e); target[handlerName](e); };
      }
      else
      {
         target['on' + eventName] = target[handlerName]; 
      }
   }
  }


function Presentation(name) {
  	var _this = this;
  	var _pointer = name;
  	var _videoSize = {}, _imageSize = {}, _sequenceSize = {};
  	var _videos = [], _images = [], _sequences = [], _propList = [];
  	var _selectedVideoIndex = -1, _selectedImageIndex = -1, _selectedSequenceIndex = -1;
  	var _cElements, _cMain, _cVideoBar, _cBackToMovies, _cLoading
  	var _btnHighlight;
  	var _timerID = -1;
  	var _isStartup = true, _isSquenceDownloadCompleted = true;
  	var _time = 150, _speed = 10, _scale = 1.25;

  	this.SetVideoSize = function(width, height) {
  		_videoSize = { 'width': width, 'height': height };
  	}
  	this.SetImageSize = function(width, height) {
  		_imageSize = { 'width': width, 'height': height };
  	}
  	this.SetSequenceSize = function(width, height) {
  		_sequenceSize = { 'width': width, 'height': height };
  	}
  	this.AddVideo = function(obj) {
  		_videos.push(obj)
  	}
  	this.AddImage = function(obj) {
  		_images.push(obj)
  	}
  	this.AddSequence = function(obj) {
  		_sequences.push(obj)
  	}
  	this.SetMainCanvas = function(name) {
  		_cMain = GetObject(name);
  	}
  	this.SetElementsCanvas = function(name) {
  		_cElements = GetObject(name);
  	}
  	this.SetVideoBarCanvas = function(name) {
  		_cVideoBar = GetObject(name);
    }
    this.SetBackToMovieCanvas = function(name) {
        _cBackToMovies = GetObject(name)
    }
    this.SetVideoButtonHighlight = function(name) {
    	_btnHighlight = name;
    }
    this.SetSequenceLoadingCanvas = function(name) {
		_cLoading = GetObject(name)
	}
	this.IsSquenceDownloadCompleted = function() {
		return _isSquenceDownloadCompleted;
	}
  	this.PlayVideo = function() {
  		if (_cMain.children.count == 0) {
  			_this.FeatureVideo(0);
  			return;
  		} else if (_cMain.children.getItem(0).toString() != 'MediaElement') {
  			_this.FeatureVideo(0);
  			return;
  		}
		_cVideoBar.children.getItem(0)["Visibility"] = "Visible";
		_cVideoBar.children.getItem(1)["Visibility"] = "Collapsed";
		_cMain.children.getItem(0).play();
  		_cMain.children.getItem(0).volume = 1.0;
		_timerID = setInterval(
            function() {
            	_this._UpdateVideoTimeSeconds();
            }
        , 250);
  		RegisterTimer(_timerID);
  	}
  	this.PauseVideo = function() {
  		_cVideoBar.children.getItem(0)["Visibility"] = "Collapsed";
  		_cVideoBar.children.getItem(1)["Visibility"] = "Visible";
  	    _cMain.children.getItem(0).pause();
  	}
  	this.StopVideo = function() {
  		_this._ClearTimers();
  		if (_cMain.children.count > 0 && _cMain.children.getItem(0).toString() == 'MediaElement') _cMain.children.getItem(0).stop();
		_cVideoBar.children.getItem(0)["Visibility"] = "Collapsed";
  		_cVideoBar.children.getItem(1)["Visibility"] = "Visible";
  		_cVideoBar.children.getItem(4)["Text"] = "0:00";
  	    _cVideoBar.children.getItem(3)["Canvas.Left"] = _cVideoBar.children.getItem(2)["Canvas.Left"];
  	}
  	this._GenerateImages = function() {
  		if (_images.length == 0) return;

  		_cElements.children.clear();

  		var str = '';
  		var margin = (_cElements["Width"] - ((_images.length * _imageSize.width) + (_images.length * 5))) / 2;

  		for (var i = 0; i < _images.length; i++) {
  			str = '<Image Source="' + _images[i].thumb + '" Width="' + _imageSize.width + '" Height="' + _imageSize.height + '" Canvas.Left="' + margin + '" Stretch="Fill" Cursor="Hand" />';
  			_cElements.children.add(_cElements.getHost().content.createFromXaml(str, false));
  			_this._HandleImageMouseClick(i);
  			_this._HandleImageMouseEnter(i);
  			_this._HandleImageMouseLeave(i);
  			_propList.push({ 'width': _imageSize.width, 'height': _imageSize.height, 'x': margin, 'y': 0, 'currentx': margin, 'currenty': 0, 'timer': -1 });
			margin += (_imageSize.width + 5);
  		}
  	}
  	this._GenerateSequences = function() {
  		if (_sequences.length == 0) return;

  		_cElements.children.clear();

  		var margin = (_cElements["Width"] - ((_sequences.length * _sequenceSize.width) + (_sequences.length * 5))) / 2;
  		for (var i = 0; i < _sequences.length; i++) {
  			var str = '<Image Source="' + _sequences[i].thumb + '" Width="' + _sequenceSize.width + '" Height="' + _sequenceSize.height + '" Canvas.Left="' + margin + '" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Cursor="Hand" />';
  			_cElements.children.add(_cElements.getHost().content.createFromXaml(str, false));
  			_this._HandleSequenceMouseClick(i);
  			_this._HandleSequenceMouseEnter(i);
  			_this._HandleSequenceMouseLeave(i);
  			_propList.push({ 'width': _sequenceSize.width, 'height': _sequenceSize.height, 'x': margin, 'y': 0, 'currentx': margin, 'currenty': 0, 'timer': -1 });
  			margin += (_sequenceSize.width + 5);
  		}
  	}
  	this._GenerateVideos = function() {
  		if (_videos.length == 0) return;

  		_cElements.children.clear();

  		var margin = (_cElements["Width"] - ((_videos.length * _videoSize.width) + (_videos.length * 5))) / 2;
  		for (var i = 0; i < _videos.length; i++) {
  			var str = '<Image Source="' + _videos[i].thumb + '" Width="' + _videoSize.width + '" Height="' + _videoSize.height + '" Canvas.Left="' + margin + '" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Cursor="Hand" />';
  			_cElements.children.add(_cElements.getHost().content.createFromXaml(str, false));
  			_this._HandleVideoMouseClick(i);
  			_this._HandleVideoMouseEnter(i);
  			_this._HandleVideoMouseLeave(i);
  			_propList.push({ 'width': _videoSize.width, 'height': _videoSize.height, 'x': margin, 'y': 0, 'currentx': margin, 'currenty': 0, 'timer': -1 });
  			margin += (_videoSize.width + 5);
  		}
  	}
  	this._HandleImageMouseEnter = function(index) {
  		_cElements.children.getItem(_cElements.children.count - 1).addEventListener("MouseEnter", function() { _this.TweenIn(index); });
  	}
	this._HandleImageMouseLeave = function(index) {
		_cElements.children.getItem(_cElements.children.count - 1).addEventListener("MouseLeave", function() { _this.TweenOut(index); });
	}
  	this._HandleImageMouseClick = function(index) {
  		_cElements.children.getItem(_cElements.children.count - 1).addEventListener("MouseLeftButtonDown", function() { _this.FeatureImage(index); });
  	}
  	this._HandleVideoMouseEnter = function(index) {
  		_cElements.children.getItem(_cElements.children.count - 1).addEventListener("MouseEnter", function() { _this.TweenIn(index); });
  	}
  	this._HandleVideoMouseLeave = function(index) {
  		_cElements.children.getItem(_cElements.children.count - 1).addEventListener("MouseLeave", function() { _this.TweenOut(index); });
  	}
  	this._HandleVideoMouseClick = function(index) {
  		_cElements.children.getItem(_cElements.children.count - 1).addEventListener("MouseLeftButtonDown", function() { _this.FeatureVideo(index); });
  	}
  	this._HandleSequenceMouseEnter = function(index) {
  		_cElements.children.getItem(_cElements.children.count - 1).addEventListener("MouseEnter", function() { _this.TweenIn(index); });
  	}
  	this._HandleSequenceMouseLeave = function(index) {
  		_cElements.children.getItem(_cElements.children.count - 1).addEventListener("MouseLeave", function() { _this.TweenOut(index); });
  	}
  	this._HandleSequenceMouseClick = function(index) {
  		_cElements.children.getItem(_cElements.children.count - 1).addEventListener("MouseLeftButtonDown", function() { _this.FeatureSequence(index); });
  	}
  	this._UpdateVideoTimeTotal = function() {
        var seconds = Math.floor(_cMain.children.getItem(0).NaturalDuration.Seconds);
        var minutes = 0;
        if (seconds >= 60) {
            minutes = Math.floor(seconds / 60);
            seconds = Math.floor(seconds % 60);
        }
        _cVideoBar.children.getItem(6)["Text"] = (minutes + ":" + seconds);
    }
    this._UpdateVideoTimeSeconds = function() {
		if (_cMain.children.count > 0 && _cMain.children.getItem(0).toString() != 'MediaElement') return;
    	var total = _cMain.children.getItem(0).NaturalDuration.Seconds;
    	var seconds = Math.floor(_cMain.children.getItem(0).Position.Seconds);

    	_cVideoBar.children.getItem(2)["Width"] = 300 * (seconds / total);
    	
    	var minutes = 0;
    	if (seconds >= 60) {
    		minutes = Math.floor(seconds / 60);
    		seconds = Math.floor(seconds % 60);
    	}
    	if (seconds < 10) seconds = ("0" + seconds);

    	_cVideoBar.children.getItem(4)["Text"] = (minutes + ":" + seconds);
    }
    this.FeatureVideo = function(index) {
        if (_selectedVideoIndex == index) return;
		if (_cVideoBar) _cVideoBar["Visibility"] = "Visible";
        if (_cBackToMovies) _cBackToMovies["Visibility"] = "Collapsed";

		_this._ClearTimers();
        _cMain.children.clear();
        var str = '<MediaElement Width="480" Height="270" Source="' + _videos[index].source + '" '

        if (_isStartup) str += 'AutoPlay="False" ';
        
        str += 'Stretch="Fill" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" />';
        _cMain.children.add(_cMain.getHost().content.createFromXaml(str, false));

        _cMain.children.getItem(0).addEventListener("MediaEnded", function() { _this.StopVideo(); });
        _cMain.children.getItem(0).addEventListener("MediaOpened", function() {
            _this._UpdateVideoTimeTotal();
        });

        if (!_isStartup) _this.PlayVideo();
        
        _selectedVideoIndex = index;
        _selectedImageIndex = -1;
        _selectedSequenceIndex = -1;
    }
    this.FeatureSequence = function(index) {
    	if (_selectedSequenceIndex == index || !_isSquenceDownloadCompleted) return;
    	if (_cBackToMovies) _cBackToMovies["Visibility"] = "Visible";
    	if (_cVideoBar) _cVideoBar["Visibility"] = "Collapsed";

    	_this._ClearTimers();
    	_cMain.children.clear();

    	for (var i = 0; i < _sequences[index].images.length; i++) {
    		var str = '<Image Width="480" Height="270" Source="' + _sequences[index].images[i] + '" Stretch="Fill" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Opacity="0" />';
    		_cMain.children.add(_cMain.getHost().content.createFromXaml(str, false));
    	}

    	_isSquenceDownloadCompleted = false;

    	var image = Control.createObject('downloader');
    	image.open('GET', 'images/' + _CurrentSite + '_Seq_' + index + '.zip');
    	image.addEventListener('DownloadProgressChanged', function(sender, args) { _this.DownloadImageSequenceChanged(sender, args); });
    	image.addEventListener('DownloadFailed', function() { alert('Sorry, there was a problem downloading the file needed to play this sequence.\n\nPlease try again or another sequence.'); _isSquenceDownloadCompleted = true; });
    	image.addEventListener('Completed', function(sender, args) { _this.DownloadImageSquenceCompleted(sender, args); });
    	image.send();

    	_selectedSequenceIndex = index;
    	_selectedImageIndex = -1;
    	_selectedVideoIndex = -1;
    }
    this.DownloadImageSquenceCompleted = function(sender, args) {
    	SetSource(sender, _cMain);
    	_this._StartPlayingLoadedSequence();
    	_isSquenceDownloadCompleted = true;
    	_cLoading.children.getItem(0)["Width"] = 0;
    	_cLoading.children.getItem(1)["Text"] = String('00');
    }
    this.DownloadImageSequenceChanged = function(sender, args) {
    	_cLoading.children.getItem(0)["Width"] = 456 * sender.downloadProgress;
    	var value = Math.floor(100 * sender.downloadProgress);
    	if (value < 10) {
    		value = String('0' + value);
    	} else if (value >= 100) {
    		value = 99;
    	}
    	_cLoading.children.getItem(1)["Text"] = String(value);
    }
    this._StartPlayingLoadedSequence = function() {
    	var i = 0;
    	_timerID = setInterval(
  				function() {
  					_cMain.children.getItem(i)["Opacity"] = 1;
  					if (i > 0) {
  						_cMain.children.getItem(i - 1)["Opacity"] = 0;
  					} else if (i == 0) {
  						_cMain.children.getItem(_cMain.children.count - 1)["Opacity"] = 0;
  					}
  					i++;
  					if (i > _cMain.children.count - 1) i = 0;
  				}
  			, 500);
    	RegisterTimer(_timerID);
    }
  	this.FeatureImage = function(index) {
  	    if (_selectedImageIndex == index) return;
		if (_cBackToMovies) _cBackToMovies["Visibility"] = "Visible";
        if (_cVideoBar) _cVideoBar["Visibility"] = "Collapsed";

        _this._ClearTimers();
  	    _cMain.children.clear();

  	    var str = '<Image Width="480" Height="270" Source="' + _images[index].source + '" Stretch="Fill" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" />';
  	    _cMain.children.add(_cMain.getHost().content.createFromXaml(str, false));

  	    _selectedImageIndex = index;
  	    _selectedVideoIndex = -1;
  	    _selectedSequenceIndex = -1;
  	}
	this._ClearTimers = function() {
  		clearInterval(_timerID);
  	}
  	this.TweenIn = function(index) {
  		var item = _cElements.children.getItem(index);
  		var time = _time;
  		var interval = _speed;
  		var scale = _scale;
  		var width = _propList[index].width;
  		var height = _propList[index].height;
  		var iWidth = width;
  		var iHeight = height;
  		var iLeft = _propList[index].x;
  		var iTop = _propList[index].y;
  		var targetWidth = (width * scale);
  		var targetHeight = (height * scale);
  		var targetLeft = (targetWidth - width) / 2;
  		var targetTop = (targetHeight - height) / 2;
  		var incWidth = (targetWidth - width) / (time / interval);
  		var incHeight = (targetHeight - height) / (time / interval);
  		var incLeft = targetLeft / (time / interval);
  		var incTop = (targetTop) / (time / interval);
  		clearInterval(_propList[index].timer);
  		item["Canvas.ZIndex"] = 50;
  		_propList[index].timer = setInterval(
  			function() {
  				item["Width"] = iWidth += incWidth;
  				item["Height"] = iHeight += incHeight;
  				item["Canvas.Left"] = iLeft -= incLeft;
  				item["Canvas.Top"] = iTop -= incTop;
  				_propList[index].currentx = item["Canvas.Left"];
  				_propList[index].currenty = item["Canvas.Top"];
  				if (iWidth >= targetWidth || iHeight >= targetHeight) {
  					clearInterval(_propList[index].timer);
  					item["Width"] = targetWidth;
  					item["Height"] = targetHeight;
  					item["Canvas.Left"] = _propList[index].x - targetLeft;
  					item["Canvas.Top"] = _propList[index].y - targetTop;
  				}
  			}
  		, interval);
  	}
  	this.TweenOut = function(index) {
  		var item = _cElements.children.getItem(index);
  		var time = _time;
  		var interval = _speed;
  		var width = item["Width"];
  		var height = item["Height"];
  		var iWidth = width;
  		var iHeight = height;
  		var iLeft = _propList[index].currentx;
  		var iTop = _propList[index].currenty;
  		var targetWidth = _propList[index].width;
  		var targetHeight = _propList[index].height;
  		var targetLeft = _propList[index].x;
  		var targetTop = _propList[index].y;
  		var incWidth = (width - targetWidth) / (time / interval);
  		var incHeight = (height - targetHeight) / (time / interval);
  		var incLeft = (targetLeft - _propList[index].currentx) / (time / interval);
  		var incTop = (targetTop - _propList[index].currenty) / (time / interval);
  		clearInterval(_propList[index].timer);
  		item["Canvas.ZIndex"] = 1;
  		_propList[index].timer = setInterval(
			function() {
				item["Width"] = iWidth -= incWidth;
				item["Height"] = iHeight -= incHeight;
				item["Canvas.Left"] = iLeft += incLeft;
				item["Canvas.Top"] = iTop += incTop;
				if (iWidth <= targetWidth || iHeight <= targetHeight) {
					clearInterval(_propList[index].timer);
					item["Width"] = _propList[index].width;
					item["Height"] = _propList[index].height;
					item["Canvas.Left"] = _propList[index].x;
					item["Canvas.Top"] = _propList[index].y;
					item["Canvas.ZIndex"] = 0;
				}
			}
  		, interval);
  	}
  	this.Init = function() {
  		if (_cVideoBar) {
  			_cVideoBar.children.getItem(0).addEventListener("MouseLeftButtonDown", function() { _this.PauseVideo(); });
  			_cVideoBar.children.getItem(0).addEventListener("MouseEnter", function() { ApplyStoryboard("sb_VideoHighlightFadeIn", _btnHighlight); });
  			_cVideoBar.children.getItem(0).addEventListener("MouseLeave", function() { ApplyStoryboard("sb_VideoHighlightFadeOut", _btnHighlight); });
  			_cVideoBar.children.getItem(1).addEventListener("MouseLeftButtonDown", function() { _this.PlayVideo(); });
  			_cVideoBar.children.getItem(1).addEventListener("MouseEnter", function() { ApplyStoryboard("sb_VideoHighlightFadeIn", _btnHighlight); });
  			_cVideoBar.children.getItem(1).addEventListener("MouseLeave", function() { ApplyStoryboard("sb_VideoHighlightFadeOut", _btnHighlight); });
  		}
  		if (_videos.length > 1) {
  			_this._GenerateVideos();
  		} else if (_videos.length == 1) {
  			if (_cBackToMovies) _cBackToMovies.children.getItem(0).addEventListener("MouseLeftButtonDown", function() { if (_isSquenceDownloadCompleted) _this.FeatureVideo(0); });
  			if (_images.length > 0) {
  				_this._GenerateImages();
  			} else if (_sequences.length > 0) {
  				_this._GenerateSequences();
  			}
  		}
  		_isStartup = false;
  	}
}