/*
*	Leandro Lemos
*	Explorer
*/

function $Get(id) { return document.getElementById(id)}

//converte um obj de cache em um array para pesquisa de indice
var obj2arr = function(arr1){
	var tempArr1 = [];// new 
	for ( i in arr1 ) tempArr1.push(arr1[i]);	
	return tempArr1;
}

var Explorer = function Explorer(){
	//basics
	var _explorer;
	var _container = $Get('explorerResults');
	var _anime = new Animate(); // animação
	var _state;
	var self = this;
	
	//Cookie e Cache
	var _marked = new JSCookieCache("Explorer");//recebe os ids desmarcados para mantê-los no update;
	var _selected = new JSCache();
	
	//comparação de nível de zoom
	var _zoomLevel;
	this.setZoomLevel = function(zoom){_zoomLevel = zoom;}
	this.getZoomLevel = function(zoom){return _zoomLevel;}
	this.setEmptyItens = function(){_newest = [];}//zera a lista de itens novos

	//Guarda os novos // retorna os últimos selecionados, ou caso não encontre, retorna todos os selecionados;
	var _newest = [];
	this.getNewest = function() {
		var arr = [];
		var obj = (_newest.length == 0) ? obj2arr(_selected.getAll()) : _newest ;
		for ( var x=0; x < obj.length; x++ )
			if(typeof(obj[x])!= "function")	arr.push(obj[x].replace("cat",""))
		
		return arr.join(";");
	}
	
	//Guarda os carregados para evitar requests desnecessários
	var _loaded = [];
	this.getLoaded = function(){return _loaded;}
	this.setEmptyLoaded = function(){_loaded = [];}
	this.addLoaded = function(item){_loaded.push(item);}
	
	//Controla o terceiro estado dos inputs	
	var setOpaqueState = function(element){$D.addClass(element, "inputOpaque")}
	var remOpaqueState = function(element){$D.removeClass(element, "inputOpaque")}
	var isOpaqueState  = function(element){return $D.hasClass(element, "inputOpaque")}
	
	//toogleState - alterna entre open - close
	this.toogleState = function(_h,animado ){
		var h=_h||0;
		var _animado = (animado != undefined) ? animado : true;
		(_state == "closed") ? this.close(h,animado) : this.open();
	}
	
	//open - expande o explorer
	this.open = function(){
		var _h = _container.scrollHeight;//altura total
		_anime._vExpand(_container, _h, 20, 10)//aumenta
		_state = "open";
	}
	
	//close - fecha o explorer
	this.close = function(_h, animado){
		_anime._vContract(_container, _h, 20, 10)//diminui
		_state = "closed";
	}
	
	//mark
	this.check = function(t){
		t.checked = true;
		_marked.add(t.id, t.id);
		id = t.id.replace("cat", "");
		markerManager.showType(id);
		this.configureFamily(t, true)
		_newest.push(t.id)
	}
	
	//unmark
	this.uncheck = function(t){
		t.checked = false;
		_marked.remove(t.id);		
		id = t.id.replace("cat","");
		markerManager.hideType(id);
		this.configureFamily(t, false)
	}

  	//showHideList
 	this.showItem = function(id,el){
        var subList = $Get(id);
	    var visible = (subList.style.display=="block");
        visible ? this.hide(subList,el) : this.show(subList,el);
	}
	
	//showHideList
	this.show = function(el,link){
		el.style.display = "block";
		$D.replaceClass(link,"e_close","e_open");
		this.open();
	}
	
  	//showHideList
	this.hide = function(el,link){
		var _h=_explorer.scrollHeight - el.scrollHeight;
		el.style.display = "none";
		$D.replaceClass(link,"e_open","e_close");
		this.close(_h);
	}
	
	//setInvisible
	this.setInvisible = function(el){
		$D.addClass($Get("listItem"+el),"invisible")
	}
	
	//selectChilds(this,{child:'sublist_cat${c.id}',parent:'puntos'}) [categorias] 
	this.selectChilds = function(_this, el, _status){
		var status = (_status != undefined) ? _status : _this.checked;
		
		//se estiver no terceiro estado deve selecionar os filhos
		if(isOpaqueState(_this)) status = !status;
		
		var _parent = _this.id;
		var inputs = document.getElementsByName(_parent);
		var isSub = false;
		_this.checked = status;
		if(inputs.length == 0){
			if(!_this.disabled)
				this.selectThis(_this, {pos:"end"}, status)
			
		}else{
		 	for ( var i=0;i<inputs.length;i++ ) {
		 		var pos = (i == (inputs.length-1))? "end" : i;
		 		(!inputs[i].disabled) ? this.selectThis(inputs[i], {pos:i}, status) : _this.checked = true;
		 	}
		 	if ((el.ref != "fn" && status) || isSub){this.updateView();}
		}
		
		
	}
	
	//selectThis(this,{parent:cat$c.id}) [item final = subcategoria]
	this.selectThis = function(_this, el, _status){
		var status = (_status != undefined) ? _status : _this.checked;
		if (!_this.disabled) (status) ? this.check(_this) : this.uncheck(_this);
		if ((el.pos == "end" && status)) this.updateView(el.parent);
		
		if (el.target=='flickr') {
			mapFeatures['flickr'] = status;
			if (status) {				
				updateMapFeature('flickr', map.getZoom(), map.getSouthWest(), map.getNorthEast());
			} else {
				map.flickHideAll();
			}
		}
		 
		if (_this.id=="cat106") $Get('panButton').checked = status;
		if (_this.id=="cat-100") $Get('flickrButton').checked = status;

	}
	
	//getSiblings - retorna as ocorrências marcadas ou não;
	this.getSiblings = function(t){
		var _true = 0;
		var _false = 0;
		var siblings = document.getElementsByName(t.name);
		for ( var x = 0; x < siblings.length ; x++ )
			(siblings[x].checked) ? _true++ :  _false++;
		
		return {
			_true:_true,
			_false:_false
		}
	}
	
	//configureFamily - alterna opacidade e visibilidade dos irmãos
	this.configureFamily = function(t, _check){
		var isChilds = ((t.name != "puntos") && (t.id != "puntos")); // panoramicas
		
		if (_check) {
			_selected.add(t.id, t.id);
		} else {
			_selected.remove(t.id);
		}
		
		//só deve executar os métodos nos filhos
		if (!isChilds) return;
		
		var sib = this.getSiblings(t);
		var parent = $Get(t.name);
		//zera a opacidade do pai
		
		setOpaqueState(parent);
		
		if (_check) {
			//_selected.add(t.id, t.id)
			parent.checked = true;
			if (sib._false == 0) {
				remOpaqueState(parent);
			}
		} else{
			//_selected.remove(t.id)
			if (sib._true == 0 || (IE && sib._true == 1)) {
				parent.checked = false;
				remOpaqueState(parent);
			}
		}
		 
	}
	
	//init
	this.init = function(){
		var inputs = _container.getElementsByTagName("INPUT");
		for ( var x=0;x<inputs.length;x++ ){
			if( inputs[x].checked ){
				this.configureFamily($Get(inputs[x].id), true)
				var idEl = inputs[x].id;
				_selected.add(idEl, idEl)
			}
		}
	}
	
	//cacheActions - desmarca os subs anteriormente desmarcados
	this.selectElements = function(){
		var elements = _marked.getAll();
		for(elem in elements){
			elem = elements[elem];
			if($Get(elem) != undefined) {$Get(elem).checked = true}//this.check($Get(elem))
			//marca o panoramicas na caixa azul
			if(elem=="cat106")$Get('panButton').checked = true;
			//marca o flickr na caixa azul e baixa as fotos
			if(elem=="cat-100"){
				$Get('flickrButton').checked = true;
				mapFeatures['flickr'] = true;
				updateMapFeature('flickr', map.getZoom(), map.getSouthWest(), map.getNorthEast());
			}
			
		}
	}
	
	//callback (refresh)
	this.update = function(mapMoved) {
		var mapMoved = (mapMoved != undefined) ? mapMoved : false;
		if(!mapMoved){
			_container = $Get('explorerResults');
			_explorer = $Get('listExplorer');
			this.selectElements();//seleciona os elementos pelo cookie.
			this.init();//inicia os status dos elementos pai.
		}
		
		this.getInvisibleCategories();//seta as categorias invisíveis
		this.updateView(mapMoved);//baixa os ipoints
	}
	
	//baixa a arvore de categorias
	this.refresh = function() { // updateExplorer		
		if (requestManager['explorer']) requestManager['explorer'].abort();
		
		var coords = getCurrentCoordinates();
		var action = 'categories.do';	
		var uri = action + '?sll=' + coords.sLL + '&nll=' + coords.nLL;
		
		// faz a requisição
		requestManager['explorer'] = new Request();
		requestManager['explorer'].getAsync(uri, 'explorerResults',null);
		
	}
	
	this.getInvisibleCategories = function(){
		var invisibles = $D.getElementsByClassName("invisible", "li", $D.get("listExplorer"));
		for (var x = 0; x < invisibles.length ; x++){
			$D.removeClass(invisibles[x], "invisible");
		}
		if (requestManager['invisiblecategories']) requestManager['invisiblecategories'].abort();
		
		var coords = getCurrentCoordinates();
		var actionInvisible = 'invisiblecategories.do';	
		var uriInvisible = actionInvisible + '?sll=' + coords.sLL + '&nll=' + coords.nLL;
		
		// faz a requisição
		requestManager['invisiblecategories'] = new Request();
		requestManager['invisiblecategories'].getAsync(uriInvisible, 'javascript', null);
	}
	
	//updateView - updateIpoints + updateCategories (visible)
	this.updateView = function(changed){
		var zoomLevel = map.getZoom();
		var coords = getCurrentCoordinates();
		
		if (changed) {
	    	explorer.setEmptyItens();////zera a lista de itens novos sempre que mudar o zoom
			if ((explorer.getZoomLevel()) && (explorer.getZoomLevel() != zoomLevel)) {
	    		markerManager.clearAll();//destrói ipoints
    		}
	    }
	
		var action = 'ipoints.do';
		var uri = action + '?sll=' + coords.sLL + '&nll=' + coords.nLL + '&zl=' + zoomLevel;					
		
		var newest = self.getNewest();
		var categories = newest.split(";")
		var loaded = self.getLoaded();
		var _catLoadedNum = 0;
		var _doDownload = [];
		requestManager['ipoints'] = [];
		
		for( var _r=0 ; _r<categories.length; _r++ ){
			var _catLoaded = (loaded.indexOf(categories[_r])!=-1);
			if(!_catLoaded){
				_doDownload.push(categories[_r]);
				this.addLoaded(categories[_r]);
			 }
		}
		
		//1 request
		if(_doDownload.length>0 && _doDownload[0]!=""){
			var uriCategorie = uri + '&v=' + _doDownload.join(";");
			_doDownload = null;
			
			if(requestManager['ipoints'][_r])	requestManager['ipoints'][_r].abort();
			requestManager['ipoints'][_r] = new Request();
		    requestManager['ipoints'][_r].getAsync(uriCategorie, 'ipoints', null);
		    explorer.addLoaded(categories[_r]);
		 
			requestManager['ipoints'] = [];
		}
		
		// armazena o zoom atual
	    explorer.setZoomLevel(zoomLevel);
	    explorer.setEmptyItens();
	}
	
	this.moreResults = function(link){
		_moreItens(link, 'explorerResults');
		var _h=_explorer.scrollHeight;
		$D.hasClass($Get('explorerResults'),'compact')?	this.close(_h):this.open();
	}		
	
}


