﻿function check_open_window(downloadUrl)
{
    // Only called by IE 7 to see if we launched the program ok.
    if (comradePopup.closed == false)
    {
        //The popup is still open.  In IE we launched ok, in other browsers, we don't know.
        comrade_popup_close();
    }
    else
    {
        //IE 7 will tell us we have a closed window when the protocol failed, but it is still open.  Close it.
        comrade_fail_ie(downloadUrl);
    }
}

function check_open_iframe(downloadUrl)
{
   try
   {
        if (window.frames["dlfrm"].location.href.length > 0)
        {
            comrade_popup_close();
        }
        else
        {
            comrade_fail_ie(downloadUrl);
        }
   }
   catch (err)
   {
       comrade_fail_ie(downloadUrl);
   }
}

function start_download_click(downloadUrl) 
{
    var launchedOk = 1;
    if (navigator.appName.match("Microsoft") == "Microsoft")
    {
        //Check version of IE
        if (navigator.appVersion.match("MSIE 7.0") == "MSIE 7.0" || navigator.appVersion.match("MSIE 8.0") == "MSIE 8.0")
        {
            comradePopup.location.replace(downloadUrl);
            
            //We need to let the window open and render.  1 second should be long enough.
            setTimeout(function(){
                check_open_window(downloadUrl);
            }, 1000);
        }
        else
        {
            window.frames["dlfrm"].location = downloadUrl;
            //We need to let the window re-layout.
            setTimeout(function(){
                check_open_iframe(downloadUrl);
            }, 1000);
        }
    }
    else {
        var hasPlugin =  mimeTypeExists();
        
        if ( hasPlugin )
        {
            try
            {
                // Dummy fast loading web site.
                comradePopup.location.replace(downloadUrl);
            }
            catch(err)
            {
                launchedOk = 0;
            }

            if (launchedOk == 0)
            {
                comrade_fail_ff(downloadUrl);
            }
            else
            {
                comrade_popup_close();
            }
        }
        else
        {
            comrade_fail_ff(downloadUrl);
        }
    }
}

function comrade_popup_open(popupUrl) 
{
    //Change the size of the window depending on the browser version.
    if (navigator.appName.match("Microsoft") == "Microsoft")
    {
        comradePopup = window.open(popupUrl, "comradeDL", "location=no, menubar=no, height=665, width=733, status=no, resizable=no, scrollbar=no");
    }
    else
    {
        comradePopup = window.open(popupUrl, "comradeDL", "location=no, menubar=no, height=330, width=600, status=no, resizable=no, scrollbar=no");
    }    
}

var comrade_timer = -1;
function comrade_popup_close() 
{
    //Sometimes the web browser will pop-up a dialog for the user.  When this happens, the close() is not processed.
    //So we loop until the popup is closed.
	if((typeof(comradePopup) != "undefined") && (comradePopup.closed == false))
	{
       comradePopup.close();
       if (comrade_timer == -1)
       {
           comrade_timer = setInterval("comrade_popup_close()", 1000);
           //Close overlay
           tb_remove();
       }
   }
   else
   {
       clearInterval(comrade_timer);
       comrade_timer = -1;	
    }
}

function comrade_fail_ie(downloadUrl) 
{
    //Clear out the error on the page with an empty page before we bring the window forward for the user.
    comrade_popup_open(EmptyPageUrl);
    tb_remove(true);
    comrade_popup_open(dlLink);
    comradePopup.focus();
}

function comrade_fail_ff(downloadUrl)
{
    //The popup has been closed, so do nothing.
	if((typeof(comradePopup) != "undefined") && (comradePopup.closed == true))
	{
        tb_remove();
        return;
    }
    
    tb_remove(true);
    downloadProductDLM();
}

function mimeTypeExists()
{
    navigator.plugins.refresh();
    if (navigator.mimeTypes["application/x-comrade"])
    {
        return true;
    }
    else
    {
        return false;
    }
}

//Fallback to DLM overlay
function downloadProductDLM()
{
    comradePopup.location.replace(dlLink);
    comradePopup.focus();
    window.blur();
}

//download overlay
var ComradeProtocolUrl = '/JsonRequests/ComradeProtocolUrl.aspx';
var PendingDownloadUrl = '/pendingdownloads/default.aspx';
var ActivationPixelUrl = 'https://activation.direct2drive.com/downloadCookiePixel.aspx';
var EmptyPageUrl = '/DownloadBackground.html';
var FileID;
var docIsReady = false;
var dlLink = "";
var dlName = "";

$(document).ready(function() {
    docIsReady = true;
    if (dlLink.length > 0) {
        fileWindow(dlLink, dlName);
    }
});

