/*
 *
 * Copyright (c) 2006-2009 Sam Collett (http://www.texotela.co.uk)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Version 2.2.4
 * Demo: http://www.texotela.co.uk/code/jquery/select/
 *
 * $LastChangedDate: 2010-05-10 16:05:54 +0200 (Mon, 10 May 2010) $
 * $Rev: 1966 $
 *
 */
 
;(function($) {
 
/**
 * Adds (single/multiple) options to a select box (or series of select boxes)
 * 
 * @name addOption
 * @author Sam Collett (http://www.texotela.co.uk)
 * @type jQuery
 * @example $("#myselect").addOption("Value", "Text"); // add single value (will
 *          be selected)
 * @example $("#myselect").addOption("Value 2", "Text 2", false); // add single
 *          value (won't be selected)
 * @example $("#myselect").addOption({"foo":"bar","bar":"baz"}, false); // add
 *          multiple values, but don't select
 * 
 */
$.fn.addOption = function()
{
    var add = function(el, v, t, sO)
    {
        var option = document.createElement("option");
        option.value = v, option.text = t;
        // get options
        var o = el.options;
        // get number of options
        var oL = o.length;
        if(!el.cache)
        {
            el.cache = {};
            // loop through existing options, adding to cache
            for(var i = 0; i < oL; i++)
            {
                el.cache[o[i].value] = i;
            }
        }
        // add to cache if it isn't already
        if(typeof el.cache[v] == "undefined") el.cache[v] = oL;
        el.options[el.cache[v]] = option;
        if(sO)
        {
            option.selected = true;
        }
    };
    
    var a = arguments;
    if(a.length == 0) return this;
    // select option when added? default is true
    var sO = true;
    // multiple items
    var m = false;
    // other variables
    var items, v, t;
    if(typeof(a[0]) == "object")
    {
        m = true;
        items = a[0];
    }
    if(a.length >= 2)
    {
        if(typeof(a[1]) == "boolean") sO = a[1];
        else if(typeof(a[2]) == "boolean") sO = a[2];
        if(!m)
        {
            v = a[0];
            t = a[1];
        }
    }
    this.each(
        function()
        {
            if(this.nodeName.toLowerCase() != "select") return;
            if(m)
            {
                for(var item in items)
                {
                    add(this, item, items[item], sO);
                }
            }
            else
            {
                add(this, v, t, sO);
            }
        }
    );
    return this;
};

/**
 * Add options via ajax
 * 
 * @name ajaxAddOption
 * @author Sam Collett (http://www.texotela.co.uk)
 * @type jQuery
 * @param String
 *            url Page to get options from (must be valid JSON)
 * @param Object
 *            params (optional) Any parameters to send with the request
 * @param Boolean
 *            select (optional) Select the added options, default true
 * @param Function
 *            fn (optional) Call this function with the select object as param
 *            after completion
 * @param Array
 *            args (optional) Array with params to pass to the function
 *            afterwards
 * @example $("#myselect").ajaxAddOption("myoptions.php");
 * @example $("#myselect").ajaxAddOption("myoptions.php", {"code" : "007"});
 * @example $("#myselect").ajaxAddOption("myoptions.php", {"code" : "007"},
 *          false, sortoptions, [{"dir": "desc"}]);
 * 
 */
$.fn.ajaxAddOption = function(url, params, select, fn, args)
{
    if(typeof(url) != "string") return this;
    if(typeof(params) != "object") params = {};
    if(typeof(select) != "boolean") select = true;
    this.each(
        function()
        {
            var el = this;
            $.getJSON(url,
                params,
                function(r)
                {
                    $(el).addOption(r, select);
                    if(typeof fn == "function")
                    {
                        if(typeof args == "object")
                        {
                            fn.apply(el, args);
                        } 
                        else
                        {
                            fn.call(el);
                        }
                    }
                }
            );
        }
    );
    return this;
};

/**
 * Removes an option (by value or index) from a select box (or series of select
 * boxes)
 * 
 * @name removeOption
 * @author Sam Collett (http://www.texotela.co.uk)
 * @type jQuery
 * @param String|RegExp|Number
 *            what Option to remove
 * @param Boolean
 *            selectedOnly (optional) Remove only if it has been selected
 *            (default false)
 * @example $("#myselect").removeOption("Value"); // remove by value
 * @example $("#myselect").removeOption(/^val/i); // remove options with a value
 *          starting with 'val'
 * @example $("#myselect").removeOption(/./); // remove all options
 * @example $("#myselect").removeOption(/./, true); // remove all options that
 *          have been selected
 * @example $("#myselect").removeOption(0); // remove by index
 * @example $("#myselect").removeOption(["myselect_1","myselect_2"]); // values
 *          contained in passed array
 * 
 */
$.fn.removeOption = function()
{
    var a = arguments;
    if(a.length == 0) return this;
    var ta = typeof(a[0]);
    var v, index;
    // has to be a string or regular expression (object in IE, function in
	// Firefox)
    if(ta == "string" || ta == "object" || ta == "function" )
    {
        v = a[0];
        // if an array, remove items
        if(v.constructor == Array)
        {
            var l = v.length;
            for(var i = 0; i<l; i++)
            {
                this.removeOption(v[i], a[1]); 
            }
            return this;
        }
    }
    else if(ta == "number") index = a[0];
    else return this;
    this.each(
        function()
        {
            if(this.nodeName.toLowerCase() != "select") return;
            // clear cache
            if(this.cache) this.cache = null;
            // does the option need to be removed?
            var remove = false;
            // get options
            var o = this.options;
            if(!!v)
            {
                // get number of options
                var oL = o.length;
                for(var i=oL-1; i>=0; i--)
                {
                    if(v.constructor == RegExp)
                    {
                        if(o[i].value.match(v))
                        {
                            remove = true;
                        }
                    }
                    else if(o[i].value == v)
                    {
                        remove = true;
                    }
                    // if the option is only to be removed if selected
                    if(remove && a[1] === true) remove = o[i].selected;
                    if(remove)
                    {
                        o[i] = null;
                    }
                    remove = false;
                }
            }
            else
            {
                // only remove if selected?
                if(a[1] === true)
                {
                    remove = o[index].selected;
                }
                else
                {
                    remove = true;
                }
                if(remove)
                {
                    this.remove(index);
                }
            }
        }
    );
    return this;
};

/**
 * Sort options (ascending or descending) in a select box (or series of select
 * boxes)
 * 
 * @name sortOptions
 * @author Sam Collett (http://www.texotela.co.uk)
 * @type jQuery
 * @param Boolean
 *            ascending (optional) Sort ascending (true/undefined), or
 *            descending (false)
 * @example // ascending $("#myselect").sortOptions(); // or
 *          $("#myselect").sortOptions(true);
 * @example // descending $("#myselect").sortOptions(false);
 * 
 */
$.fn.sortOptions = function(ascending)
{
    // get selected values first
    var sel = $(this).selectedValues();
    var a = typeof(ascending) == "undefined" ? true : !!ascending;
    this.each(
        function()
        {
            if(this.nodeName.toLowerCase() != "select") return;
            // get options
            var o = this.options;
            // get number of options
            var oL = o.length;
            // create an array for sorting
            var sA = [];
            // loop through options, adding to sort array
            for(var i = 0; i<oL; i++)
            {
                sA[i] = {
                    v: o[i].value,
                    t: o[i].text
                };
            }
            // sort items in array
            sA.sort(
                function(o1, o2)
                {
                    // option text is made lowercase for case insensitive
					// sorting
                    o1t = o1.t.toLowerCase(), o2t = o2.t.toLowerCase();
                    // if options are the same, no sorting is needed
                    if(o1t == o2t) return 0;
                    if(a)
                    {
                        return o1t < o2t ? -1 : 1;
                    }
                    else
                    {
                        return o1t > o2t ? -1 : 1;
                    }
                }
            );
            // change the options to match the sort array
            for(var i = 0; i<oL; i++)
            {
                o[i].text = sA[i].t;
                o[i].value = sA[i].v;
            }
        }
    ).selectOptions(sel, true); // select values, clearing existing ones
    return this;
};
/**
 * Selects an option by value
 * 
 * @name selectOptions
 * @author Mathias Bank (http://www.mathias-bank.de), original function
 * @author Sam Collett (http://www.texotela.co.uk), addition of regular
 *         expression matching
 * @type jQuery
 * @param String|RegExp|Array
 *            value Which options should be selected can be a string or regular
 *            expression, or an array of strings / regular expressions
 * @param Boolean
 *            clear Clear existing selected options, default false
 * @example $("#myselect").selectOptions("val1"); // with the value 'val1'
 * @example $("#myselect").selectOptions(["val1","val2","val3"]); // with the
 *          values 'val1' 'val2' 'val3'
 * @example $("#myselect").selectOptions(/^val/i); // with the value starting
 *          with 'val', case insensitive
 * 
 */
$.fn.selectOptions = function(value, clear)
{
    var v = value;
    var vT = typeof(value);
    // handle arrays
    if(vT == "object" && v.constructor == Array)
    {
        var $this = this;
        $.each(v, function()
            {
                    $this.selectOptions(this, clear);
                }
        );
    };
    var c = clear || false;
    // has to be a string or regular expression (object in IE, function in
	// Firefox)
    if(vT != "string" && vT != "function" && vT != "object") return this;
    this.each(
        function()
        {
            if(this.nodeName.toLowerCase() != "select") return this;
            // get options
            var o = this.options;
            // get number of options
            var oL = o.length;
            for(var i = 0; i<oL; i++)
            {
                if(v.constructor == RegExp)
                {
                    if(o[i].value.match(v))
                    {
                        o[i].selected = true;
                    }
                    else if(c)
                    {
                        o[i].selected = false;
                    }
                }
                else
                {
                    if(o[i].value == v)
                    {
                        o[i].selected = true;
                    }
                    else if(c)
                    {
                        o[i].selected = false;
                    }
                }
            }
        }
    );
    return this;
};

/**
 * Copy options to another select
 * 
 * @name copyOptions
 * @author Sam Collett (http://www.texotela.co.uk)
 * @type jQuery
 * @param String
 *            to Element to copy to
 * @param String
 *            which (optional) Specifies which options should be copied - 'all'
 *            or 'selected'. Default is 'selected'
 * @example $("#myselect").copyOptions("#myselect2"); // copy selected options
 *          from 'myselect' to 'myselect2'
 * @example $("#myselect").copyOptions("#myselect2","selected"); // same as
 *          above
 * @example $("#myselect").copyOptions("#myselect2","all"); // copy all options
 *          from 'myselect' to 'myselect2'
 * 
 */
$.fn.copyOptions = function(to, which)
{
    var w = which || "selected";
    if($(to).size() == 0) return this;
    this.each(
        function()
        {
            if(this.nodeName.toLowerCase() != "select") return this;
            // get options
            var o = this.options;
            // get number of options
            var oL = o.length;
            for(var i = 0; i<oL; i++)
            {
                if(w == "all" || (w == "selected" && o[i].selected))
                {
                    $(to).addOption(o[i].value, o[i].text);
                }
            }
        }
    );
    return this;
};

/**
 * Checks if a select box has an option with the supplied value
 * 
 * @name containsOption
 * @author Sam Collett (http://www.texotela.co.uk)
 * @type Boolean|jQuery
 * @param String|RegExp
 *            value Which value to check for. Can be a string or regular
 *            expression
 * @param Function
 *            fn (optional) Function to apply if an option with the given value
 *            is found. Use this if you don't want to break the chaining
 * @example if($("#myselect").containsOption("val1")) alert("Has an option with
 *          the value 'val1'");
 * @example if($("#myselect").containsOption(/^val/i)) alert("Has an option with
 *          the value starting with 'val'");
 * @example $("#myselect").containsOption("val1",
 *          copyoption).doSomethingElseWithSelect(); // calls copyoption (user
 *          defined function) for any options found, chain is continued
 * 
 */
$.fn.containsOption = function(value, fn)
{
    var found = false;
    var v = value;
    var vT = typeof(v);
    var fT = typeof(fn);
    // has to be a string or regular expression (object in IE, function in
	// Firefox)
    if(vT != "string" && vT != "function" && vT != "object") return fT == "function" ? this: found;
    this.each(
        function()
        {
            if(this.nodeName.toLowerCase() != "select") return this;
            // option already found
            if(found && fT != "function") return false;
            // get options
            var o = this.options;
            // get number of options
            var oL = o.length;
            for(var i = 0; i<oL; i++)
            {
                if(v.constructor == RegExp)
                {
                    if (o[i].value.match(v))
                    {
                        found = true;
                        if(fT == "function") fn.call(o[i], i);
                    }
                }
                else
                {
                    if (o[i].value == v)
                    {
                        found = true;
                        if(fT == "function") fn.call(o[i], i);
                    }
                }
            }
        }
    );
    return fT == "function" ? this : found;
};

/**
 * Returns values which have been selected
 * 
 * @name selectedValues
 * @author Sam Collett (http://www.texotela.co.uk)
 * @type Array
 * @example $("#myselect").selectedValues();
 * 
 */
$.fn.selectedValues = function()
{
    var v = [];
    this.selectedOptions().each(
        function()
        {
            v[v.length] = this.value;
        }
    );
    return v;
};

/**
 * Returns text which has been selected
 * 
 * @name selectedTexts
 * @author Sam Collett (http://www.texotela.co.uk)
 * @type Array
 * @example $("#myselect").selectedTexts();
 * 
 */
$.fn.selectedTexts = function()
{
    var t = [];
    this.selectedOptions().each(
        function()
        {
            t[t.length] = this.text;
        }
    );
    return t;
};

/**
 * Returns options which have been selected
 * 
 * @name selectedOptions
 * @author Sam Collett (http://www.texotela.co.uk)
 * @type jQuery
 * @example $("#myselect").selectedOptions();
 * 
 */
$.fn.selectedOptions = function()
{
    return this.find("option:selected");
};

})(jQuery);
$(document).ready(function () 
{

  	toggleSpecsDataOnLoad('#account_specs');
	toggleChecksumOnLoad('#contact_selectChecksum');
	toggleChecksumOnLoad('#locality_selectChecksum');
	toggleSpecsDataOnLoad('#contact_specs');
	togglePluginDataOnLoad('#content_type');
	toggleSpecsDataOnLoad('#userApply_specs');

	toggleSpecsData('#account_specs');
	toggleSpecsData('#contact_specs');
	togglePluginData('#content_type');

	//if($('#unassociated_category_subsidiary_clients_list').length > 0) {
	//	autoComplete('subsidiary_clients', '', 'category');
	//}

	if($('#unassociated_account_subsidiary_clients_list').length > 0) {
		autoComplete('subsidiary_clients_list', '', 'account');
	}

	if($('#unassociated_account_superior_client').length > 0) {
		autoComplete('superior_client', '', 'account');
	}

	if($('#unassociated_account_subsidiary_editors').length > 0) {;
		autoComplete('subsidiary_editors', '_subeditor', 'account');
	}

	if($('#unassociated_account_superior_reseller_list').length > 0) {
		autoComplete('superior_reseller_list', '_supreseller', 'account');
	}
	if($('#event_exception_allDay').length > 0) {

    if($('#event_exception_allDay').val() == '0') {
					$('.sf_admin_form_field_time_from').show();
					$('.sf_admin_form_field_time_to').show();
			} else {
					$('.sf_admin_form_field_time_from').hide();
					$('.sf_admin_form_field_time_to').hide();
			}


		$('#event_exception_allDay').change(function () {
      if($('#event_exception_allDay').val() == '0') {
					$('.sf_admin_form_field_time_from').show();
					$('.sf_admin_form_field_time_to').show();
			} else {
					$('.sf_admin_form_field_time_from').hide();
					$('.sf_admin_form_field_time_to').hide();
			}
    });
	}


	
	function autoComplete(field, appendix, section) 
	{
      if($('#'+section+'_search_options'+appendix).val() == '2') {
		$('#'+section+'_alphabet_choice'+appendix).parent().parent().hide();
      } else
        {
		$('#'+section+'_search_input'+appendix).parent().parent().hide();
		}
		if($('#'+section+'_search_options'+appendix))
		{
			$('#'+section+'_search_options'+appendix).change(function ()
			{
				if($('#'+section+'_search_options'+appendix).val() == '1') {
					$('#'+section+'_alphabet_choice'+appendix).parent().parent().show();
				} else {
					$('#'+section+'_alphabet_choice'+appendix).parent().parent().hide();
				}
				
				if($('#'+section+'_search_options'+appendix).val() == '2') {
					$('#'+section+'_search_input'+appendix).parent().parent().show();
				} else {
					$('#'+section+'_search_input'+appendix).parent().parent().hide();
				}
				
				if($('#'+section+'_search_options'+appendix).val() == '0') {

					$("#unassociated_"+section+"_"+field).removeOption(/./);
			        $("#unassociated_"+section+"_"+field).addOption("-", "warte auf eingabe ...", false);

			        if(section == 'account') 
			        {
			        
			        	 switch(field)
					        {
		        	case 'subsidiary_clients_list':
		        		$.getJSON("/backend.php/account/findall",{l:field},subsidiary_clients_list_generate);
		        		break;
		        	case 'superior_client':
		        		$.getJSON("/backend.php/account/findall",{l:field},superior_client_list_generate);
		        		break;
		        	case 'subsidiary_editors':
		        		$.getJSON("/backend.php/account/findall",{l:field},subsidiary_editors_list_generate);
		        		break;
		        	case 'superior_reseller_list':
		        		$.getJSON("/backend.php/account/findall",{l:field},superior_reseller_list_generate);
		        		break;
			        }
			        } else  if(section == 'category') {
			        	 switch(field)
					        {
		        	case 'subsidiary_clients_list':			        		
		        		$.getJSON("/backend.php/account/findall",{l:field},category_subsidiary_clients_list_generate);
		        		break;
					        }}
				} 
			});
		}

		if($('#'+section+'_alphabet_choice'+appendix)) 
	    {
			$('#'+section+'_alphabet_choice'+appendix).change(function () 
			{
				var str = "";

		        $("#"+section+"_alphabet_choice"+appendix+" option:selected").each(function () { str = $(this).text(); });
		        $("#unassociated_"+section+"_"+field).removeOption(/./);
		        $("#unassociated_"+section+"_"+field).addOption("-", "wird geladen ...", false);

		        if(section == 'account') {
		        switch(field)
		        {
		        	case 'subsidiary_clients_list':
		        		$.getJSON("/backend.php/account/findalpha",{search:str,l:field},subsidiary_clients_list_generate);
		        		break;
		        	case 'superior_client':
		        		$.getJSON("/backend.php/account/findalpha",{search:str,l:field},superior_client_list_generate);
		        		break;
		        	case 'subsidiary_editors':
		        		$.getJSON("/backend.php/account/findalpha",{search:str,l:field},subsidiary_editors_list_generate);
		        		break;
		        	case 'superior_reseller_list':
		        		$.getJSON("/backend.php/account/findalpha",{search:str,l:field},superior_reseller_list_generate);
		        		break;
		        }} else  if(section == 'category') {
		        	 switch(field)
				        {
	        	case 'subsidiary_clients_list':
	        		$.getJSON("/backend.php/account/findalpha",{search:str,l:field},category_subsidiary_clients_list_generate);
	        		break;
				        }}
				
			});
	    }
		

		if($('#'+section+'_search_input'+appendix)) 
	    {
			$('#'+section+'_search_input'+appendix).keyup(function()
			{
				var str = $(this).val();
				
				if(str.length >= 1)
				{
     
					$("#unassociated_"+section+"_"+field).removeOption(/./);
					$("#unassociated_"+section+"_"+field).addOption("-", "wird geladen ...", false);
			        if(section == 'account') {

			        switch(field)
			        {
			        	case 'subsidiary_clients_list':
			        		$.getJSON("/backend.php/account/find",{search:str,l:field},subsidiary_clients_list_generate);
			        		break;
			        	case 'superior_client':
			        		$.getJSON("/backend.php/account/find",{search:str,l:field},superior_client_list_generate);
			        		break;
			        	case 'subsidiary_editors':
			        		$.getJSON("/backend.php/account/find",{search:str,l:field},subsidiary_editors_list_generate);
			        		break;
			        	case 'superior_reseller_list':
			        		$.getJSON("/backend.php/account/find",{search:str,l:field},superior_reseller_list_generate);
			        		break;
			        }} else  if(section == 'category') {
			        	 switch(field)
					        {
		        	case 'subsidiary_clients':			        		
		        		$.getJSON("/backend.php/account/find",{search:str,l:field},category_subsidiary_clients_list_generate);
		        		break;
					        }}
				} 
				
				
			});
	    }
	}
	
	
	

	function countProperties(obj) {
		  var prop;
		  var propCount = 0;
		  
		  for (prop in obj) {
		    propCount++;
		  }
		  return propCount;
		}
	
	function category_subsidiary_clients_list_generate(users) 
	{
		$("#unassociated_category_subsidiary_clients_list").removeOption(/./);

		    for(i in users) {
		        $("#unassociated_category_subsidiary_clients_list").addOption(i, users[i], false);
		    }
		    
			$('#category_subsidiary_clients_list option:enabled').each(function () { 
				$("#unassociated_category_subsidiary_clients_list").removeOption($(this).val());
			});
			
			$("#unassociated_category_subsidiary_clients_list").removeOption("-");

			if($("#unassociated_category_subsidiary_clients_list option:enabled").length == 0) {
				$("#unassociated_category_subsidiary_clients_list").addOption("-", "keine einträge ...", false);
			}
	}
	function subsidiary_clients_list_generate(users)
	{
		$("#unassociated_account_subsidiary_clients_list").removeOption(/./);

		    for(i in users) {
		        $("#unassociated_account_subsidiary_clients_list").addOption(i, users[i], false);
		    }
		    
			$('#account_subsidiary_clients_list option:enabled').each(function () { 
				$("#unassociated_account_subsidiary_clients_list").removeOption($(this).val());
			});
			
			$("#unassociated_account_subsidiary_clients_list").removeOption("-");

			if($("#unassociated_account_subsidiary_clients_list option:enabled").length == 0) {
				$("#unassociated_account_subsidiary_clients_list").addOption("-", "keine einträge ...", false);
			}
	}
	

	function superior_client_list_generate(users) 
	{
		$("#unassociated_account_superior_client").removeOption(/./);

		    for(i in users) {
		        $("#unassociated_account_superior_client").addOption(i, users[i], false);
		    }
		    
			$('#account_superior_client option:enabled').each(function () { 
				$("#unassociated_account_superior_client").removeOption($(this).val());
			});
			
			$("#unassociated_account_superior_client").removeOption("-");

			if($("#unassociated_account_superior_client option:enabled").length == 0) {
				$("#unassociated_account_superior_client").addOption("-", "keine einträge ...", false);
			}
	}
	

	function subsidiary_editors_list_generate(users) 
	{
		$("#unassociated_account_subsidiary_editors").removeOption(/./);

		    for(i in users) {
		        $("#unassociated_account_subsidiary_editors").addOption(i, users[i], false);
		    }
		    
			$('#account_subsidiary_editors option:enabled').each(function () { 
				$("#unassociated_account_subsidiary_editors").removeOption($(this).val());
			});
			
			$("#unassociated_account_subsidiary_editors").removeOption("-");

			if($("#unassociated_account_subsidiary_editors option:enabled").length == 0) {
				$("#unassociated_account_subsidiary_editors").addOption("-", "keine einträge ...", false);
			}
	}
	

	function superior_reseller_list_generate(users) 
	{
		$("#unassociated_account_superior_reseller_list").removeOption(/./);

		    for(i in users) {
		        $("#unassociated_account_superior_reseller_list").addOption(i, users[i], false);
		    }
		    
			$('#account_superior_reseller_list option:enabled').each(function () { 
				$("#unassociated_account_superior_reseller_list").removeOption($(this).val());
			});
			
			$("#unassociated_account_superior_reseller_list").removeOption("-");

			if($("#unassociated_account_superior_reseller_list option:enabled").length == 0) {
				$("#unassociated_account_superior_reseller_list").addOption("-", "keine einträge ...", false);
			}
	}
	
	
	$('#group2').mouseover(function(){
	  $(this).addClass('tabgroupfield');
	  $('#group1').removeClass('tabgroupfield');
	});
	
	$('#group1').mouseover(function(){
	  $(this).addClass('tabgroupfield');
	  $('#group2').removeClass('tabgroupfield');
	});
	
	showFilter();
	hideFilter();
	
	/**
	 * Linkcreator start
	 */
	if($('#link_only_top')) 
    {
      if($('#link_only_top').attr('checked') == true) 
      {
        $('#sf_fieldset_filter_vorauswahl').hide();
        $('#sf_fieldset_filter_optional').hide();
      }
      
      $('#link_only_top').change(function () 
      {
        if($('#link_only_top').attr('checked') == true) 
        {
          $('#sf_fieldset_filter_vorauswahl').hide();
          $('#sf_fieldset_filter_optional').hide();
        } else {
          $('#sf_fieldset_filter_vorauswahl').show();
          $('#sf_fieldset_filter_optional').show();        
        }
       });
    }
    
    if($('#link_datetime')) 
    {
      if($('#link_datetime').val() != 'none') 
      {
        $('.sf_admin_form_field_date_from').hide();
        $('.sf_admin_form_field_date_to').hide();
      }
      
      $('#link_datetime').change(function () 
      {
        if($('#link_datetime').val() == 'none') 
        {
          $('div.sf_admin_form_field_date_from').show();
          $('div.sf_admin_form_field_date_to').show();
        } 
        else 
        {
          $('div.sf_admin_form_field_date_from').hide();
          $('div.sf_admin_form_field_date_to').hide();
        }
       });
    }
    
    if($('#link_component_id')) 
    {

      if($('#link_status').val() == 'new') 
      {
        var module = $('#link_component_id').val();
        var client = $('#link_client_id').val();
        
        $("#link_branches").removeOption(/./);
        $("#link_branches").addOption("-", "wird geladen ...", false);
        
        $.getJSON("/backend.php/category/find",{id:module,client:client},generateBranchList);
      }
      
      /**
		 * Veranstaltungen
		 */
      if($('#link_component_id').val() == '2') 
      {
        $("#link_datetime").addOption("today", "Heute", false);
        $("#link_datetime").addOption("weekend", "Wochenende", false);
        $("#link_datetime").addOption("week", "plus 7 Tage", false);
        $("#link_datetime").addOption("month", "plus 1 Monat", false);
        $("#link_datetime").addOption("future", "Zukünftig", false);

        if($('#link_status').val() == 'edit') 
        {
            $("#link_datetime").selectOptions($('#link_defdt').val(), true);

            $('.sf_admin_form_field_date_from').hide();
            $('.sf_admin_form_field_date_to').hide();
        }
        
      } 
       
      
      
      $('#link_component_id').change(function () 
      {

        var module = $('#link_component_id').val();
        var client = $('#link_client_id').val();
        
        $("#link_branches").removeOption(/./);
        $("#link_branches").addOption("-", "wird geladen ...", false);
        
        $.getJSON("/backend.php/category/find",{id:module,client:client},generateBranchList);
        
        // Anzeigen da Detailsuche sofort ausgewählt wird.
        $('.sf_admin_form_field_date_from').show();
        $('.sf_admin_form_field_date_to').show();
        
        $("#link_datetime").removeOption(/./);
        $("#link_datetime").addOption("none", "Datumauswahl", false);

        /**
		 * Veranstaltungen
		 */
        if($('#link_component_id').val() == '2') 
        {
          $("#link_datetime").addOption("today", "Heute", false);
          $("#link_datetime").addOption("weekend", "Wochenende", false);
          $("#link_datetime").addOption("week", "plus 7 Tage", false);
          $("#link_datetime").addOption("month", "plus 1 Monat", false);
          $("#link_datetime").addOption("future", "Zukünftig", false);
          
          if($('#link_status').val() == 'edit') 
          {
              $("#link_datetime").selectOptions($('#link_defdt').val(), true);
              $('.sf_admin_form_field_date_from').hide();
              $('.sf_admin_form_field_date_to').hide();
          }
        } 
        
        
       });
      

      
    }
    
    

    if($('#link_region_id')) 
    {
      $('#link_region_id').change(function () 
        {
          var region = $('#link_region_id').val();
          var client = $('#link_client_id').val();

          $("#unassociated_link_locations").removeOption(/./);
          $("#unassociated_link_locations").addOption("-", "wird geladen ...", false);
          $("#link_locations").removeOption(/./);
          
          $("#unassociated_link_organizer").removeOption(/./);
          $("#link_organizer").removeOption(/./);
          $("#unassociated_link_organizer").addOption("-", "wird geladen ...", false);
          
          $.getJSON("/backend.php/contact/find",{id:region,location:'1',client:client},generateRegionLocations);
          $.getJSON("/backend.php/contact/find",{id:region,organizer:'1',client:client},generateRegionOrganizer);
        });
    }


    function generateBranchList(branches) {

        for(i in branches) {
          
          var string = new String(branches[i]);
          
          $("#link_branches").addOption(i, string, false);
        }
        
        $("#link_branches").removeOption("-");
        $("#link_branches").selectOptions($("#link_defcat").val());
    }


    function generateRegionLocations(locations) {

        for(i in locations) {
            $("#unassociated_link_locations").addOption(i, locations[i], false);
        }
        
        $("#unassociated_link_locations").removeOption("-");
        
    }

    function generateRegionOrganizer(organizer) {

        for(i in organizer) {
            $("#unassociated_link_organizer").addOption(i, organizer[i], false);
        }
        
        $("#unassociated_link_organizer").removeOption("-");
        
    }
    
    
    
    
    
    
    

	/**
	 * Linkcreator end
	 */
	

    if($('#market_categories')) 
    {
        $('#market_categories').change(function (elem) 
            	    {
			$("#market_categories option:selected").each(function () 
	        { 
				if($("#market_categories option:selected").size() > 3) 
				{
					this.selected = false;
					alert('Sie können nur max. 3 Rubriken auswählen');
					return false;
				}
	        });
	    });
	}
	
	if($('#event_categories')) 
	{
		$('#event_categories').change(function (elem) 
	    {
			$("#event_categories option:selected").each(function () 
	        { 
				if($("#event_categories option:selected").size() > 3) 
				{
					this.selected = false;
					alert('Sie können nur max. 3 Rubriken auswählen');
					return false;
				}
	        });
	    });
	}
	
	if($('#region_country')) 
	{
		$('#region_country').change(function () {
			var str = "";

	          $("#region_country option:selected").each(function () { str = $(this).val(); });
	          $("#unassociated_region_districts_list").removeOption(/./);
	          $("#unassociated_region_districts_list").addOption("-", "Bitte warten ...", false);
	          $("#region_zonechoice").removeOption(/./);
	          $("#region_zonechoice").addOption("-", "Bitte warten ...", false);
	          
            $.getJSON("/backend.php/autocomplete/zone",{c:str},generateZones);
	  	});
	}
	
	if($('#region_zonechoice')) 
	{
		$('#region_zonechoice').change(function () {
			var str = "";

	        $("#region_zonechoice option:selected").each(function () { str = $(this).val(); });
	        $("#unassociated_region_localities_list").removeOption(/./);
	        $("#unassociated_region_localities_list").addOption("-", "Bitte warten ...", false);
	        $("#unassociated_region_localities_list").ajaxAddOption("/backend.php/find/locality", {c:str}, false, removeAssignedLocalities);
	    });
	}
	
	if($('#associate_company_id')) 
	{
		$('#associate_company_id').change(function () {
			var str = "";
			var con = $('#associate_employee_id').val();
	        $("#associate_company_id option:selected").each(function () { str = $(this).val(); });
	        $("#associate_structure_id").removeOption(/./);
	        $("#associate_structure_id").ajaxAddOption("/backend.php/find/structure", {c:str,u:con}, false, removeAssignedLocalities);
	    });
	}
	
	if($('#associate_employee_id')) 
	{
		$('#associate_employee_id').change(function () {
			var con = "";
			var str = $('#associate_company_id').val();
	        $("#associate_employee_id option:selected").each(function () { con = $(this).val(); });
	        $("#associate_structure_id").removeOption(/./);
	        $("#associate_structure_id").ajaxAddOption("/backend.php/find/structure", {c:str,u:con}, false, removeAssignedLocalities);
	    });
	}
	
});