//home
function _explorerHome(){//home
	explorer.refresh();
}
//home
var showExplorer = function(){
	var visible = ($Get("linkFakeExplorer").style.display != "none");
	var arrVis = (visible) ? ["none","block"]:["block","none"];
	var loaded = ($Get('loadingExplorer') == null);
	
	this.showHide = function(){
		loaded = $Get('loadingExplorer') == null;
		try {
			$D.setStyle($Get("linkFakeExplorer"),"display",arrVis[0]);
			$D.setStyle($Get("explorer"),"display",arrVis[1]);
			$D.setStyle($Get("explorerResults"),"display",arrVis[1]);
			$D.setStyle($Get("listExplorer"),"display",arrVis[1]);
			$D.setStyle($Get("list_cat1"),"display",arrVis[0]);
			explorer.showItem('list_cat1',$Get("puntosLink"));
			explorer.toogleState();
		} catch(e){}
		
		/*
		var _function = (loaded) ? 'this.scrollDown()' : 'this.showHide()';
		setTimeout(_function ,300);
		*/
	}
	
	this.scrollDown = function(){
		$Get("leftContent").scrollTop=$Get("leftContent").scrollHeight;
	}
	
	this.showHide();
}
//home
function showList(sublistId,_self){
	if($Get(sublistId)!=null){
		var visible = ($Get(sublistId).style.display != "none");
		if (visible){
			$Get(sublistId).style.display = "none";
			$Get("explorerResults").style.display = "none";
			$D.replaceClass(_self,"e_open","e_close");
			explorer.close(0);
		} else {
			$Get(sublistId).style.display = "block";
			$Get("explorerResults").style.display = "block";
			$D.replaceClass(_self,"e_close","e_open");
			explorer.open();
		}
	} 
}

function changeExplorer(target, el) {
	var flickrId = "cat-100";
	var panId = "cat106";
	var id = null;
	var action;
	var category;
	
	var enable = el.checked;
	
	if (target == "flickr") {
		id = flickrId;
		category = $D.get(flickrId);		
		action = function() {
			mapFeatures["flickr"] = enable;
			if (enable) {
				updateMapFeature("flickr", map.getZoom(), map.getSouthWest(), map.getNorthEast());
			} else {
				map.flickHideAll();
			}				
		}
	} else if (target == "pan") {
		id = panId;
		category = $D.get(panId);
		action = function() {
			explorer.updateView();
		}
	}
	
	if (enable) {
		explorer.check(category);		
	} else {
		explorer.uncheck(category);	
	}
	
	action();	
	return false;	
}