//Script dedicated to the pseudo-select box located in the main search form.
//It's pretty much the same as the script that displays the "freguesias" pseudo-select box

//String trimming prototype - Removes white spaces
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); };

//Create an Hidden field in a specific form
function createHiddenNew(name,value,formid,extraArg){
  if(typeof(extraArg)!='undefined'){
    var suplement='';
    if(extraArg.charAt(0)!='_' && extraArg!='')suplement='_';
    var string='<input id="id'+name+suplement+extraArg+'" name="'+name+'" type="hidden" value="'+value+'">';
    $('#'+formid+suplement+extraArg).append(string);
  }else{
    var string='<input id="id'+name+'" name="'+name+'" type="hidden" value="'+value+'">';
    $('#'+formid).append(string);
  } 
}

//Show and hide the zones' 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 zones
function showHideZones(location){
    //If dist and count have the desired values, go get the XML with all the info
    if(($('#dist').val()=='Lisboa' && $('#count').val()=='Lisboa')){
        if(zonesXML==null){
            getXMLZones($('#dist').val()+'_'+$('#count').val());
        }
    }
    //Position the list and display it
    jQuery('#zonesList'+location).css('top',jQuery("#selectedOptsOuter_zones"+location).offset().top+jQuery("#selectedOpts_zones"+location).height()+3+'px');
    jQuery('#zonesList'+location).css('left',jQuery("#selectedOptsOuter_zones"+location).offset().left+'px');
    jQuery('#zonesList'+location).slideToggle("slow");
    jQuery('#fregsList'+location).slideUp("slow");
}

//Clears selected check boxes and returns the pseudo-select to its default value
function clearSelectedZones(location){
    $('#zonesUL'+location+' input:checkbox:checked').removeAttr('checked');
    $('#selectedOpts_zones'+location).html('Por Zonas');
    $('input[name=location]').val('');
    $('#idzones'+location).val('');
    $('#fregsUL'+location+' input:checkbox:checked').removeAttr('checked');
    $('#realFreg'+location).val('');
    $('#selectedOpts'+location).html('Por Freguesias');
    switch2Both(location,true);
}

//Recursive function that clears the edges of a string of undesirable characters
function trimEdges(string,character){
    if(string.charAt(0)==character){
       return trimEdges(string.slice(1,string.length),character);
    }else if(string.charAt(string.length-1)==character){
       return trimEdges(string.slice(0,string.length-1),character);
    }else return string
}

//Function which finds and returns a zone by its ID
function zoneFinder(id){
    //alert(id);
    for(k in parsedZones){
        if(parsedZones[k]['id']==id)return parsedZones[k]
    }
}

//Function that will change the pseudo-select's label accordingly
//as the options are checked or unchecked
function changeLabel(location){
    //If the zones field isn't empty
    if($('#idzones'+location).val()!=''){
        //Gather the zones' IDs
        var zonesArray=$('#idzones'+location).val().split(',');
        //String that will serve as the builder of this label
        var returnString='';
        var zoneArray;
        //Gather each one of the zones' names
        for(j in zonesArray){
            //If the label already has more than 15 chars, there's no point in going on: the cycle breaks
            if(returnString.length<15){
                zoneArray=zoneFinder(zonesArray[j]);
                var nameIteration=zoneArray['name'];
                //Replace ; by commas
                nameIteration=nameIteration.replace(/;/gi,',');
                nameIteration=nameIteration.replace(/,,/gi,',');
                //Add thet zones' name and a ";" as a separator
                nameIteration=trimEdges(nameIteration,',');
                returnString=returnString+nameIteration+',';
            //If the label already has more than 15 chars, there's no point in going on: the cycle breaks
            }else break;
        }
        
        //In case the return string comes empty
        if(returnString.trim()=='')$('#selectedOpts_zones'+location).html('Por Zonas');
        //Return string isn't empty
        else{
            if(returnString.length>15)$('#selectedOpts_zones'+location).html(returnString.slice(0,15)+'...');
            else $('#selectedOpts_zones'+location).html(trimEdges(returnString,','));
        }
    //If the zones field is empty
    }else $('#selectedOpts_zones'+location).html('Por Zonas');
}

