﻿var mkt; // this value is set by generated server side code

var translatedMarkets = ["de-de", "en-us", "es-es", "fr-fr", "it-it", "ja-jp", "nl-nl", "pt-br", "zh-cn", "zh-tw"];

var localizedBannerMarkets = {
    'deat': true,
    'dech': true,
    'dede': true,
    'enau': false,
    'enca': false,
    'engb': false,
    'enhk': false,
    'enir': false,
    'ennz': false,
    'ensg': false,
    'enus': false,
    'entt': false,
    'slsi': false,
    'eses': true,
    'esmx': true,
    'esco': true,
    'esve': true,
    'escl': true,
    'esec': true,
    'espe': true,
    'esar': true,
    'esuy': true,
    'escr': true,
    'espr': true,
    'esbo': true,
    'esdo': true,
    'essv': true,
    'esgt': true,
    'eshn': true,
    'esni': true,
    'espy': true,
    'espa': true,
    'frbe': true,
    'frca': true,
    'frch': true,
    'frfr': true,
    'heil': true,
    'itit': true,
    'jajp': false,
    'nlbe': false,
    'nlnl': false,
    'ptbr': true,
    'zhcn': false,
    'zhhk': false,
    'zhtw': false
};

var xpFileName = "mssefullinstall-x86fre-{0}-xp.exe";
var vw732bitFileName = "mssefullinstall-x86fre-{0}-vista-win7.exe";
var vw764bitFileName = "mssefullinstall-amd64fre-{0}-vista-win7.exe";

var downloadMarketPath = new Array();
downloadMarketPath["de-de"] = '/0/2/C/02C8AB73-0774-4975-826F-9E8A0FD7F65D/';
downloadMarketPath["en-us"] = '/A/3/8/A38FFBF2-1122-48B4-AF60-E44F6DC28BD8/';
downloadMarketPath["es-es"] = '/2/A/C/2AC6E889-9EBB-4E06-A011-1AA9DAEDDB69/';
downloadMarketPath["fr-fr"] = '/F/3/9/F392321B-C03D-498A-BEBB-141E2F367E44/';
downloadMarketPath["it-it"] = '/9/D/F/9DFBA9B6-FFA2-4762-ABFE-72133C338ED1/';
downloadMarketPath["ja-jp"] = '/6/B/A/6BA6CAB0-DDB8-4DDD-88E3-F707D96E84D7/';
downloadMarketPath["nl-nl"] = '/9/F/D/9FDD1ABA-8A02-465A-A321-535388226BD7/';
downloadMarketPath["pt-br"] = '/4/1/5/415CADB4-C974-4DB7-9C44-565EEEBF5509/';
downloadMarketPath["zh-cn"] = '/1/E/D/1ED80C09-218B-44D7-B72D-E1451634E72D/';
downloadMarketPath["zh-tw"] = '/3/8/5/385C19C3-1107-4EE5-9C47-D3FAB986B06C/';

var downloadUrlPrefix = "http://download.microsoft.com/download"; // TODO: this should be set to real dms location
var dlPageUrlPrefix = "http://localhost/security_essentials/beta_golden_bits/"; // TODO: this should be set to real dl page location

var fullDownloadUrl;
var downloadContentToShow; // 'ThankYou', 'Unsupported', or 'PickVersion'

var hasDeclinedSL = false;

function getDownloadFileUrl(os, mrkt) {
    var market = GetTranslatedMarket(mrkt);
    var marketPath = downloadMarketPath[market];

    switch (os) {
        case 'xp': return downloadUrlPrefix + marketPath + xpFileName.format(market); break;
        case 'v32': return downloadUrlPrefix + marketPath + vw732bitFileName.format(market); break;
        case 'v64': return downloadUrlPrefix + marketPath + vw764bitFileName.format(market); break;
    }
}

function GetTranslatedMarket(mrkt) {
    // check for parent language markets
    for (index = 0; index < translatedMarkets.length; index++) {
        if (translatedMarkets[index] == mrkt) {
            return translatedMarkets[index];
        }
    }

    // check for sub markets
    var lang = mrkt.substr(0, 2);
    for (index = 0; index < translatedMarkets.length; index++) {
        if (translatedMarkets[index].indexOf(lang) > -1) {
            return translatedMarkets[index];
        }
    }

    // defalut to en-us
    return "en-us";
}

