

function suggest_format_item(item) {
	if (item.type=='head') {
		return '<div class="suggest-group ' + item.subclass + '">' + item.name + ((item.count) ? '' : '') + '</div>';
	} else if (item.type=='category') {
		return '<div class="suggest-entry category">' + item.name + '</div>';
	} else {
		return '<div class="suggest-entry tag">' + item.name + '</div>';
	}
}

function replaceUmlaute(string){
	var anArray = new Array(2);
	anArray[0] = new Array("ö", "ä", "ü", "ß", "&", ",", " ");
	anArray[1] = new Array("oe", "ae", "ue", "sz", "und", "", "-");

	for (var i=0; i<anArray[0].length; i++){
		myRegExp = new RegExp(anArray[0][i],"g");
		string = string.replace(myRegExp, anArray[1][i]);
	}
	return string;
}

function doSearch() {
	if ($("#search-in-category").val() == 1) {
		newLocation = replaceUmlaute($("#search-what-dir").val()).toLowerCase();
		if($("#search-where-dir").val() != "" && $("#search-where-dir").val() != $("#search-where-dir")[0].defaultValue) {
			newLocation = newLocation + "/" + replaceUmlaute($("#search-where-dir").val()).toLowerCase();
		}
		location.href = "/" + newLocation;
		return false;
	} else {
		return true;
	}
}

function doChange() {
	$("#search-in-category").val(0);
	return false;
}

function generateDynamicHeaderParts() {
	//setup search provider url
	if (_headerstate.main == 'directory') {
		$('#header-search').html(_headersearchdir);
	} else if (_headerstate.main == 'marketplace') {
		$('#header-search').html(_headersearchmp);
	}
	//link setzen
	if (_headerstate.user_role == 'AN'){
		$('#subtab-help').attr({href: "/howItWorks/howItWorks_an.php"});
	}

	//set up greeting text, login text and show up teaser button
	if(_headerstate.user_name) {
		$("#header-login-state").html(_headerdata.GREETINGS.replace('_USERNAME_', _headerstate.user_name));
		$("#header-login-text").html(_headerdata.LOGIN_STATUS);
		if(_headerstate.user_reg == '-1') {
			$("#teaser_activate_account").show();
		} else {
			if (_headerstate.main == 'directory') {
				if (_headerstate.user_role == 'AG') {
					$("#teaser_dir_login_ag").show();
				} else if (_headerstate.user_role == 'AN') {

					switch (_headerstate.user_level) {
						case 'BUSINESS':
							if (!_headerstate.user_reg) {
								$("#teaser_dir_login_an_business_reg0").show();
							} else {
								if(_headerstate.user_reg == '1') {
									$("#teaser_dir_login_an_business_reg0").show();
								} else if(_headerstate.user_reg == '2') {
									// kein Teaser wenn user_level = BUSINESS und user_reg = 2
								}
							}
							break;
						case 'PRO':
							$("#teaser_dir_login_an_pro").show();
							break;
						case 'BASE':
							$("#teaser_dir_login_an_base").show();
							break;
						default:
							$("#teaser_dir_login_an_base").show();
							break;
					}
				}
			} else if (_headerstate.main == 'marketplace') {
				if (_headerstate.user_role == 'AG') {
					if (_headerstate.user_reg) {
						$("#teaser_mp_login_ag_reqs").show();
					} else {
						$("#teaser_mp_login_ag_noreqs").show();
					}
				} else if (_headerstate.user_role == 'AN') {
					switch (_headerstate.user_level) {
						case 'BUSINESS':
							if (!_headerstate.user_reg) {
								$("#teaser_mp_login_an_business_reg0").show();
							} else {
								if(_headerstate.user_reg == '1') {
									$("#teaser_mp_login_an_business_reg0").show();
								} else if(_headerstate.user_reg == '2') {
									// kein Teaser wenn user_level = BUSINESS und user_reg = 2
								}
							}
							break;
						case 'PRO':
							$("#teaser_mp_login_an_pro").show();
							break;
						case 'BASE':
							$("#teaser_mp_login_an_base").show();
							break;
						default:
							$("#teaser_mp_login_an_base").show();
							break;
					}
				}
			}
		}
	} else {
		$("#header-login-state").html(_headerdata.GREETINGS.replace('_USERNAME_', _headerdata.GUEST));
		$("#header-login-text").html(_headerdata.LOGIN_REGISTER);
		if(_headerstate.user_reg == '-1') {
			$("#teaser_activate_account").show();
		} else {
			if (_headerstate.main == 'directory') {
				$("#teaser_dir_nologin").show();
			} else {
				$("#teaser_mp_nologin").show();
			}
		}
	}
	//remove flag of active language
	if(_headerstate.lid && $("#header-lang-" + _headerstate.lid).length) {
		$("#header-lang-"+ _headerstate.lid).css('display', 'none');
	}
	//set active main tab
	if(_headerstate.main) {
		$("#header-tabs .header-tabs-selected").removeClass('header-tabs-selected');
		$("#tab-" + _headerstate.main).addClass('header-tabs-selected')
	}
	//set active sub tab
	if(_headerstate.sub) {
		$(".subtab .selected").removeClass('selected');
		$("#subtab-" + _headerstate.sub).addClass('selected')
	}

	$("#header-search .input-text").focus(function() {
        $(this).addClass("aktiv");
        if ($(this).val() == this.defaultValue) {
        	$(this).val("");
		};
        }).blur(function() {
           if ($(this).val() == "") {
               $(this).val(this.defaultValue);
               $(this).removeClass("aktiv");
           }
	});

	$("#header-search-marketplace, #header-search-directory").submit(function(){
		$("#header-search .input-text").each(function(){
			if ($(this).val() == this.defaultValue) {
				$(this).val("");
			};
		});
	});


	if (_headerstate.main == 'directory') {
		$(".input-what").autocomplete('/ajax/inline-search.php', {
			extraParams: {method: 'categories'},
			width: '213px',
			scroll: false,
			cacheLength: 20,
			max: 20,
			parse: function(response) {
				var data = eval("(" + response + ")");
				var list=[];
				if (data.errno==0) {
					if (data.result.categories && data.result.categories.total>=0 && data.result.categories.data.length) {
						list.push({data: {type: 'head', name: _headerdata.DIRECTORY_DROPDOWN_LABEL_CATEGORIES, subclass: 'suggest-group-blue', count: data.result.categories.data.length, total: data.result.categories.total}, value: ''});
						for(var i=0;i<data.result.categories.data.length;i++) {
							list.push({data: {type: 'category', name: data.result.categories.data[i]}, value: data.result.categories.data[i], result: data.result.categories.data[i], cat: 1});
						}
					}
					if (data.result.tags && data.result.tags.total>=0 && data.result.tags.data.length) {
						list.push({data: {type: 'head', name: _headerdata.DIRECTORY_DROPDOWN_LABEL_TAGS, subclass: 'suggest-group-blue', count: data.result.tags.data.length, total: data.result.tags.total}, value: ''});
						for(var i=0;i<data.result.tags.data.length;i++) {
							list.push({data: {type: 'tag', name: data.result.tags.data[i]}, value: data.result.tags.data[i], result: data.result.tags.data[i], cat: 0});
						}
					}
				} else {
					//alert(data.error);
				}
				return list;
			},
			formatItem: function(item) {
				return suggest_format_item(item);
			}
		});
		$(".input-where").autocomplete('/ajax/inline-search.php', {
			extraParams: {method: 'cities'},
			width: '159px',
			scroll: false,
			cacheLength: 20,
			max: 20,
			parse: function(response) {
				var data = eval("(" + response + ")");
				var list=[];
				if (data.errno==0) {
					if (data.result.cities && data.result.cities.total>=0 && data.result.cities.data.length) {
						list.push({data: {type: 'head', name: _headerdata.DIRECTORY_DROPDOWN_LABEL_CITIES, subclass: 'suggest-group-orange'}, value: ''});
						for(var i=0;i<data.result.cities.data.length;i++) {
							list.push({data: {type: 'entry', name: data.result.cities.data[i]}, value: data.result.cities.data[i], result: data.result.cities.data[i]});
						}
					}
					if (data.result.streets && data.result.streets.total>=0 && data.result.streets.data.length) {
						list.push({data: {type: 'head', name: _headerdata.DIRECTORY_DROPDOWN_LABEL_STREETS, subclass: 'suggest-group-orange'}, value: ''});
						for(var i=0;i<data.result.streets.data.length;i++) {
							list.push({data: {type: 'entry', name: data.result.streets.data[i]}, value: data.result.streets.data[i], result: data.result.streets.data[i]});
						}
					}
				} else {
					//alert(data.error);
				}
				return list;
			},
			formatItem: function(item) {
				return suggest_format_item(item);
			}
		});
	}
}

/*
 * jQuery Form Plugin
 * version: 2.16 (17-OCT-2008)
 * @requires jQuery v1.2.2 or later
 *
 * Examples and documentation at: http://malsup.com/jquery/form/
 * 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.form.js,v 1.1 2008/10/29 11:18:13 thomas Exp $
 */
;(function($) {

/*
    Usage Note:  
    -----------
    Do not use both ajaxSubmit and ajaxForm on the same form.  These
    functions are intended to be exclusive.  Use ajaxSubmit if you want
    to bind your own submit handler to the form.  For example,

    $(document).ready(function() {
        $('#myForm').bind('submit', function() {
            $(this).ajaxSubmit({
                target: '#output'
            });
            return false; // <-- important!
        });
    });

    Use ajaxForm when you want the plugin to manage all the event binding
    for you.  For example,

    $(document).ready(function() {
        $('#myForm').ajaxForm({
            target: '#output'
        });
    });
        
    When using ajaxForm, the ajaxSubmit function will be invoked for you
    at the appropriate time.  
*/

/**
 * ajaxSubmit() provides a mechanism for immediately submitting 
 * an HTML form using AJAX.
 */
$.fn.ajaxSubmit = function(options) {
    // fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
    if (!this.length) {
        log('ajaxSubmit: skipping submit process - no element selected');
        return this;
    }

    if (typeof options == 'function')
        options = { success: options };

    options = $.extend({
        url:  this.attr('action') || window.location.toString(),
        type: this.attr('method') || 'GET'
    }, options || {});

    // hook for manipulating the form data before it is extracted;
    // convenient for use with rich editors like tinyMCE or FCKEditor
    var veto = {};
    this.trigger('form-pre-serialize', [this, options, veto]);
    if (veto.veto) {
        log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
        return this;
   }

    var a = this.formToArray(options.semantic);
    if (options.data) {
        options.extraData = options.data;
        for (var n in options.data) {
          if(options.data[n] instanceof Array) {
            for (var k in options.data[n])
              a.push( { name: n, value: options.data[n][k] } )
          }  
          else
             a.push( { name: n, value: options.data[n] } );
        }
    }

    // give pre-submit callback an opportunity to abort the submit
    if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
        log('ajaxSubmit: submit aborted via beforeSubmit callback');
        return this;
    }    

    // fire vetoable 'validate' event
    this.trigger('form-submit-validate', [a, this, options, veto]);
    if (veto.veto) {
        log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
        return this;
    }    

    var q = $.param(a);

    if (options.type.toUpperCase() == 'GET') {
        options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
        options.data = null;  // data is null for 'get'
    }
    else
        options.data = q; // data is the query string for 'post'

    var $form = this, callbacks = [];
    if (options.resetForm) callbacks.push(function() { $form.resetForm(); });
    if (options.clearForm) callbacks.push(function() { $form.clearForm(); });

    // perform a load on the target only if dataType is not provided
    if (!options.dataType && options.target) {
        var oldSuccess = options.success || function(){};
        callbacks.push(function(data) {
            $(options.target).html(data).each(oldSuccess, arguments);
        });
    }
    else if (options.success)
        callbacks.push(options.success);

    options.success = function(data, status) {
        for (var i=0, max=callbacks.length; i < max; i++)
            callbacks[i].apply(options, [data, status, $form]);
    };

    // are there files to upload?
    var files = $('input:file', this).fieldValue();
    var found = false;
    for (var j=0; j < files.length; j++)
        if (files[j])
            found = true;

    // options.iframe allows user to force iframe mode
   if (options.iframe || found) { 
       // hack to fix Safari hang (thanks to Tim Molendijk for this)
       // see:  http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
       if ($.browser.safari && options.closeKeepAlive)
           $.get(options.closeKeepAlive, fileUpload);
       else
           fileUpload();
       }
   else
       $.ajax(options);

    // fire 'notify' event
    this.trigger('form-submit-notify', [this, options]);
    return this;


    // private function for handling file uploads (hat tip to YAHOO!)
    function fileUpload() {
        var form = $form[0];
        
        if ($(':input[name=submit]', form).length) {
            alert('Error: Form elements must not be named "submit".');
            return;
        }
        
        var opts = $.extend({}, $.ajaxSettings, options);
		var s = jQuery.extend(true, {}, $.extend(true, {}, $.ajaxSettings), opts);

        var id = 'jqFormIO' + (new Date().getTime());
        var $io = $('<iframe id="' + id + '" name="' + id + '" />');
        var io = $io[0];

        if ($.browser.msie || $.browser.opera) 
            io.src = 'javascript:false;document.write("");';
        $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });

        var xhr = { // mock object
            aborted: 0,
            responseText: null,
            responseXML: null,
            status: 0,
            statusText: 'n/a',
            getAllResponseHeaders: function() {},
            getResponseHeader: function() {},
            setRequestHeader: function() {},
            abort: function() { 
                this.aborted = 1; 
                $io.attr('src','about:blank'); // abort op in progress
            }
        };

        var g = opts.global;
        // trigger ajax global events so that activity/block indicators work like normal
        if (g && ! $.active++) $.event.trigger("ajaxStart");
        if (g) $.event.trigger("ajaxSend", [xhr, opts]);

		if (s.beforeSend && s.beforeSend(xhr, s) === false) {
			s.global && jQuery.active--;
			return;
        }
        if (xhr.aborted)
            return;
        
        var cbInvoked = 0;
        var timedOut = 0;

        // add submitting element to data if we know it
        var sub = form.clk;
        if (sub) {
            var n = sub.name;
            if (n && !sub.disabled) {
                options.extraData = options.extraData || {};
                options.extraData[n] = sub.value;
                if (sub.type == "image") {
                    options.extraData[name+'.x'] = form.clk_x;
                    options.extraData[name+'.y'] = form.clk_y;
                }
            }
        }

        // take a breath so that pending repaints get some cpu time before the upload starts
        setTimeout(function() {
            // make sure form attrs are set
            var t = $form.attr('target'), a = $form.attr('action');
            $form.attr({
                target:   id,
                method:   'POST',
                action:   opts.url
            });
            
            // ie borks in some cases when setting encoding
            if (! options.skipEncodingOverride) {
                $form.attr({
                    encoding: 'multipart/form-data',
                    enctype:  'multipart/form-data'
                });
            }

            // support timout
            if (opts.timeout)
                setTimeout(function() { timedOut = true; cb(); }, opts.timeout);

            // add "extra" data to form if provided in options
            var extraInputs = [];
            try {
                if (options.extraData)
                    for (var n in options.extraData)
                        extraInputs.push(
                            $('<input type="hidden" name="'+n+'" value="'+options.extraData[n]+'" />')
                                .appendTo(form)[0]);
            
                // add iframe to doc and submit the form
                $io.appendTo('body');
                io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
                form.submit();
            }
            finally {
                // reset attrs and remove "extra" input elements
                $form.attr('action', a);
                t ? $form.attr('target', t) : $form.removeAttr('target');
                $(extraInputs).remove();
            }
        }, 10);

        function cb() {
            if (cbInvoked++) return;
            
            io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);

            var operaHack = 0;
            var ok = true;
            try {
                if (timedOut) throw 'timeout';
                // extract the server response from the iframe
                var data, doc;

                doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
                
                if (doc.body == null && !operaHack && $.browser.opera) {
                    // In Opera 9.2.x the iframe DOM is not always traversable when
                    // the onload callback fires so we give Opera 100ms to right itself
                    operaHack = 1;
                    cbInvoked--;
                    setTimeout(cb, 100);
                    return;
                }
                
                xhr.responseText = doc.body ? doc.body.innerHTML : null;
                xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
                xhr.getResponseHeader = function(header){
                    var headers = {'content-type': opts.dataType};
                    return headers[header];
                };

                if (opts.dataType == 'json' || opts.dataType == 'script') {
                    var ta = doc.getElementsByTagName('textarea')[0];
                    xhr.responseText = ta ? ta.value : xhr.responseText;
                }
                else if (opts.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
                    xhr.responseXML = toXml(xhr.responseText);
                }
                data = $.httpData(xhr, opts.dataType);
            }
            catch(e){
                ok = false;
                $.handleError(opts, xhr, 'error', e);
            }

            // ordering of these callbacks/triggers is odd, but that's how $.ajax does it
            if (ok) {
                opts.success(data, 'success');
                if (g) $.event.trigger("ajaxSuccess", [xhr, opts]);
            }
            if (g) $.event.trigger("ajaxComplete", [xhr, opts]);
            if (g && ! --$.active) $.event.trigger("ajaxStop");
            if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error');

            // clean up
            setTimeout(function() {
                $io.remove();
                xhr.responseXML = null;
            }, 100);
        };

        function toXml(s, doc) {
            if (window.ActiveXObject) {
                doc = new ActiveXObject('Microsoft.XMLDOM');
                doc.async = 'false';
                doc.loadXML(s);
            }
            else
                doc = (new DOMParser()).parseFromString(s, 'text/xml');
            return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null;
        };
    };
};

/**
 * ajaxForm() provides a mechanism for fully automating form submission.
 *
 * The advantages of using this method instead of ajaxSubmit() are:
 *
 * 1: This method will include coordinates for <input type="image" /> elements (if the element
 *    is used to submit the form).
 * 2. This method will include the submit element's name/value data (for the element that was
 *    used to submit the form).
 * 3. This method binds the submit() method to the form for you.
 *
 * The options argument for ajaxForm works exactly as it does for ajaxSubmit.  ajaxForm merely
 * passes the options argument along after properly binding events for submit elements and
 * the form itself.
 */ 
$.fn.ajaxForm = function(options) {
    return this.ajaxFormUnbind().bind('submit.form-plugin',function() {
        $(this).ajaxSubmit(options);
        return false;
    }).each(function() {
        // store options in hash
        $(":submit,input:image", this).bind('click.form-plugin',function(e) {
            var form = this.form;
            form.clk = this;
            if (this.type == 'image') {
                if (e.offsetX != undefined) {
                    form.clk_x = e.offsetX;
                    form.clk_y = e.offsetY;
                } else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
                    var offset = $(this).offset();
                    form.clk_x = e.pageX - offset.left;
                    form.clk_y = e.pageY - offset.top;
                } else {
                    form.clk_x = e.pageX - this.offsetLeft;
                    form.clk_y = e.pageY - this.offsetTop;
                }
            }
            // clear form vars
            setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 10);
        });
    });
};

// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
$.fn.ajaxFormUnbind = function() {
    this.unbind('submit.form-plugin');
    return this.each(function() {
        $(":submit,input:image", this).unbind('click.form-plugin');
    });

};

/**
 * formToArray() gathers form element data into an array of objects that can
 * be passed to any of the following ajax functions: $.get, $.post, or load.
 * Each object in the array has both a 'name' and 'value' property.  An example of
 * an array for a simple login form might be:
 *
 * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
 *
 * It is this array that is passed to pre-submit callback functions provided to the
 * ajaxSubmit() and ajaxForm() methods.
 */
$.fn.formToArray = function(semantic) {
    var a = [];
    if (this.length == 0) return a;

    var form = this[0];
    var els = semantic ? form.getElementsByTagName('*') : form.elements;
    if (!els) return a;
    for(var i=0, max=els.length; i < max; i++) {
        var el = els[i];
        var n = el.name;
        if (!n) continue;

        if (semantic && form.clk && el.type == "image") {
            // handle image inputs on the fly when semantic == true
            if(!el.disabled && form.clk == el)
                a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
            continue;
        }

        var v = $.fieldValue(el, true);
        if (v && v.constructor == Array) {
            for(var j=0, jmax=v.length; j < jmax; j++)
                a.push({name: n, value: v[j]});
        }
        else if (v !== null && typeof v != 'undefined')
            a.push({name: n, value: v});
    }

    if (!semantic && form.clk) {
        // input type=='image' are not found in elements array! handle them here
        var inputs = form.getElementsByTagName("input");
        for(var i=0, max=inputs.length; i < max; i++) {
            var input = inputs[i];
            var n = input.name;
            if(n && !input.disabled && input.type == "image" && form.clk == input)
                a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
        }
    }
    return a;
};

/**
 * Serializes form data into a 'submittable' string. This method will return a string
 * in the format: name1=value1&amp;name2=value2
 */
$.fn.formSerialize = function(semantic) {
    //hand off to jQuery.param for proper encoding
    return $.param(this.formToArray(semantic));
};

/**
 * Serializes all field elements in the jQuery object into a query string.
 * This method will return a string in the format: name1=value1&amp;name2=value2
 */
$.fn.fieldSerialize = function(successful) {
    var a = [];
    this.each(function() {
        var n = this.name;
        if (!n) return;
        var v = $.fieldValue(this, successful);
        if (v && v.constructor == Array) {
            for (var i=0,max=v.length; i < max; i++)
                a.push({name: n, value: v[i]});
        }
        else if (v !== null && typeof v != 'undefined')
            a.push({name: this.name, value: v});
    });
    //hand off to jQuery.param for proper encoding
    return $.param(a);
};

/**
 * Returns the value(s) of the element in the matched set.  For example, consider the following form:
 *
 *  <form><fieldset>
 *      <input name="A" type="text" />
 *      <input name="A" type="text" />
 *      <input name="B" type="checkbox" value="B1" />
 *      <input name="B" type="checkbox" value="B2"/>
 *      <input name="C" type="radio" value="C1" />
 *      <input name="C" type="radio" value="C2" />
 *  </fieldset></form>
 *
 *  var v = $(':text').fieldValue();
 *  // if no values are entered into the text inputs
 *  v == ['','']
 *  // if values entered into the text inputs are 'foo' and 'bar'
 *  v == ['foo','bar']
 *
 *  var v = $(':checkbox').fieldValue();
 *  // if neither checkbox is checked
 *  v === undefined
 *  // if both checkboxes are checked
 *  v == ['B1', 'B2']
 *
 *  var v = $(':radio').fieldValue();
 *  // if neither radio is checked
 *  v === undefined
 *  // if first radio is checked
 *  v == ['C1']
 *
 * The successful argument controls whether or not the field element must be 'successful'
 * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
 * The default value of the successful argument is true.  If this value is false the value(s)
 * for each element is returned.
 *
 * Note: This method *always* returns an array.  If no valid value can be determined the
 *       array will be empty, otherwise it will contain one or more values.
 */
$.fn.fieldValue = function(successful) {
    for (var val=[], i=0, max=this.length; i < max; i++) {
        var el = this[i];
        var v = $.fieldValue(el, successful);
        if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
            continue;
        v.constructor == Array ? $.merge(val, v) : val.push(v);
    }
    return val;
};

/**
 * Returns the value of the field element.
 */
$.fieldValue = function(el, successful) {
    var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
    if (typeof successful == 'undefined') successful = true;

    if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
        (t == 'checkbox' || t == 'radio') && !el.checked ||
        (t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
        tag == 'select' && el.selectedIndex == -1))
            return null;

    if (tag == 'select') {
        var index = el.selectedIndex;
        if (index < 0) return null;
        var a = [], ops = el.options;
        var one = (t == 'select-one');
        var max = (one ? index+1 : ops.length);
        for(var i=(one ? index : 0); i < max; i++) {
            var op = ops[i];
            if (op.selected) {
                // extra pain for IE...
                var v = $.browser.msie && !(op.attributes['value'].specified) ? op.text : op.value;
                if (one) return v;
                a.push(v);
            }
        }
        return a;
    }
    return el.value;
};

/**
 * Clears the form data.  Takes the following actions on the form's input fields:
 *  - input text fields will have their 'value' property set to the empty string
 *  - select elements will have their 'selectedIndex' property set to -1
 *  - checkbox and radio inputs will have their 'checked' property set to false
 *  - inputs of type submit, button, reset, and hidden will *not* be effected
 *  - button elements will *not* be effected
 */
$.fn.clearForm = function() {
    return this.each(function() {
        $('input,select,textarea', this).clearFields();
    });
};

