
/* Merged Plone Javascript file
 * This file is dynamically assembled from separate parts.
 * Some of these parts have 3rd party licenses or copyright information attached
 * Such information is valid for that section,
 * not for the entire composite file
 * originating files are separated by - filename.js -
 */

/* - ++resource++collective.z3cform.datagridfield/datagridfield.js - */
dataGridField2Functions = new Object();

(function($) {
  $(document).ready(function(){

    dataGridField2Functions.getInputOrSelect = function(node) {
        /* Get the (first) input or select form element under the given node */
        
        var inputs = node.getElementsByTagName("input");
        if(inputs.length > 0) {
            return inputs[0];
        }
        
        var selects = node.getElementsByTagName("select");
        if(selects.length > 0) {
            return selects[0];
        }

        return null;
    }

    dataGridField2Functions.getWidgetRows = function(currnode) {
        /* Return primary <tr>s of current node's parent DGW */
        tbody = this.getParentElementById(currnode, "datagridwidget-tbody");
        return this.getRows(tbody);
    }

    dataGridField2Functions.getRows = function(tbody) {
        /* Return <tr> rows of <table> element */
        
        var rows = new Array()
        
        child = tbody.firstChild;
        while(child != null) {
            if(child.tagName != null) {
                if(child.tagName.toLowerCase() == "tr") {
                    rows = rows.concat(child);
                }
            }
            child = child.nextSibling;
        }
                      
        return rows;   
    } 

    dataGridField2Functions.autoInsertRow = function(e) {
        /* Add a new row when changing the last row 
           (i.e. the infamous auto insert feature)
        
         */
        var currnode = window.event ? window.event.srcElement : e.currentTarget;


        // fetch required data structure   
        var tbody = dataGridField2Functions.getParentElement(currnode, "TBODY");
        var rows = dataGridField2Functions.getRows(tbody);        
        var lastRow = rows[rows.length-1]; 
        
        var thisRow = dataGridField2Functions.getParentElementById(currnode, "datagridwidget-row");      
        $(thisRow).removeClass('auto-append');
        dataGridField2Functions.reindexRow(tbody, thisRow, 0); /* updateOrderIndex will give it the right value later */
        $(thisRow).find('td.datagridwidget-cell').children().each(function(){
            $(this).unbind('change');
        });
        
        /* Skip the very last row which is a hidden template row */
        if (rows.length-1 == (thisRow.rowIndex)) {
            // Create a new row
            var newtr = dataGridField2Functions.createNewRow(lastRow);
            $(newtr).addClass('auto-append');
            $(newtr).find('td.datagridwidget-cell').children().each(function(){
                $(this).change(dataGridField2Functions.autoInsertRow);
            });
            dataGridField2Functions.reindexRow(tbody, newtr, 'AA');
                                                                
            // Put new row to DOM tree before template row        
            lastRow.parentNode.insertBefore(newtr, lastRow);
            
            // update orderindex hidden fields
            dataGridField2Functions.updateOrderIndex(tbody);	        	    
        }    
    }

    dataGridField2Functions.addRowAfter = function(currnode) {
        /*
            Creates a new row before the clicked row
        */
        
        // fetch required data structure
        var tbody = this.getParentElementById(currnode, "datagridwidget-tbody"); 
        var thisRow = this.getParentElementById(currnode, "datagridwidget-row"); 

        var newtr = this.createNewRow(thisRow);
            
        thisRow.parentNode.insertBefore(newtr, thisRow);
        
        // update orderindex hidden fields
        this.updateOrderIndex(tbody);	
      
    }

    dataGridField2Functions.addRow = function(id) {
        /* Explitcly add row for given dataGridField2 
        
            @param id Archetypes field id for the widget	
        */
        
        // fetch required data structure
        var tbody = document.getElementById("datagridwidget-tbody-" + id);    
        var rows = this.getRows(tbody);    
        var lastRow = rows[rows.length-1];
            
        var oldRows = rows.length;
                      
        // Create a new row
        var newtr = this.createNewRow(lastRow);
        
        // Put new row to DOM tree before template row        
        newNode = lastRow.parentNode.insertBefore(newtr, lastRow);
        $(newNode).removeClass('datagridwidget-empty-row');
        
        // update orderindex hidden fields
        this.updateOrderIndex(tbody);		
          
    }

    dataGridField2Functions.createNewRow = function(tr) { 
        /* Creates a new row 
               
           @param tr A row in a table where we'll be adding the new row
        */
        
        var tbody = this.getParentElementById(tr, "datagridwidget-tbody"); 
        var rows = this.getRows(tbody);   
        
        // hidden template row 
        var lastRow = rows[rows.length-1]; 
        
        var newtr = document.createElement("tr");
        newtr.setAttribute("id", "datagridwidget-row");
        newtr.setAttribute("class", "datagridwidget-row");
            
        // clone template contents from the last row to the newly created row
        // HOX HOX HOX
        // If f****ng IE clones lastRow directly it doesn't work.
        // lastRow is in hidden state and no matter what you do it remains hidden.
        // i.e. overriding class doesn't bring it visible.
        // In Firefox everything worked like a charm.
        // So the code below is really a hack to satisfy Microsoft codeborgs.
        // keywords: IE javascript clone clonenode hidden element render visibility visual
        child = lastRow.firstChild;
        while(child != null) {
            newchild = child.cloneNode(true);
            newtr.appendChild(newchild);
            child = child.nextSibling;
        }		
            
        return newtr;	 
    }


    dataGridField2Functions.removeFieldRow = function(node) {
        /* Remove the row in which the given node is found */
        
        var row = this.getParentElementById(node, 'datagridwidget-row');
        var tbody = this.getParentElementById(node, 'datagridwidget-tbody');
        tbody.removeChild(row);
        this.updateOrderIndex(tbody);	        	    
    }

    dataGridField2Functions.moveRowDown = function(currnode){
        /* Move the given row down one */
               
        var tbody = this.getParentElementById(currnode, "datagridwidget-tbody");    
        
        var rows = this.getWidgetRows(currnode);
        
        var row = this.getParentElementById(currnode, "datagridwidget-row");      
        if(row == null) {
            alert("Couldn't find DataGridWidget row");
            return;
        }
        
        var idx = null
        
        // We can't use nextSibling because of blank text nodes in some browsers
        // Need to find the index of the row
        for(var t = 0; t < rows.length; t++) {
            if(rows[t] == row) {
                idx = t;
                break;
            }
        }

        // Abort if the current row wasn't found
        if(idx == null)
            return;     
            
        // If this was the last row (before the blank row at the end used to create
        // new rows), move to the top, else move down one.
        if(idx + 2 == rows.length) {
            var nextRow = rows.item[0]
            this.shiftRow(row, nextRow)
        } else {
            var nextRow = rows[idx+1]
            this.shiftRow(nextRow, row)
        }
        
        this.updateOrderIndex(tbody)

    }

    dataGridField2Functions.moveRowUp = function(currnode){
        /* Move the given row up one */
        
        var tbody = this.getParentElementById(currnode, "datagridwidget-tbody");    
        var rows = this.getWidgetRows(currnode);
        
        var row = this.getParentElementById(currnode, "datagridwidget-row");      
        if(row == null) {
            alert("Couldn't find DataGridWidget row");
            return;
        }

        var idx = null
        
        // We can't use nextSibling because of blank text nodes in some browsers
        // Need to find the index of the row
        for(var t = 0; t < rows.length; t++) {
            if(rows[t] == row) {
                idx = t;
                break;
            }
        }
        
        // Abort if the current row wasn't found
        if(idx == null)
            return;
            
        // If this was the first row, move to the end (i.e. before the blank row
        // at the end used to create new rows), else move up one
        if(idx == 0) {
            var previousRow = rows[rows.length - 1]
            this.shiftRow(row, previousRow);
        } else {
            var previousRow = rows[idx-1];
            this.shiftRow(row, previousRow);
        }
        
        this.updateOrderIndex(tbody);
    }

    dataGridField2Functions.shiftRow = function(bottom, top){
        /* Put node top before node bottom */
        
        bottom.parentNode.insertBefore(bottom, top)   
    }

    dataGridField2Functions.reindexRow = function (tbody, row, newindex) {
        var data=$(tbody).data();
        var name_prefix = data.name_prefix + '.';
        var id_prefix = data.id_prefix + '-';

        $(row).find('[name^="' + name_prefix +'"]').each(function(){
            var oldname = this.name.substr(name_prefix.length);
            var oldindex1 = oldname.split('.', 1)[0];
            var oldindex2 = oldname.split('-', 1)[0];
            /* Name fields can have '-' for empty values */
            var oldindex = 0;
            if (oldindex1.length < oldindex2.length)
            {
                oldindex = oldindex1;
            } else {
                oldindex = oldindex2;
            }
            this.name = name_prefix + newindex + oldname.substr(oldindex.length);
        });
        $(row).find('[id^="' + id_prefix +'"]').each(function(){
            var oldid = this.id.substr(id_prefix.length);
            var oldindex = oldid.split('-', 1)[0];
            this.id = id_prefix + newindex + oldid.substr(oldindex.length);
        });
    }


    dataGridField2Functions.updateOrderIndex = function (tbody) {

        /* Split from the dataGridField2 approach here - and just re-do
         * the numbers produced by z3c.form
         */
        var data=$(tbody).data();
        var name_prefix = data.name_prefix + '.';

        var rows = this.getRows(tbody); 
        for (var i=0; i<rows.length; i++) {
            var row = rows[i];
            if ($(row).hasClass('datagridwidget-empty-row') || $(row).hasClass('auto-append')) {
                continue
            }
            dataGridField2Functions.reindexRow(tbody, row, i);
        }

        $(document).find('input[name="' + name_prefix + 'count"]').each(function(){
            // do not include the TT and the AA rows in the count
            var count = rows.length;
            if ($(rows[count-1]).hasClass('datagridwidget-empty-row')) {
                count--;
            }
            if ($(rows[count-1]).hasClass('auto-append')) {
                count--;
            }
            this.value = count;
        });
    }

    dataGridField2Functions.getParentElement = function(currnode, tagname) {
        /* Find the first parent node with the given tag name */

        tagname = tagname.toUpperCase();
        var parent = currnode.parentNode;

        while(parent.tagName.toUpperCase() != tagname) {
            parent = parent.parentNode;
            // Next line is a safety belt
            if(parent.tagName.toUpperCase() == "BODY") 
                return null;
        }

        return parent;
    }

    dataGridField2Functions.getParentElementById = function(currnode, id) {
        /* Find the first parent node with the given id 
        
            Id is partially matched: the beginning of
            an element id matches parameter id string.
        
            Currnode: Node where ascending in DOM tree beings
            Id: Id string to look for. 
                    
        */
        
        id = id.toLowerCase();
        var parent = currnode.parentNode;

        while(true) {
           
            var parentId = parent.getAttribute("id");
            if(parentId != null) {    	
                 if(parentId.toLowerCase().substring(0, id.length) == id) break;
            }
                
            parent = parent.parentNode;
            // Next line is a safety belt
            if(parent.tagName.toUpperCase() == "BODY") 
                return null;
        }

        return parent;
    }

    /* Bind the handlers to the auto append rows */
    $('tr.auto-append > td.datagridwidget-cell').live('change', dataGridField2Functions.autoInsertRow);
  });
})(jQuery);



