
var TAB_BUSS_ID = 1;
var TAB_ADDRESS_ID = 2;
var TAB_ROUTE_ID = 3;
var TAB_ROUTE2_ID = 4;
var TAB_TOC_ID = 5;

var prevTabID = TAB_ADDRESS_ID;
var prevTabDIV = "";
var shutWidth = 0;
var mapTypes = new Array();

var busyIndicator=null;
var copyRightMap = 'סיסטמטיקס בע"מ © 2008, מפה בע"מ © 2008';
var copyRightAerial = 'סיסטמטיקס בע"מ © 2008, המרכז למיפוי ישראל © 2008';
var copyRightMap_eng = 'Systematics LTD © 2008, Mapa LTD © 2008';
var copyRightAerial_eng = 'Systematics LTD © 2008, MAPI © 2008';

// 15.10.2008
String.prototype.trim = function(){ return this.replace(/^\s+|\s+$/g,'')}



shutterOpen=new Image();
shutterClose=new Image();
if (clientLang=="heb")
{
    shutterOpen.src="images/shutter_open.gif";
    shutterClose.src="images/shutter_close.gif";
}
else
{
    shutterOpen.src="images/eng_shutter_open.gif";
    shutterClose.src="images/eng_shutter_close.gif";
}    

stationOpen=new Image();
stationOpen.src="images/station_open.gif";
stationClose=new Image();
stationClose.src="images/station_close.gif";



var resizeExtent=true;
var tabPanelWidth = 243;
//var tabPanelWidth = 400;
var shutterWidth = 12;
var commonHeight = 0;
var mapPixCorrect = 6;
var contTabPixCorrect = 16;

var resizeTimer = null;
var resizeWinCount = 500;
var resizeMapCount = 300;

// Current dimensions


function ChangeImage(obj, newSrc) {
 obj.src = newSrc.src;
}


var isIE=(document.all)?true:false
var isNN=(document.getElementById && !isIE)?true:false
var isMAC=(navigator.userAgent.toLowerCase().indexOf("mac")!=-1)?true:false

var browser=new Browser();
//alert(browser.isFF + ' ' + browser.version);
var winWidth, winHeight, d=document; 

var startPos, diffpos=0;
var ee = false;

function Browser() {
  var ua, s, i;
  this.isIE= false;  // Internet Explorer
  this.isNS= false;  // Netscape
  this.isMac = false;
  this.isFF = false; //Firefox
  this.version= null;
  ua = navigator.userAgent;
  

  s = "MSIE";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isIE = true;
    this.version=parseFloat(ua.substr(i + s.length));
    return;
  }

  s = 'Firefox';
  if ((i = ua.indexOf(s.toLowerCase())) >=0){
    this.isFF = true;
    this.version=parseFloat(ua.substr(i + s.length));
    return;
  }

  s = "Netscape6/";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS=true;
    this.version=parseFloat(ua.substr(i + s.length));
    return;
  }
  
  s = "Mac";
  if((i = ua.indexOf(s.toLowerCase())) >=0){
    this.isMac = true;
    this.version=parseFloat(ua.substr(i + s.length));
    return;
  }
  
  // Treat any other "Gecko" browser as NS 6.1.
  s = "Gecko";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = 6.1;
    return;
  }
}

function MapTypeObject(name,dfi,dsi,hi,si,cr)
{
    this.defaultImage = dfi || "";
    this.disabledImage = dsi || "";
    this.hoverImage = hi || "";
    this.selectedImage = si || "";
    this.name = name || "";
    this.copyright = cr || "";
}

function setMapType(bar,name)
{
    var item; // = Toolbars["MapTypeToolbar"].item[name];
    var copyR = $get("emapCopyright");
    var tb = Toolbars[bar].items;
    if ((tb==null) || (typeof(tb)=='undefined'))
        return;
    for (var i=0;i<mapTypes.length;i++)
    {
        item = tb[mapTypes[i].name];
        if ((item==null) || (typeof(item)=='undefined'))
            continue;
        if (mapTypes[i].name == name) // make it selected. Selected image saved as disabled
        {
            item.defaultImage = mapTypes[i].disabledImage;
            item.hoverImage = mapTypes[i].disabledImage;
            ToolbarMouseOver(bar,name);
            if (copyR!=null)
                copyR.innerText = mapTypes[i].copyright;
        }
        else // restore images links
        {
            item.defaultImage = mapTypes[i].defaultImage;
            item.hoverImage = mapTypes[i].hoverImage;
            ToolbarMouseOut(bar,mapTypes[i].name);
        }    
    }    
}

