/**
 * DEVELOPMENT, compress and change references for production!
 * 
 * @version $Id$
 */
var DDD = {};
var SIMPLE_SEARCH_VALUE = 'Voorbeeld: vergaan Titanic';
var ADVANCED_SEARCH_VALUE = 'Zoekterm invullen is niet verplicht'; 

/**
 * Common functionality
 */
DDD.Common = {
    init: function (){
	
		$(function(){
	        $('a[class~=icon_pdf]').click(function(){
	            window.open(this.href);
	            return false;
	        });
	    });
    },
    
    /**
     * Escape a string to be regex safe
     * @param {string} s
     */
    Rescape: function (s){
        return s.replace(/([.*+?\^${}=!:()|\[\]\/\\])/g, '\\$1');
    }, 

    
    /**
     * Closes the grandfather object of the caller by setting its CSS property display to none (for SearchErrorBox)
     * @param object: The object whose Granddaddy should be closed
     */	
    Close: function (object){
    	$(object).parent().parent().css("display", "none");    	
    }
    
};

/**
 * Viewer specific implementations
 */
DDD.Viewer = {
	init : function () {
		
		$('a#action_store').bind('click', DDD.Viewer.set_attributes).bind('click', DDD.Popup.new_window_save);
		$('a#action_print').bind('click', DDD.Viewer.set_attributes).bind('click', DDD.Popup.new_window_print);
		$('form#pagenumber_form').bind('submit', DDD.Viewer.input_validator_pageindex);
	},
	
	set_attributes : function () {
	    $(this).attr(
	      'href',
	      $('div#DDDviewer_image_layer1>img').attr('src')
	    );

	    $(this).attr(
	     'rel',
	         'width='+ $('div#DDDviewer_image_layer1>img').css('width') +
	         ',height='+ $('div#DDDviewer_image_layer1>img').css('height')
	     );
	
	    return false;
	},

	input_validator_pageindex : function () {
		if ($('input#total_pages')) {
			var a = parseInt($('input#total_pages').val()), b = parseInt($('input#pagenumber').val());

			// Don't do anything when the input is out of bounds
			if (!isNaN(a) && (isNaN(b) || b < 1 || b > a)) {
				alert('Invoer onjuist');
				return false;
			}

			return true;
		}
	}
};

/**
 * Popup specific fucntions
 */
