///GLOBALS
SGVersion = "5.0.0";
baseurl   = "http://www.skylineglobe.com/SkylineGlobe/TerraExplorer/";
baseurlv  = baseurl + "v" + SGVersion + "/";
dlgpath   = baseurlv+"dlg/";
iepath    = "http://www.skylineglobe.com/SkylineGlobe/WebClient/PresentationLayer/webclient/3dwebclient.aspx?"; 
ffpath    = baseurlv+"shell/SkylineGlobeShellUrl.asp?"+iepath;
ffpathurl = baseurlv+"shell/SkylineGlobeShellUrl.asp?";
sginstall = baseurl +"install/SkylineGlobeSetup.exe";
sginstall = "http://www.skylineglobe.com/SkylineGlobe/TerraExplorer/install/SkylineGlobeSetup.exe";

//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;

///PUBLIC
function SGDownload(param)
{
  if (param==undefined)
    param="";
  showDialog(dlgpath+"download.html?"+param,"Download TerraExplorer Plugin","SG_Download","30%","15%","400px","420px","decline_accept");
}
///PUBLIC
function SGStart(Param,target)
{
    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);
}
///PUBLIC
function SGStartURL(url,target)
{
    g_UseTerraExplorer=false;
    g_UrlIE=url;
	g_UrlFF=ffpathurl+url;
	g_Param="";

    if (target!=undefined)
	  g_Target=target;
	else
      g_Target="_self";

    DetectTE(SGVersion);
}
///PUBLIC
function TEStart(fly)
{
    g_UseTerraExplorer=true;
    g_UrlIE=fly;
    DetectTE(SGVersion); 
}



function SGTest()
{
	showDialog(dlgpath+"security.html","Warning","SG_Security","30%","20%","400px","250px");
    SGDownload("o=Enter");
	showDialog(dlgpath+"infobar.html","Warning","SG_InfoBar","25%","20%","550px","350px");
	showDialog(dlgpath+"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(dlgpath+"security.html","Warning","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(dlgpath+"security.html","Warning","SG_Security","30%","20%","400px","250px");
					site(-2); // error
				}
			}		 
		}
		myobj.classid = clsid; 
		myobj.onerror = function()
		{
			werok = 0;
        	site(-100); // error - we need to download ....
		}
	}
	catch(e)
	{
		if (werok != 2)
		{
			werok = 0;
			if (e.number==-2147024891)//access denied 0x80070005
			{
				showDialog(dlgpath+"infobar.html","Warning","SG_InfoBar","25%","20%","550px","350px");
                site(-3); // error - just to let the site know

			}
			else
			{
				//alert("some other error"+e.description);
				showDialog(dlgpath+"unknownerror.html","Warning","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
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;

  mydiv=document.all[id];
  if (mydiv)
  {
	return;
  }
  else
  {
    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.border="solid 1px #ffcc00";
   
    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>";
    s=s+"<TR height='100%' style='border-width:20px'><TD colspan='2'><IFRAME id='"+id+"frame'style='border-color:#f8f8ff;border-width:0px;border-style:none;' src='' width='100%' height='100%'></IFRAME></TD></TR>";
    if (ftype=='decline_accept')
	{
      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>I 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>I Accept</u> </a><TD width='5px'></TD></TD></TR>";
	}
    s=s+"</TABLE>";

    mydiv.innerHTML=s;
    document.all[id+"frame"].src=url;
  }

}


function hideDialog(id)
{
  var mydiv=document.all[id];
  n=document.body.removeChild(mydiv);
  document.all[id]=null;
}



//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////

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)
{
    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 = v1[1]; minor < 10; minor++)
            {        
                for (build = v1[2]; build < 10; build++)
                {
                    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);
    }
}


