﻿//street View
var markerSV;
var overlayInstance;
var clientSV;
var lastMarkerLocation;
var panorama;
var LinkSVObject;
var StreetView;
var LinkSV = "";
var LinkSVN = "";
var LinkHideSVN ="";
function handleNoFlash(errorCode) {
    if (errorCode == FLASH_UNAVAILABLE) {
        alert("Error: Parece que el navegador no admite el uso de Flash.");
        return;}}  
function VerStreetView(y,x,LinkX) {
    onNewLocation(y, x);
    var latlng = markerSV.getLatLng();
    LinkSVObject = LinkX;
    clientSV.getNearestPanorama(latlng, onResponse);
    if (!overlayInstance) { toggleOverlay() };
    }
function openPanoramaBubble() {
    var contentNode = document.createElement('div');
    contentNode.style.textAlign = 'center';
    contentNode.style.width = '99%';
    contentNode.style.height = '99%';
    contentNode.innerHTML = '';
    var smallNode = document.createElement('div');
    smallNode.style.width = '250px';
    smallNode.style.height = '200px';
    smallNode.id = 'pano';
    markerSV.openInfoWindow(smallNode, { maxContent: contentNode, maxTitle: "Full screen" });
    panorama = new GStreetviewPanorama(smallNode);
    panorama.setLocationAndPOV(markerSV.getLatLng(), null);
    GEvent.addListener(panorama, "newpano", onNewLocation);
    GEvent.addListener(panorama, "yawchanged", onYawChange);
    var iw = map.getInfoWindow();
    GEvent.addListener(iw, "maximizeend", function() {
        panorama.setContainer(contentNode);
        window.setTimeout("panorama.checkResize()", 5);
    });
    GEvent.addListener(iw, "closeclick", function() {
        panorama.remove();
    });
}
function toggleOverlay() {
    if (!overlayInstance) {
        markerSV.show();
        overlayInstance = new GStreetviewOverlay();
        map.addOverlay(overlayInstance);
        var latlng = markerSV.getLatLng();
        lastMarkerLocation = latlng;
        clientSV.getNearestPanorama(latlng, onResponse);
    } 
    else {
        if (panorama) {panorama.remove(); }
        var iw = map.getInfoWindow();
        if (iw) { iw.hide(); }
        map.closeInfoWindow();
        markerSV.hide();
        map.removeOverlay(overlayInstance);
        overlayInstance = null;
    }
}
function onYawChange(newYaw) {
    var GUY_NUM_ICONS = 16;
    var GUY_ANGULAR_RES = 360 / GUY_NUM_ICONS;
    if (newYaw < 0) {
        newYaw += 360;
    }
    guyImageNum = Math.round(newYaw / GUY_ANGULAR_RES) % GUY_NUM_ICONS;
    guyImageUrl = imageStreetViewPath + "man_arrow-" + guyImageNum + ".png";
    markerSV.setImage(guyImageUrl);
}
function onNewLocation(lat, lng) {
    var latlng = new GLatLng(lat, lng);
    markerSV.setLatLng(latlng);
}
function onDragStart() {
    map.closeInfoWindow();
}
function onDragEnd() {
    var latlng = markerSV.getLatLng();
    //if (panorama) {
        clientSV.getNearestPanorama(latlng, onResponse);
    //}
}

function onResponse(response) {
    if (response.code != 200) {
        //markerSV.setLatLng(lastMarkerLocation);
        var LinkToggle = '<br/><a href="javascript:void();" onclick="toggleOverlay();">' + LinkHideSVN + '</a>';
        var infoTabs1 = [new GInfoWindowTab("Street View", LinkSVN + LinkToggle)];
        markerSV.openInfoWindowTabsHtml(infoTabs1);
        //if (LinkSVObject) {LinkSVObject.innerHTML = LinkSVN + LinkToggle;}
    } else {
        var latlng = new GLatLng(response.Location.lat, response.Location.lng);
        markerSV.setLatLng(latlng);
        lastMarkerLocation = latlng;
        openPanoramaBubble();
    }
}