//Get cookie routine by Shelley Powers 
function get_cookie(Name) {
    var search = Name + "="
    var returnvalue = "";
    if (document.cookie.length > 0) {
        offset = document.cookie.indexOf(search)
        // if cookie exists
        if (offset != -1) {
            offset += search.length
            // set index of beginning of value
            end = document.cookie.indexOf(";", offset);
            // set index of end of cookie value
            if (end == -1) {
                end = document.cookie.length;
            }
            returnvalue = unescape(document.cookie.substring(offset, end))
        }
    }
    return returnvalue;
}

function preShowVisibleHelpSection() {
    var shownHelpSectionString = get_cookie("shownHelpSection");
    var shownHelpLiString = get_cookie("shownHelpLi");
    if (shownHelpSectionString.length > 0) {
        var shownHelpSection = shownHelpSectionString.split(",");
        for (var i = 0; i < shownHelpSection.length; i++) {
            if (document.getElementById(shownHelpSection[i])) {
                document.getElementById(shownHelpSection[i]).style.display = "block";
            }
        }
    }
    if (shownHelpLiString.length > 0) {
        var shownHelpLi = shownHelpLiString.split(",");
        for (var i = 0; i < shownHelpLi.length; i++) {
            if (document.getElementById(shownHelpLi[i])) {
                document.getElementById(shownHelpLi[i]).className = "helpTitleMinus";
            }
        }
    }
}

function toggleVisibleHelpSection(liId, sectionId) {
    var action;
    var obj = document.getElementById(sectionId);
    if (obj.style.display == "block") {
        action = "remove";
        obj.style.display = "none";
        document.getElementById(liId).className = "helpTitlePlus";
    } else if (obj.style.display == "none") {
        action = "add";
        obj.style.display = "block";
        document.getElementById(liId).className = "helpTitleMinus";
    }
    // update cookie
    var shownHelpSectionString = get_cookie("shownHelpSection");
    var shownHelpLiString = get_cookie("shownHelpLi");
    var newShownHelpSectionString;
    var newShownHelpLiString;
    if (action == "remove" && shownHelpSectionString.length > 0) {
        // first take care of the title section
        var startIndex = shownHelpSectionString.indexOf(sectionId);
        if (startIndex > -1) {
            // found... so proceed with deleting
            var stopIndex = shownHelpSectionString.indexOf(",", startIndex);
            if (stopIndex == -1) {
                stopIndex = shownHelpSectionString.length;
            }
            newShownHelpSectionString = shownHelpSectionString.substring(0, startIndex) + shownHelpSectionString.substring(stopIndex + 1, shownHelpSectionString.length);
        }
        // then take care of the actual +/- sign
        startIndex = shownHelpLiString.indexOf(liId);
        if (startIndex > -1) {
            // found... so proceed with deleting
            var stopIndex = shownHelpLiString.indexOf(",", startIndex);
            if (stopIndex == -1) {
                stopIndex = shownHelpLiString.length;
            }
            newShownHelpLiString = shownHelpLiString.substring(0, startIndex) + shownHelpLiString.substring(stopIndex + 1, shownHelpLiString.length);
        }
    } else if (action == "add" && shownHelpSectionString.indexOf(sectionId) == -1) {
        // only add if it doesn't exist.
        newShownHelpSectionString = shownHelpSectionString + (shownHelpSectionString.length == 0 ? "" : ",") + sectionId;
        newShownHelpLiString = shownHelpLiString + (shownHelpLiString.length == 0 ? "" : ",") + liId;
    }
    document.cookie = "shownHelpSection=" + newShownHelpSectionString;
    document.cookie = "shownHelpLi=" + newShownHelpLiString;
}