function removeStructures() 
{
	$('#associate_structure_id').each(function () { 
		$("#associate_structure_id").removeOption($(this).val());
	});
}



function checkAllByPrefix(name, field) 
{
	var choice = "id";
	
	if(typeof field == 'string') {
		choice = field;
	}
	
	var prefix = name;
	var options = [
	            { search: 'p'+prefix, name: "#"+prefix+"_ca" }, // relation
	            { search: 'r'+prefix, name: "#"+prefix+"_car" },// read
	            { search: 'w'+prefix, name: "#"+prefix+"_caw" },// write
	            { search: 'a'+prefix, name: "#"+prefix+"_caa" } // automatic
	          ];

	$.each( options , function(i, obj)
	{
		if($(obj.name)) 
		{
			$(obj.name).change(function()
					{
						$(".box_"+prefix).find("input["+choice+"^='"+obj.search+"']").each(function()
						{
							if($(obj.name).attr('checked') == true && this.disabled == false) {
								this.checked = true;
							} else {
								this.checked = false;
							}
						});
					});
		}
	});
}



function generateZones(zones) {

    $("#region_zonechoice").addOption("", "Bitte Zone auswählen:");
    
    for(i in zones) {
        $("#unassociated_region_districts_list").addOption(i, zones[i], false);
        $("#region_zonechoice").addOption(i, zones[i], false);
    }
    
    $("#unassociated_region_districts_list").removeOption("-");
    $("#region_zonechoice").removeOption("-");
    
    removeAssignedZones();
}
function removeAssignedZones() 
{
    $('#region_districts_list option:enabled').each(function () { 
        $("#unassociated_region_districts_list").removeOption($(this).val());
    });
}

