//Script responsible for the search form's location select boxes and the new pseudo-select box
//for "freguesias".

//Comments by CA (at least, most of them)
//Original func by RMC

//Prototype that trims white spaces on strings
String.prototype.trim = function(){return this.replace(/^\s+|\s+$/g,"")}

//String that fills the fake select's value
var mainLabelFullString='';
var mainLabelFullString_bottom='';

//Old prototyping of getElementById - Not sure why this is here.
//Prototyping by RMC
if (/msie/i.test (navigator.userAgent)){
	document.nativeGetElementById = document.getElementById;
	document.getElementById = function(id){
		var elem = document.nativeGetElementById(id);
		if(elem){
			//make sure that it is a valid match on id
			if(elem.id == id){
				return elem;
			}else{
				//otherwise find the correct element
				for(var i=1;i<document.all[id].length;i++){
					if(document.all[id][i].id == id){
						return document.all[id][i];
					}
				}
			}
		}
		return null;
	};
}

//Simplification of the getElementById method
function obj(id){
	return document.getElementById(id);
}

//Not sure why this is here, but I guess it is used to clear countie's names of undesirable characters
function gup(name){
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )	return "";
  else return results[1];
}

//Adds and <option> element to a select box (useful for ajax calls that return district's and contie's names)
function addOption(oListbox, sName, sValue){
	var oOption = document.createElement("option");				
	oOption.appendChild(document.createTextNode(sName));				
	if (arguments.length == 3)oOption.setAttribute("value", sValue);
	oListbox.appendChild(oOption);				
}	

//Check how many options are selected on a multiple selection select box - Guess this was here for the old search. Can't hurt to leave it alone...
function checkMultiple(selectBox){							
	var choices=[];
	for( var i = 0; i < selectBox.options.length; i++ ){
		if( selectBox.options[i].selected == 1){
			choices.push( i );
		}
	}
	return choices.length;
}			 							

function fillLabelFreg(location){
	var labelString='';
	if($('#fregsUL'+location).length>0){
		$('#fregsUL'+location+' input:checkbox:checked').each(
			function(){
				var id=$(this).attr('id');
				var splitter=id.split('_')[1];
				//alert('#label_cb_'+splitter+location);
				if($('#label_cb_'+splitter+'_catalog').length>0)var intermediateValue=$('#label_cb_'+splitter+'_catalog').html();
				else var intermediateValue=$('#label_cb_'+splitter+location).html();
				intermediateValue=intermediateValue.trim();
				//alert('Label: '+'#label_cb_'+splitter+location+' Valor: '+$('#label_cb_'+splitter+location).html());
				labelString=labelString+intermediateValue+',';
			}
		)
		if(labelString=='') labelString='Por Freguesias';
		if(labelString.charAt(labelString.length-1)==',')labelString=labelString.substring(0,labelString.length-1)
		$('#selectedOpts'+location).html(labelString);
		if(location=='' || location=='_catalog')mainLabelFullString=labelString;
		else if(location=='_bottom')mainLabelFullString_bottom=labelString;
	}
}