function WinSize()
{

winWidth=0;
winHeight=0;
var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    winWidth = window.innerWidth;
    winHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    winWidth = document.documentElement.clientWidth;
    winHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    winWidth = document.body.clientWidth;
    winHeight = document.body.clientHeight;
  }
 //   alert(winWidth + ',' + winHeight);
} 

function resizeMap(w,h)
{

var mapWidth;
var mapHeight;
  theDiv=$get('emapMapDiv');
  if ((typeof(theDiv)=='undefined') || (theDiv==null))
    return;
//  dw = (typeof theDiv.clientWidth != 'undefined') ? theDiv.clientWidth : theDiv.innerWidth;
//  dh = (typeof theDiv.clientHeight != 'undefined') ? theDiv.clientHeight : theDiv.innerHeight;
  
  var b = Sys.UI.DomElement.getBounds(theDiv);
  dw = b.width;
  dh = b.height;
  
  mapWidth= w || dw;
  mapHeight=h || dh;

  map.resize(mapWidth, mapHeight, resizeExtent);
}

function showBusyIndicator(sender)
{
    if (busyIndicator != null)
    {
     busyIndicator.style.display = "block";
     busyIndicator.style.visibility = "visible";
//     busyIndicator.style.zIndex = 100;
//     busyIndicator.style.left = winWidth/3;
//     busyIndicator.style.top = winHeight/3;
    if (clientLang=="heb")
        busyIndicator.style.left = 100 + 'px';
    else    
        busyIndicator.style.right = 100 + 'px';
     busyIndicator.style.top = 150 + 'px';

    }
}
function hideBusyIndicator(sender)
{
    if (busyIndicator != null)
        busyIndicator.style.display = "none";
        busyIndicator.style.visibility = "hidden";
}

function startEmap()
{
// 15.10.2008
    if(document.getElementById('ZoomLevel').innerHTML.trim()==""){
	    var currLocation = document.location;
	    document.location = currLocation;
	    return;
    }

    WinSize();
    busyIndicator = $get("emapLoading");

    $get("emap").style.display = "block";

// Add handlers for busy indocator    
    map.pendingTiles.add_onRequestsPending(showBusyIndicator);
//    map.pendingTiles.add_onRequestsRemove(showPendingTiles);
    map.pendingTiles.add_onRequestsCompleted(hideBusyIndicator);    
 
    var tb = Toolbars["MapTypeToolbar"];
    var item;
    if (tb!=null)
    {
        for (var i=0;i<tb.commands.length;i++)
        {
            item = tb.items[tb.commands[i]];

            if (tb.commands[i]=='Regular')
                mapTypes[i] = new MapTypeObject(tb.commands[i],item.defaultImage,item.disabledImage,item.hoverImage,item.selectedImage,((clientLang=="heb") ? copyRightMap : copyRightMap_eng));
            else    
                mapTypes[i] = new MapTypeObject(tb.commands[i],item.defaultImage,item.disabledImage,item.hoverImage,item.selectedImage,((clientLang=="heb") ? copyRightAerial : copyRightAerial_eng));
        }        
        setMapType("MapTypeToolbar","Regular");
    }    
    tabPanelWidth=Sys.UI.DomElement.getBounds($get("emapTabContentDiv")).width;
    Sys.Net.WebRequestManager.add_invokingRequest( intercept );
    setMapLayout();
    window.onresize=onResizeHandler;
}