function removeAssignedLocalities() 
{
	$('#region_localities_list option:enabled').each(function () { 
		$("#unassociated_region_localities_list").removeOption($(this).val());
	});

	$("#unassociated_region_localities_list").removeOption("-");
	$("#unassociated_region_localities_list").removeAttr("disabled");  
	
	if($("#unassociated_region_localities_list option:enabled").length < 1){
		$("#unassociated_region_localities_list").addOption("-", "Keine Ortschaften vorhanden", false);
		$("#unassociated_region_localities_list").attr("disabled","disabled"); 
	}
}

function toggleChecksumOnLoad(name) {

	if ($(name)) 
	{
		if ($(name).val() == '2') {
			$(".sf_admin_form_field_mapchecksum").show();

		} else {

			$(".sf_admin_form_field_mapchecksum").hide();
		}
		
		$(name).change( function() 
		{
			if ($(name).val() == '2') {
				$(".sf_admin_form_field_mapchecksum").show();
	
			} else {
	
				$(".sf_admin_form_field_mapchecksum").hide();
			}
		});
	}
	
	return true;
}
function togglePluginDataOnLoad(name) {

	if ($(name).val()) 
	{

		if ($(name).val() == '0') {
			$("#sf_fieldset_bild").hide();
			$("#sf_fieldset_text").hide();
		}

		else if ($(name).val() == '1') {

			$("#sf_fieldset_bild").show();
			$("#sf_fieldset_text").hide();

		}

		else if ($(name).val() == '2') {
			$("#sf_fieldset_text").show();
			$("#sf_fieldset_bild").hide();

		}

		else  {
			$("#sf_fieldset_bild").hide();
			$("#sf_fieldset_text").hide();
		}
	
	}
	
	return true;
}