function handleDownloadLink() {
    var downloadLink = document.getElementById("downloadLink");

    if (location.href.indexOf("market.aspx") != -1) {
        // unsupported market page, disable download button
        downloadLink.href = "javascript:void(0);";
    } else {
        // prep the download button
        if (window.navigator.userAgent.indexOf("Windows") != -1) {
            // windows
            if (window.navigator.userAgent.indexOf("MSIE") != -1) {
                // IE
                downloadContentToShow = "ThankYou";
                if (window.navigator.userAgent.indexOf("Windows NT 5.1") != -1) {
                    // get XP bit
                    fullDownloadUrl = getDownloadFileUrl('xp', mkt);
                } else if (window.navigator.userAgent.indexOf("Windows NT 6.0") != -1 || window.navigator.userAgent.indexOf("Windows NT 6.1") != -1) {
                    // vista/win7
                    if (window.navigator.userAgent.indexOf("Win64") != -1 || window.navigator.userAgent.indexOf("WOW64") != -1) {
                        // 64 bit
                        fullDownloadUrl = getDownloadFileUrl('v64', mkt);
                    } else {
                        // 32 bit
                        fullDownloadUrl = getDownloadFileUrl('v32', mkt);
                    }
                } else {
                    // unknown OS... ask for version
                    downloadContentToShow = "PickVersion";
                    fullDownloadUrl = "";
                }
            } else {
                // non IE... ask for version
                downloadContentToShow = "PickVersion";
                fullDownloadUrl = "";
            }
        }
        else {
            // everything else... unsupported
            downloadContentToShow = "PickVersion";
            fullDownloadUrl = "";
        }
        //update the link downloadLink
        if (downloadContentToShow == "ThankYou") {
            downloadLink.href = fullDownloadUrl;

            if (mkt == "en-us") {
                AddHandler(downloadLink, "click", function() { FireAtlasTag('http://quantum.universalmccann.com/umat/FY10_iMpact_Security Essentials_event.html'); });
            }

            document.getElementById("lnkStartDownload").href = fullDownloadUrl;
            $("#cn-sec2-4-link").attr("href", fullDownloadUrl);
            $("#cn-sec3-right-btn2").attr("href", fullDownloadUrl);
        } else {
            downloadLink.href = "javascript:void(0);";
            $("#cn-sec2-4-link").attr("href", "javascript:void(0);");
            $("#cn-sec3-right-btn2").attr("href", "javascript:void(0);");
        }
        $("#downloadLink").click(function() { $("#downloadModal").dialog("open"); showDownloadModal(downloadContentToShow); });

        if (document.getElementById(downloadSelectionLinkId) != null) {
            var lnkDownloadSelection = document.getElementById(downloadSelectionLinkId);
            $("#" + downloadSelectionLinkId).click(function() { $("#downloadModal").dialog("open"); showDownloadModal('PickVersion') });
        }

        setSelectedMarket();
    }
}

var fileUrl;
function navigateToDlPage(os) {
    var locDropDown = document.getElementById("localeDropDown");
    var location = locDropDown.options[locDropDown.selectedIndex].value;
    var dlPageUrl = getDownloadFileUrl(os, location);

    fileUrl = dlPageUrl;

    if (mkt == "en-us") {
        FireAtlasTag('http://quantum.universalmccann.com/umat/FY10_iMpact_Security Essentials_event.html');
    }

    // defeat ie6 file download issues
    setTimeout(dlFileCallback, 500);
}

function dlFileCallback() {
    window.location.replace(fileUrl);
}

function setSelectedMarket() {
    var locDropDown = document.getElementById("localeDropDown");

    // check for parent language markets
    for (index = 0; index < locDropDown.length; index++) {
        if (locDropDown.options[index].value == mkt) {
            locDropDown.selectedIndex = index;
            return;
        }
    }

    // check for sub markets
    var lang = mkt.substr(0, 2);
    for (index = 0; index < locDropDown.length; index++) {
        if (locDropDown.options[index].value.indexOf(lang) > -1) {
            locDropDown.selectedIndex = index;
            return;
        }
    }

    // defalut to en-us
    for (index = 0; index < locDropDown.length; index++) {
        if (locDropDown.options[index].value == "en-us") {
            locDropDown.selectedIndex = index;
            return;
        }
    }
}

