// ######################################################################################
// ########## Tourality JS Functions - (c) creative workline 2004-2010 ##################
// ######################################################################################



// ########## map functions ###################################

// loads the google map for the first time
function loadGMap(mapElementName) {
	if (GBrowserIsCompatible()) {
		//map = new GMap2(document.getElementById("map"));
		map = new GMap2(document.getElementById(mapElementName));
		// OLD:
		//map.addControl(new GSmallMapControl());
		//map.addControl(new GMapTypeControl());

	    //SCALE: puts metric scale on top:
	    //_mPreferMetric = true;
	    //var scale = new GScaleControl();
	    //map.addControl(scale, GControlPosition.G_ANCHOR_BOTTOM_LEFT);
		
	    //To hide the miles/feet scale:
	    //scale.fpsLbl.style.visibility="hidden";
	    //scale.fpsBar.style.visibility="hidden"; 
	    //scale.maxLength = 100;
				
		// use default controls, disable hybrid view
		var customUI = map.getDefaultUI();
        // Remove MapType.G_HYBRID_MAP      
		customUI.maptypes.hybrid = false;
        map.setUI(customUI);

		// enable zooming by scrolling
		map.enableScrollWheelZoom();
		
		// disable dragging of the map
		//map.disableDragging();
		//map.setCenter(new GLatLng(48.2217, 16.3412), 13);
	   
	    // center to world
	    //map.setCenter(new GLatLng(34, 0), 1);
		
		// geocoder to search for addresses
		geocoder = new GClientGeocoder();		
		
	} else {
		alert("ERROR: Your Browser is not GBrowser compatible. - Cannot display game map.");
	}
	return map;
}


//Sets the bounds of the gmap as specified
function setGMapBounds(map, lng_ulx, lat_uly, lng_lrx, lat_lry) {
  // vienna
  //	var lng_ulx = 16.156769; var lat_uly = 48.326126;
  //	var lng_lrx = 16.641541; var lat_lry = 48.074868;
  
  	var sw =  new GLatLng(lat_uly, lng_ulx);
	var ne = new GLatLng(lat_lry, lng_lrx);
	//alert("sw="+sw+" ne=" + ne);
	//alert("set gmap to bounds1 ");
    var bounds = new GLatLngBounds(sw,ne);	  
/*	
	  var bounds = new GLatLngBounds(
       new GLatLng(lat_uly, lng_ulx),
       new GLatLng(lat_lry, lng_lrx));
*/	  
      //alert("set gmap to bounds " + bounds);
      //alert("bounds.getCenter " + bounds.getCenter());
      //alert("map.getBoundsZoomLevel(bounds) " + map.getBoundsZoomLevel(bounds));	  
	  map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));             // <<-- IE fatal "seite kann nicht geladen werden" wtf??
}


function getGMapBounds(map) {
	bounds = map.getBounds();
	sw = bounds.getSouthWest();
	ne = bounds.getNorthEast();
	returnBounds = new Array(sw.lng(), ne.lat(), ne.lng(), sw.lat());
	//alert("returning bounds " + returnBounds);
	return returnBounds;
}

function getGMapBoundsSmaller(map) {
	// TODO getGMapBoundsSmaller
	//map.fromLatLngToDivPixel(ne);
	var bounds = map.getBounds();
	var sw = bounds.getSouthWest();
	var ne = bounds.getNorthEast();
	
	var leftLngX = map.fromDivPixelToLatLng(new GPoint(0,0));
	var rightLngX =  map.fromDivPixelToLatLng(new GPoint(640,0));
	var topLatY =  map.fromDivPixelToLatLng(new GPoint(0,0));	
	var bottomLatY =  map.fromDivPixelToLatLng(new GPoint(0,480));
	
	returnBoundsSmaller = new Array(leftLngX.lng(), topLatY.lat(), rightLngX.lng(), bottomLatY.lat());
	
	alert("getGMapBoundsSmaller=" + returnBoundsSmaller);
	return returnBoundsSmaller;
}