function togglePluginData(name) {

	if ($(name)) 
	{

		$(name).change( function() 
		{
			if ($(name).val() == '0') {
				$("#sf_fieldset_bild").hide();
				$("#sf_fieldset_text").hide();
			}

			else if ($(name).val() == '1') {
	
				$("#sf_fieldset_bild").show();
				$("#sf_fieldset_text").hide();
	
			}
	
			else if ($(name).val() == '2') {
				$("#sf_fieldset_bild").hide();
				$("#sf_fieldset_text").show();
	
			}
	
			else {
				$("#sf_fieldset_person").hide();
				$("#sf_fieldset_unternehmen").hide();
			}
		});
	}
	
	return true;
}



function toggleSpecsData(name) {

	if ($(name)) 
	{

		$(name).change( function() 
		{
			if ($(name).val() == '0') {
				$("#sf_fieldset_person").hide();
				$("#sf_fieldset_unternehmen").hide();
			}

			else if ($(name).val() == '1') {
	
				$("#sf_fieldset_person").show();
				$("#sf_fieldset_unternehmen").hide();
	
			}
	
			else if ($(name).val() == '2') {
				$("#sf_fieldset_person").show();
				$("#sf_fieldset_unternehmen").hide();
	
			}
	
			else if ($(name).val() == '3') {
				$("#sf_fieldset_person").hide();
				$("#sf_fieldset_unternehmen").show();
	
			}
	
			else {
	
				$("#sf_fieldset_person").show();
				$("#sf_fieldset_unternehmen").show();
	
			}
		});
	}
	
	return true;
}