/* - atgooglemaps.js - */
// http://www.eu-hbm.info/portal_javascripts/atgooglemaps.js?original=1
function createMap(map_id,lat,lng,zoom,mapType,typeCtl,navCtl){var options={zoom:zoom,center:new google.maps.LatLng(lat,lng),scaleControl:false,streetViewControl:false,scrollwheel:false,keyboardShortcuts:false,disableDoubleClickZoom:true,draggable:false};options.mapTypeId=eval("google.maps.MapTypeId."+mapType);if(typeCtl!=null){if(typeCtl=="hide"){options.mapTypeControl=false}
else{options.mapTypeControl=true;options.mapTypeControlOptions={};options.mapTypeControlOptions.style=eval("google.maps.MapTypeControlStyle."+typeCtl)}}
if(navCtl!=null){if(navCtl=="hide"){options.navigationControl=false}
else{options.navigationControl=true;options.navigationControlOptions={};options.navigationControlOptions.style=eval("google.maps.NavigationControlStyle."+navCtl)}}
var map;map=new google.maps.Map(document.getElementById(map_id),options);return map}
var visibleInfoWindow=null;
function createMarker(map,lat,lng,index,title,draggable){var shape={coord:[9,34,10,34,13,20,20,12,20,7,13,0,6,0,0,7,0,12,6,20],type:'poly'};var icon=new google.maps.MarkerImage("http://www.eu-hbm.info/gmap_marker.png",new google.maps.Size(20,34),new google.maps.Point(0,0),new google.maps.Point(10,34));var shadow=new google.maps.MarkerImage("http://www.eu-hbm.info/gmap_shadow.png",new google.maps.Size(37,34),new google.maps.Point(0,0),new google.maps.Point(10,34));if(draggable==null){draggable=false}
var marker=new google.maps.Marker({position:new google.maps.LatLng(lat,lng),map:map,title:title,icon:icon,shadow:shadow,shape:shape,draggable:draggable});if(index){var content=document.getElementById('infowindow_html_'+index).innerHTML;var infoWindow=new google.maps.InfoWindow({content:content});google.maps.event.addListener(marker,'click', function(){if(visibleInfoWindow){visibleInfoWindow.close()}
infoWindow.open(map,marker);visibleInfoWindow=infoWindow});var link=document.getElementById("infowindow_link_"+index);link.onclick=function(){google.maps.event.trigger(marker,"click")}}
return marker}
function createPolyline(map,color,opacity,weight,title){var polyline=new google.maps.Polyline({strokeColor:color,strokeOpacity:opacity,strokeWeight:weight});polyline.setMap(map);return polyline}
function createPath(array){var mvcArray=new google.maps.MVCArray();for(var i=0;i<array.length;i++){mvcArray.push(new google.maps.LatLng(array[i][0],array[i][1]))}
return mvcArray}
function updatePartnerList(countryName){$.get('updatePartnerList',{countryName:countryName},
function(responseText){$(".gmarkerBox").html(responseText)},"html")}
$(document).ready(function(){$('.countrySelector').change(function(){var countryName=$(this).val();if(countryName!='Europe'){updatePartnerList(countryName);var geocoder=new google.maps.Geocoder();geocoder.geocode({'address':countryName,'partialmatch':true}, function(locations){map.fitBounds(locations[0].geometry.viewport)})}
else{location.reload()}})});

