///GLOBALS
SGVersion = "5.1.0";

domain = "http://www.skylineglobe.com";
//domain = "http://alex";

baseurl = domain + "/SkylineGlobe/TerraExplorer/";
baseurlv = baseurl + "v" + SGVersion + "/";
dlgpath = baseurlv + "dlg/";
iepath = domain + "/SkylineGlobe/WebClient/PresentationLayer/webclient/3dwebclient.aspx?";
ffpath = baseurlv + "shell/SkylineGlobeShellUrl.asp?" + iepath;
ffpathurl = baseurlv + "shell/SkylineGlobeShellUrl.asp?";

var sgbasicinstall = new Array();
var sgproinstall = new Array();

var g_LocaleList = new Array();

g_LocaleList[0] = { name: "English",
    locale: "en",
    basic: domain + "/SkylineGlobe/TerraExplorer/install/SkylineGlobeSetup.exe",
    plus: domain + "/SkylineGlobe/TerraExplorer/install/TerraExplorerPlusSetup.exe",
    pro: domain + "/SkylineGlobe/TerraExplorer/install/SkylineGlobeProSetup.exe",
    picture: dlgpath + "/images/england.gif",
    downloadCaption: "Download TerraExplorer Plugin",
    warningCaption: "Warning",
    accept: "I Accept",
    decline: "I Decline",
    dlgpath: dlgpath
};

g_LocaleList[1] = { name: "Français",
    locale: "fr",
    basic: domain + "/SkylineGlobe/TerraExplorer/install/SkylineGlobeSetupFrench.exe",
    pro: domain + "/SkylineGlobe/TerraExplorer/install/SkylineGlobeProSetup.exe",
    picture: dlgpath + "/images/france.gif",
    downloadCaption: "Télécharger le Plugin de TerraExplorer",
    warningCaption: "Avertissement",
    accept: "J’accepte",
    decline: "Je refuse",
    dlgpath: dlgpath + "fr/"
};

g_LocaleList[2] = { name: "Español",
    locale: "es",
    basic: domain + "/SkylineGlobe/TerraExplorer/install/SkylineGlobeSetup.exe",
    pro: domain + "/SkylineGlobe/TerraExplorer/install/SkylineGlobeProSetup.exe",
    picture: dlgpath + "/images/spain.gif",
    downloadCaption: "Descargar TerraExplorer plugin",
    warningCaption: "Advertencia",
    accept: "I Accept",
    decline: "I Decline",
    dlgpath: dlgpath
};

g_LocaleList[3] = { name: "Deutsch",
    locale: "de",
    basic: domain + "/SkylineGlobe/TerraExplorer/install/SkylineGlobeSetup.exe",
    pro: domain + "/SkylineGlobe/TerraExplorer/install/SkylineGlobeProSetup.exe",
    picture: dlgpath + "/images/germany.gif",
    downloadCaption: "Download TerraExplorer Plugin",
    warningCaption: "Warning",
    accept: "I Accept", 
    decline: "I Decline",
    dlgpath: dlgpath
};
//Traditional Chinese
g_LocaleList[4] = { name: "中國傳統",
    locale: "cht",
    basic: domain + "/SkylineGlobe/TerraExplorer/install/SkylineGlobeSetupTC.exe",
    pro: domain + "/SkylineGlobe/TerraExplorer/install/SkylineGlobeProSetup.exe",
    picture: dlgpath + "/images/china.gif",
    downloadCaption: "下載TerraExplorer Plug-in(插件)",
    warningCaption: "警告",
    accept: "我接受",
    decline: "我拒絕",
    dlgpath: dlgpath + "cht/"
};

// Simplified Chinese
g_LocaleList[5] = { name: "简体中文",
    locale: "chs",
    basic: domain + "/SkylineGlobe/TerraExplorer/install/SkylineGlobeSetupSC.exe",
    pro: domain + "/SkylineGlobe/TerraExplorer/install/SkylineGlobeProSetup.exe",
    picture: dlgpath + "/images/china.gif",
    downloadCaption: "下载TerraExplorer插件",
    warningCaption: "警告",
    accept: "我接受",
    decline: "我拒绝接受",
    dlgpath: dlgpath + "chs/"
};