function toggleSpecsDataOnLoad(name) {

	if ($(name)) 
	{

		if ($(name).val() == '0') {
			$("#sf_fieldset_person").hide();
			$("#sf_fieldset_unternehmen").hide();
		}

		else if ($(name).val() == '1') {

			$("#sf_fieldset_person").show();
			$("#sf_fieldset_unternehmen").hide();

		}

		else if ($(name).val() == '2') {
			$("#sf_fieldset_person").show();
			$("#sf_fieldset_unternehmen").hide();

		}

		else if ($(name).val() == '3') {
			$("#sf_fieldset_person").hide();
			$("#sf_fieldset_unternehmen").show();

		}
	
	}
	
	return true;
}



function pictureAssociate()
{
    $("td>input#contact_attachment_filename").hide();
    var cloneThumbnail = '<img class="thumbnail" id="insertedThumb" src="'+$('img.thumbnail').attr('src')+'" />';

    $('#associate_a_picture_id').change(function ()
    {
        if($('#associate_a_picture_id').attr('checked') == 1)
        {
            $('#associate_attachment_filename').val($('#contact_attachment_filename').val());
            $('#associate_attachment_title').val($('#contact_attachment_title').val());
            $('#associate_attachment_title').attr('readonly','readonly');
            $('#associate_attachment_source').val($('#contact_attachment_source').val());
            $('#associate_attachment_source').attr('readonly','readonly');
            $('#associate_attachment_copyright').val($('#contact_attachment_copyright').val());
            $('#associate_attachment_copyright').attr('readonly','readonly');
            $('#associate_attachment_description').val($('#contact_attachment_description').val());
            $('#associate_attachment_description').attr('readonly','readonly');
            $('#associate_attachment_id').val($('#contact_attachment_id').val());
            $("#associate_attachment_thumbnail").after(cloneThumbnail);
            $("#associate_attachment_thumbnail").remove();
        } else {
            $("#insertedThumb").after('<div id="associate_attachment_thumbnail">nicht verfügbar<\/div>');
            $("#insertedThumb").remove();

            $('#associate_attachment_title').removeAttr("readonly");
            $('#associate_attachment_source').removeAttr("readonly");
            $('#associate_attachment_copyright').removeAttr("readonly");
            $('#associate_attachment_description').removeAttr("readonly");
            $('#associate_attachment_id').removeAttr("value");
        }
    });
}