/* - ++resource++plone.formwidget.autocomplete/jquery.autocomplete.min.js - */
/*
 * Autocomplete - jQuery plugin 1.0.2
 *
 * Copyright (c) 2007 Dylan Verheul, Dan G. Switzer, Anjesh Tuladhar, Jörn Zaefferer
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id: jquery.autocomplete.js 5747 2008-06-25 18:30:55Z joern.zaefferer $
 *
 */;(function($){$.fn.extend({autocomplete:function(urlOrData,options){var isUrl=typeof urlOrData=="string";options=$.extend({},$.Autocompleter.defaults,{url:isUrl?urlOrData:null,data:isUrl?null:urlOrData,delay:isUrl?$.Autocompleter.defaults.delay:10,max:options&&!options.scroll?10:150},options);options.highlight=options.highlight||function(value){return value;};options.formatMatch=options.formatMatch||options.formatItem;return this.each(function(){new $.Autocompleter(this,options);});},result:function(handler){return this.bind("result",handler);},search:function(handler){return this.trigger("search",[handler]);},flushCache:function(){return this.trigger("flushCache");},setOptions:function(options){return this.trigger("setOptions",[options]);},unautocomplete:function(){return this.trigger("unautocomplete");}});$.Autocompleter=function(input,options){var KEY={UP:38,DOWN:40,DEL:46,TAB:9,RETURN:13,ESC:27,COMMA:188,PAGEUP:33,PAGEDOWN:34,BACKSPACE:8};var $input=$(input).attr("autocomplete","off").addClass(options.inputClass);var timeout;var previousValue="";var cache=$.Autocompleter.Cache(options);var hasFocus=0;var lastKeyPressCode;var config={mouseDownOnSelect:false};var select=$.Autocompleter.Select(options,input,selectCurrent,config);var blockSubmit;$.browser.opera&&$(input.form).bind("submit.autocomplete",function(){if(blockSubmit){blockSubmit=false;return false;}});$input.bind(($.browser.opera?"keypress":"keydown")+".autocomplete",function(event){lastKeyPressCode=event.keyCode;switch(event.keyCode){case KEY.UP:event.preventDefault();if(select.visible()){select.prev();}else{onChange(0,true);}break;case KEY.DOWN:event.preventDefault();if(select.visible()){select.next();}else{onChange(0,true);}break;case KEY.PAGEUP:event.preventDefault();if(select.visible()){select.pageUp();}else{onChange(0,true);}break;case KEY.PAGEDOWN:event.preventDefault();if(select.visible()){select.pageDown();}else{onChange(0,true);}break;case options.multiple&&$.trim(options.multipleSeparator)==","&&KEY.COMMA:case KEY.TAB:case KEY.RETURN:if(selectCurrent()){event.preventDefault();blockSubmit=true;return false;}break;case KEY.ESC:select.hide();break;default:clearTimeout(timeout);timeout=setTimeout(onChange,options.delay);break;}}).focus(function(){hasFocus++;}).blur(function(){hasFocus=0;if(!config.mouseDownOnSelect){hideResults();}}).click(function(){if(hasFocus++>1&&!select.visible()){onChange(0,true);}}).bind("search",function(){var fn=(arguments.length>1)?arguments[1]:null;function findValueCallback(q,data){var result;if(data&&data.length){for(var i=0;i<data.length;i++){if(data[i].result.toLowerCase()==q.toLowerCase()){result=data[i];break;}}}if(typeof fn=="function")fn(result);else $input.trigger("result",result&&[result.data,result.value]);}$.each(trimWords($input.val()),function(i,value){request(value,findValueCallback,findValueCallback);});}).bind("flushCache",function(){cache.flush();}).bind("setOptions",function(){$.extend(options,arguments[1]);if("data"in arguments[1])cache.populate();}).bind("unautocomplete",function(){select.unbind();$input.unbind();$(input.form).unbind(".autocomplete");});function selectCurrent(){var selected=select.selected();if(!selected)return false;var v=selected.result;previousValue=v;if(options.multiple){var words=trimWords($input.val());if(words.length>1){v=words.slice(0,words.length-1).join(options.multipleSeparator)+options.multipleSeparator+v;}v+=options.multipleSeparator;}$input.val(v);hideResultsNow();$input.trigger("result",[selected.data,selected.value]);return true;}function onChange(crap,skipPrevCheck){if(lastKeyPressCode==KEY.DEL){select.hide();return;}var currentValue=$input.val();if(!skipPrevCheck&&currentValue==previousValue)return;previousValue=currentValue;currentValue=lastWord(currentValue);if(currentValue.length>=options.minChars){$input.addClass(options.loadingClass);if(!options.matchCase)currentValue=currentValue.toLowerCase();request(currentValue,receiveData,hideResultsNow);}else{stopLoading();select.hide();}};function trimWords(value){if(!value){return[""];}var words=value.split(options.multipleSeparator);var result=[];$.each(words,function(i,value){if($.trim(value))result[i]=$.trim(value);});return result;}function lastWord(value){if(!options.multiple)return value;var words=trimWords(value);return words[words.length-1];}function autoFill(q,sValue){if(options.autoFill&&(lastWord($input.val()).toLowerCase()==q.toLowerCase())&&lastKeyPressCode!=KEY.BACKSPACE){$input.val($input.val()+sValue.substring(lastWord(previousValue).length));$.Autocompleter.Selection(input,previousValue.length,previousValue.length+sValue.length);}};function hideResults(){clearTimeout(timeout);timeout=setTimeout(hideResultsNow,200);};function hideResultsNow(){var wasVisible=select.visible();select.hide();clearTimeout(timeout);stopLoading();if(options.mustMatch){$input.search(function(result){if(!result){if(options.multiple){var words=trimWords($input.val()).slice(0,-1);$input.val(words.join(options.multipleSeparator)+(words.length?options.multipleSeparator:""));}else
$input.val("");}});}if(wasVisible)$.Autocompleter.Selection(input,input.value.length,input.value.length);};function receiveData(q,data){if(data&&data.length&&hasFocus){stopLoading();select.display(data,q);autoFill(q,data[0].value);select.show();}else{hideResultsNow();}};function request(term,success,failure){if(!options.matchCase)term=term.toLowerCase();var data=cache.load(term);if(data&&data.length){success(term,data);}else if((typeof options.url=="string")&&(options.url.length>0)){var extraParams={timestamp:+new Date()};$.each(options.extraParams,function(key,param){extraParams[key]=typeof param=="function"?param():param;});$.ajax({mode:"abort",port:"autocomplete"+input.name,dataType:options.dataType,url:options.url,data:$.extend({q:lastWord(term),limit:options.max},extraParams),success:function(data){var parsed=options.parse&&options.parse(data)||parse(data);cache.add(term,parsed);success(term,parsed);}});}else{select.emptyList();failure(term);}};function parse(data){var parsed=[];var rows=data.split("\n");for(var i=0;i<rows.length;i++){var row=$.trim(rows[i]);if(row){row=row.split("|");parsed[parsed.length]={data:row,value:row[0],result:options.formatResult&&options.formatResult(row,row[0])||row[0]};}}return parsed;};function stopLoading(){$input.removeClass(options.loadingClass);};};$.Autocompleter.defaults={inputClass:"ac_input",resultsClass:"ac_results",loadingClass:"ac_loading",minChars:1,delay:400,matchCase:false,matchSubset:true,matchContains:false,cacheLength:10,max:100,mustMatch:false,extraParams:{},selectFirst:true,formatItem:function(row){return row[0];},formatMatch:null,autoFill:false,width:0,multiple:false,multipleSeparator:", ",highlight:function(value,term){return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)("+term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi,"\\$1")+")(?![^<>]*>)(?![^&;]+;)","gi"),"<strong>$1</strong>");},scroll:true,scrollHeight:180};$.Autocompleter.Cache=function(options){var data={};var length=0;function matchSubset(s,sub){if(!options.matchCase)s=s.toLowerCase();var i=s.indexOf(sub);if(i==-1)return false;return i==0||options.matchContains;};function add(q,value){if(length>options.cacheLength){flush();}if(!data[q]){length++;}data[q]=value;}function populate(){if(!options.data)return false;var stMatchSets={},nullData=0;if(!options.url)options.cacheLength=1;stMatchSets[""]=[];for(var i=0,ol=options.data.length;i<ol;i++){var rawValue=options.data[i];rawValue=(typeof rawValue=="string")?[rawValue]:rawValue;var value=options.formatMatch(rawValue,i+1,options.data.length);if(value===false)continue;var firstChar=value.charAt(0).toLowerCase();if(!stMatchSets[firstChar])stMatchSets[firstChar]=[];var row={value:value,data:rawValue,result:options.formatResult&&options.formatResult(rawValue)||value};stMatchSets[firstChar].push(row);if(nullData++<options.max){stMatchSets[""].push(row);}};$.each(stMatchSets,function(i,value){options.cacheLength++;add(i,value);});}setTimeout(populate,25);function flush(){data={};length=0;}return{flush:flush,add:add,populate:populate,load:function(q){if(!options.cacheLength||!length)return null;if(!options.url&&options.matchContains){var csub=[];for(var k in data){if(k.length>0){var c=data[k];$.each(c,function(i,x){if(matchSubset(x.value,q)){csub.push(x);}});}}return csub;}else
if(data[q]){return data[q];}else
if(options.matchSubset){for(var i=q.length-1;i>=options.minChars;i--){var c=data[q.substr(0,i)];if(c){var csub=[];$.each(c,function(i,x){if(matchSubset(x.value,q)){csub[csub.length]=x;}});return csub;}}}return null;}};};$.Autocompleter.Select=function(options,input,select,config){var CLASSES={ACTIVE:"ac_over"};var listItems,active=-1,data,term="",needsInit=true,element,list;function init(){if(!needsInit)return;element=$("<div/>").hide().addClass(options.resultsClass).css("position","absolute").appendTo(document.body);list=$("<ul/>").appendTo(element).mouseover(function(event){if(target(event).nodeName&&target(event).nodeName.toUpperCase()=='LI'){active=$("li",list).removeClass(CLASSES.ACTIVE).index(target(event));$(target(event)).addClass(CLASSES.ACTIVE);}}).click(function(event){$(target(event)).addClass(CLASSES.ACTIVE);select();input.focus();return false;}).mousedown(function(){config.mouseDownOnSelect=true;}).mouseup(function(){config.mouseDownOnSelect=false;});if(options.width>0)element.css("width",options.width);needsInit=false;}function target(event){var element=event.target;while(element&&element.tagName!="LI")element=element.parentNode;if(!element)return[];return element;}function moveSelect(step){listItems.slice(active,active+1).removeClass(CLASSES.ACTIVE);movePosition(step);var activeItem=listItems.slice(active,active+1).addClass(CLASSES.ACTIVE);if(options.scroll){var offset=0;listItems.slice(0,active).each(function(){offset+=this.offsetHeight;});if((offset+activeItem[0].offsetHeight-list.scrollTop())>list[0].clientHeight){list.scrollTop(offset+activeItem[0].offsetHeight-list.innerHeight());}else if(offset<list.scrollTop()){list.scrollTop(offset);}}};function movePosition(step){active+=step;if(active<0){active=listItems.size()-1;}else if(active>=listItems.size()){active=0;}}function limitNumberOfItems(available){return options.max&&options.max<available?options.max:available;}function fillList(){list.empty();var max=limitNumberOfItems(data.length);for(var i=0;i<max;i++){if(!data[i])continue;var formatted=options.formatItem(data[i].data,i+1,max,data[i].value,term);if(formatted===false)continue;var li=$("<li/>").html(options.highlight(formatted,term)).addClass(i%2==0?"ac_even":"ac_odd").appendTo(list)[0];$.data(li,"ac_data",data[i]);}listItems=list.find("li");if(options.selectFirst){listItems.slice(0,1).addClass(CLASSES.ACTIVE);active=0;}if($.fn.bgiframe)list.bgiframe();}return{display:function(d,q){init();data=d;term=q;fillList();},next:function(){moveSelect(1);},prev:function(){moveSelect(-1);},pageUp:function(){if(active!=0&&active-8<0){moveSelect(-active);}else{moveSelect(-8);}},pageDown:function(){if(active!=listItems.size()-1&&active+8>listItems.size()){moveSelect(listItems.size()-1-active);}else{moveSelect(8);}},hide:function(){element&&element.hide();listItems&&listItems.removeClass(CLASSES.ACTIVE);active=-1;},visible:function(){return element&&element.is(":visible");},current:function(){return this.visible()&&(listItems.filter("."+CLASSES.ACTIVE)[0]||options.selectFirst&&listItems[0]);},show:function(){var offset=$(input).offset();element.css({width:typeof options.width=="string"||options.width>0?options.width:$(input).width(),top:offset.top+input.offsetHeight,left:offset.left}).show();if(options.scroll){list.scrollTop(0);list.css({maxHeight:options.scrollHeight,overflow:'auto'});if($.browser.msie&&typeof document.body.style.maxHeight==="undefined"){var listHeight=0;listItems.each(function(){listHeight+=this.offsetHeight;});var scrollbarsVisible=listHeight>options.scrollHeight;list.css('height',scrollbarsVisible?options.scrollHeight:listHeight);if(!scrollbarsVisible){listItems.width(list.width()-parseInt(listItems.css("padding-left"))-parseInt(listItems.css("padding-right")));}}}},selected:function(){var selected=listItems&&listItems.filter("."+CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);return selected&&selected.length&&$.data(selected[0],"ac_data");},emptyList:function(){list&&list.empty();},unbind:function(){element&&element.remove();}};};$.Autocompleter.Selection=function(field,start,end){if(field.createTextRange){var selRange=field.createTextRange();selRange.collapse(true);selRange.moveStart("character",start);selRange.moveEnd("character",end);selRange.select();}else if(field.setSelectionRange){field.setSelectionRange(start,end);}else{if(field.selectionStart){field.selectionStart=start;field.selectionEnd=end;}}field.focus();};})(jQuery);