DDD.Popup = {
	get_window_width : function (win) {
		var w = 0;
		if( typeof( win.innerWidth ) === 'number' ) {
			//Non-IE
			w = win.innerWidth;
		} else if( win.document.documentElement && win.document.documentElement.clientWidth ) {
			//IE 6+ in 'standards compliant mode'
			w = win.document.documentElement.clientWidth;
		} else if( win.frames.document.documentElement && win.frames.document.documentElement.clientWidth ) {
			//IE 6+ in 'standards compliant mode' alternate
			w = win.frames.document.documentElement.clientWidth;
		} else if( win.document.body && win.document.body.clientWidth ) {
			//IE 4 compatible
			w = win.document.body.clientWidth;
		}
		return w;
	},
	get_window_height : function (win) {
		var h = 0;
		if( typeof( win.innerHeight ) === 'number' ) {
			//Non-IE
			h = win.innerHeight;
		} else if( win.document.documentElement && win.document.documentElement.clientHeight ) {
			//IE 6+ in 'standards compliant mode'
			h = win.document.documentElement.clientHeight;
		} else if( win.frames.document.documentElement && win.frames.document.documentElement.clientHeight ) {
			//IE 6+ in 'standards compliant mode' alternate
			h = win.frames.document.documentElement.clientHeight;
		} else if( win.document.body && win.document.body.clientHeight ) {
			//IE 4 compatible
			h = win.document.body.clientHeight;
		}
		return h;
	},

    create_new_window : function (href,opt) {
		if (DDD.Popup.win) {
			DDD.Popup.win.close();
		}
        if (opt != '') {
            opt = ','+ opt; 
        }
        DDD.Popup.win = window.open(href, 'Viewer', 'scrollbars=yes,location=no,toolbar=no,directories=no,resizable=no'+opt);

        // Add some spacing, if we can read the w&h (which we can't in IE..)
        var IE = /*@cc_on!@*/false; // Should return true only for IE
        if (!IE) {
			var w = DDD.Popup.get_window_width(DDD.Popup.win), h = DDD.Popup.get_window_height(DDD.Popup.win);
			if (w && h) {
				DDD.Popup.win.resizeTo((25+w), (100+h));
			}
        }

        if (!DDD.Popup.win.focus) {
			DDD.Popup.win.focus();
        }

        return DDD.Popup.win;
    },

    /**
     * onClick action that opens a new window
     * supports options being set with the 'rel' attribute
     */
    new_window : function () {
        DDD.Popup.create_new_window($(this).attr('href'), $(this).attr('rel'));
        return false;
    },
	
	new_window_save : function () {
		var url = escape( $(this).attr('href') );
		var baseUrl	= $('head>base').attr('href');
		if (!baseUrl) {
			baseUrl = '/';
		}

        DDD.Popup.create_new_window(baseUrl +'retrieve/image/to/'+ url.replace(/\//g, '%2F'), $(this).attr('rel'));
        return false;
	},
    
	/**
	 * New window with immediate print() call
	 */    
	new_window_print : function () {
    	var url = escape( $(this).attr('href') );

    	var baseUrl	= $('head>base').attr('href');
    	if (!baseUrl) {
    		baseUrl = '/';
    	}	
    	var win = DDD.Popup.create_new_window('', $(this).attr('rel'));

    	if (win) {
    		win.document.writeln('<img src="' + baseUrl + 'retrieve/image/to/' + url.replace(/\//g, '%2F') + '" alt="image" />');		
    		win.document.close();	
    		win.print();		
    	}
    }
};

/**
 * Styling related, optional.
 */
DDD.Styling = {

    init: function (){
		$('a.new-window').bind('click', DDD.Popup.new_window);
		
		/**
		 * For each checkbox or it's label, mark it's label as 'checked'
		 */
		$('input[type="checkbox"].checkbox').each(function (){
			var chckbx = $(this), lbl;
			
			// Correct on change (but we use 'click' because of IE)
			chckbx.click(function () {
				var acb;
				lbl = $('label[for="'+ $(this).attr('id') +'"]');
				
				// Check if we have others to 'uncheck'
				if ($(this).hasClass('all')) {
					if ($(this).attr('checked') === true) {
						$(this).parents('div.select-box').find('input[type="checkbox"]').each(function(){
							if (!$(this).hasClass('all')) {
								$(this).attr('checked', false);
								$('label[for="' + $(this).attr('id') + '"]').removeClass('checked');
							}
						});
					}
				} else {
					acb = $(this).parents('div.select-box').find('input[type="checkbox"][class*=all]');
					if (acb) {
						acb.attr('checked', false);
						$('label[for="' + acb.attr('id') + '"]').removeClass('checked');
					}
				}
				
				// Adjust the style
				if (lbl) {
					if ($(this).attr('checked') === true) {
						lbl.addClass('checked');
					} else {
						lbl.removeClass('checked');
					}					
				}
				
				
			});

			// Correct on page load
			lbl = $('label[for="'+ chckbx.attr('id') +'"]');
			if (lbl) {
				if (chckbx.attr('checked') === true) {
					lbl.addClass('checked');
				} else {
					lbl.removeClass('checked');
				}					
			}
		});
    }
};


/**
 * Cookie related methods
 */
DDD.Cookie = {

    /**
     * Set a cookie
     * @param {string} n name
     * @param {scalar} v value
     * @param {int} days
     */
    set: function (n, v, days){
        var e = '', d;
        if (days) {
            d = new Date();
            d.setTime(d.getTime() + (days * 86400000));
            e = "; expires=" + d.toGMTString();
        }
        document.cookie = n + "=" + v + e + "; path=/";
    },
    
    /**
     * get a cookie
     * @param {string} n name
     */
    get: function (n){
        var match = n + "=", c = '', ca = document.cookie.split(';'), i;
        for (i = 0; i < ca.length; i++) {
            c = jQuery.trim(ca[i]);
            if (c.indexOf(match) === 0) {
                return c.substring(match.length, c.length);
            }
        }
        
        return null;
    },
    
    /**
     * Delete a cookie
     * @param {string} n name
     */
    del: function (n){
        DDD.Cookie.set(n, "", -1);
    }
};

function print_r(theObj){
	var result = "";
	
	if (theObj.constructor == Array || theObj.constructor == Object) {		
		for (var p in theObj) {
			if (theObj[p] != null) {
				if (theObj[p].constructor == Array || theObj[p].constructor == Object) {
					result += "["+p+"] => "+typeof(theObj);				
					result += print_r(theObj[p]);				
				} else {
					result += "["+p+"] => "+theObj[p];
					//result += theObj[p];
				}
			} 
		}		
	} else {
		result = theObj;
	}
	return result;
}

/**
 * Tooltip specific
 */
DDD.Tooltip = {
    init: function (){
        DDD.Tooltip.tte = '<div class="tooltip-container"><div class="tooltip"><div class="top"></div><div class="bottom">&nbsp;</div></div></div>';
        DDD.Tooltip.tter = '<div class="tooltip-container"><div class="tooltip tooltip_r"><div class="top"></div><div class="bottom">&nbsp;</div></div></div>';
        //DDD.Tooltip.ttem = '<div class="tooltip-container"><div class="tooltip_meta"><a class="icon-info metainfo tooltip-close" href="#"><strong>X</strong></a><div id="bla" class="tooltip_meta">X</div><div class="top"></div></div></div>';        
        DDD.Tooltip.ttem = '<div class="tooltip-container"><div class="tooltip_meta"><div id="tt-closer" style="background-color:#7A7064; text-align:right;"><strong style="color:white;cursor:pointer;">X&nbsp;</strong></div><div class="top"></div></div></div>';        
		
        DDD.Tooltip.lastSelected = '';
        
        /**
         * Bring all (non-meta) tooltips alive
         */
        $('a.icon-info:not([class*=metainfo])').bind('click', DDD.Tooltip.bind_action);        
    },
	
	close_action: function (e) {
		var c, a = $(this);
			
		c = $('div#tooltip_metadata div.tooltip-container');
		c.children('div').animate({
			opacity: 'toggle'
		}, 50);
					
		return false;
	},
    
    bind_action: function (e){
        var c, a = $(this), ttip = '';
        
        if (a.hasClass('metainfo')) {
            if ($('div#tooltip_metadata div.tooltip-container').length === 0) {
                $('div#tooltip_metadata').html(DDD.Tooltip.ttem);
				$('div#tt-closer').bind('click', DDD.Tooltip.close_action);
				$('div#tooltip_metadata' > '.tooltip-container').bind('click', DDD.Tooltip.close_action);
                $('div#tooltip_metadata').show();
                DDD.Tooltip.lastSelected = '';
            }
            
            c = $('div#tooltip_metadata div.tooltip-container');
            if (DDD.Tooltip.lastSelected === a.attr('href')) {				
                c.children('div').animate({
                    opacity: 'toggle'
                }, 50);
            }
            else {
                cTop = c.children('div').children('div.top');
                cTop.html('Loading...');
                c.children('div').fadeIn(50);
                
                if (ttip === '') {
                    cTop.load(a.attr('href'), function (data){
                        ttip = data;
                    });
                }
                else {
                    cTop.html(ttip);
                }
            }
            
            DDD.Tooltip.lastSelected = a.attr('href');
            
        }
        else {
            c = a.next('div.tooltip-container');
            
            // If the container doesn't exists yet, create it
            if (c.length === 0) {
                if (a.hasClass('tooltip_r')) {
                    a.after(DDD.Tooltip.tter);
                }
                else {
                    a.after(DDD.Tooltip.tte);
                }
                c = a.next('div.tooltip-container');
            }
            
            // Fetch the data, if we haven't done so already
            if (c.length === 0 || c.children().children('div.top').html() === '') {
            
                c.children().children('div.top').html('Loading...');
                
                // (Re-)select the added element
                c.find('div').fadeIn(50);
                c.find('div.top').load(a.attr('href'));
                
            }
            else {
                //c.find('div.tooltip').animate({opacity: 'toggle'}, 50);				
                c.children('div').animate({
                    opacity: 'toggle'
                }, 50);
            }
        }
        
        
        
        // Hiding all active elements
        $('div.tooltip-container').each(function (){
            if (c.index(this) !== 0) {				
                $(this).children('div.tooltip').hide();
            }
        });
        
        
        // Disabling the click event
        return false;
    }
};


/**
 * Form specific
 */
DDD.Form = {
    init: function () {
		this.oldval = '';

        /**
         * Finding search forms on the page,
         * and disable submit if validation fails
         */
        $('form.searchForm').each(function (){
            $(this).submit(function (){
                return DDD.Form._validateForm(this);
            });
            
            /**
             * Attaching the marker and 'on focus' features to the search input
             */
            $(this).find('input.searchQuery').keypress(function (){
                DDD.Form._mark($(this), 'valid');
            }).focus(function (){
            	/**
            	 * Change the if statement if the default text of the searchboxes changes
            	 */                    
                if (SIMPLE_SEARCH_VALUE === $(this).val() || ADVANCED_SEARCH_VALUE === $(this).val()) {                    
					$(this).val('');
                }
            });
        });


        // hardcoding the image, because fetching it from CSS causes problems in IE (doh..)
        var img = 'images/icon-calendar.gif';
        
        
        // jQuery UI datepicker		
        if ($('input#date_start').length !== 0) {
            $('input#date_start').next('a.calendar').remove();
            $("input#date_start").datepicker({
                changeMonth: true,
                changeYear: true,
                showOtherMonths: true,
                yearRange: '1618:1995',
                minDate: new Date('01/01/1618'),
                navigationAsDateFormat: true,
                dateFormat: 'dd-mm-yy',
                firstDay: 1,
                hideIfNoPrevNext: true,
                duration: 0,
                showOn: 'button',
                buttonImage: img,
                buttonImageOnly: true,
				dayNamesMin: ['Zo', 'Ma', 'Di', 'Wo', 'Do', 'Vr', 'Za'], 
				dayNamesShort: ['Zon', 'Maa', 'Din', 'Woe', 'Don', 'Vrij', 'Zat'],
				monthNames: ['Januari','Februari','Maart','April','Mei','Juni','Juli','Augustus','September','Oktober','November','December'],
				monthNamesShort: ['Jan','Feb','Mar','Apr','Mei','Jun','Jul','Aug','Sep','Okt','Nov','Dec']
            });
        }

        if ($('input#date_end').length !== 0) {
            $('input#date_end').next('a.calendar').remove();
            $("input#date_end").datepicker({
                changeMonth: true,
                changeYear: true,
                showOtherMonths: true,
                yearRange: '1618:1995',
                minDate: new Date('01/01/1618'),
                navigationAsDateFormat: true,
                dateFormat: 'dd-mm-yy',
                firstDay: 1,
                hideIfNoPrevNext: true,
                duration: 0,
                showOn: 'button',
                buttonImage: img,
                buttonImageOnly: true,
				dayNamesMin: ['Zo', 'Ma', 'Di', 'Wo', 'Do', 'Vr', 'Za'], 
				dayNamesShort: ['Zon', 'Maa', 'Din', 'Woe', 'Don', 'Vrij', 'Zat'],
				monthNames: ['Januari','Februari','Maart','April','Mei','Juni','Juli','Augustus','September','Oktober','November','December'],
				monthNamesShort: ['Jan','Feb','Mar','Apr','Mei','Jun','Jul','Aug','Sep','Okt','Nov','Dec']
            });
        }
    },
    
    /**
     * The select sequence in advanced search
     */
    show_select_selected: function (type){
        
        // Out with the old
        $('#' + type + 's_all').removeClass('checked');
        $('label[for="'+ type +'s_all"]').removeClass('checked');
        
        // In with the new
        $('#' + type + '_select_list').show();
        $('#' + type + 's_selected').parent('div.row').addClass('tab-checked');
        
        $('#' + type + 's_selected').attr('checked', 'checked');
    },

    /**
     * The deselect sequence in advanced search
     */
    show_select_unselected: function (type){
        
        // In with the new
        $('#' + type + '_select_list').hide();
        $('#' + type + 's_all').removeClass('checked');
        $('#' + type + 's_selected').parent('div.row').removeClass('tab-checked');
        $('label[for="'+ type +'s_selected"]').removeClass('checked');
    },
    
    
    /**
     * Find and validate the search string
     * @param {Object} el
     * @return {boolean}
     */
    _validateForm: function (el){
        var status = 1;
        $(el).find('input.searchQuery').each(function (){
            status &= DDD.Form._validateSearchQuery($(this).val());
            DDD.Form._mark(this, status);
        });
        
        return (status == 1);
    },
    
    
    /**
     * Visual feedback
     *
     * @param {Object} el
     * @param {string} valid or invalid, default invalid
     */
    _mark: function (el, type){
        if (type === "valid" || type === 1) {
            $('fieldset.q div.search-error').hide();
        } else {
            $('fieldset.q div.search-error').show();
        }
    },
    
    
    /**
     * Roughly validate the input string for search phrase correctness
     * @param {string} str
     * @return {int} 1 for true, 0 for false
     */
    _validateSearchQuery: function (str) {
        var s = 1;

        /**
         * @todo Unicode syntax
         */
        if (str.length !== 0) {
			// At least two alpha or three num or num+alpha
			s &= /^(?:[^*])?(?:[\w\s\xC0-\xFF\.\']){2}/i.test(jQuery.trim(str));
		}

		// The search on the frontpage can not be left empty.
		if ($('div#simple-search-form').length > 0) {			
			s &= (DDD.Form.oldval !== str);			
		}
		
		// The simple search value cannot be the same as the default value
		if (str === SIMPLE_SEARCH_VALUE) {				
			s &= 0;			
		}
		
        return s;
    }
};

/**
 *
 */
 DDD.Demo = {
   init: function() {

     $('.demolink').each( function(i)
        {
          $(this).bind("click",
          (function (e) {
               swfobject.embedSWF(this.href, "democontent", "710", "500", "9.0.0");
               e.preventDefault();
                           })
           )});
     $('#demobutton').click(function (e){
          var demo = $('#demo');
          var maincol = $('.maincol-holder');
          if(demo.css('display') == 'none')
          {
             maincol.hide();
             demo.show();

          }
          else
          {
             demo.hide();
             maincol.show();
          }
          e.preventDefault();

     });
     }
};

 

/**
 *
 */
DDD.Select = {

    init: function () {
    
		this.loading = {'place': false, 'title': false};
    
        /**
         * Finding title_select anchors on the page and
         * update the select_list divs with titles
         */
        $('a#title_select').click(function (e){
            DDD.Select.title_load_list();
            return DDD.Select.activate('title');
        });
        
        $('input#titles_selected').click(function (e){
			$('a#title_select').trigger('click');
        });
        
        $('input#titles_all').click(function (e){
        	$('input#titles_all').trigger('change');
        });
        
        $('a#place_select').click(function (){
            DDD.Select.place_load_list();
            return DDD.Select.activate('place');
        });
        
        sdivli = $('div#place_select_selected ul.sub-links li');
        if(sdivli.length < 10 )
        {
                $('input#places_selected').click(function (e){
                                $('a#place_select').trigger('click');
                });
        }
        else
        {
           $('div#place_select_container ul.sub-links li > a').each(function(i){ $(this).attr('disable', 'disable').addClass('inactive');}
           );
        }

                
        $('input#places_all').click(function (e){
        	$('input#places_all').trigger('change');
        });
		
		$('input#titles_all').change(function () {
			DDD.Form.show_select_unselected('title');
		});

		$('input#places_all').change(function () {
			DDD.Form.show_select_unselected('place');
		});
		
		$('label[for=places_all]').click(function () {
			$('input#places_all').trigger('change');
		});

		$('label[for=titles_all]').click(function () {
			$('input#titles_all').trigger('change');
		});

        /**
         * Event handler on the title selection section
         */
        $('input#titles_selected').change(function (){
            $('a#title_select').trigger('click');
        });
        
        /**
         * Event handler on the place selection section
         */
        $('input#places_selected').change(function (){
            $('a#place_select').trigger('click');
        });

        
        // Binding actions
        DDD.Select.select_actions('title');
        DDD.Select.select_actions('place');
        
        // Attach the filter listener
        DDD.Select.select_filter_actions('title');
        DDD.Select.select_filter_actions('place');
	},
    
    activate: function (type){
    
        if ($('#result_select_list').length === 1) {
            return DDD.Select.result_load_list(type);
        } else {
            DDD.Form.show_select_selected(type);
            DDD.Form.show_select_unselected(type === 'title' ? 'place' : 'title');
			return false;
        }
    },
    
    show_result_titles: function (){
        this.holder = $('div#main-column');
        $('div#main-column').attr({
            "class": "brown-maincol"
        });
        $('#result_select_list').show();
    },
    
    title_load_list: function () {
        return DDD.Select.load_list('title');
    },
    
    place_load_list: function () {
        return DDD.Select.load_list('place');
    },
    
    load_list: function (type) {
                        
		// Preventing firing multiple ajax requests while one is active.
		if (DDD.Select.loading[ type ] === true) {
			return false;
		} else {
			DDD.Select.loading[ type ] = true;
		}

        // Only re-download the list if we don't have one already
        if ($('#' + type + '_select_list>div.description>div.load').length === 1) {
            var url = $('#' + type + '_select').attr('href'), tsl = $('#' + type + '_select_list');

			tsl.load(url, {nocache : true}, function (rText,sText,rObj) {
				// Done with the request, reset our 'queue'
				DDD.Select.loading[ type ] = false;

				if (sText === 'success') {
	                // Binding actions on the newly fetched titles and their actions
	                DDD.Select.select_actions(type);
	                
	                // Binding actions to the title filtering, and data mining
	                DDD.Select.select_filter_actions(type);
	
	                // Show the list when done
	                tsl.show();
					
				} else {
					rObj.abort();

					$(this).find('img.spinner').hide();
					$(this).find('strong').html('Probleem tijdens ophalen gegevens.');

					return false;
				}
        	});
        }
    
        return false;
    },
    
    result_load_list: function (type) {
        
        if ($('#result_select_list>div.description>div.load').length === 1) {
        
            var url = $('#title_select').attr('href'), tsl = $('div#main-column div.maincol-holder');
            $('#result_select_list').show();
            
            tsl.load(url, {nocache : true}, function (){
                // Binding actions on the newly fetched titles and their actions
                DDD.Select.select_actions(type);
                
                // Binding actions to the title filtering, and data mining
                DDD.Select.select_filter_actions(type);
                
                // Show the list when done
                tsl.show();
            });
			return false;
        }
		return true;
    },
    
    /**
     * Finding anchors in the title_select container for initial binding
     */
    select_actions: function (type){
    
        if ($('#' + type + '_select_list ul.sub-links>li>a:first-child').length > 0) {
            $('#' + type + '_select_list ul.sub-links>li>a:first-child').one('click', {
                t: type
            }, DDD.Select.bind_action).bind('click', DDD.Select.bind_dummy_action);
            
        }

        if ($('#' + type + '_select_list ul.sub-links>li>a[class*=icon-info]').length > 0) {             
            $('#' + type + '_select_list ul.sub-links>li>a[class*=icon-info]').bind('click', DDD.Tooltip.bind_action);
        }
    },

    /**
     * Disabling the anchor by simply doing nothing. Preventing multiple actions.
     */
	bind_dummy_action : function () {
		return false;
	},
	
    /**
     * Ajax request and re-binding
     * @return {boolean} false on success, true on failure !
     */
    bind_action: function (e){
        var el = $(this), nel, type;       
        if (e.data.t !== 'undefined') {
            type = e.data.t;
        }
        
        if ($('div#' + type + '_select_selected ul.sub-links li').length > 9 &&
        	el.parents('div#' + type + '_select_unselected').length !== 0) {
            return false;
        }
        
        
        jQuery.post(el.attr('href'), function (data,s) {
			if (s !== 'success') {
				alert('Er ging iets mis, probeer het later nog eens.');
				return false;
			}
			
            if (data !== '') {
                data = '<li>' + data + '</li>';
                nel = $(data);
                var url = nel.children('a:first').attr('href');

                if (url !== 'undefined') {
                	var id = (/([title|place])+\_del/.test(url)) ? '#' + type + '_select_selected' : '#' + type + '_select_unselected';

                	var sortel = nel.children('a:first').html();
                	var cmpr = 0;
                	                	
                    // Removing the old element
                    el.parent('li').remove();
                    
                    // Sort option 1
                    if ($('div' + id + ' ul.sub-links li').length > 0) {	
                        // Just put the item on top
                        if ($('div' + id + ' ul.sub-links li').length > 10) {
    						$('div' + id + ' ul.sub-links').prepend(nel);    															
    					} else {
    						$('div' + id + ' ul.sub-links').append(nel);
    						selements = $('div' + id + ' ul.sub-links li').remove();
							    						
    						selements.sort(function (a, b) {
    							left = $(a).children('a:first').html();
    							right = $(b).children('a:first').html();

    							if (left < right) {
    								return -1;
    							} else if (left > right) {
    								return 1;
    							} else {
    								return 0;
    							}
    						});

    						$('div' + id + ' ul.sub-links').append(selements);	
    					}
					} else {
                        nel.appendTo($('div' + id + ' ul.sub-links'));
                    }
                    
                    $('div' + id + ' ul.sub-links li a:first-child').unbind().one('click', {
                        t: type
                    }, DDD.Select.bind_action).bind('click', DDD.Select.bind_dummy_action);

                    $('div' + id + ' ul.sub-links li a[class*=icon-info]').unbind().bind('click', {
                        t: type
                    }, DDD.Tooltip.bind_action);
					
                    sdivli = $('div#' + type + '_select_selected ul.sub-links li');                    
                    
					// hiding 'selected titles' container
                    if (sdivli.length === 0) {
                        $('div#' + type + '_select_selected').hide(200);
                    } else if (sdivli.length === 1) {
                        $('div#' + type + '_select_selected').show(200);
                    }
                    
					if (sdivli.length > 9) {
						$('div#' + type + '_select_unselected ul.sub-links li a:not([class*=icon-info])').each(function(){
							$(this).attr('disable', 'disable').addClass('inactive');
						});
					} else if (sdivli.length === 9) {
						$('div#' + type + '_select_unselected ul.sub-links li a:first-child.inactive').each(function(){
							$(this).removeAttr('disable').removeClass('inactive');
						});
					}
					
					// Update the counter next to the arrow of the 'selectionscreen'
					$('span.'+ type +'_count').html( sdivli.length );
					
					DDD.Select.select_filter_actions(type);					
                }
            }
        });

        return false;
    },
    
    /**
     * Title select filtering, autocomplete and titel select list updating
     */
    select_filter_actions: function (type){
    
        // The HTML anchor object of the titles, select only the anchor without a class
        var inp, rgx = new RegExp(), items = $('#' + type + '_select_container>ul.sub-links>li>a:not([class])'), keys = [13, 27, 37, 38, 39, 40];

        if (items.length === 0) {
            return false;
        }

        // Disabling (and hiding) submit
        $('input#' + type + '_select_search_submit').hide().click(function (){
            return false;
        });
        
		// Disabling the form		
		$('input#' + type + '_select_search_filter').parents('form').submit(function() {
			return false;
		});
        
        // updating the title_select list based on the action performed
        $('input#' + type + '_select_search_filter').unbind('blur keyup').bind('blur keyup', function (e){
        
            // Skip the following characters (esc, arrows, return, etc)
            if (jQuery.inArray(e.keyCode, keys) >= 0) {
                return false;
            }
            
            // Building the regex from our user input
            inp = $(this).attr('value');
            try {
                rgx.compile(DDD.Common.Rescape(inp), 'im');
                for (var i = 0; i < items.length; i++) {
                    if (rgx.source !== '' && !rgx.test(items[i].innerHTML)) {
                        items[i].parentNode.style.display = 'none';
                    }
                    else {
                        items[i].parentNode.style.display = '';
                    }
                }

                // Silently ignore the regex errors		
            } catch (e) {}
            
        });
    },
    
    filter: function (){
        // Building the regex from our user input
        var data, inp = $('input#title_select_search_filter').attr('value'), titles = $('#title_select_container>ul.sub-links>li>a'), rgx = new RegExp(DDD.Common.Rescape(inp), 'im');
        
        titles.each(function (){
            if (rgx.source !== '' && !rgx.test($(this).html())) {
                $(this).parent('li').hide();
            } else {
                $(this).parent('li').show();
            }
        });
    }
};


if (typeof(jQuery) != "undefined") {
    $(document).ready(function (){
    
        // Never wait longer then 5 seconds
        jQuery.ajaxSetup({
            timeout: 3000
        });
        
        /**
         * Ordering is important
         */
        DDD.Common.init();
        DDD.Form.init();
        DDD.Select.init();
        DDD.Tooltip.init();
		DDD.Viewer.init();
        
        // Optional
        DDD.Styling.init();
        DDD.Demo.init();

    });
}

