﻿var ComradeProtocolUrl = '/JsonRequests/ComradeProtocolUrl.aspx';
var PendingDownloadUrl = '/pendingdownloads/default.aspx';
var EmptyPageUrl = '/DownloadBackground.html';
var FileID;
var MirrorID = 0;
var docIsReady = false;
var dlLink = "";
var dlName = "";

$(document).ready(function () 
{
    docIsReady = true;
    if (dlLink.length > 0)
    {
        fileWindow(dlLink, dlName);
    }
});


function fileWindow(link, name)
{
    if (docIsReady)
    {
        document.body.style.cursor = "default";
        showLoading();
        setUp();

        dlLink = link;
        dlName = name;


        if (!isCompatibleForComrade())
        {
            // $("#comradeDownloading").hide();
            // $("#comradeIncompatible").show();
	        var height = $("#downloadOverlayWrapper").height() + 10;
	        tb_callshow("", "#TB_inline?width=660&height=" + height + "&inlineId=downloadOverlayWrapper", "");
        	
	        openDlWindowFromOverlay();
        }
        else
        {
	        // Call download service
	        FileID = GetQueryStringValue(link, 'f');
	        MirrorID = GetQueryStringValue(link, 'm');
        	
	        if (FileID == '')
		        FileID = GetFileID(GetQueryStringValue(link, 'r'));
        	
	        getComradeProtocolUrl(FileID);
        	
	        // Load the overlay
	        var height = $("#downloadOverlayWrapper").height() + 10;
	        tb_callshow("", "#TB_inline?width=660&height=" + height + "&inlineId=downloadOverlayWrapper", "");
        }
	}
	else
	{
	    document.body.style.cursor = "wait";
	    setUp();
	    
	    dlLink = link;
        dlName = name;
	}
}

function Preorder_DlOverlay(link, fileID)
{
    if (showLogin(link))
    {
        if (!loggedIn)
        {
            window.location = gsidLoginUrl();
            return false;
        }
    
        if (UseComrade)
        {
            if (!isCompatibleForComrade())
            {
                return true;
            }
            else
            {
                showLoading();
                setUp();
                
	            getComradeProtocolUrl(fileID);
            	
	            // Load the overlay
	            var height = $("#downloadOverlayWrapper").height() + 10;
	            tb_callshow("", "#TB_inline?width=660&height=" + height + "&inlineId=downloadOverlayWrapper", "");
    	        
	            return false;
            }
        }
    }
    else
    {
        return true;
    }
}

function GetFileID(link)
{
    var index = link.indexOf("f%3d");
    return link.substr(index + 4);
}

function getComradeProtocolUrl(fileID)
{
    var jsonUrl = ComradeProtocolUrl + "?f=" + fileID;
    if ( MirrorID > 0 )
        jsonUrl = jsonUrl + "&m=" + MirrorID;
    
    $.ajax({
        type: "GET",
        url: jsonUrl,
        cache: false,
        dataType: "json",
        success: function(jsonData) { launchProtocol(jsonData); }
    })
}

function launchProtocol(jsonData)
{
    $('#comradeDownloadUrl').attr('href', jsonData.ComradeDownloadLink);
    $('#protocolRetryLink').attr('href', 'javascript:retry(' + FileID + ')');
    $('#fileTitle').html(jsonData.FileTitle);
    
    if (jsonData.ErrorMsg.length > 0)
    {
        $("#comradeDownloading").hide();
        $("#comradeError").show();
        $("#comradeErrorMsg").html(jsonData.ErrorMsg);

        if ((typeof (comradePopup) != "undefined") && (comradePopup.closed == false))
            comradePopup.close();
    }
    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('downloadOverlayWrapper').innerHTML += '<iframe name="dlfrm" id="dlfrm" src="' + EmptyPageUrl + '" frameborder="0" width="0" height="0">No iframe Support</iframe>';
            else
                window.frames["dlfrm"].location = EmptyPageUrl;
        }
        comradePopup = window.open(EmptyPageUrl, "comradeDL", "location=no, menubar=no, height=330, width=600, status=no, resizable=no, scrollbar=no");
        comradePopup.blur();
        window.focus();
    }
}

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
}

function openDlWindowFromOverlay()
{
    window.open(dlLink, dlName, 'height=330,width=600,status=no,scrollbars=no,toolbar=no,menubar=no,location=no,resizable=no'); 
    setTimeout('tb_remove()', 1000);
    return true;
}

function showLoading()
{
    fadeBackground();
    $("body").append("<div id='TB_load'><img src='"+tb_pathToImage+"' /></div>"); //add loader to the page
	$('#TB_load').show(); //show loader
}

function hideLoading()
{
    $('#TB_load').remove();
}

function fadeBackground()
{
    if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
		$("body","html").css({height: "100%", width: "100%"});
		$("html").css("overflow","hidden");
		if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
			$("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window' style='display:none'></div>");
			$("#TB_overlay").click(tb_remove);
		}
	}else{//all others
		if(document.getElementById("TB_overlay") === null){
			$("body").append("<div id='TB_overlay'></div><div id='TB_window' style='display:none'></div>");
			$("#TB_overlay").click(tb_remove);
		}
	}
    if(tb_detectMacXFF()){
		$("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
	}else{
		$("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
	}
}

function tb_callshow(caption, url, imageGroup)
{
    tb_show(caption, url, imageGroup)
    return false;
}