function featuredAssociate(name, from)
{

    /**
	 * Erstmal die Originaldaten als Readonly deklarieren
	 */
    if(!from)
    {
        $('#autocomplete_contact_'+name).attr('readonly','readonly');
        $('#contact_'+name).attr('readonly','readonly');
    } else {
        $('#autocomplete_contact_'+from).attr('readonly','readonly');
        $('#contact_'+from).attr('readonly','readonly');
    }

    /**
	 * Dann schauen wir mal ob das feld als invisible markiert ist und folglich
	 * das feld dann kennzeichnen.
	 */
    if($('#associate_i_'+name).attr('checked') == 1)
    {
        $('#associate_'+name).attr('style', 'background-color:#efefef; border:1px; margin:0; padding:1px;border: 1px solid #ddd;');
        $('#associate_'+name).attr('readonly','readonly');

        // selbige logischerweise auch mit autocomplete feldern
        if($('#autocomplete_associate_'+name))
    {
            $('#autocomplete_associate_'+name).attr('style', 'background-color:#efefef; border:1px; margin:0; padding:1px;border: 1px solid #ddd;');
            $('#autocomplete_associate_'+name).attr('readonly','readonly');
        }
    }

    /**
	 * Dann schauen wir gleich mal ob das automatisierungsfeld markiert ist und
	 * folglich das feld dann kennzeichnen.
	 */
    if($('#associate_a_'+name).attr('checked') == 1)
    {
        $('#associate_'+name).attr('readonly','readonly');

        // selbige logischerweise auch mit autocomplete feldern
        if($('#autocomplete_associate_'+name)) {
            $('#autocomplete_associate_'+name).attr('readonly','readonly');
        }
    }

    /**
	 * Nun folgt die abfrage und handlung für die automatische zuordnung eines
	 * feldes
	 */
    if($('#associate_a_'+name))
    {
        if(!from)
        {
            $('#associate_a_'+name).change(function ()
            {
              // wenn automatismus markiert wurde
              if($('#associate_a_'+name).attr('checked') == 1)
              {
                // Werte übernehmen
                // $('#associate_'+name).text($('#contact_'+name).text());
                $('#associate_'+name).val($('#contact_'+name).val());

                // und als readonly markieren
                $('#associate_'+name).attr('readonly','readonly');

                if($('#autocomplete_associate_'+name))
                {
                  $('#autocomplete_associate_'+name).val($('#autocomplete_contact_'+name).val());
                  $('#autocomplete_associate_'+name).attr('readonly','readonly');
                }
              }

              // wenn automatismus demarkiert wurde
              else
              {
                // felder wieder beschreibbar machen sofern nicht invisible
				// gewählt
                if($('#associate_i_'+name).attr('checked') == 0)
                {
                  // felder wieder beschreibbar machen
                  $("#associate_"+name).removeAttr("readonly");
                  if($('#autocomplete_associate_'+name))
                  {
                    $('#autocomplete_associate_'+name).removeAttr("readonly");
                  }
                }
              }
            });

        } else {

            $('#associate_a_'+name).change(function ()
            {
              // wenn automatismus markiert wurde
              if($('#associate_a_'+name).attr('checked') == 1)
              {
                // Werte übernehmen
                // $('#associate_'+name).text($('#contact_'+from).text());
                $('#associate_'+name).val($('#contact_'+from).val());

                // und als readonly markieren
                $('#associate_'+name).attr('readonly','readonly');

                if($('#autocomplete_associate_'+name))
                {
                  $('#autocomplete_associate_'+name).val($('#autocomplete_contact_'+from).val());
                  $('#autocomplete_associate_'+name).attr('readonly','readonly');
                }
              }

              // wenn automatismus demarkiert wurde
              else
              {
                // felder wieder beschreibbar machen sofern nicht invisible
				// gewählt
                if($('#associate_i_'+name).attr('checked') == 0)
                {
                  $("#associate_"+name).removeAttr("readonly");

                  // selbige auch für autocomplete felder

                          if($('#autocomplete_associate_'+name))
                    {
                        $('#autocomplete_associate_'+name).removeAttr("readonly");
                    }
                }
              }
            });
        }
    }


    /**
	 * Nun folgt die abfrage und handlung für die als invisible deklarierten
	 * daten
	 */
    if($('#associate_i_'+name))
    {
      $('#associate_i_'+name).change(function ()
      {
        // wenn automatismus markiert wurde
        if($('#associate_i_'+name).attr('checked') == 1)
        {
          // Feld dementsprechend markieren
          $('#associate_'+name).attr('style', 'background-color:#efefef; border:1px; margin:0; padding:1px;border: 1px solid #ddd;');

          // und als readonly markieren
          $('#associate_'+name).attr('readonly','readonly');

          // selbige auch für autocomplete felder
          if($('#autocomplete_associate_'+name))
          {
            $('#autocomplete_associate_'+name).attr('style', 'background-color:#efefef; border:1px; margin:0; padding:1px;border: 1px solid #ddd;');
            $('#autocomplete_associate_'+name).attr('readonly','readonly');
          }
        }

        // wenn automatismus demarkiert wurde
        else
        {
          // felder wieder beschreibbar machen sofern nicht automatismus
			// gewählt
          if($('#associate_a_'+name).attr('checked') == 0)
          {
            $("#associate_"+name).removeAttr("readonly");
          }

          // und stylische formatierung zurücksetzen
          $("#associate_"+name).attr('style', 'background-color:#FFFFFF;');

          // selbige auch für autocomplete felder
          if($('#autocomplete_associate_'+name))
          {
            $('#autocomplete_associate_'+name).attr('style', 'background-color:#FFFFFF;');

            if($('#associate_a_'+name).attr('checked') == 0)
            {
              $("#autocomplete_associate_"+name).removeAttr("readonly");
            }
          }
        }
      });
    }
}