// Czech
g_LocaleList[6] = { name: "Czech",
    locale: "cz",
    basic: domain + "/SkylineGlobe/TerraExplorer/install/SkylineGlobeSetupCz.exe",
    pro: domain + "/SkylineGlobe/TerraExplorer/install/SkylineGlobeProSetup.exe",
    picture: dlgpath + "/images/Czech.gif",
    downloadCaption: "Download TerraExplorer Plugin",
    warningCaption: "Warning",
    accept: "I Accept",
    decline: "I Decline",
    dlgpath: dlgpath
};

sginstall = g_LocaleList[0].basic;

//dlgpath="dlg/";

var g_Param = "";
var g_UrlIE = iepath;
var g_UrlFF = ffpath;
var g_Target = "_self";
var g_UseURL = false;
var g_UseTerraExplorer = false;
var g_Locale = g_LocaleList[0];

///PUBLIC
function SGDownload(param, locale)
{
    var foot = "decline_accept";
    if (param == undefined)
        param = "";
    else if (param.indexOf("SGPro") >= 0)
        foot = "decline_accept_sgpro";
    else if (param.indexOf("TEPlus") >= 0)
        foot = "decline_accept_teplus";

    SetLocale(locale);

    showDialog("download.html?" + param, g_Locale.downloadCaption, "SG_Download", "30%", "15%", "400px", "420px", foot);
}
///PUBLIC
function SGStart(Param, target, locale)
{
    g_UseTerraExplorer = false;
    g_UrlIE = iepath;
    g_UrlFF = ffpath;

    if (target != undefined)
        g_Target = target;
    else
        g_Target = "_self";

    if (Param != undefined)
        g_Param = Param;
    else
        g_Param = "";

    SetLocale(locale);
    DetectTE(SGVersion);
}
///PUBLIC
function SGStartURL(url, target, locale)
{
    g_UseTerraExplorer = false;
    g_UrlIE = url;
    g_UrlFF = ffpathurl + url;
    g_Param = "";

    if (target != undefined)
        g_Target = target;
    else
        g_Target = "_self";

    SetLocale(locale);

    DetectTE(SGVersion);
}
///PUBLIC
function TEStart(fly, locale)
{
    g_UseTerraExplorer = true;
    g_UrlIE = fly;

    SetLocale(locale);

    DetectTE(SGVersion);
}


// PRIVATE
function SetLocale(locale)
{
    g_Locale = g_LocaleList[0];
    if (locale != undefined)
    {
        for (var i = 0; i < g_LocaleList.length; i++)
        {
            if (g_LocaleList[i].locale == locale)
            {
                g_Locale = g_LocaleList[i];
                break;
            }
        }
    }
}

function SGTest()
{
    showDialog("security.html", "Warning", "SG_Security", "30%", "20%", "400px", "250px");
    SGDownload("o=Enter");
    showDialog("infobar.html", "Warning", "SG_InfoBar", "25%", "20%", "550px", "350px");
    showDialog("unknownerror.html", "Warning", "SG_Unknown", "30%", "20%", "380px", "200px");
}

//PRIVATE
function SGStartDownload()
{
    window.setTimeout("hideDialog('SG_Download')", 1000);
    window.location.href = sginstall;
}



//   0 object is ok
//-100 need to download object handled external
//-101 need to update object handled external
//  -1 unknown error ( handled internal)
//  -2 security ( handled internal)
//  -3 info bar ( handled internal)

//this function check for one property
function testDetectProp(obj)
{
    var tmp = obj.Type;
    if (tmp == undefined)
    {
        var tmp = obj.IsTEExist;
        if (tmp == undefined)
            return -1;
        else
            return 0;
    }
    return 0;
}