//Function used to remove a zone and all info associated to it
function removeZone(toDelete,location){
    //Find the zone within the parsed XML by its ID
    var zoneToRemove=zoneFinder(toDelete);
    
    //Removing a set of localities
    //var actualLocalities=$('#idlocality'+location).val();
    //var localitiesToRemove=zoneToRemove['localities'];
    
    //Find where to cut
    //var startIndexLocalities=actualLocalities.indexOf(localitiesToRemove);
    //var endIndexLocalities=startIndexLocalities+localitiesToRemove.length;
    
    //Cut
    //var slicedLocalities=actualLocalities.slice(0,startIndexLocalities)+actualLocalities.slice(endIndexLocalities+1,actualLocalities.length);
    
    //Trim it
    //slicedLocalities=trimEdges(slicedLocalities,',');
    //Final result    
    //$('#idlocality'+location).val(slicedLocalities);
    
    //Removing a set of "freguesias"
    /*if(zoneToRemove['fregs']!=''){
      var actualFregs=$('#realFreg'+location).val();
      //The XML's separator is ; so, I have to normalize it to commas for this field, otherwise the func will freak out... I guess...
      var fregsNormalized=zoneToRemove['fregs'].replace(/;/gi,',');
      //Find where to cut
      var startIndexFregs=actualFregs.indexOf(fregsNormalized);
      var endIndexFregs=startIndexFregs+fregsNormalized.length;
      //Cut
      var slicedFregs=actualFregs.slice(0,startIndexFregs)+actualFregs.slice(endIndexFregs+1,actualFregs.length);
      //Trim it
      slicedFregs=trimEdges(slicedFregs,',');
      //Final result    
      $('#realFreg'+location).val(slicedFregs);
    }*/
}

//Function used to add a zone and all info associated to it
function addZone(toAdd,location){    
    //Find the zone within the parsed XML by its ID
    var zoneToAdd=zoneFinder(toAdd);
    
    //The XML's separator is ; so, I have to normalize it to commas for this field, otherwise the func will freak out... I guess...
    //var fregsToadd=zoneToAdd['fregs'].replace(/;/gi,',');
    //alert(fregsToadd);
    //$('#realFreg'+location).val(trimEdges(trimEdges($('#realFreg'+location).val(),',')+','+trimEdges(fregsToadd,','),','));
    
    //If the field exists or doesn't exist, act accordingly
    /*if($('#idlocality'+location).exists()){
       $('#idlocality'+location).val(trimEdges(trimEdges($('#idlocality').val(),',')+','+trimEdges(zoneToAdd['localities'],','),','));
    }else{
       createHiddenNew('locality'+location,trimEdges(zoneToAdd['localities'],','),'search_form'+location);
    }*/
}

//Adds and removes selected zones from the hidden field that is sent with the form to perform a search
function addRemoveZones(id){    
    //Figure out the location of the click (top or bottom form)
    if(id.split('_').length>2)if(id.split('_')[3]=='bottom') var location='_bottom';
    else var location='';
    
    //Getting the id of the clicked zone based on the field's value
    var focusedZone=$('#'+id).val();
    
    //If the field with the selectedzones IDs is present, then the var inherits its value. Otherwise... It doesn't...
    if($('#idzones'+location).exists())var selectedZones=$('#idzones'+location).val();
    else var selectedZones='';
    
    //If the focused zone is found withing the selected zones string
    var zoneToDelete;
    var mySelectedSplit=selectedZones.split(',');
    
    if(typeof(selectedZones.indexOf(focusedZone))=='number'){
      for(var z in mySelectedSplit){
        if(mySelectedSplit[z]==focusedZone){
          zoneToDelete=mySelectedSplit[z];
          mySelectedSplit.splice(z,1);
        }
      } 
    }
    
    //If the value has been found, slice it off
    if(zoneToDelete!=null){
        removeZone(zoneToDelete,location);
        selectedZones=mySelectedSplit.join(',');
    //If the value wasn't among the selected ones, put it on the string
    }else{
        addZone(focusedZone,location);
        selectedZones=mySelectedSplit.join(',').concat(','+focusedZone);
    }
    
    //alert('After slice or concat: '+selectedZones);
    //Trim an eventual comma in the first position of the string
    if(selectedZones.charAt(0)==',')selectedZones=selectedZones.substr(1,selectedZones.length);
    if(selectedZones.charAt(selectedZones.length-1)==',')selectedZones=selectedZones.substr(0,selectedZones.length-1);
    //The field gets its value or gets created
    if($('#idzones'+location).exists())$('#idzones'+location).val(selectedZones);
    else{ createHiddenNew('zones',selectedZones,'search_form',location)}
    changeLabel(location);
    if($('#idzones'+location).val()==''){
        switch2Both(location,'zones');
    }else switch2Zones(location,true,true);
}