/* - ++resource++plone.formwidget.contenttree/contenttree.js - */
// This is based on jQueryFileTree by   Cory S.N. LaViska
if(jQuery) (function($){
    
    $.extend($.fn, {
        showDialog: function() {
            $(document.body).append($(document.createElement("div")).addClass("contenttreeWindowBlocker"))
            this[0].oldparent = $(this).parent()[0]; // store old parent element
            $(".contenttreeWindowBlocker").before(this);
            $(this).show();
            $(this).width($(window).width() * 0.75);
            $(this).height($(window).height() * 0.75);
            $(this).css({
                'left': $(window).width() * 0.125,
                'top': $(window).height() * 0.125
            })
        },
        contentTreeAdd: function(id, name, klass, title, base_path, multi_select) {
            var termCount = multi_select ? $('#' +id + '-input-fields').children().length : 0;


            $(this).parents(".contenttreeWindow").find('.navTreeCurrentItem > a').each(function () {
                var path = $(this).attr('href').substr(base_path.length);
                var field = $('#' + id + '-input-fields input[value="' + path + '"]');
                if(field.length == 0) {
                    if (multi_select) {
                        $('#' + id + '-input-fields').append('<span id="' + id + '-' + termCount + '-wrapper" class="option"><label for="' + id + '-' + termCount + '"><input type="checkbox" id="' + id + '-' + termCount + '" name="' + name + ':list" class="' + klass + '" title="' + title + '" checked="checked" value="' + path + '" /><span class="label">' + $.trim($(this).text()) + '</span></label></span>');
                    } else {
                        $('#' + id + '-input-fields').find(".option").remove();
                        $('#' + id + '-input-fields').append('<span id="' + id + '-' + termCount + '-wrapper" class="option"><label for="' + id + '-' + termCount + '"><input type="radio" id="' + id + '-' + termCount + '" name="' + name + ':list" class="' + klass + '" title="' + title + '" checked="checked" value="' + path + '" /><span class="label">' + $.trim($(this).text()) + '</span></label></span>');
                    }
                } else {
                    field.each(function() { this.checked = true });
                }
            });

            $(this).contentTreeCancel();
        },
        contentTreeCancel: function() {
            $(".contenttreeWindowBlocker").remove();
            var popup = $(this).parents(".contenttreeWindow");
            popup.hide();
            $(popup[0].oldparent).append(popup);
            popup[0].oldparent = null;
        },
        contentTree: function(o, h) {

            // Defaults
            if(!o) var o = {};
            if(o.script == undefined) o.script = 'fetch';
               
            if(o.folderEvent == undefined) o.folderEvent = 'click';
            if(o.selectEvent == undefined) o.selectEvent = 'click';
               
            if(o.expandSpeed == undefined) o.expandSpeed = -1;
            if(o.collapseSpeed == undefined) o.collapseSpeed = -1;
               
            if(o.multiFolder == undefined) o.multiFolder = true;
            if(o.multiSelect == undefined) o.multiSelect = false;

            o.root = $(this);

            function loadTree(c, t, r) {
                $(c).addClass('wait');
                $.post(o.script, { href: t, rel: r}, function(data) {
                    $(c).removeClass('wait').append(data);
                    $(c).find('ul:hidden').slideDown({ duration: o.expandSpeed });
                    bindTree(c);
                });
            }
            
            function handleFolderEvent() {
                var li = $(this).parent();
                if(li.hasClass('collapsed')) {
                    if(!o.multiFolder) {
                        li.parent().find('ul:visible').slideUp({ duration: o.collapseSpeed });
                        li.parent().find('li.navTreeFolderish').removeClass('expanded').addClass('collapsed');
                    }
                    
                    if(li.find('ul').length == 0)
                        loadTree(li, escape($(this).attr('href')), escape($(this).attr('rel')));
                    else
                        li.find('ul:hidden').slideDown({ duration: o.expandSpeed });
                    
                    li.removeClass('collapsed').addClass('expanded');
                } else {
                    li.find('ul').slideUp({ duration: o.collapseSpeed });
                    li.removeClass('expanded').addClass('collapsed');
                }
                return false;
            }
            
            function handleSelectEvent(event) {
                var li = $(this).parent();
                var selected = true;
                if(!li.hasClass('navTreeCurrentItem')) {
                    var multi_key = ((event.ctrlKey) || (navigator.userAgent.toLowerCase().indexOf('macintosh') != -1 && event.metaKey));

                    if(!o.multiSelect || !multi_key) {
                        o.root.find('li.navTreeCurrentItem').removeClass('navTreeCurrentItem');
                    }

                    li.addClass('navTreeCurrentItem');
                    selected = true;
                } else {
                    li.removeClass('navTreeCurrentItem');
                    selected = false;
                }

                h(event, true, $(this).attr('href'), $.trim($(this).text()));
            }

            function bindTree(t) {
                $(t).find('li a').bind('click', function() { return false; });
                $(t).find('li.navTreeFolderish a').bind(o.folderEvent, handleFolderEvent);
                $(t).find('li.selectable a').bind(o.selectEvent, handleSelectEvent);
            }

            $(this).each(function() {
                bindTree($(this));
            });
        }
    });
    
})(jQuery);