// modals
function showDownloadModal(content) {
    document.getElementById("downloadModalContentThankYou").style.display = 'none';
    document.getElementById("downloadModalContentPickVersion").style.display = 'none';
    document.getElementById("downloadModalContentUnsupported").style.display = 'none';
    document.getElementById("downloadModalContent" + content).style.display = 'block';
}

// hasRun variable is necessary to stop having the javascript inside videoModal from being executed twice.
// Once when the page loads, and once when the modal is prepped by the code below.
var hasRun = false;

$(document).ready(function() {
    hasRun = true;
    $("#videoModal").dialog({ autoOpen: false, modal: true, width: 824, height: 532, draggable: false, resizable: false });
    $("#videoModal_Close").click(function() { stopVideo(); $('#videoModal').dialog('close'); });
    $("#downloadModal").dialog({ autoOpen: false, modal: true, width: 824, height: 532, draggable: false, resizable: false });
    handleDownloadLink();

    if (hideChineseTradBits) {
        document.getElementById('localeDropDown').remove(1);
    }
});

// string format utility
String.prototype.format = function() {
    var pattern = /\{\d+\}/g;
    var args = arguments;
    return this.replace(pattern, function(capture) { return args[capture.match(/\d+/)]; });
}

// video player related
var selectedVideo = "";
function playVideo(index, url) {
    if (hasDeclinedSL) {
        window.open(url);
    } else {
        $("#videoModal").dialog("open");
        if (document.getElementById("noSLLink") != null) {
            document.getElementById("noSLLink").href = url;
        }
        if (url.indexOf("mms:") == -1) {
            setVideoDelay(index);
        }
        else {
            setVideoDelayCn(index);
        }
        selectedVideo = url;
    }
}

function onSilverlightError(sender, args) {
    var appSource = "";
    if (sender != null && sender != 0) {
        appSource = sender.getHost().Source;
    }
    var errorType = args.ErrorType;
    var iErrorCode = args.ErrorCode;

    var errMsg = "Unhandled Error in Silverlight 2 Application " + appSource + "\n";

    errMsg += "Code: " + iErrorCode + "    \n";
    errMsg += "Category: " + errorType + "       \n";
    errMsg += "Message: " + args.ErrorMessage + "     \n";

    if (errorType == "ParserError") {
        errMsg += "File: " + args.xamlFile + "     \n";
        errMsg += "Line: " + args.lineNumber + "     \n";
        errMsg += "Position: " + args.charPosition + "     \n";
    }
    else if (errorType == "RuntimeError") {
        if (args.lineNumber != 0) {
            errMsg += "Line: " + args.lineNumber + "     \n";
            errMsg += "Position: " + args.charPosition + "     \n";
        }
        errMsg += "MethodName: " + args.methodName + "     \n";
    }
}

function setVideoDelay(index) {
    setTimeout("setVideo(" + index + ", 0)", 500);
}

function setVideoDelayCn(index) {
    setTimeout("setVideo(" + index + ", 1)", 500);
}

function setVideo(index, IN_start) {
    var slPlugin = document.getElementById("sl_Player");
    try {
        slPlugin.content.PlayerApp.PlayVideo(index, IN_start);
    }
    catch (e) {
    }
}

function stopVideo() {
    var slPlugin = document.getElementById("sl_Player");
    try {
        if (slPlugin) {
            slPlugin.content.PlayerApp.StopVideo();
        }
    } catch (e) {
    }
}

function hasLocalizedBanner() {
    var mktShort = mkt.replace(/-/, "");
    var result = localizedBannerMarkets[mktShort];
    return localizedBannerMarkets[mktShort];
}

//*********************** Event Handler Creation ***************************
function AddHandler(object, eventName, handler) {
    if (object != null) {
        if (object.addEventListener) { object.addEventListener(eventName, handler, false); }
        else { object.attachEvent("on" + eventName, handler); }
    }
}

function RemoveHandler(object, eventName, handler) {
    if (object != null) {
        if (object.removeEventListener) { object.removeEventListener(eventName, handler, false); }
        else { object.detachEvent("on" + eventName, handler); }
    }
}

// this function uses closure and Function.apply()
// to create an event handler and specify its context/scope
function CreateDelegate(object, method) {
    return (function() { return method.apply(object, arguments); })
}