//add object tag into bag 
function insertTagObject(bag, name, clsid, site, testfunc)
{
    var werok = 1; // we are ok. - need to put it ontop of myobj
    try
    {
        var myobj = document.createElement('object');
        bag.appendChild(myobj);
        myobj.name = name;
        myobj.id = name;
        myobj.onreadystatechange = function()
        {
            if (window.event.srcElement.readyState == 4)
            {
                //start work
                try
                {
                    if (werok == 1)
                    {
                        val = testfunc(myobj);
                        if (val == -1)
                        {
                            // We got the info bar, but this time because a very high security.
                            werok = 2;
                            showDialog("security.html", g_Locale.warningCaption, "SG_Security", "30%", "20%", "400px", "250px");
                            //alert("Your securety setting may be to high - can't run activeX");
                            site(-2); // security too high
                        }
                        else
                        {
                            site(0); // we are ok 
                        }
                    }
                }
                catch (e)
                {
                    //if we got here -> known issue
                    //if you uninstall while the page is on , you need to reopen the IE or refresh the page 
                    //alert("Code Fatal Error "+"("+e.number+"):"+e.description+" ");
                    showDialog("security.html", g_Locale.warningCaption, "SG_Security", "30%", "20%", "400px", "250px");
                    site(-2); // error
                }
            }
        }
        myobj.onerror = function()
        {
            werok = 0;
            site(-100); // error - we need to download ....
        }
        myobj.classid = clsid;
    }
    catch (e)
    {
        if (werok != 2)
        {
            werok = 0;
            if (e.number == -2147024891)//access denied 0x80070005
            {
                showDialog("infobar.html", g_Locale.warningCaption, "SG_InfoBar", "25%", "20%", "550px", "350px");
                site(-3); // error - just to let the site know

            }
            else
            {
                //alert("some other error"+e.description);
                showDialog("unknownerror.html", g_Locale.warningCaption, "SG_UnknownError", "30%", "20%", "380px", "200px");
                site(-1); // error - just to let the site know
            }
        }
    }
}


function EnterSkylineGlobe(res)
{
    try
    {
        if (res == 0) // we are ok we can start SkylineGlobe
        {
            if (g_UseTerraExplorer)
            {
                window.location.href = g_UrlIE;
            }
            else
            {

                tIEVersion = msieversion();

                if (tIEVersion != 0)
                    window.open(g_UrlIE + g_Param, g_Target);    // IE version
                else
                    window.open(g_UrlFF + g_Param, "_self");    // Other browsers version
            }

        }
        if (res == -100) // we need to download SkylineGlobe
            SGDownload("o=Enter");
        if (res == -101) // we need to update SkylineGlobe
            SGDownload("o=Update");
    }
    catch (e)
    {
        alert("site " + e.description);
    }
}


//create bag if needed
//add object
//site - call to site when done
//testfunc - check one of the object properties - make sure it is a real object.
//name - name and id of the object
//clsid - clsid ofer the object  
//example for detect  insertObject("DETECT","CLSID:A5606C7C-13E8-4403-B5C1-72CE1AEE1CA2",EnterSkylineGlobe,testDetectProp);
//will run only on IE
function insertObject(name, clsid, site, testfunc)
{
    //if not define create bag
    if (document.all["sg__bag"] == undefined)
    {
        var mybag = document.createElement('span');
        document.body.appendChild(mybag);
        mybag.outerHTML = "<span id='sg__bag' style='display:none'></span>";
    }
    //remove old object if exist
    if (document.all[name])
    {
        var mydiv = document.all[name];
        sg__bag.removeChild(mydiv);
        document.all[name] = null;
    }
    insertTagObject(sg__bag, name, clsid, site, testfunc);
}