function zoomToAddress(address, alertTextNotFound) {
  if (geocoder) {
    geocoder.getLatLng(
      address,
      function(point) {
        if (!point) {
          alert("'" + address + "' " + alertTextNotFound);
        } else {
          map.setCenter(point, 15);
          //var marker = new GMarker(point);
          //map.addOverlay(marker);
          //marker.openInfoWindowHtml(address);
        }
      }
    );
  }
}

function showAddress(address) {
	//alert("showAddress: " + address);
	if (geocoder) {
	  geocoder.getLatLng(
	    address,
	    function(point) {
	      if (!point) {
	        alert(address + " not found");
	      } else {
	        map.setCenter(point, 12);
	      }
	    }
	  );
	}
}



// ########## menu functions ###################################

var MENU_DELAY = 0; //this is the delay in ms for the menu

var activeTimout;
var activeTimoutLeave;
//var activeTimoutHide;

//TO = timeout
//=====
function showSubmenuTO(smstr, ctxPath) {
  if(activeTimout){
    window.clearTimeout(activeTimout);
  }
  activeTimout = window.setTimeout("showSubmenu('"+smstr+"', '"+ctxPath+"')", MENU_DELAY);
}

//=====
function showSubmenu(smstr, ctxPath) {

	var smContainer = $("submenu");
	var subMenus = smContainer.getElementsByTagName("ul");
	for (var i = 0; i < subMenus.length; i++) {
	  subMenus[i].style.display="none";
	}
	
	var subMenus = smContainer.getElementsByTagName("div");
	for (var i = 0; i < subMenus.length; i++) {
	  subMenus[i].style.display="none";
	}
	
  var sm = $(smstr);
  if (sm) {
	  	//alert("submenu: " + sm);
		sm.style.display="";
		var smstrul = smstr + "_ul";
		var smUL = $(smstrul);
		if(smUL){
			smUL.style.display="";
		}
    showMenuOfSubmenu(smstr, ctxPath);
	}	
	return true;
}

//=====
function showMenuOfSubmenu(smstr, ctxPath) {
	var menuName = smstr.substring("sm_".length, smstr.length).toLowerCase();
	/*
  var m = $(menuName);
	if (m) {
		m.firstChild.firstChild.src = ctxPath + "/img/menu/mm_" + menuName + "_sel.jpg";
	}
  */
  //iterate over all mainmenu points..
  var lis = $("mainmenu").getElementsByTagName("ul")[0].getElementsByTagName("li");
  for(var i = 0; i < lis.length; i++) {
    var liMM = lis[i];
    if(menuName == liMM.id){
      //selected
      liMM.getElementsByTagName("a")[0].getElementsByTagName("img")[0].src = ctxPath + "/img/menu/mm_" + liMM.id + "_sel.jpg";
    } else {
      //not selected
      liMM.getElementsByTagName("a")[0].getElementsByTagName("img")[0].src = ctxPath + "/img/menu/mm_" + liMM.id + ".jpg";
    }
  }
}

/*
//TO = timeout
function hideMenuOfSubmenuTO(smstr, ctxPath) {
  if(activeTimoutHide){
    window.clearTimeout(activeTimoutHide);
  }
  activeTimoutHide = window.setTimeout("hideMenuOfSubmenu('"+smstr+"', '"+ctxPath+"')", MENU_DELAY);
}

function hideMenuOfSubmenu(smstr, ctxPath) {
  var menuName = smstr.substring("sm_".length, smstr.length).toLowerCase();
	var m = $(menuName);
	if (m) {
		m.firstChild.firstChild.src= ctxPath + "/img/menu/mm_" + menuName + ".jpg";
	}
}
*/

//=====
function leaveMenuTO(ctxPath){
  if(activeTimoutLeave){
    window.clearTimeout(activeTimoutLeave);
  }
  activeTimoutLeave = window.setTimeout("leaveMenu('"+ctxPath+"')", MENU_DELAY);
}