function onResizeHandler(e)
{
    window.clearTimeout(resizeTimer);
    resizeTimer = window.setTimeout('setMapLayout()',resizeWinCount);
}
function setMapLayout()
{
  WinSize();
  // Reset the map div and on Map tools
  var theMap=$get('emapMapDiv');
  if ((theMap==null) || (typeof(theMap)=='undefined'))
    return;
  var topPos=getPageOffsetTop(theMap);
  var leftPos=getPageOffsetLeft(theMap);
  commonHeight = winHeight-topPos-mapPixCorrect;
  theMap.style.height = commonHeight + "px";
  var theContDiv = $get("emapTabContentDiv");
  //theContDiv.style.width = tabPanelWidth;
  var mapWidth=winWidth - ((theContDiv.offsetWidth=="0") ? 0 : tabPanelWidth) - shutterWidth - 10;
  var mapHeight = commonHeight;
  theMap.style.width = mapWidth + 'px';
  map.resize(mapWidth , mapHeight, resizeExtent);
  if (theContDiv.offsetWidth!="0")
     doTab(prevTabID);
   
// Get map position once more after resizing    
  topPos=getPageOffsetTop(theMap);
  leftPos=getPageOffsetLeft(theMap);
  maptypeDiv=$get('emapMapTypeDiv');
  if (!((typeof(maptypeDiv)=='undefined') || (maptypeDiv==null)))
  {
      maptypeDiv.style.top=(topPos+7) + 'px';
      maptypeDiv.style.left=(leftPos+78) + 'px';
      maptypeDiv.style.display="block";
  }
  
  panDiv=$get('emapMapPanDiv');
  if (!((typeof(panDiv)=='undefined') || (panDiv==null)))
  {
      panDiv.style.top=(topPos+7) + 'px';
      panDiv.style.left=(leftPos+13) + 'px';
      panDiv.style.display="block";
  }

  zoomDiv=$get('emapMapZoomDiv');
  if (!((typeof(zoomDiv)=='undefined') || (zoomDiv==null)))
  {
      zoomDiv.style.top=(topPos+72) + 'px';
      zoomDiv.style.left=(leftPos+30) + 'px';
      zoomDiv.style.display="block";
  }
    
}


function initDiv(oDiv,pixCorrect)
{
  theDiv=$get(oDiv);
  if ((theDiv==null) || (typeof(theDiv)=='undefined'))
    return;
  topPos=getPageOffsetTop(theDiv);
  leftPos=getPageOffsetLeft(theDiv);
//  newHeight = winHeight-topPos-pixCorrect;
  newHeight = commonHeight + mapPixCorrect - pixCorrect;
  theDiv.style.height=newHeight+'px';
//  theDiv.style.pixelHeight = newHeight;
}

function getPageOffsetLeft(el) {
  return Sys.UI.DomElement.getBounds(el).x;

  var x;
  x = el.offsetLeft;
  if (el.offsetParent != null)
  {
    x += getPageOffsetLeft(el.offsetParent) - 2;
  }
  return x;
}

function getPageOffsetTop(el) {
  return Sys.UI.DomElement.getBounds(el).y;

  var y;
  y = el.offsetTop;
  if (el.offsetParent != null)
    y += getPageOffsetTop(el.offsetParent);
  return y;
}


function doShutter(theDiv,theMap, theImg)
{
 objDiv=$get(theDiv);
 objImage=$get(theImg);
 if(objDiv.style.display=="none")
 {
  mapDiv=$get(theMap);
  resizeMap(mapDiv.clientWidth + 6 - shutWidth);
  objImage.src=shutterClose.src;
  objDiv.style.display="block";
 }
 else
 {
  shutWidth = objDiv.offsetWidth;
  objImage.src=shutterOpen.src;
  objDiv.style.display="none";
 }
  setMapLayout();
}

function showDOMTree(theObj,indent)
{
return;
    var ind = indent || "";
    showMessage("emapMessage",ind + "Name=" + theObj.name + ", id=" + theObj.id + ", width=" + theObj.offsetWidth,0,false);
    for (var i=0; i<theObj.childNodes.length;i++)
    {
        showDOMTree(theObj.childNodes[i],ind + " ");
    }
}