//end street view
var KML_base="";
function updtResults() {
    // alert(document.getElementById("dnn_ctr" + MapaID + "_PMView_KmlPath").innerHTML);
   //sólo se lanza la primera vez que se carga la página
    if (KML_base != document.getElementById("dnn_ctr" + MapaID + "_PMView_cmdSearchHide").href) {
       eval(document.getElementById("dnn_ctr" + MapaID + "_PMView_cmdSearchHide").href);
       KML_base = document.getElementById("dnn_ctr" + MapaID + "_PMView_cmdSearchHide").href;
    } 
}

function NewKMLPath(anchor)
{
    var kml_base2;
    var bounds=map.getBounds();
    var center=bounds.getCenter();
    var coords = [center.lat(), center.lng()];
    var location =  coords.join('|');
    var zoom = parseInt(map.getZoom());
    var alt = Math.pow(2, 17 - zoom) * 1000;
    //alert(document.getElementById("dnn_ctr" + MapaID + "_PMView_KmlPath").innerHTML);

    kml_base2=document.getElementById("dnn_ctr" + MapaID + "_PMView_KmlPath").innerHTML;
    var pos = kml_base2.indexOf("?");
    if(pos==-1){
        kml_base2=kml_base2 + '?kmz=true&coord=' + location + '&range=' + alt}
    else{
        kml_base2=kml_base2.replace('?','?kmz=true&coord=' + location + '&range=' + alt + '&') 
    }
    kml_base2.replace(/\/+/, '/');
    document.location=kml_base2;
}
function Add2Push(contador,title,coordenadas,icono,infotxt){
var c1=coordenadas.split(",");
batch.push(AddMarker(contador,title,new GMarker(new GLatLng(c1[0],c1[1]),{icon: getMarkIcon(icono) }),infotxt));
}
function getMarkIcon(ruta) {
    var icon = new GIcon(G_DEFAULT_ICON);
    var IconInfo=ruta.split('|');
    icon.image = IconInfo[0] ;
    icon.iconSize = new GSize(IconInfo[1], IconInfo[2]); 
    icon.shadow='';
    return icon;}
function AddMarker(i,title,marker, txtHTML){
    marker.tooltip = title;
    if (StreetView) {
        txtHTML = txtHTML + '<a href="javascript:void(0);"  onclick="VerStreetView(' + marker.getLatLng().y + ',' + marker.getLatLng().x + ',this)">' + LinkSV + '</a>';
    } 
    txtHTML="<div style='position: relative; float: left; width: 270px;'>" + txtHTML + "</div>";
    GEvent.addListener(marker, 'click', function() {map.closeInfoWindow(); marker.openInfoWindowHtml(txtHTML);});
    GEvent.addListener(marker,"mouseover", function() {showTooltip(this);});
    GEvent.addListener(marker,"mouseout", function() {ToolTip.style.visibility="hidden";});
    htmls[i] = txtHTML;
    return marker;}
function showTooltip(marker){
    var pixel = map.fromLatLngToDivPixel(marker.getLatLng());
    var x=pixel.x;var y=pixel.y;
    ToolTip.innerHTML = "<div class='tooltip'><nobr>" + marker.tooltip + "</nobr></div>";
    ToolTip.style.visibility = 'visible';
    var centro=map.fromLatLngToDivPixel(map.getCenter());
    var limitD=centro.x + (map.getSize().width/2);
    var limitI=centro.x - (map.getSize().width/2);
    var limitB=centro.y + (map.getSize().height/2);
    var diff=((x + ToolTip.offsetWidth)- limitD);
    if ((x + ToolTip.offsetWidth)> limitD)
    {   if (x>0){x=x - diff;}
        else{x=x + (diff * -1);}
    }
    if(x<limitI){x=limitI;}
    if ((y+ToolTip.offsetHeight)>limitB){y=limitB - ToolTip.offsetHeight;}
	var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(x,y));
	pos.apply(ToolTip);    
}

function mymouseover(i)
{   var marker=batch[i];
    map.closeInfoWindow();
    //if (map.getBounds().containsLatLng(marker.getLatLng())==false) 
    //{
      map.panTo(new GLatLng(marker.getLatLng().y,marker.getLatLng().x));
       window.setTimeout(function(){showTooltip(marker)},500);
    //}
    //else{showTooltip(marker)}
}