//=====
function leaveMenu(ctxPath){
	var menuContainer = $("myMenuID");
	var menuID = menuContainer.getElementsByTagName("div")[0].id;
  //alert("menuID=" + menuID);
  if(menuID){
    var menuName = menuID.substring("menu".length, menuID.length).toLowerCase();
    var submenuName = "sm_" + menuName;
    //alert("submenuName=" + submenuName);
    showSubmenu(submenuName, ctxPath);
  }
	return true;
}

//===== this method is called on the various pages
function selectSubmenuPoint(submenustr) {

	var menuContainer = $("myMenuID");
	var menuID = menuContainer.getElementsByTagName("div")[0].id;
	var submenuName = "sm_" + menuID.substring("menu".length, menuID.length).toLowerCase();
  var menu = $(submenuName);
  //alert("menu="+ menu);
	var subMenus = menu.getElementsByTagName("li");
	for (var i = 0; i < subMenus.length; i++) {
	  if(subMenus[i].id == submenustr){
	  	// alert("found selected="+ subMenus[i].id);
   		subMenus[i].className ="submenuSelected";
	  } else {
		  subMenus[i].className ="submenuNotSelected";
	  }
	}
}


// ##########  screenshots slideshow functions ###################################


function initScreenshotsSlideshow(ctxPath) {

		touralityCtxPath = ctxPath;
		
		imageNames = new Array();
		imageNames[0] = "Tourality_Screenshot_01.jpg";
		imageNames[1] = "Tourality_Screenshot_02.jpg";
		imageNames[2] = "Tourality_Screenshot_03.jpg";
		imageNames[3] = "Tourality_Screenshot_04.jpg";
		imageNames[4] = "Tourality_Screenshot_05.jpg";
		imageNames[5] = "Tourality_Screenshot_06.jpg";
		imageNames[6] = "Tourality_Screenshot_07.jpg";
		imageNames[7] = "Tourality_Screenshot_08.jpg";
		imageNames[8] = "Tourality_Screenshot_09.jpg";
		imageNames[9] = "Tourality_Screenshot_10.jpg";		
		imageNames[10] = "Tourality_Screenshot_11.jpg";		
		imageNames[11] = "Tourality_Screenshot_12.jpg";		
		imageNames[12] = "Tourality_Screenshot_13.jpg";		
		imageNames[13] = "Tourality_Screenshot_14.jpg";		
		imageNames[14] = "Tourality_Screenshot_15.jpg";		
		imageNames[15] = "Tourality_Screenshot_16.jpg";		
		imageNames[16] = "Tourality_Screenshot_17.jpg";		
		imageNames[17] = "Tourality_Screenshot_18.jpg";		
		imageNames[18] = "Tourality_Screenshot_19.jpg";		
		imageNames[19] = "Tourality_Screenshot_20.jpg";		
		imageNames[20] = "Tourality_Screenshot_21.jpg";		
    imageNames[21] = "Tourality_Screenshot_22.jpg";		
    imageNames[22] = "Tourality_Screenshot_23.jpg";		
    imageNames[23] = "Tourality_Screenshot_24.jpg";		
    imageNames[24] = "Tourality_Screenshot_25.jpg";		
    imageNames[25] = "Tourality_Screenshot_26.jpg";		
    imageNames[26] = "Tourality_Screenshot_27.jpg";		
    imageNames[27] = "Tourality_Screenshot_28.jpg";		
    imageNames[28] = "Tourality_Screenshot_29.jpg";		
    imageNames[29] = "Tourality_Screenshot_30.jpg";		

		imageCount = imageNames.length;


		currentImageIdx = -1;
		imgTag = $('homeScreenshotImg');

		currentScreenshotIndex = $('currentScreenshotIdx');
		//currentScreenshotIndex.innerHTML = (currentImageIdx + 1) + " / " + imageCount;
		
		switchScreenshotNext();
		startScreenshotsSlideshow();

}

function startScreenshotsSlideshow() {
		timer = setInterval("switchScreenshotNext()", 5000);
}