//Keep the zones pseudo-select box closed
function keepClosed(location){
    alert("Para pesquisar por zonas, por favor seleccione Lisboa como concelho e distrito")
}

function lineBreaker(string){
    var myCounter=0;
    for(i=0;i<string.length;i++){
        myCounter++;
        if((string.charAt(i)==' ' || string.charAt(i)==',') && myCounter>=15){
            string=string.slice(0,i)+'<br />'+string.slice(i+1,string.length);
            myCounter=0;
        }
    }
    return string;
}

//Object that will receive the zone's raw info (from the xml file)
var zonesXML;

//Function that will get the xml file via AJAX
function getXMLZones(target,myZonesID){
  $.ajax({
    type: "GET",
    url: "/media/reform/maps/xml/"+target+".xml",
    dataType: "xml",
    success: function(data){
        switch(data){
            case '':
                alert('Occorreu um erro de comunicação com o servidor. Tente novamente mais tarde, por favor. Pedimos desculpa pelo inconveniente.');
                break;
            case null:
                alert('Occorreu um erro de comunicação com o servidor. Tente novamente mais tarde, por favor. Pedimos desculpa pelo inconveniente.');
                break;
            default:
                zonesXML=data;
                parseZonesXML(data,myZonesID);
                break;
        }
    }
  });
}

//Array that will receive all the info from the zones parsed from the XML file
var parsedZones=new Array;

function parseZonesXML(xmlDoc,myZonesID){
    $(xmlDoc).find('area').each(
        function(){
            parsedZones.push({'id':$(this).attr('id'),'name':$(this).attr('name'),'fregs':$(this).attr('fregs'),'localities':$(this).attr('localities')});
        }
    )
    parsedZones.sort();
    for(i in parsedZones){
        var tempString=parsedZones[i]['name'].replace(/;/gi,',');
        var tempString=parsedZones[i]['name'].replace(/,,/gi,',');
        var currentID=parsedZones[i]['id'];
        var nameString=lineBreaker(tempString);
        $('#zonesUL').append('<li style="display:block;margin:3px;overflow:hidden;width:165px"><input id="cb_zones_'+currentID+'" class="fleft mright5" type="checkbox" value="'+currentID+'" onclick="addRemoveZones(\'cb_zones_'+currentID+'\')"><label for="cb_zones_'+currentID+'" class="fleft hidden block" style="width:140px">'+nameString+'</label></li>');
        $('#zonesUL_bottom').append('<li style="display:block;margin:3px;overflow:hidden;width:165px"><input id="cb_zones_'+currentID+'_bottom" class="fleft mright5" type="checkbox" value="'+currentID+'" onclick="addRemoveZones(\'cb_zones_'+currentID+'_bottom\')"><label for="cb_zones_'+currentID+'_bottom" class="fleft hidden block" style="width:140px">'+nameString+'</label></li>');
    }
    if(myZonesID){
        var myTempZones='';
        for(i in myZonesID){
            for(j in parsedZones){
                if(myZonesID[i]==parsedZones[j]['id']){
                    $('#cb_zones_'+parsedZones[j]['id']+', #cb_zones_'+parsedZones[j]['id']+'_bottom').attr('checked','checked');
                    myTempZones=myTempZones+','+parsedZones[j]['name'].replace(/;/gi,',');
                    myTempZones=myTempZones+','+parsedZones[j]['name'].replace(/,,/gi,',');
                    myTempZones+=',';
                }
            }
        }
        if(myTempZones.charAt(0)==','){
            myTempZones=myTempZones.substr(1,myTempZones.length)
        }
        if(myTempZones.length>15){
            myTempZones=myTempZones.substr(0,15);
            myTempZones=myTempZones+'...';
        }
        if(myTempZones=='')$('#selectedOpts_zones, #selectedOpts_zones_bottom').html('Por Zonas');
        else $('#selectedOpts_zones, #selectedOpts_zones_bottom').html(trimEdges(myTempZones,','));
    }
}