function featuredAssociate2(name, from)
{
    /**
	 * Dann schauen wir gleich mal ob das automatisierungsfeld markiert ist und
	 * folglich das feld dann kennzeichnen.
	 */
    if($('#associate_a_'+name).attr('checked') == 1)
    {
        $('#associate_'+name).attr('readonly','readonly');
    } 

    $('#associate_a_'+name).change(function ()
    {
      // wenn automatismus markiert wurde
      if($('#associate_a_'+name).attr('checked') == 1)
      {
        // Werte übernehmen
        // $('#associate_'+name).text($('#contact_'+from).text());
        $('#associate_'+name).val($('#contact_'+from).val());

        // und als readonly markieren
        $('#associate_'+name).attr('readonly','readonly');

        if($('#autocomplete_associate_'+name))
        {
          $('#autocomplete_associate_'+name).val($('#autocomplete_contact_'+from).val());
          $('#autocomplete_associate_'+name).attr('readonly','readonly');
        }
      }

      // wenn automatismus demarkiert wurde
      else
      {
        $("#associate_"+name).removeAttr("readonly");
      }
    });
}

function viewbar(id) {
  $('#'+id).css('visibility', 'visible');
}

function hidebar(id) {
  $('#'+id).css('visibility', 'hidden');
}

function showFilter() 
{
  $('#sf_filter_show').click(function(){
    $('td.tdleft').show();
    $('.sf_admin_action_filter_show').hide();
    $('.sf_admin_action_filter_hide').show();
  });
}