//On load executions
$(function(){
	//Vars that control if the user is able or unable to select and county or a "freguesia"
	var select_county=false;
	var select_freg=false;
	if($('input[name=zones]').length==0 || $('input[name=zones]').val()==''){
		fillLabelFreg('');
		fillLabelFreg('_bottom');
	}else{
		$('#selectedOpts').html('Por Freguesias');
		$('#selectedOpts_bottom').html('Por Freguesias');
	}
	mainLabelFullString.trim();
	mainLabelFullString_bottom.trim();
	$('#selectedOptsOuter_zones, #selectedOptsOuter_zones_bottom').addClass('bggray');
	$('#selectedOptsOuter_zones, #selectedOptsOuter_zones_bottom').addClass('disabled');
	//$('#clickOpen').click(function(){if($('#count').val()!='' && $('#count').val()!='0' && $('#realFreg').val()=='')$('#count').trigger('change')})
	//District select change triggers thw following:
	$('#dist, #dist_bottom').change(function(){
		if($(this).attr('id')=='dist')mainLabelFullString='';
		else if($(this).attr(id)=='dist_bottom')mainLabelFullString_bottom='';
		//Determine change location (top or bottom search form)
		var location='';
		if(this.id.split('_')[1]=='bottom'){
            location='_bottom';
		}
		changeZonesUsability($(this).attr('id'),location);
		//Return "Freguesias" pseudo-select to its default value
		//Clear everything related to it
		
		$('#selectedOptsOuter'+location).removeClass('bgwhite');
		$('#selectedOptsOuter'+location).addClass('bggray');
		$('#realFreg'+location).val('');
		$('#clickOpen'+location).attr('href','javascript:alert(\'Primeiro deve seleccionar um distrito e um concelho.\')');
		
		if($('#fregsList'+location).css('display')=='block'){
			$('#fregsList'+location).hide();
			toggle=true;
		}


		$('#selectedOptsOuter_zones' + location ).removeClass('bgwhite');							
		$('#selectedOptsOuter_zones' + location ).addClass('disabled');
		$('#selectedOptsOuter_zones' + location ).addClass('bggray');

		
		//alert($(this).val());
		//If its value is returned to the default, must clear the countie's select
		if($(this).val()==0){
			county_cb=document.getElementById('count'+location);
			for (i = county_cb.length - 1; i>=0; i--){
				county_cb.remove(i);
			}
			if(!county_cb.multiple)	addOption(county_cb,"Concelho",0);
			if(document.getElementById('partners'))	document.getElementById('count'+location).disabled=true;
			//alert("nao pode escolher concelhos");
			document.getElementById('count'+location).disabled=true;
			document.getElementById('count'+location).style.background="transparent";
		}
		//If value is Any other than the default, must get respective counties via-AJAX
		else{
			$.ajax({
				type:'GET',
				url:'/gen.pl?p=county',
				data:'district='+escape($(this).val()),
				success:function(data){
					//alert(data);
					//Remove previous options
					county_cb=document.getElementById('count'+location);
					for (i = county_cb.length - 1; i>=0; i--){
						county_cb.remove(i);
					}
					//If not multiple selection select, add the default option
					if(!county_cb.multiple)	addOption(county_cb,"Concelho",0);	
					/*if(freg_cb==document.getElementById('freg'+location)){
						for (i = freg_cb.length - 1; i>=0; i--){
							freg_cb.remove(i);
						}
						if(!freg_cb.multiple)addOption(freg_cb,"Freguesia",0);
					}*/	
				

					//Split the comma separated data	
					var counties=data.split(",");									
					
					//Add an option for each county
					for(i=0;i<counties.length;i++){
						var label=counties[i].split(';')[0];
						if(counties[i].split(';').length>1)var value=counties[i].split(';')[1];
						else var value=label;
						addOption(county_cb,counties[i],label,value);
					}
					
					//alert("ja pode escolher concelho");
					obj('count'+location).removeAttribute("disabled");
					obj('count'+location).style.background="#FFFFFF";

					if(!select_county){
						var count_index=unescape(gup('count_index'));	
						var nr_count_index=count_index.split(",");
						//Old check used for multiple counties or single county selection.
						//Left it here because the old advanced search is still used to define alerts
						
						//One index selected only
						if(nr_count_index.length==1 && !isNaN(parseInt(count_index))){
							if((count_index>=0 && county_cb.multiple) || (count_index>0 && !county_cb.multiple)){
								obj('count'+location).selectedIndex=count_index;
								$('#count'+location).trigger('change');
							}
						}
						//Multiple index selection
						else if(nr_count_index.length>1){
							for(var i = 0; i < obj('count'+location).options.length; i++){
								var selected=false;
								for(var j=0;j<nr_count_index.length;j++){
									if(nr_count_index[j]==i)
										selected=true;
								}
								
								if(selected)obj('count'+location).options[i].selected=true;
							}
						}
						//Now able to select a county
						select_county=true;
					}
								
		  			// Update zones select
					if( ( $('#dist' + location).find('option:selected').val() =="Lisboa") && ( $('#count' + location).find('option:selected').val() == "Lisboa" )){
						$('#selectedOptsOuter_zones' + location ).addClass('bgwhite');					
						$('#selectedOptsOuter_zones' + location ).removeClass('disabled');
						$('#selectedOptsOuter_zones' + location ).removeClass('bggray');
					} else {
						$('#selectedOptsOuter_zones' + location ).removeClass('bgwhite');							
						$('#selectedOptsOuter_zones' + location ).addClass('disabled');
						$('#selectedOptsOuter_zones' + location ).addClass('bggray');
					}
		
					//edit User
					if(obj('s_count'+location)){
						if($('#s_count'+location).value!=""){
							var s_index;
							for(i=0; i<obj('count'+location).length - 1; i++){
								if(obj('count'+location).options[i].value==obj('s_count'+location).value){
									s_index=i;
									break;
								}
							}
							obj('count'+location).selectedIndex=s_index;
							$('#count'+location).trigger('change');	
						}
					}
				}
			});
		}		
		
							
	});
    
	//Left these here, not sure why they were used. I'm sure RMC had his reasons...
    if(obj('ikind')){
		$('#ikind').trigger('change');
	}
	if(obj('ikind_bottom')){
		$('#ikind_bottom').trigger('change');
	}
    
    //Counties' select was changed
    $('#count, #count_bottom').change(function(){
        //Determine if the select used was on top or at the bottom
		var location='';
        if(this.id.split('_')[1]=='bottom')location='_bottom';
		changeZonesUsability($(this).attr('id'),location);
		if($(this).attr('id')=='count')mainLabelFullString='';
		else if($(this).attr(id)=='count_bottom')mainLabelFullString_bottom='';
        //Clear "freguesias"'s pseudo-select
		clearSelectedFregs(location);
		
		//Switch that detemrines what to do in which case (default value selected or any other was selected)
        switch ($(this).val()){
			//Assumes default value for the "freguesias" pseudo-select
			case '0':
				$('#selectedOptsOuter'+location).removeClass('bgwhite');
				$('#selectedOptsOuter'+location).addClass('bggray');
                $('#realFreg'+location).val('');
                $('#clickOpen'+location).attr('href','javascript:alert(\'Primeiro deve seleccionar um distrito e um concelho.\')');
                
                if($('#fregsList'+location).css('display')=='block'){
                    $('#fregsList'+location).hide();
                    toggle=true;
                }
                break;
			//Anything else triggers an AJAX call
            default:
                //Openning the "freguesias"'s container
				$('#clickOpen'+location).attr('href','javascript:showHideFregs(\''+location+'\')');
                $('#realFreg'+location).val('');
                $('#fregsUL'+location).html('<div id="fregsULLoading'+location+'" style="margin:80px auto auto auto;text-align:center"><img src="/images/reform/icons/ic_loading.gif" alt="A carregar..."></div>');
			

                $.ajax({
                    type:'GET',
                    url:'/gen.pl?p=freg',
                    data:'county='+escape($(this).val()),
					//Shows a little loading icon
                    beforeSend: function(){$('#selectedOpts'+location).html('<img id="loadingSearch'+location+'" src="/images/reform/icons/ic_loading.gif" style="height:16px;" alt="A carregar...">');},
                    success:function(data){
						//Removes loading icon and a bunch of other stuff in the container if it's there
                        $('#fregsULLoading'+location).remove();
                        $('#loadingSearch'+location).remove();
                        $('#selectedOpts'+location).html('Por Freguesias');
						
			  			// Update zones select
						if( ( $('#dist' + location).find('option:selected').val() =="Lisboa") && ( $('#count' + location).find('option:selected').val() == "Lisboa" )){
							$('#selectedOptsOuter_zones' + location ).addClass('bgwhite');
							$('#selectedOptsOuter_zones' + location ).removeClass('disabled');
							$('#selectedOptsOuter_zones' + location ).removeClass('bggray');

						} else {
							$('#selectedOptsOuter_zones' + location ).removeClass('bgwhite');
							$('#selectedOptsOuter_zones' + location ).addClass('disabled');
							$('#selectedOptsOuter_zones' + location ).addClass('bggray');
						}
				
						
						$('#selectedOptsOuter'+location).addClass('bgwhite');
						$('#selectedOptsOuter'+location).removeClass('bggray');
                        freg_cb=$('#freg'+location);
                        $('#fregsUL'+location).html('');
                        //Start filling the options as list items with checkboxes and a label
						var frgs=data.split(',');
                        $('#fregsUL'+location).append('<li class="bold blue block" style="font-size:9px;margin:2px 2px 5px 2px">Seleccione 1 ou mais+</li>');
                        var o=0;
						if(window['catalogLocation'] != undefined && location=='')locationmod='_catalog';
						else locationmod=location;
                        for(var k in frgs){
							var label=frgs[k].split(';')[0];
							if(frgs[k].split(';').length>1)var value=frgs[k].split(';')[1];
							else var value=label;
							
							if(window['catalogLocation']!= undefined)value=label;
                            $('#fregsUL'+location).append('<li style="display:block;margin:3px;overflow:hidden;width:165px"><input id="cb_'+o+locationmod+'" class="fleft mright5" type="checkbox" onclick="addRemoveFreg(\'cb_'+o+locationmod+'\')" name="'+label+'" value="'+value+'">	<label id="label_cb_'+o+locationmod+'" for="cb_'+o+locationmod+'" class="fleft hidden block" style="width:140px">'+label+'</label></li>');
                            o++;
                        }
                    }   
                });
                break;
        }
    });
    

	//If no selected fregs, assume default value for pseudo-select box
    if($('#selectedOpts').html().trim()==''){
		$('#selectedOpts, #selectedOpts_bottom').html('Por Freguesias');
	}
});