function switchScreenshotNextManual() {
	if(timer){
		clearInterval(timer);
	}
	if ("undefined" != typeof(timeout)) {
		clearTimeout(timeout);
	}
	timeout = setTimeout("startScreenshotsSlideshow()", 6500);
	switchScreenshotNext();
}

function switchScreenshotPreviousManual() {
	if(timer){
		clearInterval(timer);
	}
	if ("undefined" != typeof(timeout)) {
		clearTimeout(timeout);
	}
	timeout = setTimeout("startScreenshotsSlideshow()", 6500);
	switchScreenshotPrevious();
}

function switchScreenshotNext() {
	++currentImageIdx;
	if(currentImageIdx >= imageCount){
		currentImageIdx = 0;
	}
	imgTag.src = touralityCtxPath + "/img/screenshots/slideshow/" + imageNames[currentImageIdx];
	currentScreenshotIndex.innerHTML = (currentImageIdx + 1) + " / " + imageCount;
}

function switchScreenshotPrevious() {
	--currentImageIdx;
	if(currentImageIdx < 0){
		currentImageIdx = imageCount - 1;
	}
	imgTag.src = touralityCtxPath + "/img/screenshots/slideshow/" + imageNames[currentImageIdx];
	currentScreenshotIndex.innerHTML = (currentImageIdx + 1) + " / " + imageCount;
}


// ############ string & input functions ##########################

function checkLengthAndCut(inputField, maxLength) {
	if (inputField.value.length > maxLength) {
		inputField.value = inputField.value.substring(0,maxLength);
	}
}									


// ########## general functions ###################################

 function openWindow(location, name, params) {	  	
		if (isIE()) {
			myWindow = window.open(location, "TouralityPopup", params); // IE 7 bug - title as param seems not to be supported or buggy in ie7 *wtf* - wrong window size and incl adress bar etc....
			//myWindow.moveTo(150, 250);  // thanks to this lovely IE we don't have window.outerWidth and window.outerHeight - you gotta hate MS!
			myWindow.focus();
		} else {
			myWindow = window.open(location, name, params);
			myWindow.moveTo(screen.width/2 - myWindow.outerWidth/2, screen.height/2 - myWindow.outerHeight/2);
			myWindow.focus();
		}	
 }


//adjust the height of the "main" div element to a minimum height
function adjustHeight(){
  var ieVersion = getInternetExplorerVersion();
  if (ieVersion > -1 && ieVersion < 7){ //only IE 6 and older
    var main = document.getElementById("main");
    //alert(main.style.height);
    if(main.style.getAttribute("height", false) < 512){
      main.style.setAttribute("height", 512, false);
      //alert(main + " - " + main.style.getAttribute("height", false));
    }
  }
}

//sets the tooptip-spans to visible because they were hidden during page loading
function setDojoTooltipsVisible() {
  var dojos = document.getElementsByTagName('span');
  for (var i = 0; i < dojos.length; i++) {
    if(dojos[i].className == 'dojoTT'){
      dojos[i].style.display='';
    }
  }
}

// wether or not the browser is an internet explorer
function isIE() {
	if (document.all) {
		return true;
	} 
	return false;
}

// Returns the version of Internet Explorer or a -1 (indicating the use of another browser). 
// see http://msdn2.microsoft.com/en-us/library/ms537509.aspx
function getInternetExplorerVersion() {
  var rv = -1; // Return value assumes failure.
  if (navigator.appName == 'Microsoft Internet Explorer'){
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null) {
      rv = parseFloat( RegExp.$1 );
    }
  }
  return rv;
}

// returns the users timezone gmt offset in minutes (incl DST)
function getUserTimezoneOffset() {
	var now = new Date();
	return now.getTimezoneOffset();
}
	
// ########### ad functions #######################################