function mymouseout(i){ToolTip.style.visibility="hidden";}
function myclick(i){map.closeInfoWindow();batch[i].openInfoWindowHtml(htmls[i]);}

       
function MaximizeMap()
{ 
    shortcut.add("escape",function() {RestoreMap();});
    scroll(0,0);
   this.document.body.style.overflow="hidden";
 
    var divX=document.getElementById("map_canvas" + MapaID);
    divX.focus();
    divX.style.position="absolute";
    divX.style.zIndex="1000000";
    divX.style.top=0;
    divX.style.left=0;
    divX.style.width=TamVentana()[0];
    divX.style.height=TamVentana()[1];
    var mTop=findPos(divX);
    scroll(0,mTop[1]);
    window.onresize=function(){MaximizeMap();};
    if(map!=null){ map.checkResize();}
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) 
{
	do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
	} while (obj = obj.offsetParent);
	return [curleft,curtop];
}
}



function RestoreMap()
{   shortcut.remove("escape");
    var divX = document.getElementById(idMapa);
    divX.style.height = AltoMap;
    divX.style.width = AnchoMap;
     divX.style.position="relative";
    divX.style.top =0;
    divX.style.left = 0;
    if (map != null) { map.checkResize(); }
     window.onresize=null;
     this.document.body.style.overflow="auto";
     var Seccion=document.getElementById(idBuscador);
     if (Seccion.style.display=="none")
     {   Seccion.style.display="";}
     else{Seccion.style.display="none";}
     Alternar(); 
     
  }
     

function TamVentana() {
    var Tamanyo = [0, 0];
    var h = 0; // height
    var w = 0; // width
    if( typeof( window.innerHeight ) == 'number' ) {
//no es IE
    h = window.innerHeight;
    w = window.innerWidth;
} else if( document.body && document.body.clientHeight ) {
//IE 4 o superior
    h = document.body.clientHeight;
    w = document.body.clientWidth;
    }
    Tamanyo[0]=w;
    Tamanyo[1]=h;
  return Tamanyo;
}
function SetZindex(marker, b) {
    return 100000000;
}

/**
 * http://www.openjs.com/scripts/events/keyboard_shortcuts/
 * Version : 2.01.B
 * By Binny V A
 * License : BSD
 */
