///GLOBALS
SGVersion = "5.1.0";
domain = "http://bhuvan2.nrsc.gov.in";
baseurl = domain + "/bhuvan/TerraExplorer/";
baseurlv = baseurl + "v" + SGVersion + "/";
ffpathurl = baseurlv + "shell/bhuvanShellUrl.asp?";


var g_Param = "";
var g_UrlIE;
var g_UrlFF;
var g_Target = "_self";
var g_UseURL = false;
var g_UseTerraExplorer = false;



///PUBLIC
function SGStart(Param, target, locale)
{
	
iepath = domain + "/bhuvan/WebClient/PresentationLayer/webclient/bhuvan3d.aspx";
ffpath = baseurlv + "shell/bhuvanShellUrl.asp?" + iepath;
    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 = "";

   DetectTE(SGVersion);
}

//   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;
                           
                            //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+" ");
                   
                    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
            {
                
                site(-3); // error - just to let the site know

            }
            else
            {
                //alert("some other error"+e.description);
               
                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, "_blank");    // IE version
             else
               window.open(g_UrlFF + g_Param, "_self");    // Other browsers version
            }

        }
        if (res == -100) // we need to download SkylineGlobe
   	   {
	   var answer = confirm ("Bhuvan Plugin is not found. Do you want to download?")
	if (answer)
	window.location.href="http://bhuvan.nrsc.gov.in/bhuvan/BhuvanSetup2.0.exe";
	
	   }
        
           
        if (res == -101) // we need to update SkylineGlobe
   	    {
	   var answer = confirm ("Bhuvan Plugin is not found. Do you want to download?")
	if (answer)
	window.location.href="http://bhuvan.nrsc.gov.in/bhuvan/BhuvanSetup2.0.exe";
	
	   }

         
    }
    catch (e)
    {
	alert('error');
     }
}


//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);
}


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 version 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
        {
                        EnterSkylineGlobe(Res);
        }
    }
    catch (e)
    {
        alert("Unknown Error: " + e.description + e.number);
    }
}