//Force the fill of additional zones Boxes
function forceFill(location){
    if(zonesXML==null && $('#dist'+location).val()=='Lisboa' && $('#count'+location).val()=='Lisboa'){
        getXMLZones($('#dist'+location).val()+'_'+$('#count'+location).val());
    }
    if(parsedZones==''){
        $(zonesXML).find('area').each(
            function(){
                parsedZones.push({'id':$(this).attr('id'),'name':$(this).attr('name'),'fregs':$(this).attr('fregs'),'localities':$(this).attr('localities')});
            }
        )
    }
    for(i in parsedZones){
        $('#zonesUL'+location).append('<li style="display:block;margin:3px;overflow:hidden;width:165px"><input id="cb_zones_'+parsedZones[i]['id']+location+'" class="fleft mright5" type="checkbox" value="'+parsedZones[i]['id']+'" onclick="addRemoveZones(\'cb_zones_'+parsedZones[i]['id']+location+'\')"><label for="cb_zones_'+parsedZones[i]['id']+location+'" class="fleft hidden block" style="width:140px">'+parsedZones[i]['name'].replace(/;/gi,',')+'</label></li>');
    }
}

//Function which switches the operation mode to Fregs
function switch2Fregs(location,noshow,noclearfregs){
    if(!noclearfregs)clearSelectedFregs(location);
    //Clear everything related to zones
    $('#idzones').val('');
    $('#idlocality').val('');
    $('#zonesUL'+location+' input:checkbox:checked').removeAttr('checked');
    $('#selectedOpts_zones'+location).html('Por Zonas');
    //News actions for pseudo-select buttons
    $('#clickOpen'+location).attr('href','javascript:showHideFregs(\''+location+'\')');
    $('#clickOpen_zones'+location).attr('href',"javascript:if(!$('#selectedOptsOuter_zones" + location +"').hasClass('disabled')) { if(confirm('Para aceder a esta opção a sua selecção por freguesias irá ser removida. Deseja continuar?')) switch2Zones('"+location+"') }");
    if(!noshow)if($('#fregsList'+location).css('display')=='none')showHideFregs(location);
    if($('#zonesList'+location).css('display')=='block')$('#zonesList'+location).slideUp('slow');
    allowZoneOperations=false;
}

//Function which switches the operation mode to Zones
function switch2Zones(location,noshow,noclearfregs){
    if(($('#dist'+location).val()=='Lisboa' && $('#count'+location).val()=='Lisboa')){
        if(!noclearfregs)clearSelectedFregs(location);
        $('#clickOpen'+location).attr('href',"javascript:if(!$('#selectedOptsOuter_zones" + location +"').hasClass('disabled')) { if(confirm('Para aceder a esta opção a sua selecção por zonas irá ser removida. Deseja continuar?')) switch2Fregs('"+location+"') }");
        $('#clickOpen_zones'+location).attr('href','javascript:showHideZones(\''+location+'\')');
        if($('#fregsList'+location).css('display')=='block')showHideFregs(location);
        if(!noshow)if($('#zonesList'+location).css('display')=='none')showHideZones(location);
        if(zonesXML==null){
            getXMLZones($('#dist').val()+'_'+$('#count').val());
        }
    }else{
        keepClosed(location)
    }
    allowZoneOperations=true;
}