function doTab(tabID){
 if (prevTabID>0){
  prevA="TabA" + prevTabID;
  prevSpan="TabSpan"+prevTabID;
  $get(prevA).className="normal";
  $get(prevSpan).className="normal";

 }
 currentA="TabA" + tabID;
 currentSpan="TabSpan" + tabID;
 $get(currentA).className="selected";
 $get(currentSpan).className="selected";

 prevTabID=tabID;
 
 if (prevTabDIV!="")
 {
   $get(prevTabDIV).style.display = "none";
//   document.getElementById(prevTabDIV).style.visibility = "hidden";
 }
 
 switch(tabID)
 {
  case TAB_BUSS_ID:
   $get("emapTabBusiness").style.display = "block";
   initDiv("emapTabBusiness",8);
   prevTabDIV="emapTabBusiness";
   break;  

  case TAB_ADDRESS_ID:
   $get("emapTabAddress").style.display = "block";
//   $get("emapTabAddress").style.visibility = "visible";
   initDiv("emapTabAddress",18);
   prevTabDIV="emapTabAddress";
// showDOMTree($get("emapTabContentDiv"),"");
   break;

  case TAB_ROUTE_ID:

    var inRoute = ($get('emapDrivingDirections').style.display=='block');
  if (inRoute)  // directions visible
   {
       HideDrivingDirections();
   }
//  Switch to multiroute
       $get("Point2TR").style.display = "none";   
       $get("PointListTR").style.display = "block"
       $get("Point2TR").style.visibility = "hidden";   
       $get("PointListTR").style.visibility = "visible"
       $get("RoutePoint_addRoute0").style.display = "block"
       $get("RoutePoint_addRoute0").style.visibility = "visible"       
       $get("RoutePoint_addRoute1").style.display = "block"
       $get("RoutePoint_addRoute1").style.visibility = "visible"  
       $get("CircularOption").style.visibility = "visible";     
       $get("CircularOption").style.display = "block";     

       $get("opt_tr").style.display="block";

       
       $get("emapTabRoute").style.display = "block";
       $get("emapStationsFooter").style.display = "block";
       $get("emapOptionsValues").style.display = "block";
           initDiv("emapTabRoute",18);
           initDiv("emapStations",195);
//           initDiv("emapTabRoute",6);
//           initDiv("emapStations",190);

       $get("emapStationList").style.overflowY="auto";
       $get("emapStationList").style.overflowX="hidden";
       h = $get("emapTabRoute").offsetHeight - 
          $get("emapStationsFooter").offsetHeight - $get("RoutePoint").offsetHeight - 42;
       if (h>=0)   
           $get("emapStationList").style.height = h + 'px';
   if (inRoute)
        showDirections();        
//    showDOMTree($get("emapTabContentDiv"),"");
   prevTabDIV="emapTabRoute";  
   break;
   
  case TAB_ROUTE2_ID:

    var inRoute = ($get('emapDrivingDirections').style.display=='block');
  if (inRoute)  // directions visible
   {
       HideDrivingDirections();
   }
//  Switch to 2-point route
       $get("Point2TR").style.display = "block";   
       $get("PointListTR").style.display = "none"
       $get("Point2TR").style.visibility = "visible";   
       $get("PointListTR").style.visibility = "hidden"
       $get("RoutePoint_addRoute0").style.display = "none"
       $get("RoutePoint_addRoute0").style.visibility = "hidden"       
       $get("RoutePoint_addRoute1").style.display = "none"
       $get("RoutePoint_addRoute1").style.visibility = "hidden"       
       $get("CircularOption").style.visibility = "hidden";     
       $get("CircularOption").style.display = "none";     

$get("opt_tr").style.display="none";

       $get("emapTabRoute").style.display = "block";
       $get("emapStationsFooter").style.display = "block";
       $get("emapOptionsValues").style.display = "block";
       initDiv("emapTabRoute",18);
       initDiv("emapStations",165);
   if (inRoute)
        showDirections();        

   prevTabDIV="emapTabRoute";  
   break;
   

  case TAB_TOC_ID:
   $get("emapTabLayers").style.display = "block";
   initDiv("emapTabLayers",8);
   prevTabDIV="emapTabLayers";
   break;

  default:
   break;
 }
}


//function doStation(stationID,imgID, placeID){
// stationDiv=document.getElementById(stationID).style;
// placeDiv=document.getElementById(placeID).style;
// objImage=document.getElementById(imgID);
// if(stationDiv.display=="none")
// {
//  objImage.src=stationClose.src;
//  stationDiv.display="block";
//  placeDiv.display="none";
// }
// else
// {
//  objImage.src=stationOpen.src;
//  stationDiv.display="none";
//  placeDiv.display="block";
// }
//}