shortcut = {
	'all_shortcuts':{},//All the shortcuts are stored in this array
	'add': function(shortcut_combination,callback,opt) {
		//Provide a set of default options
		var default_options = {
			'type':'keydown',
			'propagate':false,
			'disable_in_input':false,
			'target':document,
			'keycode':false
		}
		if(!opt) opt = default_options;
		else {
			for(var dfo in default_options) {
				if(typeof opt[dfo] == 'undefined') opt[dfo] = default_options[dfo];
			}
		}

		var ele = opt.target
		if(typeof opt.target == 'string') ele = document.getElementById(opt.target);
		var ths = this;
		shortcut_combination = shortcut_combination.toLowerCase();

		//The function to be called at keypress
		var func = function(e) {
			e = e || window.event;
			
			if(opt['disable_in_input']) { //Don't enable shortcut keys in Input, Textarea fields
				var element;
				if(e.target) element=e.target;
				else if(e.srcElement) element=e.srcElement;
				if(element.nodeType==3) element=element.parentNode;

				if(element.tagName == 'INPUT' || element.tagName == 'TEXTAREA') return;
			}
	
			//Find Which key is pressed
			if (e.keyCode) code = e.keyCode;
			else if (e.which) code = e.which;
			var character = String.fromCharCode(code);
			
			if(code == 188) character=","; //If the user presses , when the type is onkeydown
			if(code == 190) character="."; //If the user presses , when the type is onkeydown

			var keys = shortcut_combination.split("+");
			//Key Pressed - counts the number of valid keypresses - if it is same as the number of keys, the shortcut function is invoked
			var kp = 0;
			
			//Work around for stupid Shift key bug created by using lowercase - as a result the shift+num combination was broken
			var shift_nums = {
				"`":"~",
				"1":"!",
				"2":"@",
				"3":"#",
				"4":"$",
				"5":"%",
				"6":"^",
				"7":"&",
				"8":"*",
				"9":"(",
				"0":")",
				"-":"_",
				"=":"+",
				";":":",
				"'":"\"",
				",":"<",
				".":">",
				"/":"?",
				"\\":"|"
			}
			//Special Keys - and their codes
			var special_keys = {
				'esc':27,
				'escape':27,
				'tab':9,
				'space':32,
				'return':13,
				'enter':13,
				'backspace':8,
	
				'scrolllock':145,
				'scroll_lock':145,
				'scroll':145,
				'capslock':20,
				'caps_lock':20,
				'caps':20,
				'numlock':144,
				'num_lock':144,
				'num':144,
				
				'pause':19,
				'break':19,
				
				'insert':45,
				'home':36,
				'delete':46,
				'end':35,
				
				'pageup':33,
				'page_up':33,
				'pu':33,
	
				'pagedown':34,
				'page_down':34,
				'pd':34,
	
				'left':37,
				'up':38,
				'right':39,
				'down':40,
	
				'f1':112,
				'f2':113,
				'f3':114,
				'f4':115,
				'f5':116,
				'f6':117,
				'f7':118,
				'f8':119,
				'f9':120,
				'f10':121,
				'f11':122,
				'f12':123
			}
	
			var modifiers = { 
				shift: { wanted:false, pressed:false},
				ctrl : { wanted:false, pressed:false},
				alt  : { wanted:false, pressed:false},
				meta : { wanted:false, pressed:false}	//Meta is Mac specific
			};
                        
			if(e.ctrlKey)	modifiers.ctrl.pressed = true;
			if(e.shiftKey)	modifiers.shift.pressed = true;
			if(e.altKey)	modifiers.alt.pressed = true;
			if(e.metaKey)   modifiers.meta.pressed = true;
                        
			for(var i=0; k=keys[i],i<keys.length; i++) {
				//Modifiers
				if(k == 'ctrl' || k == 'control') {
					kp++;
					modifiers.ctrl.wanted = true;

				} else if(k == 'shift') {
					kp++;
					modifiers.shift.wanted = true;

				} else if(k == 'alt') {
					kp++;
					modifiers.alt.wanted = true;
				} else if(k == 'meta') {
					kp++;
					modifiers.meta.wanted = true;
				} else if(k.length > 1) { //If it is a special key
					if(special_keys[k] == code) kp++;
					
				} else if(opt['keycode']) {
					if(opt['keycode'] == code) kp++;

				} else { //The special keys did not match
					if(character == k) kp++;
					else {
						if(shift_nums[character] && e.shiftKey) { //Stupid Shift key bug created by using lowercase
							character = shift_nums[character]; 
							if(character == k) kp++;
						}
					}
				}
			}
			
			if(kp == keys.length && 
						modifiers.ctrl.pressed == modifiers.ctrl.wanted &&
						modifiers.shift.pressed == modifiers.shift.wanted &&
						modifiers.alt.pressed == modifiers.alt.wanted &&
						modifiers.meta.pressed == modifiers.meta.wanted) {
				callback(e);
	
				if(!opt['propagate']) { //Stop the event
					//e.cancelBubble is supported by IE - this will kill the bubbling process.
					e.cancelBubble = true;
					e.returnValue = false;
	
					//e.stopPropagation works in Firefox.
					if (e.stopPropagation) {
						e.stopPropagation();
						e.preventDefault();
					}
					return false;
				}
			}
		}
		this.all_shortcuts[shortcut_combination] = {
			'callback':func, 
			'target':ele, 
			'event': opt['type']
		};
		//Attach the function with the event
		if(ele.addEventListener) ele.addEventListener(opt['type'], func, false);
		else if(ele.attachEvent) ele.attachEvent('on'+opt['type'], func);
		else ele['on'+opt['type']] = func;
	},

	//Remove the shortcut - just specify the shortcut and I will remove the binding
	'remove':function(shortcut_combination) {
		shortcut_combination = shortcut_combination.toLowerCase();
		var binding = this.all_shortcuts[shortcut_combination];
		delete(this.all_shortcuts[shortcut_combination])
		if(!binding) return;
		var type = binding['event'];
		var ele = binding['target'];
		var callback = binding['callback'];

		if(ele.detachEvent) ele.detachEvent('on'+type, callback);
		else if(ele.removeEventListener) ele.removeEventListener(type, callback, false);
		else ele['on'+type] = false;
	}
}

shortcut.add("Ctrl+Return",function(){MaximizeMap()});
//fin shortcut