/**
 * Clears the selected form elements.
 */
$.fn.clearFields = $.fn.clearInputs = function() {
    return this.each(function() {
        var t = this.type, tag = this.tagName.toLowerCase();
        if (t == 'text' || t == 'password' || tag == 'textarea')
            this.value = '';
        else if (t == 'checkbox' || t == 'radio')
            this.checked = false;
        else if (tag == 'select')
            this.selectedIndex = -1;
    });
};

/**
 * Resets the form data.  Causes all form elements to be reset to their original value.
 */
$.fn.resetForm = function() {
    return this.each(function() {
        // guard against an input with the name of 'reset'
        // note that IE reports the reset function as an 'object'
        if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
            this.reset();
    });
};

/**
 * Enables or disables any matching elements.
 */
$.fn.enable = function(b) { 
    if (b == undefined) b = true;
    return this.each(function() { 
        this.disabled = !b 
    });
};

/**
 * Checks/unchecks any matching checkboxes or radio buttons and
 * selects/deselects and matching option elements.
 */
$.fn.selected = function(select) {
    if (select == undefined) select = true;
    return this.each(function() { 
        var t = this.type;
        if (t == 'checkbox' || t == 'radio')
            this.checked = select;
        else if (this.tagName.toLowerCase() == 'option') {
            var $sel = $(this).parent('select');
            if (select && $sel[0] && $sel[0].type == 'select-one') {
                // deselect all other options
                $sel.find('option').selected(false);
            }
            this.selected = select;
        }
    });
};

// helper fn for console logging
// set $.fn.ajaxSubmit.debug to true to enable debug logging
function log() {
    if ($.fn.ajaxSubmit.debug && window.console && window.console.log)
        window.console.log('[jquery.form] ' + Array.prototype.join.call(arguments,''));
};

})(jQuery);


/**
*
*  AJAX IFRAME METHOD (AIM)
*  http://www.webtoolkit.info/
*
**/

AIM = {

	frame : function(c) {

		var n = 'f' + Math.floor(Math.random() * 99999);
		var d = document.createElement('DIV');
		d.innerHTML = '<iframe style="display:none; width:800px; height:400px; border: 1px solid red;" src="about:blank" id="'+n+'" name="'+n+'" onload="AIM.loaded(\''+n+'\')"></iframe>';
		document.body.appendChild(d);

		var i = document.getElementById(n);
		if (c && typeof(c.onComplete) == 'function') {
			i.onComplete = c.onComplete;
		}

		return n;
	},

	form : function(f, name) {
		f.setAttribute('target', name);
	},

	submit : function(f, c) {
		AIM.form(f, AIM.frame(c));
		if (c && typeof(c.onStart) == 'function') {
			return c.onStart();
		} else {
			return true;
		}
	},

	loaded : function(id) {
		var i = document.getElementById(id);
		if (i.contentDocument) {
			var d = i.contentDocument;
		} else if (i.contentWindow) {
			var d = i.contentWindow.document;
		} else {
			var d = window.frames[id].document;
		}
		if (d.location.href == "about:blank") {
			return;
		}

		if (typeof(i.onComplete) == 'function') {
			i.onComplete(d.body.innerHTML, id);
		}
	}

}

//-----------------Start----------------//
//- Low Pro port to jQuery by Dan Webb -//
//--------------------------------------//
;(function($) {
  
  var addMethods = function(source) {
    var ancestor   = this.superclass && this.superclass.prototype;
    var properties = $.keys(source);

    if (!$.keys({ toString: true }).length) properties.push("toString", "valueOf");

    for (var i = 0, length = properties.length; i < length; i++) {
      var property = properties[i], value = source[property];
      if (ancestor && $.isFunction(value) && $.argumentNames(value)[0] == "$super") {
        
        var method = value, value = $.extend($.wrap((function(m) {
          return function() { return ancestor[m].apply(this, arguments) };
        })(property), method), {
          valueOf:  function() { return method },
          toString: function() { return method.toString() }
        });
      }
      this.prototype[property] = value;
    }

    return this;
  }
  
  $.extend({
    keys: function(obj) {
      var keys = [];
      for (var key in obj) keys.push(key);
      return keys;
    },

    argumentNames: function(func) {
      var names = func.toString().match(/^[\s\(]*function[^(]*\((.*?)\)/)[1].split(/, ?/);
      return names.length == 1 && !names[0] ? [] : names;
    },

    bind: function(func, scope) {
      return function() {
        return func.apply(scope, $.makeArray(arguments));
      }
    },

    wrap: function(func, wrapper) {
      var __method = func;
      return function() {
        return wrapper.apply(this, [$.bind(__method, this)].concat($.makeArray(arguments)));
      }
    },
    
    klass: function() {
      var parent = null, properties = $.makeArray(arguments);
      if ($.isFunction(properties[0])) parent = properties.shift();

      var klass = function() { 
        this.initialize.apply(this, arguments);
      };

      klass.superclass = parent;
      klass.subclasses = [];
      klass.addMethods = addMethods;

      if (parent) {
        var subclass = function() { };
        subclass.prototype = parent.prototype;
        klass.prototype = new subclass;
        parent.subclasses.push(klass);
      }

      for (var i = 0; i < properties.length; i++)
        klass.addMethods(properties[i]);

      if (!klass.prototype.initialize)
        klass.prototype.initialize = function() {};

      klass.prototype.constructor = klass;

      return klass;
    },
    delegate: function(rules) {
      return function(e) {
        var target = $(e.target), parent = null;
        for (var selector in rules) {
          if (target.is(selector) || ((parent = target.parents(selector)) && parent.length > 0)) {
            return rules[selector].apply(this, [parent || target].concat($.makeArray(arguments)));
          }
          parent = null;
        }
      }
    }
  });
  
  var bindEvents = function(instance) {
    for (var member in instance) {
      if (member.match(/^on(.+)/) && typeof instance[member] == 'function') {
        instance.element.bind(RegExp.$1, $.bind(instance[member], instance));
      }
    }
  }
  
  var behaviorWrapper = function(behavior) {
    return $.klass(behavior, {
      initialize: function($super, element, args) {
        this.element = $(element);
        if ($super) $super.apply(this, args);
      }
    });
  }
  
  var attachBehavior = function(el, behavior, args) {
      var wrapper = behaviorWrapper(behavior);
      instance = new wrapper(el, args);

      bindEvents(instance);

      if (!behavior.instances) behavior.instances = [];

      behavior.instances.push(instance);
      
      return instance;
  };
  
  
  $.fn.extend({
    attach: function() {
      var args = $.makeArray(arguments), behavior = args.shift();
      
      if ($.livequery && this.selector) {
        return this.livequery(function() {
          attachBehavior(this, behavior, args);
        });
      } else {
        return this.each(function() {
          attachBehavior(this, behavior, args);
        });
      }
    },
    attachAndReturn: function() {
      var args = $.makeArray(arguments), behavior = args.shift();
      
      return $.map(this, function(el) {
        return attachBehavior(el, behavior, args);
      });
    },
    delegate: function(type, rules) {
      return this.bind(type, $.delegate(rules));
    },
    attached: function(behavior) {
      var instances = [];
      
      if (!behavior.instances) return instances;
      
      this.each(function(i, element) {
        $.each(behavior.instances, function(i, instance) {
          if (instance.element.get(0) == element) instances.push(instance);
        });
      });
      
      return instances;
    },
    firstAttached: function(behavior) {
      return this.attached(behavior)[0];
    }
  });
  
  Remote = $.klass({
    initialize: function(options) {
      if (this.element.attr('nodeName') == 'FORM') this.element.attach(Remote.Form, options);
      else this.element.attach(Remote.Link, options);
    }
  });
  
  Remote.Base = $.klass({
    initialize : function(options) {
      this.options = $.extend({
        
      }, options || {});
    },
    _makeRequest : function(options) {
      $.ajax(options);
      return false;
    }
  });
  
  Remote.Link = $.klass(Remote.Base, {
    onclick: function() {
      var options = $.extend({ url: this.element.attr('href'), type: 'GET' }, this.options);
      return this._makeRequest(options);
    }
  });
  
  Remote.Form = $.klass(Remote.Base, {
    onclick: function(e) {
      var target = e.target;
      
      if ($.inArray(target.nodeName.toLowerCase(), ['input', 'button']) >= 0 && target.type.match(/submit|image/))
        this._submitButton = target;
    },
    onsubmit: function() {
      var data = this.element.serializeArray();
      
      if (this._submitButton) data.push({ name: this._submitButton.name, value: this._submitButton.value });
      
      var options = $.extend({
        url : this.element.attr('action'),
        type : this.element.attr('method') || 'GET',
        data : data
      }, this.options);
      
      this._makeRequest(options);
      
      return false;
    }
  });
  
  $.ajaxSetup({ 
    beforeSend: function(xhr) {
      xhr.setRequestHeader("Accept", "text/javascript, text/html, application/xml, text/xml, */*");
    } 
  });
  
})(jQuery);
//------------------End-----------------//
//-Dan Webb's port of Low Pro to jQuery-//
//--------------------------------------//


//-----------------Start----------------//
//- InTradeSys dependencieModel:Basics -//
//--------------------------------------//

var formElement = $.klass
(
	{
		initialize: function (type, refobject, name)
		{
			this.setType(type ? type : 'formElement');
			this.setReferenceObject(refobject);
			this.setName(name);
		},
		
		setReferenceObject: function (refobject)
		{
			if (typeof refobject != 'undefined')
			{
				if (typeof refobject[0] != 'undefined')
				{
					this.setDomNode(refobject[0]);
				}
				else
				{
					this.setDomNode(refobject);
				}
			}
		},		
		
		setType: function (type)
		{
			this.type = type;
		},
		
		getType: function ()
		{
			return (this.type);
		},
		
		setName: function (name)
		{
			this.name = name;
		},
		
		getName: function ()
		{
			return (this.name);
		},

		display: function (configuration, sender)
		{
			sender = sender ? sender : null;
			useFading = configuration.useFading ? true : false;
			
			if (typeof configuration.visible != 'undefined')
			{
				configuration.visible ? this.show(useFading) : this.hide(useFading);
			}
		},
		
		show: function (useFading)
		{
			if (this.domNode && (!this.domNode.isVisible || typeof this.domNode.isVisible == 'undefined'))
			{
				this.domNode.isVisible = true;
	
				if (useFading)
				{
					this.getJObject().fadeIn("slow");
				}
				else
				{
					this.getJObject().show();
				}
			}
		},
		
		hide: function (useFading)
		{
			if (this.domNode.isVisible || typeof this.domNode.isVisible == 'undefined')
			{
				this.domNode.isVisible = false;
	
				if (useFading)
				{
					this.getJObject().fadeOut("slow");
				}
				else
				{
					this.getJObject().hide();
				}
			}
		},
		
		setDomNode: function (domNode)
		{
			this.domNode = domNode;
			
			domNode.owner = this;
		},
		
		getDomNode: function ()
		{
			return (this.domNode);
		},
		
		getJObject: function ()
		{
			return ($(this.domNode));
		},

		acceptWatcher: function (watcher, event, immediateFire)
		{
			var self = this;
			this.getJObject().bind
			(
				event,
				this,
				function(e)
				{
					watcher.handleWatchedEvent(watcher, self, event);
				}
			);
			
			if (immediateFire)
			{
				watcher.handleWatchedEvent(null, this, event);
			}
		},
		
		positionEditLayer: function (layerId, targetId, xOffset, yOffset)
		{
			var layerNode = $('#' + layerId);
			var withoutTarget = false;
			
			if (targetId)
			{		
				var targetNode = $('#' + targetId);
			}
			else
			{
				withoutTarget = true; 
			}
			
			if (!xOffset)
			{
				xOffset = 0;
			}
			
			if (!yOffset)
			{
				yOffset = 0;
			}
			
			if (!withoutTarget)
			{		
				var targetNodeOffsets = targetNode.offset();
				
				layerNode.css("left", targetNodeOffsets.left + xOffset);
				layerNode.css("top", targetNodeOffsets.top + yOffset);
			}
			else
			{
				layerNode.css("left", xOffset);
				layerNode.css("top", yOffset);
			}
		}
	}
);

var inputElement = $.klass
(
	formElement,
	{
		initialize: function ($super, type, domNode, name, preventObservingEnterKey)
		{
			$super(type, domNode, name);
			
			thisObj = this;
			
			if (!preventObservingEnterKey)
			{
				this.getJObject().bind
				(
					'keypress',
					function (e)
					{
						// check for enter key to prevent form submit
						if (thisObj.observeKey(e, 13))
						{
							var srcElement = e.target; 
							
							if (srcElement.blur)
							{
								srcElement.blur();
							}
							
							//Event.stop(e);
							e.stopPropagation();
						}
					}
				);
			}
		},
		
		display: function ($super, configuration, sender)
		{
			$super(configuration, sender);
			
			if (typeof configuration.visible != 'undefined')
			{
				this.setValue(configuration.value);
			}
			
			if (configuration.disabled)
			{
				this.domNode.disabled = true;
			}
		},

		setValue: function (value)
		{
			this.getDomNode().value = value ? value : '';
		},
		
		getValue: function ()
		{
			return (this.getDomNode().value);
		},
		
		observeKey: function (e, keyToObserve)
		{
			keyToObserve = keyToObserve ? keyToObserve : 13; // 13 == enter key
			
			if (window.event)
			{
				var key = window.event.keyCode;
			}
			else if (e)
			{
				var key = e.keyCode || e.which;
			}
		
			return (key == keyToObserve);
		}
	}
);
//------------------End-----------------//
//- InTradeSys dependencieModel Basics -//
//--------------------------------------//

//-----------------Start------------------//
//- InTradeSys dependencieModel:myHammer -//
//----------------------------------------//

var textCounter = $.klass
(
	formElement,
	{
		initialize: function ($super, domNode, counterDomNode, name, valueToHide)
		{
			$super('textcounter', domNode, name);
			
			this.counterDomNode = counterDomNode;
			this.valueToHide = valueToHide;
		},
		
		setValue: function (value)
		{
			this.counterDomNode.html(''+value);
			
			value == String(this.valueToHide) ? this.hide() : this.show();
			
			if (value <= 10)
			{
				this.getJObject().css('color','#ff0000');
			}
			else
			{
				this.getJObject().css('color','#000000');
			}
		},
		
		getValue: function ()
		{
			return (this.counterDomNode.firstChild.nodeValue);
		},
		
		handleWatchedEvent: function (e, watchedElement, event)
		{
			switch (event)
			{
				case 'keyup':
				case 'change':
					switch (watchedElement.getType())
					{
						case 'limitedTextArea':
						this.setValue(watchedElement.getJObject().attr('maxChars') - watchedElement.getJObject().val().length);
						break;
						
						case 'text':
						this.setValue(watchedElement.getJObject().attr('maxlength') - watchedElement.getJObject().val().length);
						break;
					}
				break;
			}
		}
	}
);

var textElement = $.klass
(
	inputElement,
	{
		initialize: function ($super, domNode, name)
		{
			$super('text', domNode, name);
		},
		
		handleWatchedEvent: function (e, watchedElement, event)
		{
			var watchedElementName = watchedElement.getName();

			switch (event)
			{
				case 'change':
				case 'custom:change':
				
					switch (watchedElementName)
					{
						case 'UsePhoneLocalNumber':
						case 'UsePhone2LocalNumber':
						
							if (watchedElement.domNode.checked)
							{
								this.domNode.disabled = false;
								this.domNode.focus();
							}
							else
							{
								this.domNode.disabled = true;
							}
						
							break;
					}
					
					break;
			}
		},
		
		setValue: function ($super, value, fireCustomChange)
		{
			$super(value);
			
			if (fireCustomChange)
			{
				this.domNode.trigger('custom:change');
			}
		}
	}
);

var tabElement = $.klass
(
	formElement,
	{
		initialize: function ($super, type, domNode, name)
		{
			$super(type, domNode, name);
			this.setType('tabElement');
		},
		
		handleWatchedEvent: function (e, watchedElement, event)
		{
			switch (event)
			{
				case 'click':
				
					this.selectTab(watchedElement);
					break;
			}
		},
		
		selectTab: function (activeTab)
		{
			$('#tabCompanyProfil')[0].className = 'navBarTabContainer';
			$('#tabFeedback')[0].className = 'navBarTabContainer';
			$('#tabOffers')[0].className = 'navBarTabContainer';
			$('#tabReferences')[0].className = 'navBarTabContainer';
			$('#tabApprenticeship')[0].className = 'navBarTabContainer';
			
			activeTab.domNode.className = 'navBarTabContainerActiv';

			if (bIsOwner)			
			{
				$('.editor').each
				(
					function()
					{
						if ($(this).css('display') != 'none')
						{
							$(this).fadeOut('slow');
						}
					}
				);
			}
		}
	}
);

var pictureElement = $.klass
(
	formElement,
	{
		initialize: function ($super, type, domNode, name)
		{
			$super(type, domNode, name);
			this.setType('pictureElement');
		},
		
		handleWatchedEvent: function (e, watchedElement, event)
		{
			switch (event)
			{
				case 'change':
				
					break;
			}
		}
	}
);


var googleMapElement = $.klass (
	formElement, {
		initialize: function ($super, type, domNode, name) {
			$super(type, domNode, name);

			if (GBrowserIsCompatible())  {
		        this.map = new GMap2(document.getElementById("GoogleMapBox"));
		        this.map.setCenter(new GLatLng(46.950262, 2.944336), 6);
				this.map.addControl(new GHierarchicalMapTypeControl());
				this.map.enableScrollWheelZoom();
				this.geocoder = new GClientGeocoder();
			}
		},
		
	    showAddress: function (address) {
		  if (this.geocoder) {
			  var map = this.map;
			  this.geocoder.getLatLng(
	          address,
	          function(point) {
	            if (!point) {

		            var host = parseUri(document.URL).host;
		            if (host == 'branchenbuch.my-hammer.de') {
			            map.setCenter(new GLatLng(51.3, 10.10), 4);
		            }
		            if (host == 'directory.myhammer.co.uk') {
		                map.setCenter(new GLatLng(53.60, -3.61), 4);
		            }
		            if (host == 'branchenbuch.my-hammer.at') {
			            map.setCenter(new GLatLng(47.596, 13.644), 5);
		            }
	            } else {
		           	map.setCenter(point, 13);
					map.addOverlay(new GMarker(point));
	            }
	          }
	        );
	      }
	    }
	}
);

function parseUri (str) {
	var	o   = parseUri.options,
		m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
		uri = {},
		i   = 14;

	while (i--) uri[o.key[i]] = m[i] || "";

	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	});

	return uri;
};