function AddStation()
{
    if (currentPoint==null)
        return;
    addToList(currentPoint,'emapStations');
    currentPoint=null;
/*
 if (objDiv=document.getElementById('stEdit1').style.display="block")
  doStation('stEdit1', 'stShow1', 'stPlace1');
 if (objDiv=document.getElementById('stEdit2').style.display="block")
  doStation('stEdit2', 'stShow2', 'stPlace2');
 document.getElementById('newStation').style.display="block";
 */
}

function doOptions()
{
 return;
 objDiv=$get('emapOptionsValues').style;
 objImage=$get('stOptions');
 if(objDiv.display=="block")
 {
  initDiv("emapStations",95);
  objImage.src=stationOpen.src;
  objDiv.display="none";
 }
 else
 {
  initDiv("emapStations",152);
  objImage.src=stationClose.src;
  objDiv.display="block";
 }
}

function MoveStation()
{
}
function HideDrivingDirections()
{
 $get('emapStations').style.display="block";
 $get('emapStationsFooter').style.display="block";
 $get('emapDrivingDirections').style.display="none";
}
function showDirections()
{
$get('emapStations').style.display="none"; 
$get('emapStationsFooter').style.display="none"; 
$get('emapDrivingDirections').style.display="block";
initDiv("emapDrivingDirections",6);
initDiv("emapDirectionsStations",52);
//document.getElementById('emapDirectionsStations').innerHTML = str;
}

/*  Debug function debugRectangle('MapCtrl','%toolbar%','%toolbarItem%',false,'hand');*/
function debugRectangle(mapID,bar,item,cur){
    MapDragRectangle(mapID,item,false,'crosshair');
}

function toggleOV(controlname)
{
    return; // Overview disabled
    ctrl = $get(controlname);
    if (ctrl != null){
        if (ctrl.style.display=='none')
            ctrl.style.display='block';
        else
            ctrl.style.display='none';    
    }
    /*
    if (Overviews[controlname] != null){
        if (Overviews[controlname].divObject.style.visibility=='hidden'){
            Overviews[controlname].show();
            showLayer(Overviews[controlname].boxDivId);
            showLayer(controlname);
        }
        else{
            Overviews[controlname].hide();
            hideLayer(Overviews[controlname].boxDivId);
            hideLayer(controlname);
        }
            
    }
*/
}
function calcElementSize(elementId) {
	//window.status = elementId;
	var element = document.getElementById(elementId);
	eLeft = 0;
    eTop = 0;
    var eLeftBorder, eTopBorder;
	//eWidth = parseInt(element.style.width);
	//eHeight = parseInt(element.style.height);
	eWidth = element.clientWidth;
	eHeight = element.clientHeight;
    while(element != null) {
		eLeftBorder = 0;
		eTopBorder = 0;
        eLeft += element.offsetLeft;
        eTop += element.offsetTop;
        if (element!=document.documentElement) {
            eLeft -= element.scrollLeft;
            eTop -= element.scrollTop;
        }  
        if (element.style.borderWidth!="") {
			eLeftBorder = parseInt(element.style.borderWidth);
			eTopBorder = parseInt(element.style.borderWidth);
		} else if (element.style.borderLeftWidth!="") {
			eLeftBorder = parseInt(element.style.borderLeftWidth);
			eTopBorder = parseInt(element.style.borderTopWidth);
		}							
		if (isNaN(eLeftBorder)) eLeftBorder = 0;
		if (isNaN(eTopBorder)) eTopBorder = 0;
		eLeft += eLeftBorder;
		eTop += eTopBorder;
        element = element.offsetParent;
     }
//	 return new RectangleObject("dummy", eLeft, eTop, eWidth, eHeight);
	 return new Array(eLeft,eTop,eWidth, eHeight);
}
function printDirections()
{
    
    var div = $get('emapDirectionsStations');
    if (div==null)
        return;
    var directions = div.innerHTML;
    if (directions.length==0)
        return;   
    var prtdiv = $get('emapPrint');
    if (prtdiv==null)
        return;
    prtdiv.innerHTML='';
    if (clientLang=="heb")  
        prtdiv.style.direction='rtl';
    else    
        prtdiv.style.direction='ltr';
    var content = '<table><tr><td></td><td>'
    content+=directions;
    content+='</td></tr></table>';
    prtdiv.innerHTML=content;
    window.print();
//    prtdiv.innerHTML='';    
}