//run in fire fox / ie
var lastDialogArgList = null;
function showDialog(url, caption, id, x, y, w, h, foot)
{
    xx = "25%";
    yy = "25%";
    ww = "50%";
    hh = "50%";
    ftype = "none";

    if (x != undefined)
        xx = x;
    if (y != undefined)
        yy = y;
    if (w != undefined)
        ww = w;
    if (h != undefined)
        hh = h;
    if (foot != undefined)
        ftype = foot;

    // TODO: add something better here:    
    if (caption == "Warning")
        caption = g_Locale.warningCaption;
    else
        caption = g_Locale.downloadCaption;


    mydiv = document.getElementById(id);
    if (mydiv)
        hideDialog(id);


    var mydiv = document.createElement('div');
    document.body.appendChild(mydiv);
    mydiv.id = id;
    mydiv.name = id;
    mydiv.style.position = "absolute";
    mydiv.style.width = ww;
    mydiv.style.height = hh;
    mydiv.style.top = yy;
    mydiv.style.left = xx;
    mydiv.style.backgroundColor = "white";
    mydiv.style.border = "solid 1px #ffcc00";
    lastDialogArgList = arguments;

    s = "<TABLE border='0' width='100%' height='100%' cellspacing='0' cellpadding='0' style='font-family:  Arial, Helvetica, sans-serif; font-size: 16px; font-style: normal; font-weight: normal; color: #000000; text-decoration: none;'>";
    s = s + "<TR bgcolor='#ccccee' ><TD><B>" + caption + "</B></TD><TD align='right'><A href='javascript:hideDialog(\"" + id + "\");'><img width='21px' height='21px' style='border:0;' src='" + dlgpath + "/images/close.png'/></A></TD></TR>";
    // this build flags line, but it's disabled for now
    s = s + "<TR style='display:none' ><TD colspan='2'><table style='text-align:center;width:100%'><tr>";
    for (var i = 0; i < g_LocaleList.length; i++)
    {
        if (g_Locale.locale == g_LocaleList[i].locale)
            s = s + "<td>" + "<img src='" + g_LocaleList[i].picture + "' style='border: 2px solid black;vertical-align:middle' alt='" + g_LocaleList[i].name + "'><br><span style='font-size:10px;'><nobr>" + g_LocaleList[i].name + "</nobr></span></td>";
        else
            s = s + "<td><a href='#' onclick='SetLocale(\"" + g_LocaleList[i].locale + "\");showDialog.apply({},lastDialogArgList);'>" + "<img src='" + g_LocaleList[i].picture + "' style='border: 2px solid white;vertical-align:middle' alt='" + g_LocaleList[i].name + "'><br><span style='font-size:10px;'><nobr>" + g_LocaleList[i].name + "</nobr></span></a></td>";
    }
    s = s + "</tr></table></TD></TR>";
    s = s + "<TR height='100%' style='border-width:20px;'><TD colspan='2' style='background-color:white'><IFRAME id='" + id + "frame'style='border-color:#f8f8ff;border-width:0px;border-style:none;' src='' width='100%' height='" + (parseInt(h, 10) - 30) + "px'></IFRAME></TD></TR>";
    if (ftype == 'decline_accept' || ftype == 'decline_accept_sgpro' || ftype == 'decline_accept_teplus')
    {
        s = s + "<TR height='30px' width='100%' style='background:#f8f8ff'><TD align='right' style='font-family:  Arial, Helvetica, sans-serif; font-size: 11px; font-style: normal; font-weight: normal; color: #000000; text-decoration: none;'><a href='javascript:hideDialog(\"" + id + "\");'><img src='http://www.skylineglobe.com/SkylineGlobe/WebClient/PresentationLayer/Home/images/Decline.gif' align='absmiddle' border='0' /> <u>" + g_Locale.decline + "</u></a>&nbsp;&nbsp;&nbsp;&nbsp;";
        s = s + "<a href='javascript:SGStartDownload();'><img src='http://www.skylineglobe.com/SkylineGlobe/WebClient/PresentationLayer/Home/images/accept.gif' align='absmiddle' border='0' /> <u>" + g_Locale.accept + "</u> </a><TD width='5px'></TD></TD></TR>";

        if (ftype == 'decline_accept_sgpro')
            sginstall = g_Locale.pro;
        else if (ftype == 'decline_accept_teplus')
            sginstall = g_Locale.plus;
        else
            sginstall = g_Locale.basic;
    }
    s = s + "</TABLE>";
    mydiv.innerHTML = s;
    document.getElementById(id + "frame").src = g_Locale.dlgpath + url;

}


function hideDialog(id)
{
    var mydiv = document.getElementById(id);
    n = document.body.removeChild(mydiv);
}



//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////

var RequestedVer;

function splitversion(version)
{
    list = version.split(".");
    for (i = 0; i < 4; i++) if (!list[i]) list[i] = -1;
    return list;
}

function msieversion()
{
    var ua = window.navigator.userAgent
    var msie = ua.indexOf("MSIE ")

    if (msie > 0)      // If Internet Explorer, return version number
    {
        return (ua.substring(msie + 5, ua.indexOf(";", msie)))
    }
    else
    {                 // If another browser, return 0
        return 0
    }
}

function Test_v1_AboveEqual_TEV(v1, TEV)
{
    for (i = 0; i < 4; i++)
    {
        if (v1[i] < 0) v1[i] = TEV[i];
        if (TEV[i] < v1[i]) return 0;
        if (TEV[i] > v1[i]) return 1;
    }
    return 1;
}