function beginDownloadOverlay(link, name) {
    if (docIsReady) {
        document.body.style.cursor = "default";
        showLoading();
        setUp();

        dlLink = link;
        dlName = name;

        // Redirect activation pixel
        var rid = GetQueryStringValue(link, 'rid');
        var cid = GetQueryStringValue(link, 'cid');
        setActivationCookie(rid, cid);

        // Call download service
        FileID = GetQueryStringValue(link, 'f');

        if (FileID == '')
            FileID = GetFileID(GetQueryStringValue(link, 'r'));

        getComradeProtocolUrl(FileID);

        // Load the overlay
        var height = $("#downloadOverlayWrapper").height() + 10;
        tb_callshow("", "#TB_inline?width=584&height=" + height + "&inlineId=downloadOverlayWrapper", "");
    }
    else {
        document.body.style.cursor = "wait";
        setUp();

        dlLink = link;
        dlName = name;
    }
}

function GetFileID(link) {
    var index = link.indexOf("f%3d");
    return link.substr(index + 4);
}

function setActivationCookie(rid, cid) {
    $('#activationPixel').attr('src', ActivationPixelUrl + '?rid=' + rid + '&cid=' + cid);
}

function getComradeProtocolUrl(fileID) {
    //$.getJSON(ComradeProtocolUrl, {f: fileID}, launchProtocol);
    $.ajax({
        type: "GET",
        url: ComradeProtocolUrl + "?f=" + fileID,
        cache: false,
        dataType: "json",
        success: function(jsonData) { launchProtocol(jsonData); }
    })
}

function launchProtocol(jsonData) {
    $('#comradeDownloadUrl').attr('href', jsonData.ComradeDownloadLink);
    $('#protocolRetryLink').attr('href', 'javascript:retry(' + FileID + ')');
    $('#directDownloadUrl').attr('href', jsonData.HttpDownloadLink);
    $('#directDownloadUrl2').attr('href', jsonData.HttpDownloadLink);
    $('#fileTitle').html(jsonData.FileTitle);
    $('#fileTitle2').html(jsonData.FileTitle);

    if (jsonData.ErrorMsg.length > 0) {
        $("#comradeDownloading").hide();
        $("#comradeError").show();
        $("#comradeError").html(jsonData.ErrorMsg);

        if ((typeof (comradePopup) != "undefined") && (comradePopup.closed == false))
        {
            comradePopup.close();
        }
    }
    else if (!isCompatibleForComrade()) {
        $("#comradeDownloading").hide();
        $("#comradeIncompatible").show();

        window.frames["httpDownloadFrame"].location = jsonData.HttpDownloadLink;
    }
    else {
        start_download_click(jsonData.ProtocolUrl);
    }

    hideLoading();
}

function retry(fileID) {
    FileID = fileID;

    setUp();
    getComradeProtocolUrl(fileID);
}

function setUp() {
    $("#comradeDownloading").show();
    $("#comradeInstall").hide();
    $("#comradeUpsell").hide();
    $("#comradeError").hide();
    $("#comradeIncompatible").hide();

    if (isCompatibleForComrade()) {
        if (navigator.appName.match("Microsoft") == "Microsoft" && navigator.appVersion.match("MSIE 7.0") != "MSIE 7.0" && navigator.appVersion.match("MSIE 8.0") != "MSIE 8.0") {
            if (document.getElementById('dlfrm') == null)
                document.getElementById('divFooter').innerHTML += '<iframe name="dlfrm" id="dlfrm" src="' + EmptyPageUrl + '" frameborder="0" width="0" height="0">No iframe Support</iframe>';
            else
                window.frames["dlfrm"].location = EmptyPageUrl;
        }
        comrade_popup_open(EmptyPageUrl);
        comradePopup.blur();
        window.focus();
    }
    else {
        document.getElementById('divFooter').innerHTML += '<iframe name="httpDownloadFrame" id="httpDownloadFrame" src="' + EmptyPageUrl + '" frameborder="0" width="0" height="0">No iframe Support</iframe>';
    }
}

function isCompatibleForComrade() {
    if (navigator.platform.match("Win") != "Win")
        return false;
    if (navigator.userAgent.match("MSIE") != "MSIE" && navigator.userAgent.match("Firefox") != "Firefox")
        return false;

    return true;
}

function showComradeInstall() {
    $("#comradeUpsell").hide();
    $("#comradeInstall").show();

    $.ajax({
        type: "GET",
        url: PendingDownloadUrl + "?f=" + FileID,
        cache: false,
        dataType: "json",
        success: function(jsonData) { downloadPending(jsonData); }
    })

    return true;
}

function downloadPending(jsonData) {
    // For future use
}