parseUri.options = {
	strictMode: false,
	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
	q:   {
		name:   "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};


var textareaElement = $.klass
(
	inputElement,
	{
		initialize: function ($super, domNode, name)
		{
			$super('textarea', domNode, name, true);
		}
	}
);

var limitedTextareaElement = $.klass
(
	formElement,
	{
		initialize: function ($super, type, domNode, name)
		{
			$super(type, domNode, name);
			this.setType('limitedTextArea');
		},
		
		handleWatchedEvent: function (e, watchedElement, event)
		{
			switch (event)
			{
				case 'keyup':
					if(this.getJObject().val().length >= this.getJObject().attr('maxChars'))
					{
						this.getJObject().val(this.getJObject().val().substring(0,this.getJObject().attr('maxChars')));
					}
				break;
			}
		}
	}
);

//------------------End-------------------//
//- InTradeSys dependencieModel myHammer -//
//----------------------------------------//


function starPicUrl(score)
{
	var starpics = new Array();
	starpics[0.0] = 'http://static.myhammer.com/v3/live/icons/00starYellowNew.gif';
    starpics[0.5] = 'http://static.myhammer.com/v3/live/icons/05starYellowNew.gif';
    starpics[1.0] = 'http://static.myhammer.com/v3/live/icons/10starYellowNew.gif';
    starpics[1.5] = 'http://static.myhammer.com/v3/live/icons/15starYellowNew.gif';
    starpics[2.0] = 'http://static.myhammer.com/v3/live/icons/20starYellowNew.gif';
    starpics[2.5] = 'http://static.myhammer.com/v3/live/icons/25starYellowNew.gif';
    starpics[3.0] = 'http://static.myhammer.com/v3/live/icons/30starYellowNew.gif';
    starpics[3.5] = 'http://static.myhammer.com/v3/live/icons/35starYellowNew.gif';
    starpics[4.0] = 'http://static.myhammer.com/v3/live/icons/40starYellowNew.gif';
    starpics[4.5] = 'http://static.myhammer.com/v3/live/icons/45starYellowNew.gif';
    starpics[5.0] = 'http://static.myhammer.com/v3/live/icons/50starYellowNew.gif';
    starpics[5.5] = 'http://static.myhammer.com/v3/live/icons/50starYellowNew.gif';
    starpics[6.0] = 'http://static.myhammer.com/v3/live/icons/60starYellowNew.gif';
    
    return starpics[score];
}

function formatDate(t)
{
	var date = new Date();
	
	if (t != 'now')
	{
		date.setTime((t < 9999999999) ? t * 1000 : t);
	}
	
	var d = date.getDate();
	var m = date.getMonth() + 1;
	var y = date.getFullYear();
	return (d < 10 ? '0' : '') + d + '.' + (m < 10 ? '0' : '') + m + '.' + y;
}

function getSMPScriptPrefix()
{
	return('/v3');
}

function generate_pagination(tab, page, perpage, count) 
{
	var max = Math.ceil(count / perpage);
	
	if (page > 1) 
	{
		$('#' + tab + '_firstarr').show();
		$('#' + tab + '_prev').show();
		$('#' + tab + '_prevarr').show();
		$('#' + tab + '_prev').children().html(page - 1);
	} 
	else 
	{
		$('#' + tab + '_firstarr').hide();
		$('#' + tab + '_prevarr').hide();
		$('#' + tab + '_prev').hide();
	}
	
	if (page < max) 
	{
		$('#' + tab + '_lastarr').show();					
		$('#' + tab + '_nextarr').show();
		$('#' + tab + '_next').show();
		$('#' + tab + '_next').children().html(page + 1);
	} 
	else 
	{
		$('#' + tab + '_lastarr').hide();
		$('#' + tab + '_nextarr').hide();
		$('#' + tab + '_next').hide();
	}		
			
	$('#' + tab + '_page').html(page);
}

// Begin DIV Scroller
function ElementScroller(scrollname, scroll_element_id, up_id, down_id, left_id, right_id)
{
    this.scroll_element_id = scroll_element_id;
    this.name = scrollname;
    this.scrollCursorH = 0;
    this.scrollCursorV = 0;
    this.speed = 2;
    this.timeoutTime = 1;
    this.timeoutID = 0;
    this.element_obj = null;
    this.up_id = up_id;
    this.dn_id = down_id;
    this.lt_id = left_id;
    this.rt_id = right_id;
	
    if (document.getElementById)
    {
        this.element_obj = $('#' + this.scroll_element_id)[0];
        this.element_obj.style.overflow = 'hidden';
        
        var element_up_obj = this.up_id ? $('#' + this.up_id)[0] : null;
        var element_dn_obj = this.dn_id ? $('#' + this.dn_id)[0] : null;
        var element_lt_obj = this.lt_id ? $('#' + this.lt_id)[0] : null;
        var element_rt_obj = this.rt_id ? $('#' + this.rt_id)[0] : null;
		
		var thisObj = this;
        
        if (element_up_obj)
        {
            element_up_obj.onmouseover = function() { thisObj.scrollUp(); };
            element_up_obj.onmouseout = function() { thisObj.stopScroll(); };
        }

        if (element_dn_obj)
        {
            element_dn_obj.onmouseover = function() { thisObj.scrollDown(); };
            element_dn_obj.onmouseout = function() { thisObj.stopScroll(); };
        }

        if (element_lt_obj)
        {
            element_lt_obj.onmouseover = function() { thisObj.scrollLeft(); };
            element_lt_obj.onmouseout = function() { thisObj.stopScroll(); };
        }

        if (element_rt_obj)
        {
            element_rt_obj.onmouseover = function() { thisObj.scrollRight(); };
            element_rt_obj.onmouseout = function() { thisObj.stopScroll(); };
        }
    }

    this.stopScroll = function()
    {
        clearTimeout(this.timeoutID);
    }

    this.scrollUp = function()
    {
        if (this.element_obj)
        {
        	var self = this;
        
            this.scrollCursorV = (this.scrollCursorV - this.speed) < 0 ? 0 : this.scrollCursorV - this.speed;
            this.element_obj.scrollTop = this.scrollCursorV;
            this.timeoutID = setTimeout(function(e) {self.scrollUp()}  , this.timeoutTime);
        }
    }

    this.scrollDown = function()
    {
        if (this.element_obj)
        {
        	var self = this;
            this.scrollCursorV += this.speed;
            this.element_obj.scrollTop = this.scrollCursorV;

            if (this.element_obj.scrollTop == this.scrollCursorV)
            {
                this.timeoutID = setTimeout(function(e) {self.scrollDown()}  , this.timeoutTime);
            }
            else
            {
                this.scrollCursorV = this.element_obj.scrollTop;
            }
        }
    }

    this.scrollLeft = function()
    {
        if (this.element_obj)
        {
        	var self = this;
            this.scrollCursorH = (this.scrollCursorH - this.speed) < 0 ? 0 : this.scrollCursorH - this.speed;
            this.element_obj.scrollLeft = this.scrollCursorH;
            this.timeoutID = setTimeout(function(e) {self.scrollLeft()}  , this.timeoutTime);
        }
    }

    this.scrollRight = function()
    {
        if (this.element_obj)
        {
        	var self = this;
			var thisObj = this;
			
            this.scrollCursorH += this.speed;
            this.element_obj.scrollLeft = this.scrollCursorH;

            if (this.element_obj.scrollLeft == this.scrollCursorH)
            {
                this.timeoutID = setTimeout(function(e) {self.scrollRight()}  , this.timeoutTime);
            }
            else
            {
                this.scrollCursorH = this.element_obj.scrollLeft;
            }
        }
    }
	
    this.resetScroll = function()
    {
        if (this.element_obj)
        {
            this.element_obj.scrollTop = 0;
            this.element_obj.scrollLeft = 0;
            this.scrollCursorH = 0;
            this.scrollCursorV = 0;
        }
    }
}        
// End DIV Scroller

function showErrorBubble (element, content, isSuccessBubble)
{
	var templateNode,
		templateType;
	
	if (isSuccessBubble)
	{
		templateType = 'successBubble';
	}
	else
	{
		templateType = 'errorBubble';
	}
			
	if (templateNode = $('#' + templateType))
	{
		var errorBubbleDomNode = templateNode.clone(true);
		errorBubbleDomNode.removeAttr('id');
		
		if (content)
		{
			var bubbleContent = errorBubbleDomNode.find('#errorBubbleContent');
			bubbleContent.html(content);
		}

		$(document.body).append(errorBubbleDomNode);

		var elementOffsets = $(element).offset();
		var elementHeight = $(element).height();
		
		errorBubbleDomNode.css("left", (elementOffsets.left + 10));
		errorBubbleDomNode.css("top", (elementOffsets.top + (elementHeight / 2) - 27));
		
		errorBubbleDomNode.click
		(
			function ()
			{
				hideErrorBubble(errorBubbleDomNode);
			}
		);

		window.setTimeout
		(
			function ()
			{
				hideErrorBubble(errorBubbleDomNode)
			},
			5000
		);

	}
}

function hideErrorBubble (bubble)
{
	bubble.remove();
}

var pictureUpload = new
(
	$.klass
	(
		formElement,
		{
			initialize: function ()
			{
			},
			
			setGlobalVars: function ()
			{
				this.domNode = $('#pictureUploadElement');
				this.hiddenId = $('#pictureUploadHiddenId');
				this.previewImgDomNode = $('#pictureUploadPreviewImage');
				this.hiddenUploadForm = $('#hiddenUploadForm');
				this.hiddenAjaxMethod = $('#hiddenAjaxMethod');
				this.pictureUploadTitleDiv = $('#pictureUploadTitleDiv');
				this.pictureUploadSubTitleDiv = $('#pictureUploadSubTitleDiv');
				this.pictureUploadInputFileTemplate = $('#pictureUploadInputFileTemplate');
				this.pictureUploadFileDisplay = $('#pictureUploadFileDisplay');
				this.pictureUploadSearchButton = $('#pictureUploadSearchButton');
				this.pictureUploadDeleteDiv = $('#pictureUploadDeleteDiv');
				this.pictureUploadDeleteButton = $('#pictureUploadDeleteButton');
				this.pictureUploadDefaultImageDiv = $('#pictureUploadDefaultImageDiv');
				this.pictureUploadDefaultLabel = $('#pictureUploadDefaultLabel');
				this.pictureUploadErrorDiv = $('#pictureUploadErrorDiv');
				this.pictureUploadSubmitButton = $('#pictureUploadSubmitButton');
				
				this.globalVarsSet = true;
			},
			
			activate: function (options)
			{
				if (!this.globalVarsSet)
				{
					this.setGlobalVars();
				}
				
				if (this.domNode.isVisible)
				{
					this.deactivate(false);
					var useFading = false;
				}
				
				this.options = typeof (options) == 'object' ? $.extend({}, options) : {};
				
				if
				(
					this.options.anchorElement
						&& this.options.formAction
						&& this.options.ajaxMethods
				)
				{
					var thisObj = this,
						anchorElement = $(this.options.anchorElement);

					this.acceptPosition(anchorElement);
					this.previewImgDomNode.attr('src', anchorElement.attr('src'));
					this.previewImgDomNode.css('width', anchorElement.width() + 'px');
					this.previewImgDomNode.css('height', anchorElement.height() + 'px');
					this.domNode.css('width', (anchorElement.width() + 50) + 'px');
					this.pictureUploadFileDisplay.css('width', (anchorElement.width() - (jQuery.browser.mozilla ? 0 : 2))+ 'px');
					$(this.hiddenUploadForm[0].title).css('width', (anchorElement.width() - (jQuery.browser.mozilla ? 0 : 2)) + 'px');
					$(this.hiddenUploadForm[0].description).css('width', (anchorElement.width() - (jQuery.browser.mozilla ? 0 : 2)) + 'px');
					
					this.hiddenUploadForm.attr('action', this.options.formAction);
					
					this.attachInputFile();
					this.showDependingElements(anchorElement);
					
					if (this.options.showTitle)
					{
						this.pictureUploadTitleDiv.show();
						this.hiddenUploadForm[0].title.disabled = false;
						this.hiddenUploadForm[0].title.maxLength = this.options.maxlengthTitle ? this.options.maxlengthTitle : 0;
						this.hiddenUploadForm[0].title.value = this.options.title ? this.options.title : ''; 
					}
					else
					{
						this.pictureUploadTitleDiv.hide();
						this.hiddenUploadForm[0].title.disabled = true;
					} 

					if (this.options.showSubTitle)
					{
						this.pictureUploadSubTitleDiv.show();
						this.hiddenUploadForm[0].description.disabled = false;
						this.hiddenUploadForm[0].description.value = this.options.subtitle ? this.options.subtitle : ''; 
					}
					else
					{
						this.pictureUploadSubTitleDiv.hide();
						this.hiddenUploadForm[0].description.disabled = true;
					}
					
					this.pictureUploadDeleteButton.bind
					(
						'click',
						function (e)
						{
							thisObj.pictureUploadSubmitButton.unbind
							(
								'click'
							);
							thisObj.hiddenAjaxMethod.attr('value', thisObj.options.ajaxMethods.remove);
							thisObj.attachFormSubmitHandler(true);
							thisObj.pictureUploadSubmitButton[0].click();
						}
					);
					
					this.show(useFading);
				}
				else
				{
					return (false);
				}
			},
			
			showDependingElements: function (anchorElement)
			{
				var thisObj = this;
				
				if (this.options.id)
				{
					this.hiddenUploadForm[0].id.disabled = false;
					this.hiddenUploadForm[0].id.value = this.options.id;
					this.pictureUploadSubmitButton.show();
					this.pictureUploadSubmitButton.bind
					(
						'click',
						function (e)
						{
							thisObj.hiddenAjaxMethod.attr('value', thisObj.options.ajaxMethods.edit);
							thisObj.attachFormSubmitHandler();
						}
					);

					this.options.showRemove ? this.pictureUploadDeleteDiv.show() : this.pictureUploadDeleteDiv.hide();

					if (this.options.showDefaultCheckbox)
					{
						if (anchorElement)
						{
							pictureUploadDefaultCheckbox.acceptValue(anchorElement[0].isDefault ? 1 : 0);
						}
						
						this.pictureUploadDefaultImageDiv.show();
						this.pictureUploadDefaultLabel.html(this.options.defaultCheckboxLabel ? this.options.defaultCheckboxLabel : '');
						this.hiddenUploadForm[0]['default'].disabled = false;
					}
					else
					{
						this.pictureUploadDefaultImageDiv.hide();
						this.hiddenUploadForm[0]['default'].disabled = true;
					}
				}
				else
				{
					if (this.options.ajaxMethods)
					{
						this.hiddenAjaxMethod.attr('value', this.options.ajaxMethods.create);
					}

					this.hiddenUploadForm[0].id.disabled = true;
					this.hiddenUploadForm[0].id.value = '';
					this.pictureUploadSubmitButton.hide();
					this.pictureUploadSubmitButton.unbind
					(
						'click'
					);
					
					(this.options.showRemove && this.options.forceShowRemove) ? this.pictureUploadDeleteDiv.show() : this.pictureUploadDeleteDiv.hide();

					this.pictureUploadDefaultImageDiv.hide();
					this.hiddenUploadForm[0]['default'].disabled = true;
				}				
			},
			
			getPictureArrayFromResponse: function (response)
			{
				if (response.pictures)
				{
					return (response.pictures); 
				}
				else if (response.images)
				{
					return (response.images);
				}
				else if (response.url)
				{
					return ({0: response.url});
				}
				else
				{
					return ({});
				}
			},
			
			handlePictureUpload: function (response)
			{
				var thisObj = this,
					pictures = this.getPictureArrayFromResponse(response);
				
				jQuery.each
				(
					pictures,
					function (id, picture)
					{
									
						if (typeof (picture) == 'object' && picture.url)
						{
							picture = picture.url;
						}
						
						if (id == 0)
						{
							thisObj.options.completeCallback(picture);
							thisObj.deactivate();
						}
						else
						{
							thisObj.options.id = id;
							thisObj.previewImgDomNode.attr('src', picture);
							thisObj.showDependingElements();
						}
					}
				);
			},
			
			handlePictureDeletion: function (response)
			{
				this.options.id = 0;
				this.options.completeCallback(response.url ? response.url : response, 'remove');
				this.deactivate(true);
			},
			
			checkResponse: function (response)
			{
				if (response.errno == 0)
				{
					this.pictureUploadErrorDiv.hide();

					return (true);
				}
				else
				{
					this.pictureUploadErrorDiv.show();
					this.pictureUploadErrorDiv.text(response.error);
					
					return (false);
				}
			},
			
			deactivate: function(useFading)
			{
				this.cleanupForm();
				this.detachInputFile();

				this.options = {};
				this.hiddenUploadForm.attr('action', '');
				this.hiddenAjaxMethod.attr('value', '');
				this.hiddenUploadForm[0].title.value = '';
				this.hiddenUploadForm[0].description.value = '';
				this.hiddenUploadForm[0].id.value = '';
				this.pictureUploadFileDisplay.attr('value', '');
				this.pictureUploadErrorDiv.hide();
				this.showDependingElements();
				this.hiddenUploadForm.unbind
				(
					'submit'
				);
				this.pictureUploadSubmitButton.unbind
				(
					'click'
				);
				this.pictureUploadDeleteButton.unbind
				(
					'click'
				);
				
				
				this.hide(useFading);
			},
			
			cleanupForm: function ()
			{
				this.detachInputFile();
				this.attachInputFile();
			},
			
			attachInputFile: function ()
			{
				var thisObj = this;
				
				this.pictureUploadInputFile = this.pictureUploadInputFileTemplate.clone();
				this.pictureUploadInputFile.removeAttr('id');
				this.pictureUploadInputFile.bind
				(
					'change',
					function (e)
					{
						if (thisObj.options.id)
						{
							thisObj.hiddenAjaxMethod.attr('value', thisObj.options.ajaxMethods.edit);
						}

						thisObj.attachFormSubmitHandler(false, true);
						thisObj.pictureUploadFileDisplay.val($(e.target).val());
						thisObj.pictureUploadSubmitButton.unbind
						(
							'click'
						);
						thisObj.pictureUploadSubmitButton[0].click();
					}
				);
				
				this.pictureUploadSearchButton.before(this.pictureUploadInputFile);
			},
			
			attachFormSubmitHandler: function (forDelete, forUpload)
			{
				var thisObj = this;
					isDeletion = forDelete,
					isUpload = forUpload;
				
				this.hiddenUploadForm.unbind
				(
					'submit'
				);

				if (this.options.id && !isDeletion && !isUpload)
				{
					this.hiddenUploadForm.bind
					(
						'submit',
						function (e)
						{
							AIM.submit
							(
								thisObj.hiddenUploadForm[0],
								{
									'onStart': thisObj.options.startCallback ? thisObj.options.startCallback : null,
									'onComplete': function (response, iframeId)
									{
								
									
										response = eval('(' + response + ')');
										
										if
										(
											thisObj.checkResponse(response)
												&& thisObj.options.completeCallback
										)
										{
											thisObj.options.completeCallback(response, 'edit');
											thisObj.deactivate();
										}
										
										window.setTimeout(function() {$('#' + iframeId).remove()}, 360000);
									}
								}
							)
						}
					);
				}
				else
				{
					this.hiddenUploadForm.bind
					(
						'submit',
						function (e)
						{
							AIM.submit
							(
								thisObj.hiddenUploadForm[0],
								{
									'onComplete': function (response, iframeId)
									{
										

										response = eval('(' + response + ')');

										if (thisObj.checkResponse(response))
										{
											if (isDeletion)
											{
												thisObj.handlePictureDeletion(response);
											}
											else if (isUpload)
											{
												thisObj.handlePictureUpload(response);
											}
										}
										window.setTimeout(function() {$('#' + iframeId).remove()}, 360000);
										
									}
								}
							)
						}
					);
				}
			},
			
			detachInputFile: function ()
			{
				if (this.pictureUploadInputFile)
				{
					this.pictureUploadInputFile.remove();
					this.pictureUploadInputFile = null;
				}
			},
			
			acceptPosition: function (anchorElement)
			{
				this.domNode.css('top', anchorElement.offset().top - (jQuery.browser.msie ? 32 : 30));
				this.domNode.css('left', anchorElement.offset().left - 26);
			},
			
			show: function ($super, useFading)
			{
				$super(useFading === false ? false : true);
			},
			
			hide: function ($super, useFading)
			{
				$super(useFading === false ? false : true);
			}
		}
	)
);

var pictureTitleElement = $.klass
(
	textElement,
	{
		initialize: function ($super, domNode, name)
		{
			$super(domNode, name);
		},

		handleWatchedEvent: function (e, watchedElement, event)
		{
		}		
	}	
);

var pictureSubtitleElement = $.klass
(
	textareaElement,
	{
		initialize: function ($super, domNode, name)
		{
			$super(domNode, name);
		},

		handleWatchedEvent: function (e, watchedElement, event)
		{
		}		
	}	
);

var pictureCheckboxElement = $.klass
(
	formElement,
	{
		initialize: function ($super, domNode, name)
		{
			$super('checkboxButton', domNode, name);
		},

		acceptValue: function (value)
		{
			$('#pictureUploadDefaultImage').val(value);
			$('#pictureUploadDefaultImageCheck').attr('src', 'http://static.myhammer.com/v3/live/icons/checkbox_' + (value ? '' : 'in') + 'aktiv.gif');			
		},

		handleWatchedEvent: function (e, watchedElement, event)
		{
			var watchedElementName = watchedElement.getName();
			
			switch (watchedElementName)
			{
				case 'pictureUploadDefaultCheckbox':
				
					switch (event)
					{
						case 'click':

							if ($('#pictureUploadDefaultImage').val() == 1)
							{
								this.acceptValue(0);
							}
							else
							{
								this.acceptValue(1);
							}
							
							break;							
					}
					
					break;
			}
		}		
	}	
);

function showHelpBubble(anchorId, bubbleId, onClientPosition)
{
	var bubbleObject = document.getElementById(bubbleId);
	var inputObject = document.getElementById(anchorId);
	
	if (!bubbleObject || !inputObject)
	{
		return (false);
	}

	var position = {};
	position = onClientPosition ? $('#'+anchorId).offset() : $('#'+anchorId).position();
	
	var offsetTop = position.top - $('#' + bubbleId).height();
	var offsetLeft = position.left;
	
	$('#' + bubbleId).css('top', offsetTop + 'px');
	$('#' + bubbleId).css('left', offsetLeft + 'px');
	$('#' + bubbleId).show();
}

var editButton = $.klass
(
	formElement,
	{
		initialize: function ($super, type, domNode, name)
		{
			$super(type, domNode, name);
			this.setType('editButton');
		},

		handleWatchedEvent: function (e, watchedElement, event)
		{
			switch (watchedElement.type) 
			{
				case 'editButton':
					
					this.hide();
					break;
					
				case 'saveButton':
					
					this.show();
					break;
			}
		}		
	}	
);

var saveButton = $.klass
(
	formElement,
	{
		initialize: function ($super, type, domNode, name)
		{
			$super(type, domNode, name);
			this.setType('saveButton');
		},
		
		handleWatchedEvent: function (e, watchedElement, event)
		{
			switch (watchedElement.type) 
			{
				case 'editButton':
					
					this.show();
					break;
					
				case 'saveButton':
					
					this.hide();
					break;
			}
		}				
	}
);

var closeButton = $.klass
(
	formElement,
	{
		initialize: function ($super, type, domNode, name)
		{
			$super(type, domNode, name);
			this.setType('closeButton');
		},

		handleWatchedEvent: function (e, watchedElement, event)
		{
			switch (watchedElement.name) 
			{
				case 'makeAppointmentLayer':
				case 'sendMessageLayer':
				case 'contactDataRequestInfoLayer':
					
					watchedElement.getJObject().hide('slow');
					break;
					
			}
		}		
	}	
);


var userProfileElement = $.klass
(
	formElement,
	{
		initialize: function ($super, type, domNode, name)
		{
			$super(type, domNode, name);
			this.setType('userProfileElement');
		},
		
		reload: function(response, iframeId)
		{	
			var doReload = true;

			if (response)
			{
				response = eval('(' + response + ')');

				if (response.errorlist)
				{
					jQuery.each
					(
						response.errorlist,
						function(fieldName, error)
						{
							showErrorBubble($('#' + fieldName)[0], error);
						} 
					);
					doReload = false;
				}
				else if (response.errno)
				{
					showErrorBubble(this.watchedElement.domNode, response.error);
					doReload = false;
				}
				else if (response.errno == 0)
				{
					showErrorBubble(this.watchedElement.domNode, response.error, true);
				}
			}
		
			if (iframeId)
			{
				//$('#' + iframeId).remove();
				window.setTimeout(function() {$('#' + iframeId).remove()}, 360000);
			}
			
			if (doReload)
			{
				this.watchedElement = {name: this.name + 'ReloadTrigger'};		
				$(this.domNode).find('.cargo').empty();
				this.fetchData();
			}
		}, 
		
		addEntry: function(id, data)
		{	
			var cargoElement = $(this.domNode).find('.cargo');

			switch (this.name)
			{
				case 'uploadedDocList':
				
					cargoElement.append(data.label + '<br>');
					break;
					
				case 'uploadableDocList':

					var templateNode = $('#documentUploadForm');
					var formNode = templateNode.clone(true);

					formNode[0].id = formNode[0].id + '_' + id;
					formNode.find('#documentUploadFormTitle').html(data.title); 
					formNode.find('#iUserDocumentID').attr('value', id); 
					
					
					if (data.action1week == 'restricted') {
						$(".personalid").show();
						
					}else{
						$(".personalid").hide();
					}
					
					
					var formNodeCargo = formNode.find('#documentUploadCargo');
					
					jQuery.each
					(
						data.paths[1].groups,
						function(groupId)
						{
							var trHTML = '<tr><th>';
							
							if (this.mode == 'required')
							{
								trHTML += "<div style='display:none;'>Erforderlich: </div>";
							}
							else
							{
								trHTML += "<div style='display:none;'>Optional: </div>";
							}
							
							if (this.type == 'single')
							{
								trHTML += this.title;
								trHTML += '<input type="hidden" name="docsys-1-' + groupId + '-id" value="' + this.id + '">';
							}
							else
							{
								trHTML += '<select name="docsys-1-' + groupId + '-id">';
								
								jQuery.each
								(
									this.dropdown,
									function (dropdownId, dropdownTitle)
									{
										trHTML += '<option value="' + dropdownId + '">' + dropdownTitle + '</option>';
									}
								);
								
								trHTML += '</select>';
							}
							
							trHTML += '</th><td>';
							trHTML += '<input type="file" name="docsys-1-' + groupId + '"></td></tr>';
						
							formNodeCargo.append(trHTML);
						} 
					);
					
					var documentUploadButton = new userProfileElement(null, formNode.find('#documentUploadButton')[0], 'documentUploadButton');
					documentUploadButton.id = id;
					documentUploadButton.display
					(
						{
							visible: true
						}
					);
					
					documentUploadButton.acceptWatcher(uploadableDocList, 'click');
					
					cargoElement.append(formNode);

					break;
			}
		},
		
		fetchData: function (data, response)
		{
			var thisObj = this;

			if (!response)
			{
				var parameters = new Object();
				var feedName = 'inline-base';

				switch (this.watchedElement.name)
				{
					case 'appointmentSendButton':

						parameters.method = 'send-appointment';
						parameters.message = $('#makeAppointmentText').val();
						parameters.userID = userID;
						break;

					case 'messageSendButton':

						parameters.method = 'send-message';
						parameters.message = $('#sendMessageBody').val();
						parameters.subject  = $('#sendMessageSubject').val();
						parameters.userID = userID;
						break;

					case 'sendRequestOfferButton':

						parameters.method = 'send-offer';
						parameters.auctionID  = $('#requestOffer').val();
						parameters.message  = $('#requestOfferBody').val();
						parameters.userID = userID;
						parameters.omniturePageName = $('#omnPagename').html();
						break;
						
					case 'sendRequestOfferButton1':

						parameters.method = 'send-offer';
						parameters.auctionID  = $('#requestOffer').val();
						parameters.message  = $('#requestOfferBody').val();
						parameters.userID = userID;
						parameters.omniturePageName = $('#omnPagename').html();
						break;
						
					case 'savePasswordButton':
					
						feedName = 'inline-profile';
						parameters.method = 'change-password';
						parameters.passwordOld = $('#passwordOld').val();
						parameters.passwordNew1 = $('#passwordNew1').val();
						parameters.passwordNew2 = $('#passwordNew2').val();
						break;

					case 'documentUploadDivReloadTrigger':
					
						feedName = 'inline-profile';			
						parameters.method = 'getUploadableDocuments';
						break;
						
					case 'requestContactDataButton':
						parameters.method = 'requestContactDetails';
						parameters.userID = userID;
						break;

					default:

						parameters.method = 'setAddressInformation';
						
						parameters.companyname 		= $('#userCompanyInput').val();
						parameters.firstname 		= $('#userFirstNameInput').val();
						parameters.lastname 		= $('#userLastNameInput').val();
						parameters.street 			= $('#userStreetInput').val();
						parameters.zip 				= $('#userZipInput').val();
						parameters.city 			= $('#userCityInput').val();
						parameters.homepage 		= $('#userHomepageInput').val();
						parameters.landline_prefix 	= $('#userPhonePrefixInput').val();
						parameters.landline_number 	= $('#userPhoneInput').val();
						parameters.mobile_prefix	= $('#userMobilePrefixInput').val();
						parameters.mobile_number	= $('#userMobileInput').val();
						parameters.fax_prefix 		= $('#userFaxPrefixInput').val();
						parameters.fax_number 		= $('#userFaxInput').val();
						parameters.email 			= $('#userMailInput').val();
						
						break;
				}
				
				parameters.cachebuster = Math.random()*5;
				
				$.get
				(
					"/v3/profile-extended/ajax/" + feedName + ".php?", 
					parameters, 
					function(response)
					{
						thisObj.fetchData(data, response);
					}, 
					'json'
				);
			}
			else
			{
				if (response.errno != 0)
				{
					if (response.error != '')
					{
						showErrorBubble(this.watchedElement.domNode, response.error);
					}
					else if (response.errorlist)
					{
						jQuery.each
						(
							response.errorlist,
							function(fieldName, error)
							{
								showErrorBubble($('#' + thisObj.getErrorTarget(fieldName))[0], error);
							} 
						);
					}
					return (false);
				}
				else
				{
					switch (this.watchedElement.name)
					{
						case 'documentUploadDivReloadTrigger':

							var haveUploadedDocuments = false;
							var haveUploableDocuments = false;

							jQuery.each
							(
								response['return'],
								function(id, uploadableDocument)
								{
									if (uploadableDocument.paths[1])
									{
										if (uploadableDocument.uploaded == 1)
										{
											uploadedDocList.addEntry(id, uploadableDocument);
											haveUploadedDocuments = true;
										}
										else
										{
											uploadableDocList.addEntry(id, uploadableDocument);
											haveUploableDocuments = true;
										}
									}
								} 
							);
							
							haveUploadedDocuments ? uploadedDocList.show() : uploadedDocList.hide();
							haveUploableDocuments ? uploadableDocList.show() : uploadableDocList.hide();
							(haveUploadedDocuments || haveUploableDocuments) ? documentUploadDiv.show() : documentUploadDiv.hide();
							
							break;
								
						default:
							
							if (response.sendto)
							{
								window.location.href = response.sendto;
								return;
							}
							
							if (response.address)
							{
								$('#userCompany').html(response.address.companyname);
								$('#userFirstName').html(response.address.firstname);
								$('#userLastName').html(response.address.lastname);
								$('#userStreet').html(response.address.street);
								$('#userZip').html(response.address.zip);
								$('#userCity').html(response.address.city);
								
								if (!response.address.homepage) {
									$('#userHomepage').html($('#userUnspecified').html());
								} else {
									$('#userHomepage').html(response.address.homepage);
								}

								if (!response.address.landline_prefix || !response.address.landline_number) {
									$('#userPhone').html($('#userUnspecified').html());
								} else {
									$('#userPhone').html(response.address.landline_prefix + ' ' + response.address.landline_number);
								}

								if (!response.address.mobile_prefix || !response.address.mobile_number) {
									$('#userMobile').html($('#userUnspecified').html());
								} else {
									$('#userMobile').html(response.address.mobile_prefix + ' ' + response.address.mobile_number);
								}

								if (!response.address.fax_prefix || !response.address.fax_number) {
									$('#userFax').html($('#userUnspecified').html());
								} else {
									$('#userFax').html(response.address.fax_prefix + ' ' + response.address.fax_number);
								}

								$('#userMail').html(response.address.email);
							}
							
							break;
					}
				}
				this.watchedElement = null;
				return (true);
			}
		},
		
		getErrorTarget: function (fieldName)
		{
			var errorTargets = 
			{
				companyname: 'userCompany',
				firstname: 'userFirstName',
				lastname: 'userLastName',
				street: 'userStreet',
				zip: 'userZip',
				city: 'userCity',
				homepage: 'userHomepage',
				landline_prefix: 'userPhone',
				landline_number: 'userPhone',
				mobile_prefix: 'userMobile',
				mobile_number: 'userMobile',
				fax_prefix: 'userFax',
				fax_number: 'userFax',
				email: 'userMail'
			};

			if (errorTargets[fieldName])
			{
				return (errorTargets[fieldName]);
			}
			else
			{
				return(fieldName);
			}
		},
		
		handleWatchedEvent: function (e, watchedElement, event)
		{
			this.watchedElement = watchedElement;
			
			switch (event)
			{
				case 'click':

					switch (watchedElement.name)
					{
						case 'editUserButton':
							
							this.show(true);
							this.watchedElement = watchedElement;
							break;
							
						case 'saveUserButton':
						case 'appointmentSendButton':
						case 'messageSendButton':
						case 'sendRequestOfferButton':
						case 'sendRequestOfferButton1':
						
							this.hide(true);
							this.fetchData();							
							break;

						case 'savePasswordButton':
						
							if (this.fetchData())
							{
								this.hide(true);
							}
							break;

						case 'makeAppointmentButton':
						case 'sendMessageButton':
						case 'requestOfferButton':

							this.positionEditLayer(this.name, null, 400, 250);													
							this.show(true);
							break;	

						case 'changePasswordButton':
						
							this.positionEditLayer('changePasswordLayer', 'changePasswordButton', -300, -100);													
							this.show(true);
							break;
								
						case 'requestContactDataButton':
						
							switch (this.name)
							{
								case 'contactDataRequestInfoLayer':
									this.show(true);
									break;
									
								case 'requestContactDataButton':
									this.fetchData();
									break;
							}
							break;
							
						case 'closeAppointmentLayerButton':
						case 'closeMessageLayerButton':
						case 'closeUserDataLayerButton':
						case 'closeRequestOfferLayerButton':
						case 'closeChangePasswordLayerButton':
						case 'UploadAgainCancel':

							this.hide(true);
							this.watchedElement = null;
							break;

						case 'closeRequestContactDataLayerButton':
							
							this.hide(true);
							$('#requestContactDataButton').hide();
							$('#contactDataRequested').show();
							this.watchedElement = null;
							break;
							
						case 'documentUploadButton':
							
							var uploadForm = $('#documentUploadForm_' + watchedElement.id);
							uploadForm.attr
							(
								'action',
								 '/v3/profile-extended/ajax/inline-documentupload.php'
							);
							
							documentUploadDiv.watchedElement = watchedElement;

							AIM.submit
							(
								uploadForm[0],
								{
									onComplete: function (response, iframeId)
									{
										documentUploadDiv.reload(response, iframeId);
										
									}
								
								}
								
							);
							uploadForm[0].submit();
					
						
					}
					
					break;
				
				case 'keyup':

					switch (watchedElement.name)
					{
						case 'startAdress':
							
							var startAdress = watchedElement.domNode.value;
							var targetAddress = $('#targetAddress').val();

							this.getJObject().attr
							(
								'href', 
								googleMapsRouteUrl
								+ '&daddr='
								+ targetAddress 
								+ '&saddr=' 
								+ startAdress 
							);

							break;
					}				
				
			}
		}
	}
);


var companyDescriptionElement = $.klass
(
	formElement,
	{
		initialize: function ($super, type, domNode, name)
		{
			$super(type, domNode, name);
			this.setType('companyDescriptionElement');
		},
		
		fetchData: function (response)
		{
			var thisObj = this;

			if (!response)
			{

				var parameters = new Object();

				switch (companyAndPerformancesBox.action)
				{
					case 'edit':
						parameters.method = 'setCompanyDescription';
						parameters.text = this.CompanyDescriptionAsString;
						
						break;
				}
												
				$.get
				(
					"/v3/profile-extended/ajax/inline-base.php?", 
					parameters, 
					function(response)
					{
						thisObj.fetchData(response);
					}, 
					'json'
				);
			}
			else
			{
				if (response.errno != 0)
				{
					if (response.error != '')
					{
						showErrorBubble(this.watchedElement.domNode, response.error);
					}
				}
				else
				{
					switch (companyAndPerformancesBox.action)
					{
						case 'edit':
							$('#companyAndPerformancesBox').html(response.text.replace(/(\r\n)|(\n\r)|\r|\n/g,"<BR>"));
							this.CompanyDescriptionAsString = response.text;
							companyAndPerformancesBox.action = null;
							break;
					}
				}
				
				this.watchedElement = null;
			}
		},		
		
		handleWatchedEvent: function (e, watchedElement, event)
		{
			switch (event)
			{
				case 'click':

					switch (watchedElement.getType())
					{
						case 'editButton':
							$('#companyAndPerformancesBox_editElement').fadeIn("slow");
							$('#companyAndPerformancesTextarea').val(this.CompanyDescriptionAsString);
							companyAndPerformancesBox.action = 'edit';
							this.watchedElement = watchedElement;
							break;
							
						case 'saveButton':
						
							if (watchedElement.name == 'confirmationYes')
							{
								$('#companyAndPerformancesBox_confirmationLayer').fadeOut("slow");
							}
							
							$('#companyAndPerformancesBox_editElement').fadeOut("slow");
							this.CompanyDescriptionAsString = $('#companyAndPerformancesTextarea').val();
							
							this.fetchData();						
							break;
							
						case 'closeButton':

							if (watchedElement.name == 'confirmationNo')
							{
								$('#companyAndPerformancesBox_confirmationLayer').fadeOut("slow");
								$('#companyAndPerformancesBox_editElement').fadeOut("slow");
								searchTermsBox.action = null
								this.watchedElement = null;								
							}
							else
							{
								$('#companyAndPerformancesBox_editElement').hide();
								$('#companyAndPerformancesBox_confirmationLayer').fadeIn("slow");
							}
							break;
					}
				break;
			}
		}
	}
);

var industriesElement = $.klass
(
	formElement,
	{
		initialize: function ($super, type, domNode, name)
		{
			$super(type, domNode, name);
			this.setType('industriesElement');
		},
		
		fetchData: function (response)
		{
			var thisObj = this;

			if (!response)
			{
				var parameters = new Object();

				switch (this.action)
				{
					case 'edit':
					
						parameters.method = 'setCategories';
						parameters.categories = this.industriesAsString;

						break;
				}
												
				$.get
				(
					"/v3/profile-extended/ajax/inline.php?", 
					parameters, 
					function(response)
					{
						thisObj.fetchData(response);
					}, 
					'json'
				);
			}
			else
			{
				if (response.errno != 0)
				{
					if (response.error != '')
					{
						showErrorBubble(this.watchedElement.domNode, response.error);
					}
				}
				else
				{
					switch (this.action)
					{
						case 'edit':
							$('#industriesBox').html(response.result);
							this.industriesAsString = response.result;
							this.action 			= null;
							break;
					}
				}
				
				this.openEditor = null;
				this.watchedElement = null;				
			}
		},
		
		handleWatchedEvent: function (e, watchedElement, event)
		{
			switch (event)
			{
				case 'click':

					switch (watchedElement.type)
					{
						case 'editButton':
						
							this.positionEditLayer('industriesBox_editElement', 'industriesBox', -11, -12);													
							$('#industriesBox_editElement').fadeIn('slow');
							$('#industriesTextarea').val(this.industriesAsString);
							watchedElement.domNode.src 	= 'http://static.myhammer.com/v3/live/structure/schliessen_button.gif';
							watchedElement.domNode.style.width = watchedElement.domNode.style.height = 'auto';
							watchedElement.type 		= 'closeButton';
							this.openEditor 			= this;
							this.watchedElement 		= watchedElement;
							this.action 				= 'edit';

							break;
							
						case 'saveButton':
						
							$('#industriesBox_editElement').fadeOut('slow');
							this.watchedElement.domNode.src = 'http://static.myhammer.com/v3/live/icons/icons_edit_blue_12x12.gif';
							watchedElement.domNode.style.width = watchedElement.domNode.style.height = 'auto';
							this.watchedElement.type 		= 'editButton';
							this.industriesAsString 		= $('#industriesTextarea').val();

							this.fetchData();		
							break;
							
						case 'closeButton':

							$('#industriesBox_editElement').fadeOut('slow');
							this.watchedElement.domNode.src = 'http://static.myhammer.com/v3/live/icons/icons_edit_blue_12x12.gif';
							watchedElement.domNode.style.width = watchedElement.domNode.style.height = 'auto';
							this.watchedElement.type 		= 'editButton';
							this.openEditor 				= null;
							this.watchedElement				= null;
							this.action 					= null;
							break;
					}

					break;
			}
		}
	}
);

var imprintElement = $.klass
(
	formElement,
	{
		initialize: function ($super, type, domNode, name)
		{
			$super(type, domNode, name);
			this.setType('imprintElement');
		},
		
		fetchData: function (data, response)
		{
			var thisObj = this;

			if (!response)
			{
				var parameters = new Object();

				switch (data) 
				{
					case 'get':
						
						parameters.method = 'getImprint';
						parameters.userID = userID;						
						break;
						
					case 'set':
						
						parameters.method = 'setImprint';
						parameters.value = $('#imprintTextarea').val();						
						break;						
				}
												
				$.get
				(
					"/v3/profile-extended/ajax/inline-profile.php?", 
					parameters, 
					function(response)
					{
						thisObj.fetchData(data, response);
					}, 
					'json'
				);
			}
			else
			{
				if (response.errno != 0)
				{
					if (response.error != '')
					{
						showErrorBubble(this.watchedElement.domNode, response.error);
					}
				}
				else
				{
					$('#imprintTextarea').val(response.result);
				}
				
				this.watchedElement = null;
			}
		},
		
		handleWatchedEvent: function (e, watchedElement, event)
		{
			switch (event)
			{
				case 'click':
					
					switch (watchedElement.name)
					{
						case 'showImprintLink':
							
							this.fetchData('get');
							break;
							
						case 'saveImprintButton':
							
							this.fetchData('set');
							$('#imprintLayer').hide();
							break;
							
						case 'closeImprintLayerButton':
							
							$('#imprintLayer').hide();
							this.watchedElement = null;
							break;							
					}

					break;
			}
		}
	}
);

var profileImagesElement = $.klass
(
	formElement,
	{
		initialize: function ($super, domNode, name)
		{
			$super('profileImages', domNode, name);
			this.isOwner = $('#editProfileImage').length ? true : false;
		},
		
		display: function ($super, configuration, sender)
		{
			$super(configuration, sender);
			
			if (configuration.visible)
			{
				this.fetchImages();
			}
		},

		fetchImages: function (idToShow, response)
		{
			var image,
				index = 1,
				thisObj = this;

			if (!response)
			{
				var parameters =
				{
					method: 'getPortraitImages',
                    userID: userID
				};

				$.get
				(
					"/v3/profile-extended/ajax/inline-base.php?", 
					parameters, 
					function(response)
					{
						thisObj.fetchImages(idToShow, response);
						
					}, 
					'json'
				);
			}
			else
			{
				this.clearProfileImages();
				
				jQuery.each
				(
					response.pictures,
					function (id, picture)
					{
						image = thisObj.renderProfileImage(index, id, picture.url, picture.title);

						if (id == idToShow && index != 1)
						{
							image.showImage();
						}
						
						index++;
					}
				);
				
				if (this.isOwner)
				{
					for (index; index <= maxPortraitImages; index++)
					{
						image = this.renderProfileImage(index, 0, defaultPortraitImage, '');
					}
				}
				else
				{
					for (index; index <= 4; index++)
					{
						image = this.renderProfileImage(index, 0, defaultPortraitImage, '');
					}
				}
				
				this.calculateNodeWidth(index - 1, image);
			}
		},
		
		calculateNodeWidth: function (imageCount, image)
		{
			var widthAdjustment = 0;

			if
			(
				jQuery.browser.msie
					&& jQuery.browser.version < 7
			)
			{
				// never ever ask me why
				widthAdjustment = imageCount * 3 - 1;
				$(this.domNode).parent().css('width', $(this.domNode).parent().width() - 1);
				$(image.domNode).css('margin-right', '0px');
				$($(image.domNode).siblings()[0]).css('margin-left', '0px');
			}
			else if
			(
				jQuery.browser.mozilla
					&& jQuery.browser.version.split('.')[0] < 2
					&& jQuery.browser.version.split('.')[1] < 9
			)
			{
				$('#profileImageScroller').css('margin-left', '5px');
			}
			else if
			(
				jQuery.browser.opera
			)
			{
				$(this.domNode).parent().css('margin-left', '5px');
			}
			
			$(this.domNode).css('width', imageCount * $(image.domNode).outerWidth({margin: true}) + widthAdjustment);
		},
		
		clearProfileImages: function ()
		{
			$(this.domNode).empty();
		},
		
		renderProfileImage: function (index, id, url, title, idToShow)
		{
			var profileImageSelector = $('#profileImageSelector').clone();
			profileImageSelector.removeAttr('id');
			profileImageSelector.text(index);
			profileImageSelector.attr('title', title);

			$(this.domNode).append(profileImageSelector);

			if (id == 0)
			{
				if (this.isOwner)
				{
					profileImageSelector.addClass('disabled');

					profileImageSelector.bind
					(
						'click',
						function (e)
						{
							image.showImage();
						}
					);
				}
				else
				{
					profileImageSelector.addClass('disabled').addClass('auto');
				}
			}
			else
			{
				profileImageSelector.bind
				(
					'click',
					function (e)
					{
						image.showImage();
					}
				);
			}
				
			var image = new profileImage(profileImageSelector[0], 'profileImage');
			image.setImage(id, url, title);
			
			if (index == 1)
			{
				image.showImage();
				profileImageSelector[0].isDefault = true;
			}

			return (image);
		}
	}
);

var profileImage = $.klass
(
	formElement,
	{
		initialize: function ($super, domNode, name)
		{
			$super('profileImage', domNode, name);
		},
		
		setImage: function (id, url, title)
		{
			this.id = id;
			this.url = url;
			this.title = title;
		},
		
		showImage: function ()
		{
			var thisObj = this,
				editImageElement;
			
			$('#profileImage').attr('src', this.url);
			$('#profileImage')[0].isDefault = this.domNode.isDefault;
			
			if (editImageElement = $('#editProfileImage'))
			{
				//editImageElement.show();
				
				editImageElement.unbind('click');
				editImageElement.bind
				(
					'click',
					function (e)
					{
						pictureUpload.activate
						(
							thisObj.getImageUploadOptions()
						);
					}
				);
			}
		},
		
		getImageUploadOptions: function ()
		{
			var thisObj = this,
				imageUploadOptions = 
				{
					anchorElement: $('#profileImage'),
					formAction: '/v3/profile-extended/ajax/inline-base.php',
					ajaxMethods: {create: 'createPortraitImage', edit: 'editPortraitImage', remove: 'deletePortraitImage'},
					defaultImage: defaultPortraitImage,
					id: this.id ? this.id : 0,
					showTitle: true,
					maxlengthTitle: 50,
					title: this.title ? this.title : (defaultProfileImageTitle ? defaultProfileImageTitle : ''),
					showSubTitle: false,
					subtitle: 'default subtitle',
					showRemove: true,
					showDefaultCheckbox: true,
					defaultCheckboxLabel: DEFAULTCHECKBOXLABEL,
					startCallback: null,
					completeCallback: function (response, type)
					{
						profileImages.fetchImages
						(
							thisObj.id ? thisObj.id : thisObj.parseResponseForId(response.pictures)
						);
					} 
				};
			
			return (imageUploadOptions);
		},
		
		parseResponseForId: function (picturesObj)
		{
			var id;
			
			jQuery.each
			(
				picturesObj,
				function (index, url)
				{
					id = index;
					return (false);
				}
			);
			
			return (id);
		}	
	}	
);

var qualificationBoxEditElement = $.klass
(
	formElement,
	{
		initialize: function ($super)
		{
			$super('qualificationBoxEditElement', $('#qualificationBox_editElement'), 'qualificationBoxEditElement');

			this.setRootDefaultId(0);
			this.leafs = {};
			this.finalLeafId = 0;
		},

		setRootDefaultId: function (rootDefaultId)
		{
			this.rootDefaultId = rootDefaultId;
		},

		getRootDefaultId: function ()
		{
			return (this.rootDefaultId);
		},

		setPleaseSelectLabel: function (pleaseSelectLabel)
		{
			this.pleaseSelectLabel = pleaseSelectLabel;
		},

		getPleaseSelectLabel: function ()
		{
			return (this.pleaseSelectLabel);
		},

		setSubmitButtonContainer: function (submitButtonContainer)
		{
			this.submitButtonContainer = submitButtonContainer;
		},

		getSubmitButtonContainer: function ()
		{
			return (this.submitButtonContainer);
		},

		showLeaf: function (leafId, parentLeafId)
		{
			this.fetchLeaf
			(
				leafId ? leafId : this.getRootDefaultId(),
				parentLeafId ? parentLeafId : 0
			);
		},

		fetchLeaf: function (leafId, parentLeafId, response)
		{
			var thisObj = this;

			if (!response)
			{
				$.get
				(
					"/v3/profile-extended/ajax/inline-profile.php?",
					{
						method: 'getDocumentSystemWizard',
						leaf: leafId
					},
					function(response)
					{
						thisObj.fetchLeaf(leafId, parentLeafId, response);
					},
					'json'
				);
			}
			else
			{
				if (response.errno != 0)
				{
					showErrorBubble(this.getDomNode(), response.error);
				}
				else
				{
					this.renderLeaf(parentLeafId, response);
					this.checkSubmitAppearance(this.checkSubmitAppearanceButton);
					this.checkSubmitAppearanceButton = false;
				}
			}
		},

		renderLeaf: function (parentLeafId, response)
		{
			this.removeLeaf(parentLeafId);

			switch (response.resulttype)
			{
				case 'dropdown':

					this.renderDropDown(parentLeafId, response.id, response.label, response.resultdata);
					break;

				case 'form':

					if (response.resultdata.length < 1) {
						this.checkSubmitAppearanceButton = true;
					}

					if (response.resultdata.dropdown)
					{
						this.renderDropDown(parentLeafId, response.id, response.label, response.resultdata.dropdown, true);
					}

					if (response.resultdata.text)
					{
						var thisObj = this;

						jQuery.each
						(
							response.resultdata.text,
							function (id, label)
							{
								thisObj.renderText(parentLeafId, id, label, true);
							}
						);
					}

					break;

				default:

					showErrorBubble(this.getDomNode(), 'unknown resulttype');
					break;
			}

			this.finalLeafId = response.id;
		},

		renderDropDown: function (parentId, id, label, data, isForm)
		{
			var thisObj = this,
				containerTemplate = $('#QualificationRow_Template').clone(true),
				dropDownTemplate = $('#QualificationDropDown_Template').clone(true);

			containerTemplate.removeAttr('id');
			containerTemplate.find('#QualificationRowLabel').html(label ? label + ':' : '');

			dropDownTemplate.attr('id', 'leaf_' + id);
			dropDownTemplate.attr('name', id);
			dropDownTemplate[0].isForm = isForm;
			dropDownTemplate.append('<option value="-1">' + this.getPleaseSelectLabel() + '</option>');

			jQuery.each
			(
				data,
				function (optionId, optionLabel)
				{
					dropDownTemplate.append('<option value="' + optionId + '">' + optionLabel + '</option>');
				}
			);

			dropDownTemplate.bind
			(
				'change',
				function ()
				{
					var leafId = dropDownTemplate.val();

					if (leafId.search(/^leaf:/) != -1)
					{
						leafId = leafId.split(':')[1];

						thisObj.showLeaf
						(
							leafId,
							id
						);
					}
					else
					{
						thisObj.removeLeaf(id);
						thisObj.checkSubmitAppearance();
					}

					if (!dropDownTemplate[0].isForm)
					{
						thisObj.finalLeafId = leafId;
					}
				}
			);

			containerTemplate.formElement = isForm ? dropDownTemplate : null;

			containerTemplate.find('#QualificationRowContent').append(dropDownTemplate);
			this.getJObject().find('#qualificationBox_Cargo').append(containerTemplate);

			this.registerLeaf(parentId, id, containerTemplate);
		},

		renderText: function (parentId, id, label, isForm)
		{
			var thisObj = this,
				containerTemplate = $('#QualificationRow_Template').clone(true),
				textTemplate = $('#QualificationText_Template').clone(true);

			containerTemplate.removeAttr('id');
			containerTemplate.find('#QualificationRowLabel').html(label ? label + ':' : '');

			textTemplate.attr('id', 'leaf_' + id);
			textTemplate.attr('name', id);
			textTemplate[0].isForm = isForm;

			textTemplate.bind
			(
				'keyup change',
				function ()
				{
					thisObj.checkSubmitAppearance();
				}
			);

			containerTemplate.formElement = isForm ? textTemplate : null;

			containerTemplate.find('#QualificationRowContent').append(textTemplate);
			this.getJObject().find('#qualificationBox_Cargo').append(containerTemplate);

			this.registerLeaf(parentId, id, containerTemplate);
		},

		registerLeaf: function (parentId, id, containerTemplate)
		{
			if (!this.leafs[parentId])
			{
				this.leafs[parentId] = {};
			}

			this.leafs[parentId][id] = containerTemplate;
		},

		removeLeaf: function (parentId)
		{
			var thisObj = this;

			if (typeof (this.leafs[parentId]) != 'undefined')
			{
				jQuery.each
				(
					this.leafs[parentId],
					function (id, object)
					{
						thisObj.removeLeaf(id);

						object.remove();
						delete(thisObj.leafs[parentId]);
					}
				)
			}
		},

		reset: function ()
		{
			this.removeLeaf(0);
			this.checkSubmitAppearance();
		},

		checkSubmitAppearance: function (force)
		{
			if (force || this.validateForm())
			{
				this.getSubmitButtonContainer().fadeIn();
			}
			else
			{
				this.getSubmitButtonContainer().fadeOut();
			}
		},

		validateForm: function ()
		{
			var thisObj = this,
				formElementValue,
				isValid = true,
				hasFormElement = false;

			jQuery.each
			(
				this.leafs,
				function (parentId, objects)
				{
					jQuery.each
					(
						objects,
						function (leafId, object)
						{
							if (object.formElement)
							{
								hasFormElement = true;
								formElementValue = object.formElement.val();

								if (formElementValue == '' || formElementValue == '-1')
								{
									isValid = false;
									return (false)
								}
							}
						}
					);

					if (!isValid && hasFormElement)
					{
						return (false);
					}
				}
			);

			return (isValid && hasFormElement);
		},

		getFormValues: function ()
		{
			var thisObj = this,
				formValues = {};

			jQuery.each
			(
				this.leafs,
				function (parentId, objects)
				{
					jQuery.each
					(
						objects,
						function (leafId, object)
						{
							if
							(
								object.formElement
									&& object.formElement[0].isForm
							)
							{
								formValues[object.formElement.attr('name')] = object.formElement.val();
							}
						}
					);
				}
			);

			return (formValues);
		},

		submitForm: function (callback, response)
		{
			var thisObj = this;

			if (!response)
			{
				var parameter = this.getFormValues();
				parameter.method = 'submitDocument';
				parameter.leaf = this.finalLeafId;

				$.get
				(
					"/v3/profile-extended/ajax/inline-profile.php?",
					parameter,
					function(response)
					{
						thisObj.submitForm(callback, response);
					},
					'json'
				);
			}
			else
			{
				if (response.errno != 0)
				{
					showErrorBubble(this.getDomNode(), response.error);
				}
				else
				{
					this.reset();
					callback();
				}
			}
		}
	}
);


var membershipBoxEditElement = $.klass
(
	formElement,
	{
		initialize: function ($super)
		{
			$super('membershipBoxEditElement', $('#membershipBox_editElement'), 'membershipBoxEditElement');

			this.setRootDefaultId(0);
			this.leafs = {};
			this.finalLeafId = 0;
		},

		setRootDefaultId: function (rootDefaultId)
		{
			this.rootDefaultId = rootDefaultId;
		},

		getRootDefaultId: function ()
		{
			return (this.rootDefaultId);
		},

		setPleaseSelectLabel: function (pleaseSelectLabel)
		{
			this.pleaseSelectLabel = pleaseSelectLabel;
		},

		getPleaseSelectLabel: function ()
		{
			return (this.pleaseSelectLabel);
		},

		setSubmitButtonContainer: function (submitButtonContainer)
		{
			this.submitButtonContainer = submitButtonContainer;
		},

		getSubmitButtonContainer: function ()
		{
			return (this.submitButtonContainer);
		},

		showLeaf: function (leafId, parentLeafId)
		{
			this.fetchLeaf
			(
				leafId ? leafId : this.getRootDefaultId(),
				parentLeafId ? parentLeafId : 0
			);
		},

		fetchLeaf: function (leafId, parentLeafId, response)
		{
			var thisObj = this;

			if (!response)
			{
				$.get
				(
					"/v3/profile-extended/ajax/inline-profile.php?",
					{
						method: 'getDocumentSystemWizard',
						leaf: leafId
					},
					function(response)
					{
						thisObj.fetchLeaf(leafId, parentLeafId, response);
					},
					'json'
				);
			}
			else
			{
				if (response.errno != 0)
				{
					showErrorBubble(this.getDomNode(), response.error);
				}
				else
				{
					this.renderLeaf(parentLeafId, response);
					this.checkSubmitAppearance(this.checkSubmitAppearanceButton);
					this.checkSubmitAppearanceButton = false;

				}
			}
		},

		renderLeaf: function (parentLeafId, response)
		{
			this.removeLeaf(parentLeafId);

			switch (response.resulttype)
			{
				case 'dropdown':

					this.renderDropDown(parentLeafId, response.id, response.label, response.resultdata);
					break;

				case 'form':

					if (response.resultdata.length < 1) {
						this.checkSubmitAppearanceButton = true;
					}

					if (response.resultdata.dropdown)
					{
						this.renderDropDown(parentLeafId, response.id, response.label, response.resultdata.dropdown, true);
					}

					if (response.resultdata.text)
					{
						var thisObj = this;

						jQuery.each
						(
							response.resultdata.text,
							function (id, label)
							{
								thisObj.renderText(parentLeafId, id, label, true);
							}
						);
					}

					break;

				default:

					showErrorBubble(this.getDomNode(), 'unknown resulttype');
					break;
			}

			this.finalLeafId = response.id;
		},

		renderDropDown: function (parentId, id, label, data, isForm)
		{
			var thisObj = this,
				containerTemplate = $('#MembershipRow_Template').clone(true),
				dropDownTemplate = $('#MembershipDropDown_Template').clone(true);

			containerTemplate.removeAttr('id');
			containerTemplate.find('#MembershipRowLabel').html(label ? label + ':' : '');

			dropDownTemplate.attr('id', 'leaf_' + id);
			dropDownTemplate.attr('name', id);
			dropDownTemplate[0].isForm = isForm;
			dropDownTemplate.append('<option value="-1">' + this.getPleaseSelectLabel() + '</option>');

			jQuery.each
			(
				data,
				function (optionId, optionLabel)
				{
					dropDownTemplate.append('<option value="' + optionId + '">' + optionLabel + '</option>');
				}
			);

			dropDownTemplate.bind
			(
				'change',
				function ()
				{
					var leafId = dropDownTemplate.val();

					if (leafId.search(/^leaf:/) != -1)
					{
						leafId = leafId.split(':')[1];

						thisObj.showLeaf
						(
							leafId,
							id
						);
					}
					else
					{
						thisObj.removeLeaf(id);
						thisObj.checkSubmitAppearance();
					}

					if (!dropDownTemplate[0].isForm)
					{
						thisObj.finalLeafId = leafId;
					}
				}
			);

			containerTemplate.formElement = isForm ? dropDownTemplate : null;

			containerTemplate.find('#MembershipRowContent').append(dropDownTemplate);
			this.getJObject().find('#membershipBox_Cargo').append(containerTemplate);

			this.registerLeaf(parentId, id, containerTemplate);
		},

		renderText: function (parentId, id, label, isForm)
		{
			var thisObj = this,
				containerTemplate = $('#MembershipRow_Template').clone(true),
				textTemplate = $('#MembershipText_Template').clone(true);

			containerTemplate.removeAttr('id');
			containerTemplate.find('#MembershipRowLabel').html(label ? label + ':' : '');

			textTemplate.attr('id', 'leaf_' + id);
			textTemplate.attr('name', id);
			textTemplate[0].isForm = isForm;

			textTemplate.bind
			(
				'keyup change',
				function ()
				{
					thisObj.checkSubmitAppearance();
				}
			);

			containerTemplate.formElement = isForm ? textTemplate : null;

			containerTemplate.find('#MembershipRowContent').append(textTemplate);
			this.getJObject().find('#membershipBox_Cargo').append(containerTemplate);

			this.registerLeaf(parentId, id, containerTemplate);
		},

		registerLeaf: function (parentId, id, containerTemplate)
		{
			if (!this.leafs[parentId])
			{
				this.leafs[parentId] = {};
			}

			this.leafs[parentId][id] = containerTemplate;
		},

		removeLeaf: function (parentId)
		{
			var thisObj = this;

			if (typeof (this.leafs[parentId]) != 'undefined')
			{
				jQuery.each
				(
					this.leafs[parentId],
					function (id, object)
					{
						thisObj.removeLeaf(id);

						object.remove();
						delete(thisObj.leafs[parentId]);
					}
				)
			}
		},

		reset: function ()
		{
			this.removeLeaf(0);
			this.checkSubmitAppearance();
		},

		checkSubmitAppearance: function (force)
		{
			if (force || this.validateForm())
			{
				this.getSubmitButtonContainer().fadeIn();
			}
			else
			{
				this.getSubmitButtonContainer().fadeOut();
			}
		},

		validateForm: function ()
		{
			var thisObj = this,
				formElementValue,
				isValid = true,
				hasFormElement = false;

			jQuery.each
			(
				this.leafs,
				function (parentId, objects)
				{
					jQuery.each
					(
						objects,
						function (leafId, object)
						{
							if (object.formElement)
							{
								hasFormElement = true;
								formElementValue = object.formElement.val();

								if (formElementValue == '' || formElementValue == '-1')
								{
									isValid = false;
									return (false)
								}
							}
						}
					);

					if (!isValid && hasFormElement)
					{
						return (false);
					}
				}
			);

			return (isValid && hasFormElement);
		},

		getFormValues: function ()
		{
			var thisObj = this,
				formValues = {};

			jQuery.each
			(
				this.leafs,
				function (parentId, objects)
				{
					jQuery.each
					(
						objects,
						function (leafId, object)
						{
							if
							(
								object.formElement
									&& object.formElement[0].isForm
							)
							{
								formValues[object.formElement.attr('name')] = object.formElement.val();
							}
						}
					);
				}
			);

			return (formValues);
		},

		submitForm: function (callback, response)
		{
			var thisObj = this;

			if (!response)
			{
				var parameter = this.getFormValues();
				parameter.method = 'submitDocument';
				parameter.leaf = this.finalLeafId;

				$.get
				(
					"/v3/profile-extended/ajax/inline-profile.php?",
					parameter,
					function(response)
					{
						thisObj.submitForm(callback, response);
					},
					'json'
				);
			}
			else
			{
				if (response.errno != 0)
				{
					showErrorBubble(this.getDomNode(), response.error);
				}
				else
				{
					this.reset();
					callback();
				}
			}
		}
	}
);

var liabilityEditElement = $.klass
(
	formElement,
	{
		initialize: function ($super)
		{
			$super('liabilityEditElement', $('#liability_editElement'), 'liabilityEditElement');
			
			this.setRootDefaultId(0);
			this.leafs = {};
			this.finalLeafId = 0;
		},
		
		setRootDefaultId: function (rootDefaultId)
		{
			this.rootDefaultId = rootDefaultId;
		},
		
		getRootDefaultId: function ()
		{
			return (this.rootDefaultId);
		},
		
		setPleaseSelectLabel: function (pleaseSelectLabel)
		{
			this.pleaseSelectLabel = pleaseSelectLabel;
		},
		
		getPleaseSelectLabel: function ()
		{
			return (this.pleaseSelectLabel);
		},
		
		setSubmitButtonContainer: function (submitButtonContainer)
		{
			this.submitButtonContainer = submitButtonContainer;
		},
		
		getSubmitButtonContainer: function ()
		{
			return (this.submitButtonContainer);
		},
		
		setDocumentId: function (documentId)
		{
			this.documentId = documentId
		},
		
		getDocumentId: function ()
		{
			return (this.documentId);
		},
		
		showLeaf: function (leafId, parentLeafId)
		{
			this.fetchLeaf
			(
				leafId ? leafId : this.getRootDefaultId(),
				parentLeafId ? parentLeafId : 0 
			);
		},
		
		showNoCallLeaf: function ()
		{
			var cargo = this.getJObject().find('#liability_Cargo');
			var dropDownTemplate = cargo.find('#LiabilityYesNoDropDown_Template')[0];
			
			if (!dropDownTemplate)
			{
				var thisObj = this,
				containerTemplate = $('#LiabilityRow_Template').clone(true),
				dropDownTemplate = $('#LiabilityYesNoDropDown_Template').clone(true);

				containerTemplate.removeAttr('id');
						
				containerTemplate.find('#LiabilityRowContent').append(dropDownTemplate);
				cargo.append(containerTemplate);
			}
		},
		
		fetchLeaf: function (leafId, parentLeafId, response)
		{
			var thisObj = this;
			
			if (!response)
			{
				$.get
				(
					"/v3/profile-extended/ajax/inline-profile.php?",
					{
						method: 'getDocumentSystemWizard',
						leaf: leafId
					}, 
					function(response)
					{
						thisObj.fetchLeaf(leafId, parentLeafId, response);
					}, 
					'json'
				);
			}
			else
			{
				if (response.errno != 0)
				{
					showErrorBubble(this.getDomNode(), response.error);
				}
				else
				{
					this.renderLeaf(parentLeafId, response);
					this.checkSubmitAppearance();
				}
			}
		},
		
		renderLeaf: function (parentLeafId, response)
		{
			this.removeLeaf(parentLeafId);

			switch (response.resulttype)
			{
				case 'dropdown':
				
					this.renderDropDown(parentLeafId, response.id, response.label, response.resultdata);
					break;

				case 'form':
					
					if (response.resultdata.dropdown)
					{
						this.renderDropDown(parentLeafId, response.id, response.label, response.resultdata.dropdown, true);
					}

					if (response.resultdata.text)
					{
						var thisObj = this;

						jQuery.each
						(
							response.resultdata.text,
							function (id, label)
							{
								thisObj.renderText(parentLeafId, id, label, true);
							}
						);
					}

					break;
					
				default:
				
					showErrorBubble(this.getDomNode(), 'unknown resulttype');
					break;
			}
			
			this.finalLeafId = response.id;				
		},
		
		renderDropDown: function (parentId, id, label, data, isForm)
		{
			var thisObj = this,
				containerTemplate = $('#LiabilityRow_Template').clone(true),
				dropDownTemplate = $('#LiabilityDropDown_Template').clone(true);

			containerTemplate.removeAttr('id');
			containerTemplate.find('#LiabilityRowLabel').html(label ? label + ':' : '');
			
			dropDownTemplate.attr('id', 'leaf_' + id);
			dropDownTemplate.attr('name', id);
			dropDownTemplate[0].isForm = isForm;
			dropDownTemplate.append('<option value="-1">' + this.getPleaseSelectLabel() + '</option>');

			jQuery.each
			(
				data,
				function (optionId, optionLabel)
				{
					dropDownTemplate.append('<option value="' + optionId + '">' + optionLabel + '</option>');
				}
			);
			
			dropDownTemplate.bind
			(
				'change',
				function ()
				{
					var leafId = dropDownTemplate.val();

					if (leafId.search(/^leaf:/) != -1)
					{
						leafId = leafId.split(':')[1];
						
						thisObj.showLeaf
						(
							leafId,
							id
						);
					}
					else
					{
						thisObj.removeLeaf(id);
						thisObj.checkSubmitAppearance();
					}

					if (!dropDownTemplate[0].isForm)
					{
						thisObj.finalLeafId = leafId;
					}
				}
			);

			containerTemplate.formElement = isForm ? dropDownTemplate : null;

			containerTemplate.find('#LiabilityRowContent').append(dropDownTemplate);
			this.getJObject().find('#liability_Cargo').append(containerTemplate);
			
			this.registerLeaf(parentId, id, containerTemplate);
		},
		
		renderText: function (parentId, id, label, isForm)
		{
			var thisObj = this,
				containerTemplate = $('#LiabilityRow_Template').clone(true),
				textTemplate = $('#LiabilityText_Template').clone(true);

			containerTemplate.removeAttr('id');
			containerTemplate.find('#LiabilityRowLabel').html(label ? label + ':' : '');
			
			textTemplate.attr('id', 'leaf_' + id);
			textTemplate.attr('name', id);
			textTemplate[0].isForm = isForm;
			
			textTemplate.bind
			(
				'keyup change',
				function ()
				{
					thisObj.checkSubmitAppearance();
				}
			);

			containerTemplate.formElement = isForm ? textTemplate : null;

			containerTemplate.find('#LiabilityRowContent').append(textTemplate);
			this.getJObject().find('#liability_Cargo').append(containerTemplate);
			
			this.registerLeaf(parentId, id, containerTemplate);
		},

		registerLeaf: function (parentId, id, containerTemplate)
		{
			if (!this.leafs[parentId])
			{
				this.leafs[parentId] = {};
			}
			
			this.leafs[parentId][id] = containerTemplate;
		},
		
		removeLeaf: function (parentId)
		{
			var thisObj = this;
			
			if (typeof (this.leafs[parentId]) != 'undefined')
			{
				jQuery.each
				(
					this.leafs[parentId],
					function (id, object)
					{
						thisObj.removeLeaf(id);

						object.remove();
						delete(thisObj.leafs[parentId]);
					}
				)
			}
		},
		 
		reset: function ()
		{
			this.removeLeaf(0);
			this.checkSubmitAppearance();
		},
		
		checkSubmitAppearance: function ()
		{
			if (this.validateForm())
			{
				this.getSubmitButtonContainer().fadeIn();
			}
			else
			{
				this.getSubmitButtonContainer().fadeOut();
			}
		},
		
		validateForm: function ()
		{
			var thisObj = this,
				formElementValue,
				isValid = true,
				hasFormElement = false;
			
			jQuery.each
			(
				this.leafs,
				function (parentId, objects)
				{
					jQuery.each
					(
						objects,
						function (leafId, object)
						{
							if (object.formElement)
							{
								hasFormElement = true;
								formElementValue = object.formElement.val();

								if (formElementValue == '' || formElementValue == '-1')
								{
									isValid = false;
									return (false)
								}
							}
						}
					);

					if (!isValid && hasFormElement)
					{
						return (false);
					}
				}
			);

			return (isValid && hasFormElement);
		},
		
		getFormValues: function ()
		{
			var thisObj = this,
				formValues = {};
			
			jQuery.each
			(
				this.leafs,
				function (parentId, objects)
				{
					jQuery.each
					(
						objects,
						function (leafId, object)
						{
							if
							(
								object.formElement
									&& object.formElement[0].isForm
							)
							{
								formValues[object.formElement.attr('name')] = object.formElement.val();
							}
						}
					);
				}
			);

			return (formValues);
		},
		
		submitForm: function (callback, response)
		{
			var thisObj = this;
			
			if (!response)
			{
				var parameter = this.getFormValues();
				parameter.method = 'submitDocument';
				parameter.leaf = this.finalLeafId;  

				$.get
				(
					"/v3/profile-extended/ajax/inline-profile.php?",
					parameter, 
					function(response)
					{
						thisObj.submitForm(callback, response);
					}, 
					'json'
				);
			}
			else
			{
				if (response.errno != 0)
				{
					showErrorBubble(this.getDomNode(), response.error);
				}
				else
				{
					this.reset();
					//documentUploadDiv.reload();
					callback();
				}
			}
		},
		
		deleteLiability: function (response)
		{
			if (this.getDocumentId())
			{
				var thisObj = this;
				
				if (!response)
				{
					var parameter = new Object();
					parameter.method = 'deleteQualification';
					parameter.document = this.getDocumentId();
					
					$.get
					(
						"/v3/profile-extended/ajax/inline-profile.php?",
						parameter, 
						function(response)
						{
							thisObj.deleteLiability(response);
						}, 
						'json'
					);
				}
				else
				{
					if (response.errno != 0)
					{
						showErrorBubble(this.getDomNode(), response.error);
					}
					else
					{
						this.setDocumentId(null);
						insurence.fetchData(this.getRootDefaultId());
					}
				}
			}
		}
	}
);

var traineesEditElement = $.klass
(
	formElement,
	{
		initialize: function ($super)
		{
			$super('traineesEditElement', $('#trainees_editElement'), 'traineesEditElement');
			
			this.setRootDefaultId(0);
			this.leafs = {};
			this.finalLeafId = 0;
		},
		
		setRootDefaultId: function (rootDefaultId)
		{
			this.rootDefaultId = rootDefaultId;
		},
		
		getRootDefaultId: function ()
		{
			return (this.rootDefaultId);
		},
		
		setPleaseSelectLabel: function (pleaseSelectLabel)
		{
			this.pleaseSelectLabel = pleaseSelectLabel;
		},
		
		getPleaseSelectLabel: function ()
		{
			return (this.pleaseSelectLabel);
		},
		
		setSubmitButtonContainer: function (submitButtonContainer)
		{
			this.submitButtonContainer = submitButtonContainer;
		},
		
		getSubmitButtonContainer: function ()
		{
			return (this.submitButtonContainer);
		},
		
		setDocumentId: function (documentId)
		{
			this.documentId = documentId
		},
		
		getDocumentId: function ()
		{
			return (this.documentId);
		},
		
		showLeaf: function (leafId, parentLeafId)
		{
			this.fetchLeaf
			(
				leafId ? leafId : this.getRootDefaultId(),
				parentLeafId ? parentLeafId : 0 
			);
		},
		
		showNoCallLeaf: function ()
		{
			var cargo = this.getJObject().find('#trainees_Cargo');
			var dropDownTemplate = cargo.find('#TraineesYesNoDropDown_Template')[0];
			
			if (!dropDownTemplate)
			{
				var thisObj = this,
				containerTemplate = $('#TraineesRow_Template').clone(true),
				dropDownTemplate = $('#TraineesYesNoDropDown_Template').clone(true);

				containerTemplate.removeAttr('id');
						
				containerTemplate.find('#TraineesRowContent').append(dropDownTemplate);
				cargo.append(containerTemplate);
			}
		},
		
		fetchLeaf: function (leafId, parentLeafId, response)
		{
			var thisObj = this;
			
			if (!response)
			{
				$.get
				(
					"/v3/profile-extended/ajax/inline-profile.php?",
					{
						method: 'getDocumentSystemWizard',
						leaf: leafId
					}, 
					function(response)
					{
						thisObj.fetchLeaf(leafId, parentLeafId, response);
					}, 
					'json'
				);
			}
			else
			{
				if (response.errno != 0)
				{
					showErrorBubble(this.getDomNode(), response.error);
				}
				else
				{
					this.renderLeaf(parentLeafId, response);
					this.checkSubmitAppearance();
				}
			}
		},
		
		renderLeaf: function (parentLeafId, response)
		{
			this.removeLeaf(parentLeafId);
			
			switch (response.resulttype)
			{
				case 'dropdown':
				
					this.renderDropDown(parentLeafId, response.id, response.label, response.resultdata);
					break;

				case 'form':
					
					if (response.resultdata.dropdown)
					{
						this.renderDropDown(parentLeafId, response.id, response.label, response.resultdata.dropdown, true);
					}

					if (response.resultdata.text)
					{
						var thisObj = this;

						jQuery.each
						(
							response.resultdata.text,
							function (id, label)
							{
								thisObj.renderText(parentLeafId, id, label, true);
							}
						);
					}

					break;
					
				default:
				
					showErrorBubble(this.getDomNode(), 'unknown resulttype');
					break;
			}
			
			this.finalLeafId = response.id;				
		},
		
		renderDropDown: function (parentId, id, label, data, isForm)
		{
			var thisObj = this,
				containerTemplate = $('#TraineesRow_Template').clone(true),
				dropDownTemplate = $('#TraineesDropDown_Template').clone(true);

			containerTemplate.removeAttr('id');
			containerTemplate.find('#TraineesRowLabel').html(label ? label + ':' : '');
			
			dropDownTemplate.attr('id', 'leaf_' + id);
			dropDownTemplate.attr('name', id);
			dropDownTemplate[0].isForm = isForm;
			dropDownTemplate.append('<option value="-1">' + this.getPleaseSelectLabel() + '</option>');
			
			jQuery.each
			(
				data,
				function (optionId, optionLabel)
				{
					dropDownTemplate.append('<option value="' + optionId + '">' + optionLabel + '</option>');
				}
			);
			
			dropDownTemplate.bind
			(
				'change',
				function ()
				{
					var leafId = dropDownTemplate.val();

					if (leafId.search(/^leaf:/) != -1)
					{
						leafId = leafId.split(':')[1];
						
						thisObj.showLeaf
						(
							leafId,
							id
						);
					}
					else
					{
						thisObj.removeLeaf(id);
						thisObj.checkSubmitAppearance();
					}

					if (!dropDownTemplate[0].isForm)
					{
						thisObj.finalLeafId = leafId;
					}
				}
			);

			containerTemplate.formElement = isForm ? dropDownTemplate : null;

			containerTemplate.find('#TraineesRowContent').append(dropDownTemplate);
			this.getJObject().find('#trainees_Cargo').append(containerTemplate);
			
			this.registerLeaf(parentId, id, containerTemplate);
		},
		
		renderText: function (parentId, id, label, isForm)
		{
			var thisObj = this,
				containerTemplate = $('#TraineesRow_Template').clone(true),
				textTemplate = $('#TraineesText_Template').clone(true);

			containerTemplate.removeAttr('id');
			containerTemplate.find('#TraineesRowLabel').html(label ? label + ':' : '');
			
			textTemplate.attr('id', 'leaf_' + id);
			textTemplate.attr('name', id);
			textTemplate[0].isForm = isForm;
			
			textTemplate.bind
			(
				'keyup change',
				function ()
				{
					thisObj.checkSubmitAppearance();
				}
			);

			containerTemplate.formElement = isForm ? textTemplate : null;

			containerTemplate.find('#TraineesRowContent').append(textTemplate);
			this.getJObject().find('#trainees_Cargo').append(containerTemplate);
			
			this.registerLeaf(parentId, id, containerTemplate);
		},

		registerLeaf: function (parentId, id, containerTemplate)
		{
			if (!this.leafs[parentId])
			{
				this.leafs[parentId] = {};
			}
			
			this.leafs[parentId][id] = containerTemplate;
		},
		
		removeLeaf: function (parentId)
		{
			var thisObj = this;
			
			if (typeof (this.leafs[parentId]) != 'undefined')
			{
				jQuery.each
				(
					this.leafs[parentId],
					function (id, object)
					{
						thisObj.removeLeaf(id);

						object.remove();
						delete(thisObj.leafs[parentId]);
					}
				)
			}
		},
		 
		reset: function ()
		{
			this.removeLeaf(0);
			this.checkSubmitAppearance();
		},
		
		checkSubmitAppearance: function ()
		{
			if (this.validateForm())
			{
				this.getSubmitButtonContainer().fadeIn();
			}
			else
			{
				this.getSubmitButtonContainer().fadeOut();
			}
		},
		
		validateForm: function ()
		{
			var thisObj = this,
				formElementValue,
				isValid = true,
				hasFormElement = false;
			
			jQuery.each
			(
				this.leafs,
				function (parentId, objects)
				{
					jQuery.each
					(
						objects,
						function (leafId, object)
						{
							if (object.formElement)
							{
								hasFormElement = true;
								formElementValue = object.formElement.val();

								if (formElementValue == '' || formElementValue == '-1')
								{
									isValid = false;
									return (false)
								}
							}
						}
					);

					if (!isValid && hasFormElement)
					{
						return (false);
					}
				}
			);

			return (isValid && hasFormElement);
		},
		
		getFormValues: function ()
		{
			var thisObj = this,
				formValues = {};
			
			jQuery.each
			(
				this.leafs,
				function (parentId, objects)
				{
					jQuery.each
					(
						objects,
						function (leafId, object)
						{
							if
							(
								object.formElement
									&& object.formElement[0].isForm
							)
							{
								formValues[object.formElement.attr('name')] = object.formElement.val();
							}
						}
					);
				}
			);

			return (formValues);
		},
		
		submitForm: function (callback, response)
		{
			var thisObj = this;
			
			if (!response)
			{
				var parameter = this.getFormValues();
				parameter.method = 'submitDocument';
				parameter.leaf = this.finalLeafId;  

				$.get
				(
					"/v3/profile-extended/ajax/inline-profile.php?",
					parameter, 
					function(response)
					{
						thisObj.submitForm(callback, response);
					}, 
					'json'
				);
			}
			else
			{
				if (response.errno != 0)
				{
					showErrorBubble(this.getDomNode(), response.error);
				}
				else
				{
					this.reset();
					//documentUploadDiv.reload();
					callback();
				}
			}
		},
		
		deleteAcceptTrainees: function (documentID, response)
		{
			if (this.getDocumentId())
			{
				var thisObj = this;
				
				if (!response)
				{
					var parameter = new Object();
					parameter.method = 'deleteQualification';
					parameter.document = this.getDocumentId();
					
					$.get
					(
						"/v3/profile-extended/ajax/inline-profile.php?",
						parameter, 
						function(response)
						{
							thisObj.deleteAcceptTrainees(documentID, response);
						}, 
						'json'
					);
				}
				else
				{
					if (response.errno != 0)
					{
						showErrorBubble(this.getDomNode(), response.error);
					}
					else
					{
						this.setDocumentId(null);
						educationCompany.fetchData(this.getRootDefaultId());
					}
				}
			}
		}
	}
);

var companyProfilBox = $.klass
(
	formElement,
	{
		initialize: function ($super, type, domNode, name)
		{
			$super(type, domNode, name);
			this.setType('companyProfilBox');
		},

		handleWatchedEvent: function (e, watchedElement, event)
		{
			switch (event)
			{
				case 'click':
					
					switch (watchedElement.type)
					{
						case 'tabElement':
						
							if (watchedElement.name == 'tabCompanyProfil')
							{
								this.show();
							}
							else
							{
								this.hide();
							}	
										
							break;
					}

					break;
			}
		}
	}
);

var editButton = $.klass
(
	formElement,
	{
		initialize: function ($super, type, domNode, name)
		{
			$super(type, domNode, name);
			this.setType('editButton');
		}
	}
);

var saveButton = $.klass
(
	formElement,
	{
		initialize: function ($super, type, domNode, name)
		{
			$super(type, domNode, name);
			this.setType('saveButton');
		}
	}
);

var createButton = $.klass
(
	formElement,
	{
		initialize: function ($super, type, domNode, name)
		{
			$super(type, domNode, name);
			this.setType('createButton');
		}
	}
);

var closeButton = $.klass
(
	formElement,
	{
		initialize: function ($super, type, domNode, name)
		{
			$super(type, domNode, name);
			this.setType('closeButton');
		}
	}
);

var deleteButton = $.klass
(
	formElement,
	{
		initialize: function ($super, type, domNode, name)
		{
			$super(type, domNode, name);
			this.setType('deleteButton');
		}
	}
);

var companyProfilElement = $.klass
(
	formElement,
	{
		initialize: function ($super, type, domNode, name)
		{
			$super(type, domNode, name);
			this.setType('companyProfilElement');
		},
		
		fetchData: function (data, response)
		{
			var thisObj = this;

			if (!response)
			{
				var parameters = new Object();

				switch (this.name)
				{
					case 'legalForm':
						
						parameters.method = 'setLegalform';
						parameters.value = data.value;
						break;
					
					case 'employeeNumber':
					
						parameters.method = 'setNumberOfEmployees';
						parameters.range = data.value;
						break;
						
					case 'insurence':
					
						parameters.method = 'getUserDocumentDetails';
						parameters.leaf = data;
						break;
						
					case 'yearOfFoundation':
					
						parameters.method = 'setYearOfFoundation';
						parameters.year = data.value;
						break;
					
					case 'educationCompany':
					
						parameters.method = 'getUserDocumentDetails';
						parameters.leaf = data;
						break;
						
					case 'openingTimes':
					
						parameters.method = 'setOpeningTimes';
						parameters.text = data.value;
						break;
				}
												
				$.get
				(
					"/v3/profile-extended/ajax/inline-profile.php?", 
					parameters, 
					function(response)
					{
						thisObj.fetchData(data, response);
					}, 
					'json'
				);
			}
			else
			{
				if (response.errno != 0)
				{
					if (response.error != '')
					{
						showErrorBubble(companyProfilBox.watchedElement.domNode, response.error);
					}
				}
				else
				{
					switch (this.name)
					{
						case 'legalForm':
						
							$("#legalForm").html(response.result);
							break;
						
						case 'employeeNumber':
						
							this.getJObject().html(response.range);
							break;
							
						case 'insurence':
							
							var html = '';

							if (response.data.marked)
							{
								html += globalJsPhrase_yes;
								
								if (!response.data.reviewed)
								{
									html += ' (' + globalJsPhrase_testing + ')';
								}
							}
							else
							{
								html += globalJsPhrase_unspecified;
							}
							
							if (response.data.documentID)
							{
								liabilityEditor.setDocumentId(response.data.documentID);
							}
							
							this.getJObject().html(html);
							break;
							
						case 'yearOfFoundation':
						
							this.getJObject().html(response.year);
							break;
						
						case 'educationCompany':
					
							var html = '';
							
							if (response.data.marked)
							{
								html += globalJsPhrase_yes;
								
								if (!response.data.reviewed)
								{
									html += ' (' + globalJsPhrase_testing + ')';
								}
							}
							else
							{
								html += globalJsPhrase_unspecified;
							}
							
							if (response.data.documentID)
							{
								traineesEditor.setDocumentId(response.data.documentID);
							}
							
							this.getJObject().html(html);
							break;
						
						case 'openingTimes':
					
							this.getJObject().html(response.text);
							break;
					}
				}
				
				companyProfilBox.openEditor = null;
				companyProfilBox.watchedElement = null;
			}
		},
		
		handleWatchedEvent: function (e, watchedElement, event)
		{
			switch (event)
			{
				case 'click':

					switch (watchedElement.type)
					{
						case 'closeButton':
						
							switch (this.getName())
							{
								case 'insurence':
								
									$('#liability_editElement').fadeOut('slow');
									liabilityEditor.reset();

									break;

								case 'educationCompany':
								
									$('#trainees_editElement').fadeOut('slow');
									traineesEditor.reset();

									break;
							}
							
							break;

						case 'editButton':

							switch (this.getName())
							{
								case 'insurence':

									this.positionEditLayer('liability_editElement', 'insurence', -11, 0);
									$('#liability_editElement').fadeIn('slow');

									liabilityEditor.showNoCallLeaf();
								
									break;
									
								case 'educationCompany':

									this.positionEditLayer('trainees_editElement', 'educationCompany', -11, 0);
									$('#trainees_editElement').fadeIn('slow');

									traineesEditor.showNoCallLeaf();
								
									break;
									
								default:
								
									if (companyProfilBox.openEditor)
									{
										companyProfilBox.openEditor.getJObject().show();
										$('#' + companyProfilBox.openEditor.name + '_editElement').hide();
										companyProfilBox.watchedElement.getJObject().show();
										companyProfilBox.openEditor = null;
										companyProfilBox.watchedElement = null;
									}
									
									if (watchedElement.name == 'editOpeningTimes')
									{
										if (jQuery.browser.msie)
										{
											this.positionEditLayer(this.name + '_editElement', this.name, -7, -70);
										}
										else
										{
											this.positionEditLayer(this.name + '_editElement', this.name, 0, 0);							
										}
									}
									
									this.hide();
									$('#' + this.name + '_editElement').show();
									watchedElement.getJObject().hide();
		
									companyProfilBox.openEditor = this;
									companyProfilBox.watchedElement = watchedElement;

									break;
							}
							
							break;
							
						case 'saveButton':
						
							switch (this.getName())
							{
								case 'insurence':
								
									var thisObj = this;

									liabilityEditor.submitForm
									(
										function ()
										{
											$('#liability_editElement').fadeOut('slow');
											thisObj.fetchData(liabilityEditor.getRootDefaultId());
										}
									);

									break;
									
								case 'educationCompany':
								
									var thisObj = this;
									
									traineesEditor.submitForm
									(
										function ()
										{
											$('#trainees_editElement').fadeOut('slow');
											thisObj.fetchData(traineesEditor.getRootDefaultId());
										}
									);

									break;
									
								default:

									this.getJObject().show();
									$('#' + this.name + '_editElement').hide();
									companyProfilBox.watchedElement.getJObject().show();
																
									this.fetchData($('#' + this.name + 'Input')[0]);
								
									break;
							}
					}

					break;
			}
		}
	}
);

var moreInfoElement = $.klass
(
	formElement,
	{
		initialize: function ($super, type, domNode, name)
		{
			$super(type, domNode, name);
			this.setType('moreInfoElement');
		},
		
		fetchData: function (id, response)
		{
			var thisObj = this;

			if (!response)
			{
				var parameters = new Object();

				switch (moreInfoBox.action)
				{
					case 'create':

						parameters.method = 'createMoreInformation';
						parameters.title = $('#moreInfoTitle').val();
						parameters.description = $('#moreInfoDescription').val();
						break;
						
					case 'edit':

						parameters.method = 'editMoreInformation';
						parameters.id = $('#moreInfoId').val();
						parameters.title = $('#moreInfoTitle').val();
						parameters.description = $('#moreInfoDescription').val();
						break;
						
					case 'delete':
					
						parameters.method = 'deleteMoreInformation';
						parameters.id = id;
						break;
				}
												
				$.get
				(
					"/v3/profile-extended/ajax/inline-profile.php?", 
					parameters, 
					function(response)
					{
						thisObj.fetchData(id, response);
					}, 
					'json'
				);
			}
			else
			{
				if (response.errno != 0)
				{
					if (response.error != '')
					{
						showErrorBubble(companyProfilBox.watchedElement.domNode, response.error);
					}
				}
				else
				{
					switch (moreInfoBox.action)
					{
						case 'create':
							
							var html = '<div id="moreInfo_' + response.id + '" class="moreInfosDiv">';
							html += '<img id="editMoreInfo_' + response.id + '" style="position: absolute; top: 0px; right: 15px; cursor: pointer;" src="http://static.myhammer.com/v3/live/icons/icons_edit_blue_12x12.gif" />';
							html += '<img id="deleteMoreInfo_' + response.id + '" style="position: absolute; top: -2px; right: 0px; cursor: pointer;" src="http://static.myhammer.com/v3/live/icons/x.gif" />';
							html += '<div id="moreInfosTitle_' + response.id + '" class="moreInfosTitle">';
							html += response.data.title;
							html += '</div>';
							html += '<div id="moreInfosDescription_' + response.id + '" class="moreInfosDescription">';
							html += response.data.description.replace(/\n/g, '<br>');
							html += '</div></div>';

							html += '<script type="text/javascript">';
							html += 'var moreInfo_' + response.id + ' = new moreInfoElement(null, $("#moreInfo_' + response.id + '")[0], "moreInfo_' + response.id + '");';
							html += 'moreInfo_' + response.id + '.display({visible:true});';
							html += 'moreInfo_' + response.id + '.id = "' + response.id + '";';
							html += 'moreInfo_' + response.id + '.title = "' + response.data.title + '";';
							html += 'moreInfo_' + response.id + '.description = "' + response.data.description.replace(/\n/g, '<br>') + '";';
							html += 'var deleteMoreInfo_' + response.id + ' = new deleteButton(null, $("#deleteMoreInfo_' + response.id + '")[0], "deleteMoreInfo_' + response.id + '");';
							html += 'deleteMoreInfo_' + response.id + '.display({visible:true});';
							html += 'deleteMoreInfo_' + response.id + '.acceptWatcher(moreInfo_' + response.id + ', "click");';
							html += 'var editMoreInfo_' + response.id + ' = new editButton(null, $("#editMoreInfo_' + response.id + '")[0], "editMoreInfo_' + response.id + '");';
							html += 'editMoreInfo_' + response.id + '.display({visible:true});';
							html += 'editMoreInfo_' + response.id + '.acceptWatcher(moreInfo_' + response.id + ', "click");';
							html += '</script>';
														
							var content = html + this.getJObject().html();
							this.getJObject().html(content);
							moreInfoBox.action = null;

							break;
						
						case 'edit':

							$('#moreInfosTitle_' + response.id).html(response.data.title);
							$('#moreInfosDescription_' + response.id).html(response.data.description.replace(/\n/g, '<br>'));
							var moreInfoObject = $('#moreInfo_' + response.id)[0].owner;
							moreInfoObject.title = response.data.title;
							moreInfoObject.description = response.data.description.replace(/\n/g, '<br>');
							moreInfoBox.action = null;
							break;
							
						case 'delete':
						
							$('#moreInfo_' + id).remove();
							moreInfoBox.action = null;
							break;
					}
				}
				
				companyProfilBox.openEditor = null;
				companyProfilBox.watchedElement = null;
				
				$('#moreInfoId').val('');
				$('#moreInfoTitle').val('');
				$('#moreInfoDescription').val('');
			}
		},
		
		handleWatchedEvent: function (e, watchedElement, event)
		{
			switch (event)
			{
				case 'click':

					switch (watchedElement.type)
					{
						case 'createButton':

							this.positionEditLayer('moreInfoBox_editElement', 'moreInfoBox', -11, -12);													
							$('#moreInfoBox_editElement').fadeIn('slow');
							companyProfilBox.openEditor = this;
							companyProfilBox.watchedElement = watchedElement;
							moreInfoBox.action = 'create';
							break;
						
						case 'editButton':

							this.positionEditLayer('moreInfoBox_editElement', 'moreInfoBox', -11, -12);							
							$('#moreInfoBox_editElement').fadeIn('slow');
							$('#moreInfoId').val(this.id);
							$('#moreInfoTitle').val(this.title);
							$('#moreInfoDescription').val(this.description.replace(/<br>/g, '\n'));
							companyProfilBox.openEditor = this;
							companyProfilBox.watchedElement = watchedElement;
							moreInfoBox.action = 'edit';

							break;
							
						case 'saveButton':
						
							$('#moreInfoBox_editElement').fadeOut('slow');
							
							this.fetchData();						
							break;
							
						case 'closeButton':

							$('#moreInfoBox_editElement').fadeOut('slow');
							companyProfilBox.openEditor = null;
							companyProfilBox.watchedElement = null;
							moreInfoBox.action = null;
							break;
							
						case 'deleteButton':

							moreInfoBox.action = 'delete';
							this.fetchData(this.id);
							break;
					}

					break;
			}
		}
	}
);

var searchTermsElement = $.klass
(
	formElement,
	{
		initialize: function ($super, type, domNode, name)
		{
			$super(type, domNode, name);
			this.setType('searchTermElement');
		},
		
		fetchData: function (response)
		{
			var thisObj = this;

			if (!response)
			{
				var parameters = new Object();

				switch (searchTermsBox.action)
				{
					case 'edit':
					
						parameters.method = 'setTags';
						parameters.tags = this.tagsAsString;

						break;
				}
												
				$.get
				(
					"/v3/profile-extended/ajax/inline-base.php?", 
					parameters, 
					function(response)
					{
						thisObj.fetchData(response);
					}, 
					'json'
				);
			}
			else
			{
				if (response.errno != 0)
				{
					if (response.error != '')
					{
						showErrorBubble(companyProfilBox.watchedElement.domNode, response.error);
					}
				}
				else
				{
					switch (searchTermsBox.action)
					{
						case 'edit':

							this.tagsAsString = response.result;
							$('#searchTermsBox').html(response.result);
							searchTermsBox.action = null;
							break;
					}
					
					adaptBoxHeight();
				}
				
				companyProfilBox.openEditor = null;
				companyProfilBox.watchedElement = null;
			}
		},
		
		handleWatchedEvent: function (e, watchedElement, event)
		{
			switch (event)
			{
				case 'click':

					switch (watchedElement.type)
					{
						case 'editButton':
						
							this.positionEditLayer('searchTermsBox_editElement', 'searchTermsBox', -11, -12);
							$('#searchTermsBox_editElement').fadeIn('slow');
							watchedElement.domNode.src 	= 'http://static.myhammer.com/v3/live/structure/schliessen_button.gif';
							watchedElement.domNode.style.width = watchedElement.domNode.style.height = 'auto';
							watchedElement.type = 'closeButton';
							$('#searchTermsTextarea').val(this.tagsAsString);
							companyProfilBox.openEditor = this;
							companyProfilBox.watchedElement = watchedElement;
							searchTermsBox.action = 'edit';

							break;
							
						case 'saveButton':
						
							$('#searchTermsBox_editElement').fadeOut('slow');
							companyProfilBox.watchedElement.domNode.src = 'http://static.myhammer.com/v3/live/icons/icons_edit_blue_12x12.gif';
							companyProfilBox.domNode.style.width = watchedElement.domNode.style.height = 'auto';							
							companyProfilBox.watchedElement.type = 'editButton';
							this.tagsAsString = $('#searchTermsTextarea').val();

							this.fetchData();	


							
							this.fetchData();						
							break;
							
						case 'closeButton':

							$('#searchTermsBox_editElement').fadeOut('slow');
							companyProfilBox.watchedElement.domNode.src = 'http://static.myhammer.com/v3/live/icons/icons_edit_blue_12x12.gif';
							companyProfilBox.domNode.style.width = companyProfilBox.domNode.style.height = 'auto';
							companyProfilBox.watchedElement.type = 'editButton';
							companyProfilBox.openEditor = null;
							companyProfilBox.watchedElement = null;
							searchTermsBox.action = null;
							break;
					}

					break;
			}
		}
	}
);

var qualificationElement = $.klass
(
	formElement,
	{
		initialize: function ($super, type, domNode, name)
		{
			$super(type, domNode, name);
			this.setType('qualificationElement');
		},
		
		refresh: function (data)
		{
			var qualificationBoxDomNode = $('#qualificationBox'), 
				template = $('#qualification_template');
				
			qualificationBoxDomNode.empty();
			
			jQuery.each
			(
				data,
				function (id, member)
				{
					var newRowDomNode = template.clone(true);
					newRowDomNode.attr('id', 'qualification_' + id);
					newRowDomNode.find('#deleteQualification_template').attr('id', 'deleteQualification_' + id);
					
					newRowDomNode.find('#qualification_title').html(member.label);
					if (member.isAccepted)
					{
						newRowDomNode.find('#qualification_in_review').remove();
						newRowDomNode.find('#qualification_ok')[0].reviewDateSpan = newRowDomNode.find('#qualificationDate_template').attr('id', 'qualificationDate_' + id)[0];
						newRowDomNode.find('#qualification_review_date').html(member.acceptedDate);
						newRowDomNode.find('#qualification_ok')[0].onmouseover = function()
						{
							this.reviewDateSpan.style.display = '';
						};
						newRowDomNode.find('#qualification_ok')[0].onmouseout = function()
						{
							this.reviewDateSpan.style.display = 'none';
						};						
					}
					else
					{
						newRowDomNode.find('#qualification_accepted').remove();
					}

					qualificationBoxDomNode.append(newRowDomNode);

					var qE = new qualificationElement(null, $('#qualification_' + id)[0], 'qualification_' + id);
					qE.display({visible: true});
					qE.id = id;
					
					var dB = new deleteButton(null, $('#deleteQualification_' + id)[0], 'deleteQualification_' + id);
					dB.display({visible: bIsOwner ? true : false});
					dB.acceptWatcher(qE, 'click');

				}
			);
		},
		
		fetchData: function (id, response)
		{
			var thisObj = this;

			if (!response)
			{
				var parameters = new Object();

				switch (qualificationBox.action)
				{
					case 'delete':

						parameters.method = 'deleteQualification';
						parameters.document = id;
						break;
						
					default:
					
						parameters.method = 'getUserDocuments';
						parameters.userID = userID;
						parameters.type = 'qualification';
						break;
						
				}
												
				$.get
				(
					"/v3/profile-extended/ajax/inline-profile.php?", 
					parameters, 
					function(response)
					{
						thisObj.fetchData(id, response);
					}, 
					'json'
				);
			}
			else
			{
				if (response.errno != 0)
				{
					if (response.error != '')
					{
						showErrorBubble(companyProfilBox.watchedElement.domNode, response.error);
					}
				}
				else
				{
					switch (qualificationBox.action)
					{
						case 'delete':
						
							$('#qualification_' + id).remove();
							qualificationBox.action = null;
							break;
							
						default:
						
							this.refresh(response.result);
							break;
					}
					
					adaptBoxHeight();
				}
				
				companyProfilBox.openEditor = null;
				companyProfilBox.watchedElement = null;
			}
		},
		
		handleWatchedEvent: function (e, watchedElement, event)
		{
			switch (event)
			{
				case 'click':

					switch (watchedElement.type)
					{
						case 'createButton':
						
							this.positionEditLayer('qualificationBox_editElement', 'qualificationBox', -11, -12);
							$('#qualificationBox_editElement').fadeIn('slow');
							companyProfilBox.openEditor = this;
							companyProfilBox.watchedElement = watchedElement;
							qualificationBox.action = 'create';

							qualificationBoxEditElement.showLeaf();
							break;

						case 'saveButton':
						
							var thisObj = this;
							
							qualificationBoxEditElement.submitForm
							(
								function ()
								{
									$('#qualificationBox_editElement').fadeOut('slow');
									thisObj.fetchData();
								}
							);

							break;
							
						case 'closeButton':

							$('#qualificationBox_editElement').fadeOut('slow');
							companyProfilBox.openEditor = null;
							companyProfilBox.watchedElement = null;
							qualificationBox.action = null;

							qualificationBoxEditElement.reset();
							break;
							
						case 'deleteButton':

							qualificationBox.action = 'delete';
							this.fetchData(this.id);
							break;
					}

					break;
			}
		}
	}
);

var membershipElement = $.klass
(
	formElement,
	{
		initialize: function ($super, type, domNode, name)
		{
			$super(type, domNode, name);
			this.setType('membershipElement');
		},
		
		refresh: function (data)
		{
			var membershipBoxDomNode = $('#membershipBox'), 
				template = $('#membership_template');
				
			membershipBoxDomNode.empty();
			
			jQuery.each
			(
				data,
				function (id, member)
				{
					var newRowDomNode = template.clone(true);
					newRowDomNode.attr('id', 'membership_' + id);
					newRowDomNode.find('#deleteMembership_template').attr('id', 'deleteMembership_' + id);
					
					newRowDomNode.find('#membership_title').html(member.label);
					if (member.isAccepted)
					{
						newRowDomNode.find('#membership_in_review').remove();
						newRowDomNode.find('#membership_ok')[0].reviewDateSpan = newRowDomNode.find('#membershipDate_template').attr('id', 'membershipDate_' + id)[0];
						newRowDomNode.find('#membership_review_date').html(member.acceptedDate);
						newRowDomNode.find('#membership_ok')[0].onmouseover = function()
						{
							this.reviewDateSpan.style.display = '';
						};
						newRowDomNode.find('#membership_ok')[0].onmouseout = function()
						{
							this.reviewDateSpan.style.display = 'none';
						};						
					}
					else
					{
						newRowDomNode.find('#membership_accepted').remove();
					}
					membershipBoxDomNode.append(newRowDomNode);

					var mE = new membershipElement(null, $('#membership_' + id)[0], 'membership_' + id);
					mE.display({visible: true});
					mE.id = id;
					
					var dB = new deleteButton(null, $('#deleteMembership_' + id)[0], 'deleteMembership_' + id);
					dB.display({visible: bIsOwner ? true : false});
					dB.acceptWatcher(mE, 'click');
				}
			);
		},

		fetchData: function (id, response)
		{
			var thisObj = this;

			if (!response)
			{
				var parameters = new Object();

				switch (membershipBox.action)
				{
					case 'delete':

						parameters.method = 'deleteMembership';
						parameters.document = id;
						break;
						
					default:
					
						parameters.method = 'getUserDocuments';
						parameters.userID = userID;
						parameters.type = 'membership';
						break;
						
				}
												
				$.get
				(
					"/v3/profile-extended/ajax/inline-profile.php?", 
					parameters, 
					function(response)
					{
						thisObj.fetchData(id, response);
					}, 
					'json'
				);
			}
			else
			{
				if (response.errno != 0)
				{
					if (response.error != '')
					{
						showErrorBubble(companyProfilBox.watchedElement.domNode, response.error);
					}
				}
				else
				{
					switch (membershipBox.action)
					{
						case 'delete':
						
							$('#membership_' + id).remove();
							qualificationBox.action = null;
							break;
							
						default:
						
							this.refresh(response.result);
							break;
					}
					
					adaptBoxHeight();
				}
				
				companyProfilBox.openEditor = null;
				companyProfilBox.watchedElement = null;
			}
		},
		
		handleWatchedEvent: function (e, watchedElement, event)
		{
			switch (event)
			{
				case 'click':
					switch (watchedElement.type)
					{
						case 'createButton':
						
							this.positionEditLayer('membershipBox_editElement', 'membershipBox', -11, -12);
							$('#membershipBox_editElement').fadeIn('slow');
							companyProfilBox.openEditor = this;
							companyProfilBox.watchedElement = watchedElement;
							membershipBox.action = 'create';

							membershipBoxEditElement.showLeaf();
							break;

						case 'saveButton':
						
							var thisObj = this;
							
							membershipBoxEditElement.submitForm
							(
								function ()
								{
									$('#membershipBox_editElement').fadeOut('slow');
									thisObj.fetchData();
								}
							);

							break;
							
						case 'closeButton':

							$('#membershipBox_editElement').fadeOut('slow');
							companyProfilBox.openEditor = null;
							companyProfilBox.watchedElement = null;
							membershipBox.action = null;

							membershipBoxEditElement.reset();
							break;
							
						case 'deleteButton':

							membershipBox.action = 'delete';
							this.fetchData(this.id);
							break;
					}

					break;
			}
		}
	}
);


var downloadElement = $.klass
(
	formElement,
	{
		initialize: function ($super, type, domNode, name)
		{
			$super(type, domNode, name);
			this.setType('downloadElement');
		},
		
		fetchData: function (id, response)
		{
			var thisObj = this;

			if (!response)
			{
				var parameters = new Object();

				switch (downloadBox.action)
				{
					case 'delete':

						parameters.method = 'deleteDownloadableFile';
						parameters.id = id;
						break;
				}
												
				$.get
				(
					"/v3/profile-extended/ajax/inline-profile.php?", 
					parameters, 
					function(response)
					{
						thisObj.fetchData(id, response);
					}, 
					'json'
				);
			}
			else
			{
				if (response.errno != 0)
				{
					if (response.error != '')
					{
						showErrorBubble(companyProfilBox.watchedElement.domNode, response.error);
					}
				}
				else
				{
					switch (downloadBox.action)
					{
						case 'delete':
						
							$('#download_' + id).remove();
							downloadBox.action = null;
							break;
					}
					
					adaptBoxHeight();
				}
				
				companyProfilBox.openEditor = null;
				companyProfilBox.watchedElement = null;				
			}
		},
		
		buildData: function (response)
		{	
			var html = '';
				
			jQuery.each
			(
				response.files,
				function ()
				{
					html += '<div id="download_' + this.id + '" class="downloadsDiv" style="position: relative; width:100%">';
					html += '<img id="editDownload_' + this.id + '" style="position: absolute; top: 8px; right: 20px; cursor: pointer;" src="https://images.my-hammer.at/v3/live/icons/icons_edit_blue_12x12.gif" />';
					html += '<img id="deleteDownload_' + this.id + '" style="position: absolute; top: 6px; right: 5px; cursor: pointer;" src="https://images.my-hammer.at/v3/live/icons/x.gif" />';
					html += '<a href="' + this.url + '"><img src="https://images.my-hammer.at/v3/live/structure/download_button.gif" /></a>';
					html += '<a href="' + this.url + '">' + this.title + '</a>';
					html += '</div>';
					
					html += '<script type="text/javascript">';
					html += 'var download_' + this.id + ' = new downloadElement(null, $("#download_' + this.id + '")[0], "download_' + this.id + '");';
					html += 'download_' + this.id + '.display({visible:true});';
					html += 'download_' + this.id + '.id = "' + this.id + '";';
					html += 'download_' + this.id + '.title = "' + this.title + '";';
					html += 'download_' + this.id + '.url = "' + this.url + '";';
					html += 'var deleteDownload_' + this.id + ' = new deleteButton(null, $("#deleteDownload_' + this.id + '")[0], "deleteDownload_' + this.id + '");';
					html += 'deleteDownload_' + this.id + '.display({visible:true});';
					html += 'deleteDownload_' + this.id + '.acceptWatcher(download_' + this.id + ', "click");';
					html += 'var editDownload_' + this.id + ' = new editButton(null, $("#editDownload_' + this.id + '")[0], "editDownload_' + this.id + '");';
					html += 'editDownload_' + this.id + '.display({visible:true});';
					html += 'editDownload_' + this.id + '.acceptWatcher(download_' + this.id + ', "click");';
					html += '</script>';
				}
			);
			
			downloadBox.action = null;
			this.getJObject().html(html);
		},
		
		handleWatchedEvent: function (e, watchedElement, event)
		{
			switch (event)
			{
				case 'click':

					switch (watchedElement.type)
					{
						case 'createButton':

							this.positionEditLayer('downloadBox_editElement', 'downloadBox', -200, -12);						
							$('#downloadBox_editElement').fadeIn('slow');
							companyProfilBox.openEditor = this;
							companyProfilBox.watchedElement = watchedElement;
							downloadBox.action = 'create';
							break;

						case 'saveButton':

							if (downloadBox.action == 'create')
							{
								$('#downloadMethod').val('createDownloadableFile');
							}
							else if (downloadBox.action == 'edit')
							{
								$('#downloadMethod').val('editDownloadableFile');
							}

							this.hiddenUploadForm = $('#hiddenPDFUploadForm')[0];

							var thisObj = this;

							AIM.submit
							(
								thisObj.hiddenUploadForm,
								{
									'onStart': null,
									'onComplete': function (response, iframeId)
									{
										//$('#' + iframeId).remove();
										
										response = eval('(' + response + ')');
										
										if (response.errno != 0)
										{
											showErrorBubble($('#closeDownload')[0], response.error);
										}
										else
										{
											$('#downloadBox_editElement').fadeOut('slow');
											thisObj.buildData(response);
										}
									}
								}
							);
							
							this.hiddenUploadForm.submit()				
							$('#pdfUploadFileDisplay').val('');	
							break;
							
						case 'closeButton':

							$('#downloadBox_editElement').fadeOut('slow');
							$('#pdfUploadFileDisplay').val('');
							companyProfilBox.openEditor = null;
							companyProfilBox.watchedElement = null;
							downloadBox.action = null;
							break;
						
						case 'editButton':

							this.positionEditLayer('downloadBox_editElement', 'downloadBox', -11, -12);												
							$('#downloadBox_editElement').fadeIn('slow');
							companyProfilBox.openEditor = this;
							companyProfilBox.watchedElement = watchedElement;
							$('#pdfUploadFileName').val(this.title);
							$('#downloadId').val(this.id);
							downloadBox.action = 'edit';
							break;
							
						case 'deleteButton':

							downloadBox.action = 'delete';
							this.fetchData(this.id);
							break;
					}

					break;
					
				case 'change':
				
					$('#pdfUploadFileDisplay').val(watchedElement.getJObject().val());
					break;
			}
		}
	}
);

var userDataElement = $.klass
(
	formElement,
	{
		initialize: function ($super, type, domNode, name)
		{
			$super(type, domNode, name);
			this.setType('userDataElement');
		},
		
		fetchData: function (data, response)
		{
			var thisObj = this;

			if (!response)
			{
				var parameters = new Object();

				switch (this.name)
				{
					case 'contactGender':
						
						parameters.method = 'setContactGender';
						parameters.value = data[0].value;
						break;

					case 'directorGender':
						
						parameters.method = 'setDirectorGender';
						parameters.value = data[0].value;
						break;
						
					case 'contactName':
					
						parameters.method = 'setContactName';
						parameters.firstname = data.data('firstname');
						parameters.lastname = data.data('lastname');
						break;

					case 'directorName':
					
						parameters.method = 'setDirectorName';
						parameters.firstname = data.data('firstname');
						parameters.lastname = data.data('lastname');
						break;
						
					case 'contactBirthday':
					
						parameters.method = 'setContactBirthday';
						parameters.birthdate_year = data.data('birthdate_Year');
						parameters.birthdate_month = data.data('birthdate_Month');
						parameters.birthdate_day = data.data('birthdate_Day');						
						break;
						
					case 'companyVat':
					
						parameters.method = 'setVAT';
						parameters.vat = data[0].value;
						break;
				}
												
				$.get
				(
					"/v3/profile-extended/ajax/inline-profile.php?", 
					parameters, 
					function(response)
					{
						thisObj.fetchData(data, response);
					}, 
					'json'
				);
			}
			else
			{
				if (response.errno != 0)
				{	
					if (response.errorlist != '')
					{
					var text_error = "";	
						$.each(response.errorlist, function(k, v){
						text_error = text_error+v+"<br />";	
 						});
						showErrorBubble(companyProfilBox.watchedElement.domNode, text_error);	
					}
					
				}
				else
				{
					switch (this.name)
					{
						case 'contactGender':
						case 'directorGender':
						case 'contactBirthday':
						case 'companyVat':
						
							this.getJObject().html(response.result);
							break;

						case 'directorName':
						case 'contactName':

							$('#' + this.name + 'FirstName').html(response.firstname);
							$('#' + this.name + 'LastName').html(response.lastname);

					}
				}
				
				companyProfilBox.openEditor = null;
				companyProfilBox.watchedElement = null;
			}
		},
		
		handleWatchedEvent: function (e, watchedElement, event)
		{
			switch (event)
			{
				case 'click':

					switch (watchedElement.type)
					{
						case 'editButton':
							if (companyProfilBox.openEditor)
							{
								companyProfilBox.openEditor.getJObject().show();
								$('#' + companyProfilBox.openEditor.name + '_editElement').hide();
								companyProfilBox.watchedElement.getJObject().show();
								companyProfilBox.openEditor = null;
								companyProfilBox.watchedElement = null;
							}

							this.hide();
							$('#' + this.name + '_editElement').show();
							watchedElement.getJObject().hide();
							companyProfilBox.openEditor = this;
							companyProfilBox.watchedElement = watchedElement;

							break;
							
						case 'saveButton':
						
							this.getJObject().show();
							$('#' + this.name + '_editElement').hide();
							companyProfilBox.watchedElement.getJObject().show();
							
							switch (this.name)
							{
								case 'directorName':
								case 'contactName':
								
									$('#' + this.name + 'Input').data('firstname', $('#' + this.name + 'FirstNameInput')[0].value);
									$('#' + this.name + 'Input').data('lastname', $('#' + this.name + 'LastNameInput')[0].value);
									
									break;
									
								case 'contactBirthday':

									$('#' + this.name + 'Input').children().each
									(
										function(child)
										{
											$('#contactBirthdayInput').data(this.name, this.value);
										}
									);
									break;
							}

							this.fetchData($('#' + this.name + 'Input'));
						
							break;
					}

					break;
			}
		}
	}
);

var upsellElement = $.klass
(
	formElement,
	{
		initialize: function ($super, type, domNode, name)
		{
			$super(type, domNode, name);
			this.setType('upsellElement');
		},

		handleWatchedEvent: function (e, watchedElement, event)
		{
			switch (event)
			{
				case 'click':

					switch (watchedElement.type)
					{
						case 'editButton':
						
							if (watchedElement.name != 'upsellOpeningTimes')
							{
								this.positionEditLayer(this.name + '_editElement', this.name, -11, -27);       
							}
							else
							{
								if (jQuery.browser.msie)
								{
									this.positionEditLayer(this.name + '_editElement', this.name, -110, -50);       
								}
								else
								{
									this.positionEditLayer(this.name + '_editElement', this.name, -100, 13);
								}
							}
							
							$('#' + this.name + '_editElement').fadeIn('slow');
						
						break;
							
						case 'closeButton':
						
							$('#' + this.name + '_editElement').fadeOut('slow');

							break;
					}

					break;
			}
		}
	}
);

var feedbackBox = $.klass
(
	formElement,
	{
		initialize: function ($super, type, domNode, name)
		{
			$super(type, domNode, name);
			this.setType('feedbackBox');
			this.page = 1;
		},
		
		handleWatchedEvent: function (e, watchedElement, event)
		{
			switch (event)
			{
				case 'click':
					
					switch (watchedElement.type)
					{
						case 'tabElement':
						
							if (watchedElement.name == 'tabFeedback')
							{
								this.show();
							}
							else
							{
								this.hide();
							}	
										
							break;
					}

					break;
			}
		},
		
		fetchAbstract: function (response)
		{
			var thisObj = this;

			if (!response)
			{
				var parameters = new Object;

				parameters.method = 'getCompanyRatings';	
				parameters.userID = userID;
				parameters.submethod = 'overwiev';
				parameters.pagination = 'default:0';
				var sort = $('#tab_feedback_sort').selectedIndex;
				parameters.sortby = 'default:ASC';
				
				$.get
				(
					"/v3/profile-extended/ajax/inline-reviews.php?", 
					parameters, 
					function(response)
					{
						thisObj.fetchAbstract(response);
						
					}, 
					'json'
				);
			}
			else
			{
				for (i in response['overallrating'])
				{
					if ($('#tab_feedback_' + i))
					{
						$('#tab_feedback_' + i).html(response['overallrating'][i]);
					}
				}
				$('#tab_feedback_details').hide();
				$('#tab_feedback_abstract').show();
			}
		},
		
		getReviewIdFromHash: function() {
			var res = document.location.hash.match(/#?reviewId([0-9]+)/);
			if(!res) return -1;
			
			return parseInt(res[1]);
		},
		
		fetchDetails: function (response)
		{
			var jumpTo = this.getReviewIdFromHash();
			
			var thisObj = this;

			if (!response)
			{
				var parameters = new Object;

				parameters.method = 'getReviewList';	
				parameters.userID = userID;
				parameters.count = MAX_FEEDBACK_COUNT;
				parameters.page = this.page;
				parameters.sort = $('#tab_feedback_sort')[0].options[$('#tab_feedback_sort')[0].selectedIndex].value;
								
				$.get
				(
					"/v3/profile-extended/ajax/inline-reviews.php?", 
					parameters, 
					function(response)
					{
						thisObj.fetchDetails(response);
						
					}, 
					'json'
				);
			}
			else
			{
				var data = new Array();
				
				for (i in response['reviews'])
				{
					data.push(response['reviews'][i]);
				}
				
				this.count_all = response['total'];
				
				for (var i = 0; i < MAX_FEEDBACK_COUNT; i++) {
					if (i < data.length && this.count_all) {	
						if(data[i]['review-id'] == jumpTo) document.location.href = '#tab_orders_row_' + i;
					
						$('#tab_feedback_date_' + i).html(formatDate(data[i]['review-timestamp']));
						
						$('#tab_feedback_title_' + i).html(data[i]['review-auctiontitle']);
						$('#tab_feedback_title_' + i).attr({href: data[i]['review-auctionlink']});
						$('#tab_feedback_text_' + i).html(data[i]['review-comment']);
						
						$('#tab_feedback_userlink_' + i).html(data[i]['review-username']);
						$('#tab_feedback_userlink_' + i).attr({href: data[i]['review-userlink']});
						
						$('#tab_feedback_userfeedback_percent_' + i).html(data[i]['review-userfeedback-percent']);
						$('#tab_feedback_userfeedback_total_' + i).html(data[i]['review-userfeedback-total']);
						
						$('#tab_feedback_branch_' + i).html(data[i]['review-category']);
						
						if (data[i]['review-userfeedback-total'])
						{
							$('#tab_feedback_userfeedback_' + i).show();
						}
						else
						{
							$('#tab_feedback_userfeedback_' + i).hide();
						}
							
						if (data[i]['review-neutralization'] > 0) 
						{
							$('#tab_feedback_redeemed_' + i).show();
							$('#tab_feedback_redeemed_date_' + i).html(formatDate(data[i]['review-neutralization']));
						} 
						else
						{
							$('#tab_feedback_redeemed_' + i).hide();
						}
						
						$('#tab_feedback_img_stars_quality_' + i).attr('src', starPicUrl(data[i]['review-score-quality'])); 
						$('#tab_feedback_img_stars_quality_' + i).attr('alt' , TRANSLATION_POINTS + data[i]['review-score-quality']);
						$('#tab_feedback_img_stars_quality_' + i).attr('title' , TRANSLATION_POINTS + data[i]['review-score-quality']);
						
						$('#tab_feedback_img_stars_dependability_' + i).attr('src' , starPicUrl(data[i]['review-score-reliability']));
						$('#tab_feedback_img_stars_dependability_' + i).attr('alt' , TRANSLATION_POINTS + data[i]['review-score-reliability']);
						$('#tab_feedback_img_stars_dependability_' + i).attr('title' , TRANSLATION_POINTS + data[i]['review-score-reliability']);
						
						$('#tab_feedback_img_stars_friendliness_' + i).attr('src' , starPicUrl(data[i]['review-score-kindness']));
						$('#tab_feedback_img_stars_friendliness_' + i).attr('alt' , TRANSLATION_POINTS + data[i]['review-score-kindness']);
						$('#tab_feedback_img_stars_friendliness_' + i).attr('title' , TRANSLATION_POINTS + data[i]['review-score-kindness']);
						
						if (data[i]['review-type'] == 'positive')
						{
							$('#tab_feedback_symbol_' + i).attr('class', 'positiv');					
						}
						else if (data[i]['review-type'] == 'negative')
						{
							$('#tab_feedback_symbol_' + i).attr('class', 'negativ');
						}
						else if (data[i]['review-type'] == 'neutral')
						{
							$('#tab_feedback_symbol_' + i).attr('class', 'neutral');
						}
						
						$('#tab_feedback_row_' + i).show();
					} 
					else
					{
						$('#tab_feedback_row_' + i).hide();
					}
				}
				
				$('#tab_feedback_abstract').hide();
				$('#tab_feedback_details').show();
				$('#tab_feedback_count').html
					(
						this.count_all + ' ' + (this.count_all == 1 ? TRANSLATION_FEEDBACK : TRANSLATION_FEEDBACKS) + ' ' + TRANSLATION_GOT +
						(response['redeemed_count'] ? ' | ' + response['redeemed_count'] + ' ' + TRANSLATION_REDEEMED : '')
					);				
						
				if (this.count_all) 
				{	
					var from = (this.page - 1) * MAX_FEEDBACK_COUNT + 1;
					
					var until = from + (data.length - 1);
					
					$('#tab_feedback_pagelabel').html
						(
							'<strong>' + from + ' - ' + until + '</strong> ' + TRANSLATION_OF + ' ' + this.count_all + ' ' + 
							(this.count_all == 1 ? TRANSLATION_FEEDBACK : TRANSLATION_FEEDBACKS)
						);
						
					generate_pagination('tab_feedback', this.page, MAX_FEEDBACK_COUNT, this.count_all);
					
					$('#tab_feedback_pagination').show();
					$('#tab_feedback_sort').attr('disabled', false);
					
				} 
				else 
				{
					$('#tab_feedback_pagelabel').html('<strong>0</strong> ' + TRANSLATION_FEEDBACKS);
					$('#tab_feedback_pagination').hide();
					$('#tab_feedback_sort').attr('disabled', true);		
				}
			}
		},
		
		next: function() {
			this.page++;
			this.fetchDetails();
		},
		
		prev: function() {
			this.page--;
			this.fetchDetails();
		},
		
		first: function() {
			this.page = 1;
			this.fetchDetails();
		},
		
		last: function() {
			this.page = Math.ceil(this.count_all / MAX_FEEDBACK_COUNT);
			this.fetchDetails();
		}
	}
);



var ordersBox = $.klass
(
	formElement,
	{
		initialize: function ($super, type, domNode, name)
		{
			$super(type, domNode, name);
			this.setType('ordersBox');
			this.page = 1;
			this.mode = 'won';
		},
		
		handleWatchedEvent: function (e, watchedElement, event)
		{
			switch (event)
			{
				case 'click':
					
					switch (watchedElement.type)
					{
						case 'tabElement':
						
							if (watchedElement.name == 'tabOffers')
							{ 
								this.changeSubtab('won');
								this.show();
							}
							else
							{
								this.hide();
							}	
										
							break;
					}

					break;
			}
		},
		
		changeSubtab: function (tab) 
		{
			var subtabs = new Array('won', 'lost', 'acted', 'noted');
			for (var i = 0; i < subtabs.length; i++)
			{
				if (tab == subtabs[i]) 
				{
					this.mode = tab;
					$('#tab_orders_' + subtabs[i]).show();
				} 
				else
				{
					$('#tab_orders_' + subtabs[i]).hide();
				}
			}
			this.fetchData();
		},
		
		fetchData: function (response)
		{
			
			var thisObj = this;
			if (!response)
			{
				var parameters = new Object;

				parameters.method = 'getOrdersList';	
				parameters.userID = userID;
				parameters.type = this.mode;
				parameters.page = this.page;
				parameters.sort = $('#tab_orders_sort')[0].options[$('#tab_orders_sort')[0].selectedIndex].value;				
				
				$.get
				(
					"/v3/profile-extended/ajax/inline-requests.php?", 
					parameters, 
					function(response)
					{
						thisObj.fetchData(response);
						
					}, 
					'json'
				);
			}
			else
			{
				var data = new Array();
				for (i in response['orders'])
				data.push(response['orders'][i]);
				
				this.count_all = response['total'];
				
				for (var i = 0; i < MAX_ORDERS_COUNT; i++) 
				{
					if (i < data.length && this.count_all) 
					{
						$('#tab_orders_date_' + i).html(formatDate(data[i]['order-timestamp']));
						$('#tab_orders_title_' + i).html(data[i]['order-auctiontitle']);
						$('#tab_orders_title_' + i).attr({href: 'http://www.my-hammer.de/showAuction.php?auctionID=' + data[i]['review-auctionid']});						

						if (data[i]['order-comment'].length > 220)
						{
							var commentPart = data[i]['order-comment'].slice(0, 220);
							commentPart += '...';
							commentPart += ' <a style="color:#FF6F09;" onclick="$(\'#tab_orders_all_text_div_' + i + '\').show();" href="javascript:void(0);">mehr</a>';
							
							$('#tab_orders_text_' + i).html(commentPart);
							$('#tab_orders_all_text_' + i).html(data[i]['order-comment']);
						}
						else
						{
							$('#tab_orders_text_' + i).html(data[i]['order-comment']);					
						}

						$('#tab_orders_userlink_' + i).html(data[i]['order-username']);
						$('#tab_orders_userlink_' + i).attr({href: data[i]['order-userlink']});
						$('#tab_orders_userfeedback_percent_' + i).html(data[i]['order-userfeedback-percent']);
						$('#tab_orders_userfeedback_total_' + i).html(data[i]['order-userfeedback-total']);
						$('#tab_orders_branch_' + i).html(data[i]['order-category']);
						
						if (data[i]['order-userfeedback-total'])
						{
							$('#tab_orders_userfeedback_' + i).show();
						}
						else
						{
							$('#tab_orders_userfeedback_' + i).hide();
						}
						
						$('#tab_orders_row_' + i).show();
					} 
					else
					{
						$('#tab_orders_row_' + i).hide();
					}
				}
				if (this.count_all) 
				{
					var from = (this.page - 1) * MAX_ORDERS_COUNT + 1;
					var until = from + (data.length - 1);
					
					$('#tab_orders_pagelabel').html
					(
						'<strong>' + from + ' - ' + until + '</strong> ' + TRANSLATION_OF + ' ' + this.count_all + ' ' + 
						(this.count_all == 1 ? ressources[this.mode][0] : ressources[this.mode][1])
					);
					
					generate_pagination('tab_orders', this.page, MAX_ORDERS_COUNT, this.count_all);
					
					$('#tab_orders_pagination').show();
					$('#tab_orders_sort').attr('disabled', false);
				} 
				else 
				{
					$('#tab_orders_pagelabel').html('<strong>0</strong> ' + ressources[this.mode][1]);
					$('#tab_orders_pagination').hide();
					$('#tab_orders_sort').attr('disabled', true);				
				}
			}
		},

		next: function() {
			this.page++;
			this.fetchData();
		},
		
		prev: function() {
			this.page--;
			this.fetchData();
		},
		
		first: function() {
			this.page = 1;
			this.fetchData();
		},
		
		last: function() {
			this.page = Math.ceil(this.count_all / MAX_ORDERS_COUNT);
			this.fetchData();
		}
	}
);

var referencesBoxClass = $.klass
(
	formElement,
	{
		initialize: function ($super, type, domNode, name)
		{
			$super(type, domNode, name);
			this.setType('referencesBox');
			this.page = 1;
			this.selected_img = new Array();
			this.mapId = new Array();
			this.mapI = new Array();
			this.imagesTodo = new Array();
			this.referenceI = 0;
		},
		
		handleWatchedEvent: function (e, watchedElement, event)
		{
			switch (event)
			{
				case 'click':
					
					switch (watchedElement.type)
					{
						case 'tabElement':
						
							if (watchedElement.name == 'tabReferences')
							{
								this.fetchData();
								this.show();
							}
							else
							{
								this.hide();
							}	
										
							break;
					}

					break;
			}
		},
		
		fetchData: function (response)
		{
			var thisObj = this;
			if (!response)
			{
				var parameters = new Object;

				parameters.method = 'getReferenceList';	
				parameters.userID = userID;
				parameters.count = MAX_REFERENCES_COUNT;
				parameters.page = this.page;
				parameters.cachebuster = Math.random();
							
				$.get
				(
					"/v3/profile-extended/ajax/inline-references.php?", 
					parameters, 
					function(response)
					{
						thisObj.fetchData(response);
						
					}, 
					'json'
				);
			}
			else
			{
				var data = new Array();
				for (i in response['references']) {
					response['references'][i]['id'] = i;
					data.push(response['references'][i]);
				}
				
				this.count_all = response['total'];
				$('#tab_references_abstract').html
				(
					this.count_all + ' ' + (this.count_all == 1 ? TRANSLATION_REFERENCE : TRANSLATION_REFERENCES)
				);
				
				for (var i = 0; i < MAX_REFERENCES_COUNT; i++) 
				{
					if (i < data.length && this.count_all) 
					{
						$('#tab_references_title_' + i).html(data[i]['reference-title']);
						$('#tab_references_date_' + i).html(formatDate(data[i]['reference-date']));
						$('#tab_references_location_' + i).html(data[i]['reference-location']);
						$('#tab_references_description_' + i).html(data[i]['reference-description']);
						this.mapI[data[i]['id']] = i;
						this.mapId[i] = data[i]['id'];
						this.removeImages(i);
						this.imagesTodo.push(data[i]['id']);
						
						$('#tab_references_row_' + i).show();							
					} 
					else
					{
						$('#tab_references_row_' + i).hide();
					}
				}
				
				if (this.count_all) 
				{
					var from = (this.page - 1) * MAX_REFERENCES_COUNT + 1;
					var until = from + (data.length - 1);
					
					$('#tab_references_pagelabel').html
					(
						'<strong>' 
						+ from 
						+ ' - ' 
						+ until 
						+ '</strong> ' 
						+ TRANSLATION_OF 
						+ ' ' 
						+ this.count_all 
						+ ' ' 
						+ (this.count_all == 1 ? TRANSLATION_REFERENCE : TRANSLATION_REFERENCES)
					);
					
					generate_pagination('tab_references', this.page, MAX_REFERENCES_COUNT, this.count_all);
					
					$('#tab_references_pagination').show();
				} 
				else 
				{
					$('#tab_references_pagelabel').html('<strong>0</strong> ' + TRANSLATION_REFERENCES);
					$('#tab_references_pagination').hide();			
				}
			}
			this.fetchImages();
		},
		
		removeImages: function(i) {
			var e = $('#tab_references_scroll_container_' + i)[0];
			while (e && e.firstChild != null)
			{
				e.removeChild(e.firstChild);
			}
		},
		
		fetchImages: function (response)
		{
			var thisObj = this;
			if (!response)
			{
				var parameters = new Object;
				if (!this.imagesTodo.length)
					return;
				
				parameters.method = 'getReferenceImages';
				parameters.id = this.imagesTodo.shift();
				this.refId = parameters.id; 
				parameters.userID = userID;
				parameters.cachebuster = Math.random();
							
				$.get
				(
					"/v3/profile-extended/ajax/inline-references.php?", 
					parameters, 
					function(response)
					{
						thisObj.fetchImages(response);
						
					}, 
					'json'
				);
			}
			else
			{
				var data = new Array();
				for (i in response['images']) 
				{
					response['images'][i]['id'] = i;
					data.push(response['images'][i]);
				}

				var width = 0;
				var widthAdjustment = 0;

				if
				(
					jQuery.browser.msie
						&& jQuery.browser.version < 7
				)
				{
					widthAdjustment = 2;
				}

				var i = this.mapI[this.refId];
				var e = $('#tab_references_scroll_container_' + i)[0];
				
				// list current reference pictures
				for (j = 0; j < data.length; j++) {
					var div = document.createElement('div');
					div.className = 'scrollDiv'
					div.style.position = 'relative';
					
					var img = document.createElement('img');
					
					if (j)
					{
						img.className = 'scrollImg';
					}
					else 
					{
						var des = data[j]['description'];
						if(des.length > 64) {
							var t = des.substr(0,61);
						var t = t+'...';
						}else{
							var t = des.substr(0,61);
						}
						
						img.className = 'scrollImgHighlight';
						$('#tab_references_img_large_' + i).attr('src' , data[j]['url']);
						$('#tab_references_img_title_' + i).html(data[j]['title']);

						$('#tab_references_img_description_' + i).html(t);

						this.selected_img[i] = j; 
						img.isDefault = true;
					}
					
					img.src = data[j]['url'];
					img.id = 'tab_references_img_' + i + '_' + j;
					img.imgId = data[j]['id'];
					img.title = data[j]['title'];
					img.description = data[j]['description'];
					img.refI = i;
					img.picI = j;
					img.onclick = function(ev) {
						if (!ev) var ev = window.event;
						if (ev.target) el = ev.target;
						else if (ev.srcElement) el = ev.srcElement.id;
						if (el.nodeType == 3) // defeat Safari bug
							el = el.parentNode;
						var id;
						if (!(id = el.id))
						{
							id = el;
						}
						$('#' + id)[0].className = 'scrollImgHighlight';
						$('#tab_references_img_' + $('#' + id)[0].refI + '_' + thisObj.selected_img[$('#' + id)[0].refI])[0].className = 'scrollImg';
						$('#tab_references_img_large_' + $('#' + id)[0].refI)[0].src = $('#' + id)[0].src;
						$('#tab_references_img_title_' + $('#' + id)[0].refI)[0].innerHTML = $('#' + id)[0].title;
						
						if($('#' + id)[0].description.length > 64) {
							$('#tab_references_img_description_' + $('#' + id)[0].refI)[0].innerHTML = $('#' + id)[0].description.substr(0,61)+'...';
						}else{
							$('#tab_references_img_description_' + $('#' + id)[0].refI)[0].innerHTML = $('#' + id)[0].description;
						}
						
						thisObj.selected_img[$('#' + id)[0].refI] = $('#' + id)[0].picI;
					}				
					div.appendChild(img);
					var img = document.createElement('img');
					if (IS_OWNER) {
					
						img.src = 'http://static.myhammer.com/v3/live/structure/button_arrange.gif';
						img.style.position = 'absolute';
						img.className = 'hideInPreview';
						img.style.left = '119px';
						img.style.top = '12px';
						img.id= 'edit'+i;
						img.origImgId = 'tab_references_img_' + i + '_' + j;
						img.onclick = function(ev)
						{
							var id = this.origImgId;
							referencesBox.referenceI = $('#' + id)[0].refI;
							var referenceImageUploadOptions = 
							{
								anchorElement: $('#' + id)[0],
								formAction: '/v3/profile-extended/ajax/inline-references.php?reference=' + referencesBox.mapId[referencesBox.referenceI],
								ajaxMethods: {create: 'createReferenceImage', edit: 'editReferenceImage', remove: 'deleteReferenceImage'},
								defaultImage: 'http://static.myhammer.com/v3/live/structure/haus_dummy.gif',
								id: $('#' + id)[0].imgId, // oder defauklt
								showTitle: true,
								maxlengthTitle: 50,
								title: $('#' + id)[0].title, // el oder Titel
								showSubTitle: true,
								subtitle: $('#' + id)[0].description, // alter subtitel oder Untertitel
								showRemove: true,
								showDefaultCheckbox: true,
								defaultCheckboxLabel: 'Als Startbild nehmen',
								startCallback: function () {},
								completeCallback: function (response, type) {
									referencesBox.imagesTodo.push(referencesBox.mapId[referencesBox.referenceI]);
									referencesBox.removeImages(referencesBox.referenceI);
									referencesBox.fetchImages();
								} 
							};
							pictureUpload.activate(referenceImageUploadOptions);
						}
						div.appendChild(img);
					}
					
					var a = document.createElement('a');
					a.className = 'scrollA';
					a.href = 'javascript:void(0);';
					a.style.left = '-21px';
					a.origImgId = 'tab_references_img_' + i + '_' + j;
					
					a.innerHTML = data[j]['title'];
					a.onclick = function ()
					{
					
						$('#' + this.origImgId).trigger('click');
						
					};
/*
					a.onclick = function(ev) {
						if (!ev) var ev = window.event;
						if (ev.target) el = ev.target;
						else if (ev.srcElement) el = ev.srcElement.id;
						if (el.nodeType == 3) // defeat Safari bug
							el = el.parentNode;
						$(el.parentNode).children().trigger('click');
						return false;
					}
*/
					var innerDiv = document.createElement('div');
					innerDiv.appendChild(a);
					div.appendChild(innerDiv);
					e.appendChild(div);
					width += 158 + widthAdjustment;
				}

				// this part is for "new reference picture"
				if (IS_OWNER) {
					var img = document.createElement('img');
					
					img.className = 'scrollImg';
					img.src = 'http://static.myhammer.com/v3/live/structure/haus_dummy.gif';
					img.id = 'tab_references_img_' + i + '_' + (j + 1); 
					img.imgId = 0 
					img.title = TRANSLATION_NEW_IMG;
					img.description = '';
					img.refI = i;
					img.picI = j + 1;
					img.onclick = function(ev) {
						if (!ev) var ev = window.event;
						if (ev.target) el = ev.target;
						else if (ev.srcElement) el = ev.srcElement.id;
						if (el.nodeType == 3) // defeat Safari bug
							tar = el.parentNode;
						var id;
						if (!(id = el.id))
						{
							id = el;
						}
						referencesBox.referenceI = $('#' + id)[0].refI;
						$('#' + id)[0].className = 'scrollImgHighlight';
						if (thisObj.selected_img[$('#' + id)[0].refI]) $('#tab_references_img_' + $('#' + id)[0].refI + '_' + thisObj.selected_img[$('#' + id)[0].refI])[0].className = 'scrollImg';
						thisObj.selected_img[$('#' + id)[0].refI] = $('#' + id)[0].picI;
						var referenceImageUploadOptions = 
						{
							anchorElement: $('#tab_references_img_' + $('#' + id)[0].refI + '_' + thisObj.selected_img[$('#' + id)[0].refI])[0],
							formAction: '/v3/profile-extended/ajax/inline-references.php?reference=' + referencesBox.mapId[referencesBox.referenceI],
							ajaxMethods: {create: 'createReferenceImage', edit: 'editReferenceImage', remove: 'deleteReferenceImage'},
							defaultImage: 'http://static.myhammer.com/v3/live/structure/haus_dummy.gif',
							id: 0, 
							showTitle: true,
							maxlengthTitle: 50,
							title: TRANSLATION_TITLE, 
							showSubTitle: true,
							subtitle: TRANSLATION_DESCRIPTION,
							showRemove: true,
							showDefaultCheckbox: true,
							defaultCheckboxLabel: TRANSLATION_FIRST_IMAGE,
							startCallback: function () {},
							completeCallback: function (response, type) {
								if(type != 'remove') {
									// Omniture tracking for new reference pictures
									var aParams = new Array(
										new OmnitureParameter('eVar14', sOmnitureEVar14UploadReferencePicture),
										new OmnitureParameter('events', sOmnitureEventActionFinish)
									);
									var oOmniture = new Omniture();
									oOmniture.sendCall(aParams, true);
								}

								referencesBox.imagesTodo.push(referencesBox.mapId[referencesBox.referenceI]);
								referencesBox.removeImages(referencesBox.referenceI);
								referencesBox.fetchImages();
							} 
						};
						
						pictureUpload.activate(referenceImageUploadOptions);

						// Omniture tracking for new reference pictures
						var aParams = new Array(
							new OmnitureParameter('eVar14', sOmnitureEVar14UploadReferencePicture),
							new OmnitureParameter('events', sOmnitureEventActionStart)
						);
						var oOmniture = new Omniture();
						oOmniture.sendCall(aParams, true);
					}
					var div = document.createElement('div');
					div.className = 'scrollDiv hideInPreview';
					div.style.display = 'none';
					div.appendChild(img);
					var a = document.createElement('a');
					a.className = 'scrollA';
					a.href = 'javascript:void(0);';
					a.onclick = function() {
						$(('#'+img.id)).click();
					}
					a.innerHTML = TRANSLATION_NEW_IMG;
					var innerDiv = document.createElement('div');
					innerDiv.appendChild(a);
					div.appendChild(innerDiv);
					e.appendChild(div);
					width += 158 + widthAdjustment;
				}
				e.style.width = width + 'px';
				
				this.fetchImages();
			}
			switchView(true);
		},
		
		next: function() {
			this.page++;
			this.fetchData();
		},
		
		prev: function() {
			this.page--;
			this.fetchData();
		},
		
		first: function() {
			this.page = 1;
			this.fetchData();
		},
		
		last: function() {
			this.page = Math.ceil(this.count_all / MAX_REFERENCES_COUNT);
			this.fetchData();
		},
		
		select_image: function() {
			
		}
	}
);

var editReferenceButton = $.klass
(
	formElement,
	{
		initialize: function ($super, type, domNode, name, i)
		{
			$super(type, domNode, name);
			this.setType('editReferenceButton');
			this.referenceI = i;
		},

		handleWatchedEvent: function (e, watchedElement, event)
		{
			switch (watchedElement.type) 
			{
				case 'editReferenceButton':
				
					this.hide();
					referencesBox.referenceI = this.referenceI;
					var fields = new Array('title', 'date', 'location', 'description');
					for (var i = 0; i < fields.length; i++)
						$('#tab_references_input_' + fields[i])[0].className = '';							
					// $('#tab_references_edit')[0].style.left = 
					//		($('#tab_references_row_' + this.referenceI).offset().left - 1) + 'px';
					$('#tab_references_edit')[0].style.top = 
							($('#tab_references_row_' + this.referenceI).offset().top - 131) + 'px';
					if (this.referenceI != -1) {
						$($('#tab_references_delete')[0]).show();
						$('#tab_references_input_title')[0].value = $('#tab_references_title_' + this.referenceI)[0].innerHTML;
						$('#tab_references_input_date')[0].value = $('#tab_references_date_' + this.referenceI)[0].innerHTML;
						$('#tab_references_input_location')[0].value = $('#tab_references_location_' + this.referenceI)[0].innerHTML;
						$('#tab_references_input_description')[0].value = $('#tab_references_description_' + this.referenceI)[0].innerHTML;
					} else {
						$($('#tab_references_delete')[0]).hide();
						$('#tab_references_input_title')[0].value = '';
						$('#tab_references_input_date')[0].value = formatDate('now');
						$('#tab_references_input_location')[0].value = '';
						$('#tab_references_input_description')[0].value = '';

						// Omniture tracking for new references
						var aParams = new Array(
							new OmnitureParameter('eVar14', sOmnitureEVar14CreateReference),
							new OmnitureParameter('events', sOmnitureEventActionStart)
						);
						var oOmniture = new Omniture();
						oOmniture.sendCall(aParams, true);
					}
					$('#tab_references_input_id')[0].value = this.referenceI;
					
					$($('#tab_references_edit')[0]).show('slow');
				break;
					
				case 'saveReferenceButton':	
				case 'closeReferenceButton':
				case 'deleteReferenceButton':
					this.show();
					editReferenceButtonMain.show();
				break;
			}
		}		
	}	
);

var saveReferenceButton = $.klass
(
	formElement,
	{
		initialize: function ($super, type, domNode, name)
		{
			$super(type, domNode, name);
			this.setType('saveReferenceButton');
		},

		handleWatchedEvent: function (e, watchedElement, event)
		{
			switch (watchedElement.type) 
			{
				case 'editReferenceButton':
				
				break;
					
				case 'saveReferenceButton':
															
					this.saveData();

					break;
			}
		},
		
		saveData: function (response)
		{
			var thisObj = this;
			if (!response)
			{
				var parameters = new Object;

				parameters.userID = userID;
				parameters.title = $('#tab_references_input_title').val();
				parameters.date = $('#tab_references_input_date').val();
				parameters.location = $('#tab_references_input_location').val();
				parameters.description = $('#tab_references_input_description').val();
				if ($('#tab_references_input_id').val() == -1)
					parameters.method = 'createReference';
				else {
					parameters.method = 'editReference';
					parameters.id = referencesBox.mapId[$('#tab_references_input_id').val()];
				}	
							
				$.get
				(
					"/v3/profile-extended/ajax/inline-references.php?", 
					parameters, 
					function(response)
					{
						thisObj.saveData(response);						
					}, 
					'json'
				);
			}
			else
			{
				// fehlerbehandlung
				if (response.errno)
				{
					// alle felder resetten
					jQuery.each
					(
						['title', 'date', 'location'],
						function (i, field)
						{
							$('#tab_references_input_' + field).attr('class', '')
						}
					);
					
					jQuery.each
					(
						response.errorlist,
						function (field, errorMessage)
						{
							showErrorBubble
							(
								$('#tab_references_input_' + field).attr('class', 'highlight'),
								errorMessage
							);
						}
					);
				}
				else
				{
					$('#tab_references_edit').hide('slow');
					if ($('#tab_references_input_id').val() == -1) 
					{
						referencesBox.page = 1; 
						referencesBox.fetchData();

						// Omniture tracking for new references
						var aParams = new Array(
							new OmnitureParameter('eVar14', sOmnitureEVar14CreateReference),
							new OmnitureParameter('events', sOmnitureEventActionFinish)
						);
						var oOmniture = new Omniture();
						oOmniture.sendCall(aParams, true);
					}
					else 
					{
						var data = response['reference'];
						var row = data[referencesBox.mapId[$('#tab_references_input_id').val()]];
						
						$('#tab_references_title_' + referencesBox.referenceI).html(row['title']);
						$('#tab_references_date_' + referencesBox.referenceI).html(formatDate(row['date']));
						$('#tab_references_location_' + referencesBox.referenceI).html(row['location']);
						$('#tab_references_description_' + referencesBox.referenceI).html(row['description']);
					}
				}
			}
		}
	}	
);

var deleteReferenceButton = $.klass
(
	formElement,
	{
		initialize: function ($super, type, domNode, name)
		{
			$super(type, domNode, name);
			this.setType('deleteReferenceButton');
		},

		handleWatchedEvent: function (e, watchedElement, event)
		{
			switch (watchedElement.type) 
			{
				case 'deleteReferenceButton':
					this.deleteReference();
					$('#tab_references_edit').hide('slow');
				break;	
			}
		},
		
		deleteReference: function (response)
		{
			var thisObj = this;
			if (!response)
			{
				var parameters = new Object;

				parameters.userID = userID;
				parameters.method = 'deleteReference';
				parameters.id = referencesBox.mapId[$('#tab_references_input_id').val()];
							
				$.get
				(
					"/v3/profile-extended/ajax/inline-references.php?", 
					parameters, 
					function(response)
					{
						thisObj.deleteReference(response);						
					}, 
					'json'
				);
			}
			else
			{
				referencesBox.page = 1; 
				referencesBox.fetchData();
			}
		}
	}	
);

var closeReferenceButton = $.klass
(
	formElement,
	{
		initialize: function ($super, type, domNode, name)
		{
			$super(type, domNode, name);
			this.setType('closeReferenceButton');
		},

		handleWatchedEvent: function (e, watchedElement, event)
		{
			switch (watchedElement.type) 
			{
				case 'closeReferenceButton':
					$('#tab_references_edit').hide('slow');
				break;	
			}
		}
	}	
);


var apprenticeshipBox = $.klass
(
	formElement,
	{
		initialize: function ($super, type, domNode, name)
		{
			$super(type, domNode, name);
			this.setType('apprenticeshipBox');
		},
		
		handleWatchedEvent: function (e, watchedElement, event)
		{
			switch (event)
			{
				case 'click':
					
					switch (watchedElement.type)
					{
						case 'tabElement':
						
							if (watchedElement.name == 'tabApprenticeship')
							{
								this.show();
							}
							else
							{
								this.hide();
							}	

							break;
					}

					break;
			}
		}
	}
);



var sDirectorySearchTypeCookieName = 'searchType';

$().ready(function() {
	deleteCookie(sDirectorySearchTypeCookieName);
	$('a[class*=search-type-]').click(function() {
		directorySearchTypeClick(this);
	});
});

function directorySearchTypeClick(obj) {
	var aClasses = $(obj).attr('class').split(' ');
	var sSearchType = '';
	var sSearchTerm = '';
	for (var i = 0; i < aClasses.length; i++) {
		if (aClasses[i].substr(0, 12) == 'search-type-') {
			sSearchType = aClasses[i].substr(12);
			sSearchTerm = $(obj).html();
			break;
		}
	}
	if (sSearchType != '') {
		setCookie(sDirectorySearchTypeCookieName, sSearchType + '|' + sSearchTerm, 250, '/', getCookieDomain(), false);
	}
}