function DetectTE(version)
{
    RequestedVer = version;

    tIEVersion = msieversion();

    if (tIEVersion != 0)
        insertObject("DETECT", "CLSID:A5606C7C-13E8-4403-B5C1-72CE1AEE1CA2", DetectTEOnIESite, testDetectProp);
    else
        DetectTEMisc(version);
}


function DetectTEMisc(version)
{
    var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
    var is_safari = navigator.userAgent.toLowerCase().indexOf('safari') > -1;
    var is_opera = navigator.userAgent.toLowerCase().indexOf('opera') > -1;
    if (is_chrome || is_safari || is_opera) // if it is chrome/opera/safari then just run teh shell and hope for the best. we do not have detection of te verison in those browsers right now.
    {
        EnterSkylineGlobe(0);   // If we are here, the client did not specified a version and the mimetype exist meaning that there is a TE on this computer equal or above v5.0.0
        return;
    }

    v1 = splitversion(version);
    version = v1[0] + "." + v1[1] + "." + v1[2]; // we do not write freeze in the reg

    var appSkyline = "application/Skyline.TerraExplorer";
    var mimetype = navigator.mimeTypes[appSkyline];

    if (mimetype == undefined || mimetype == "")
    {
        EnterSkylineGlobe(-100);
        return;
    }

    // We can not detect TerraExplorer older then v5.0.0 on a non IE browsers
    // If you want to treat such cases as "FOUND", return 1 here. 

    if (v1[0] < 0)
    {
        EnterSkylineGlobe(0);   // If we are here, the client did not specified a version and the mimetype exist meaning that there is a TE on this computer equal or above v5.0.0
        return;
    }

    appSkyline = appSkyline + "." + version;
    mimetype = navigator.mimeTypes[appSkyline];

    if (mimetype == undefined || mimetype == "")
    {
        // The specific version was not detected.
        // Check if there is a higher version installed.

        v1 = splitversion(version);

        for (major = v1[0]; major < 10; major++)
        {
            for (minor = 0; minor < 10; minor++)
            {
                if (major == v1[0] && minor < v1[1])
                    continue;
                for (build = 0; build < 10; build++)
                {
                    if (major == v1[0] && minor == v1[1] && build < v1[2])
                        continue;
                    MimeVer = major + "." + minor + "." + build;
                    appSkyline = "application/Skyline.TerraExplorer." + MimeVer;

                    mimetype = navigator.mimeTypes[appSkyline];
                    if (!(mimetype == undefined || mimetype == ""))
                    {
                        TEV = splitversion(MimeVer);
                        if (Test_v1_AboveEqual_TEV(v1, TEV) == 1)
                        {
                            EnterSkylineGlobe(0);
                            return;
                        }
                    }
                }
            }
        }

        EnterSkylineGlobe(-101);   // No higher version was detected. - we need to update
        return;
    }

    EnterSkylineGlobe(0);
}

function DetectTEOnIESite(Res)
{

    try
    {
        v1 = splitversion(RequestedVer);

        if (Res == 0)
        {
            if (DETECT.IsTEExist == undefined)
            {
                // new Detect plug exist

                if (DETECT.Type == "NA")
                {
                    EnterSkylineGlobe(-101);  // An installation exist but needs to be "repaired"
                    return;
                }

                if (RequestedVer == undefined || RequestedVer == "")
                    EnterSkylineGlobe(0);
                else
                {

                    var ExistingVer;
                    ExistingVer = DETECT.Major + "." + DETECT.Minor + "." + DETECT.Build;

                    TEV = splitversion(ExistingVer);

                    if (Test_v1_AboveEqual_TEV(v1, TEV) == 0)
                        EnterSkylineGlobe(-101);
                    else
                        EnterSkylineGlobe(0);
                }
            }
            else
            {
                // We have detected an older version (prior to 5.0.0)

                if (v1[0] < 5)  // If we actually wanted an older version, then this is OK. otherwise, we need to download.
                    EnterSkylineGlobe(0);
                else
                    EnterSkylineGlobe(-101);
            }

            return;
        }
        else
        {
            // Detection plug does not exist.
            EnterSkylineGlobe(Res);
        }
    }
    catch (e)
    {
        alert("Unknown Error: " + e.description + e.number);
    }
}