// ValueClick Media INTERSTITIAL HEAD CODE v1.0 for tourality.com
function FCx(x){
  var min=15; // minimum minutes between interstitials (needs to be >15)
  if(x.indexOf('get.media')>0){
    x=unescape(x.substring(x.indexOf('&url=')+5,x.length));
  }else{
    if(document.cookie.indexOf('CxIC=1')<=0){
      x='http://media.fastclick.net/w/get.media?sid=44186&m=5&tp=6&url='+escape(x);
      var date_ob=new Date();
      date_ob.setTime(date_ob.getTime()+min*1000*60);
      document.cookie='FCxIC=1; path=/; expires='+date_ob.toGMTString();
    }
  }
  return x
}	
	
	
	
// #### other ##########################################################################

function dedectBrowser() {
	var BrowserDetect = {
		init: function () {
			this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
			this.version = this.searchVersion(navigator.userAgent)
				|| this.searchVersion(navigator.appVersion)
				|| "an unknown version";
			this.OS = this.searchString(this.dataOS) || "an unknown OS";
			alert("Browser: " + this.browser + " Version: " + this.version + " OS: " + this.OS);
		},
		searchString: function (data) {
			for (var i=0;i<data.length;i++)	{
				var dataString = data[i].string;
				var dataProp = data[i].prop;
				this.versionSearchString = data[i].versionSearch || data[i].identity;
				if (dataString) {
					if (dataString.indexOf(data[i].subString) != -1)
						return data[i].identity;
				}
				else if (dataProp)
					return data[i].identity;
			}
		},
		searchVersion: function (dataString) {
			var index = dataString.indexOf(this.versionSearchString);
			if (index == -1) return;
			return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
		},
		dataBrowser: [
			{ 	string: navigator.userAgent,
				subString: "OmniWeb",
				versionSearch: "OmniWeb/",
				identity: "OmniWeb"
			},
			{
				string: navigator.vendor,
				subString: "Apple",
				identity: "Safari"
			},
			{
				prop: window.opera,
				identity: "Opera"
			},
			{
				string: navigator.vendor,
				subString: "iCab",
				identity: "iCab"
			},
			{
				string: navigator.vendor,
				subString: "KDE",
				identity: "Konqueror"
			},
			{
				string: navigator.userAgent,
				subString: "Firefox",
				identity: "Firefox"
			},
			{
				string: navigator.vendor,
				subString: "Camino",
				identity: "Camino"
			},
			{		// for newer Netscapes (6+)
				string: navigator.userAgent,
				subString: "Netscape",
				identity: "Netscape"
			},
			{
				string: navigator.userAgent,
				subString: "MSIE",
				identity: "Explorer",
				versionSearch: "MSIE"
			},
			{
				string: navigator.userAgent,
				subString: "Gecko",
				identity: "Mozilla",
				versionSearch: "rv"
			},
			{ 		// for older Netscapes (4-)
				string: navigator.userAgent,
				subString: "Mozilla",
				identity: "Netscape",
				versionSearch: "Mozilla"
			}
		],
		dataOS : [
			{
				string: navigator.platform,
				subString: "Win",
				identity: "Windows"
			},
			{
				string: navigator.platform,
				subString: "Mac",
				identity: "Mac"
			},
			{
				string: navigator.platform,
				subString: "Linux",
				identity: "Linux"
			}
		]
	
	};
	BrowserDetect.init();
}


//===== a function to highlight cells on the devices page (devices.jsf)
function highlightCell(link){
  if(oldHighlight){
    $(oldHighlight).parentNode.className = '';  
  }
  var hrefID = link.href.substring(link.href.indexOf('#')+1);
  $(hrefID).parentNode.className = 'highlightCell';
  oldHighlight = hrefID;
}
var oldHighlight;


//===== math functions
/* keeps zeros at the end of the number */
function roundKeepZeros(x, n) {
  if (n < 1 || n > 14) return false;
  var e = Math.pow(10, n);
  var k = (Math.round(x * e) / e).toString();
  if (k.indexOf('.') == -1) k += '.';
  k += e.toString().substring(1);
  return k.substring(0, k.indexOf('.') + n+1);
}