//New area dedicated to the new pseudo-select dedicated to "freguesias"

var toggle=false;

//Show and hide the "fregeusias"' list
//The list is comprised of a div with absolute positioning relative to the document's body.
//Inside there's an unordered list with checboxes and respective labels which represent the various "fregeusias"
function showHideFregs(location){
  jQuery('#fregsList'+location).css('top',jQuery("#selectedOptsOuter"+location).offset().top+jQuery("#selectedOpts"+location).height()+3+'px');
  jQuery('#fregsList'+location).css('left',jQuery("#selectedOptsOuter"+location).offset().left+'px');
  jQuery('#fregsList'+location).slideToggle("slow");
  jQuery('#zonesList'+location).slideUp("slow");
}

//Clears selected check boxes and returns the pseudo-select to its default value
function clearSelectedFregs(location){
    $('#fregsUL'+location+' input:checkbox:checked').removeAttr('checked');
    $('#selectedOpts'+location).html('Por Freguesias');
    $('#realFreg'+location).val('');
	switch2Both(location);
}

//Adds and removes selected zones from the hidden field that is sent with the form to perform a search
function addRemoveFreg(id){
	//Determine the click's origin (top or bottom search form)
	
	var location='';
    if(id.split('_')[2]=='bottom') location='_bottom';
	if(id.split('_')[2]=='catalog') location='_catalog';
	
	var s='';
	if(location=='' || location=='_catalog')s=mainLabelFullString;
	else if(location=='_bottom')s=mainLabelFullString_bottom;
	
	
    var value=$('#'+id).val();
	var label=$('#label_cb_'+id.split('_')[1]+location).html();
	label=label.trim();
	var prepLabel=s;
    //Get the real value from the hidden field
	if(location!='_catalog')var myFregs=$('#realFreg'+location).val();
	else var myFregs=$('#realFreg').val();
    
	var selectedFregs=myFregs.split(',');
    var found=false;
	//Locate the selected value on the hidden field's comma separated String
    for(var k in selectedFregs){
        if(value==selectedFregs[k]){
			selectedFregs.splice(k,1);
            found=true;
        }
    }
	
	//The value was found on the String, so remove it
    if(found==true){
		//Rebuilding the comma separated String for the label and the hidden field's value
        var comeTogether=selectedFregs.join(',');
		if(s.indexOf(label+',')>=0){
			s=s.replace(label+',','')
		}
		
		if(s.indexOf(label)>=0){
			s=s.replace(label,'');
		}
		
		
		//Formating to become a label
        if(s=='')s='Por Freguesias';
    //Value was not found. Add it!
	}else{
		if(s.trim()=="Por Freguesias")s="";
		
		if(s!="" && s.charAt(s.length-1)!=",")s=s+",";
		
		//Add  it or become it
        if($('#realFreg'+location).val()!='' && location!='_catalog') var comeTogether=$('#realFreg'+location).val()+','+value;
		else if($('#realFreg').val()!='' && location=='_catalog') var comeTogether=$('#realFreg').val()+','+value;
        else var comeTogether=value;
		
		if(s!='')s=s+label+',';
		else s=s+label;
    }
	
	if(comeTogether.charAt(0)==',')comeTogether=comeTogether.substr(1,comeTogether.length);
	if(comeTogether.charAt(comeTogether.length-1)==',')comeTogether=comeTogether.substr(0,comeTogether.length-1);
	if(location!='_catalog')$('#realFreg'+location).val(comeTogether);
	else $('#realFreg').val(comeTogether);
	
	if(s.charAt(0)==',')s=s.substr(1,s.length);
	if(s.charAt(s.length-1)==',')s=s.substr(0,s.length-1);
	
	if(s=="")s='Por Freguesias';
	
	if(location!='_catalog')$('#selectedOpts'+location).html(s);
	else $('#selectedOpts').html(s);
	
	if(location=='' || location=='_catalog')mainLabelFullString=s;
	else if(location=='_bottom')mainLabelFullString_bottom=s;
	
	if($('#realFregs'+location).val()==''){
        switch2Both(location,'fregs');
    }else{
		switch2Fregs(location,true,true);
	}
}

//The selected value on the typology field determines the use of maximum and minimum typology
//This si done because of the parameter's specifity (only for flats and houses)
function typologyStatus(elem,location){				
	var elemValue=elem.options[elem.selectedIndex].value;
	if(obj('refopt'+location) && obj('refopt'+location).checked==false){
        if(elemValue=='Apartamento' || elemValue=='Moradia'){		
            if(obj('typmin'+location))obj('typmin'+location).disabled=false;
            if(obj('typmax'+location))obj('typmax'+location).disabled=false;	
            if(obj('typology'+location))obj('typology'+location).disabled=false;								
        }
        else{
            if(obj('typmin'+location)){
                obj('typmin'+location).selectedIndex=0;
                obj('typmin'+location).disabled=true;
            }
            
            if(obj('typmax'+location)){				
                obj('typmax'+location).selectedIndex=0;
                obj('typmax'+location).disabled=true;
            }		
            
            if(obj('typology'+location)){				
                obj('typology'+location).selectedIndex=0;
                obj('typology'+location).disabled=true;
            }																		
        }
	}
}