function switch2Both(location,activator){
    if(($('#dist'+location).val()=='Lisboa' && $('#count'+location).val()=='Lisboa')){
        //Clear Fregs
        if(activator=='zones'){
            $('#fregsUL'+location+' input:checkbox:checked').removeAttr('checked');
            $('#selectedOpts'+location).html('Por Freguesias');
            $('#realFreg'+location).val('');
        }
        ////Clear zones
        if(activator=='fregs'){
            $('#zonesUL'+location+' input:checkbox:checked').removeAttr('checked');
            $('#selectedOpts_zones'+location).html('Por Zonas');
            $('input[name=location]').val('');
            $('#idzones'+location).val('');
        }
        if(activator=='dist'){
            $('#fregsUL'+location+' input:checkbox:checked').removeAttr('checked');
            $('#selectedOpts'+location).html('Por Freguesias');
            $('#realFreg'+location).val('');
            $('#zonesUL'+location+' input:checkbox:checked').removeAttr('checked');
            $('#selectedOpts_zones'+location).html('Por Zonas');
            $('input[name=location]').val('');
            $('#idzones'+location).val('');
        }
        //Change opening button
        $('#clickOpen'+location).attr('href','javascript:showHideFregs(\''+location+'\')');
        $('#clickOpen_zones'+location).attr('href','javascript:showHideZones(\''+location+'\')');
    }else{
        $('#clickOpen'+location).attr('href','javascript:showHideFregs(\''+location+'\')');
        $('#clickOpen_zones'+location).attr('href',"javascript:if(!$('#selectedOptsOuter_zones" + location +"').hasClass('disabled')) { if(confirm('Para aceder a esta opção a sua selecção por freguesias irá ser removida. Deseja continuar?'))switch2Zones('"+location+"') }");
        if($('#zonesList'+location).css('display')=='block')$('#zonesList'+location).slideUp('slow');
        allowZoneOperations=false;
    } 
}

//Function called on change of the countie's select
function changeZonesUsability(id,location){
    if($('#'+id).val()!='Lisboa'){
        switch2Fregs(location,true);
        //Give the button the action of keeping it shut
        $('#clickOpen_zones'+location).attr('href',"javascript:keepClosed('"+location+"')");
    }else{
        switch2Both(location,'dist');
        var licounter=0;
        if(location!=''){
            $('#zonesUL'+location+' li').each(function(){licounter++})
            if(licounter<=1){
                forceFill(location)
            }
            licounter=0;
        }
    }
}

//What to do onLoad
$(function(){
    //First time load - Without Zones the field at all
    //If the combo is just right (Lisboa - Lisboa)
    if(($('#dist').val()=='Lisboa' && $('#count').val()=='Lisboa')){
        //In case the zones field doesn't exist
        if(!$('input[name=zones]').exists()){
            var myDefault='Por Zonas';
            $('#selectedOpts_zones, #selectedOpts_zones_bottom').html(myDefault);
            createHiddenNew('zones','','search_form');
            createHiddenNew('zones','','search_form_bottom','bottom');
            switch2Fregs('',true,true);
            switch2Fregs('_bottom',true,true);
        //First time load - Without Zones the field on search_form
        //In case the zones field does exist
        }else{
            //If the zones field is empty
            if($('input[name=zones]').val().trim()==''){
                switch2Fregs('',true,true);
                switch2Fregs('_bottom',true,true);
            //If the field has something
            }else{
                var myTempZones='';
                createHiddenNew('zones',trimEdges($('input[name=zones]').val(),','),'search_form');
                createHiddenNew('zones',trimEdges($('input[name=zones]').val(),','),'search_form','bottom');
                //In case, the rules apply, go get the XML
                var myZonesID=$('#idzones').val().split(',');
                if(zonesXML==null && $('#dist').val()=='Lisboa' && $('#count').val()=='Lisboa'){
                    getXMLZones($('#dist').val()+'_'+$('#count').val(),myZonesID);
                }
            }
        }
        
        //If the page has a locality field creates a new one within the searchform
        /*if($('input[name=locality]').exists()){
            createHiddenNew('locality',trimEdges($('input[name=locality]').val(),','),'search_form');
            createHiddenNew('locality',trimEdges($('input[name=locality]').val(),','),'search_form','bottom');
        }else{
            createHiddenNew('locality','','search_form');
            createHiddenNew('locality','','search_form_bottom','bottom');
        }*/

		$('#selectedOptsOuter_zones, #selectedOptsOuter_zones_bottom').addClass('bgwhite'); 							
		$('#selectedOptsOuter_zones, #selectedOptsOuter_zones_bottom').removeClass('disabled');
        $('#selectedOptsOuter_zones, #selectedOptsOuter_zones_bottom').removeClass('bggray');

    }else{
        //If neither of the above - Go to freg selection
        switch2Fregs('',true,true);
        switch2Fregs('_bottom',true,true);
    }
})