function hideFilter() 
{
  $('#sf_filter_hide').click(function(){
    $('td.tdleft').hide();
    $('.sf_admin_action_filter_show').show();
    $('.sf_admin_action_filter_hide').hide();
  });
}
var MAX_DUMP_DEPTH = 10;



       function dumpObj(obj, name, indent, depth) {

              if (depth > MAX_DUMP_DEPTH) {

                     return indent + name + ": <Maximum Depth Reached>\n";

              }

              if (typeof obj == "object") {

                     var child = null;

                     var output = indent + name + "\n";

                     indent += "\t";

                     for (var item in obj)

                     {

                           try {

                                  child = obj[item];

                           } catch (e) {

                                  child = "<Unable to Evaluate>";

                           }

                           if (typeof child == "object") {

                                  output += dumpObj(child, item, indent, depth + 1);

                           } else {

                                  output += indent + item + ": " + child + "\n";

                           }

                     }

                     return output;

              } else {

                     return obj;

              }

       }


    function showPerson(client, id)
    {
        var html = $.ajax({
          url: "/contact/pinfo/client/"+client+"?id="+id,
          async: false,
          beforeSend : function(xhr) {$("#pinfo").html('<p><img src="/images/indicator.gif" /> Daten werden geladen.</p>');}
         }).responseText;

        $("#pinfo").html(html);
        $("#nameinfo").text("Informationen über "+ $("#infoname").text());
        $("#nameinfo").parent().show();
    }
