var registerNamespace = function(space) {
    var parts = space.split('.');
    var root = window;

    var l = parts.length;
    for (var i = 0; i < l; ++i) {
        if (typeof root[parts[i]] == 'undefined') {
            root[parts[i]] = {};
        }

        root = root[parts[i]];
    }

    return root;
};
window.registerNamespace = registerNamespace;

// prepend js-errors
var FormDefaults = {};
var FieldSetCounter = {};

/*
 * form class
 *
 * general functions for forms on jobzippers platform
 * includes, cloning, select based ajax requests and more
 *
 */

var space = registerNamespace('JZ');

space.form = {
    /*
     * form::getCountryCode
     *
     * retrieve country code based on iso-db via ajax
     * update country code fields in form with responsed value
     *
     * @param: what object, country string
     * @response: string
     */
    getCountryCode: function(what) {
        var country = $(what).val();

        $.get('/ajax/echo_country_code/' + country + '.html', function(data) {
            $("input[name='phone_countrycode']").val(data);
            $("input[name='fax_countrycode']").val(data);
            $("input[name='mobile_countrycode']").val(data);
        });
    },

    /*
     * form::cloneInput
     *
     * clone input row
     *
     * @param: what object
     */
    cloneInput: function(what) {
        what = $(what);
        var clone = what.clone();

        var input = clone.find('input');
        var button = what.find('a.button,a.button_small');
        var button_new = clone.find('a.button,a.button_small');

        clone.find('div').remove();
        button_new.before(input);
        input.val('');

        // select rename regex
        //var new_name = input.attr('name').replace(/([a-z_-]+)\[([0-9]+)\]/gi, '$1[]');

        // special case with workxp[0]branches[]
        if (input.attr('name').match(/([a-z_-]+)\[([0-9]+)\]([a-z0-9\]\[_-]+)\[([0-9]*)\]/gi)) {
            var new_name = input.attr('name').replace(/([a-z_-]+)\[([0-9]+)\]([a-z0-9\]\[_-]+)\[([0-9]+)\]/gi, '$1[$2]$3[]');
        }
        else // normal case with branches[0]
        {
            var new_name = input.attr('name').replace(/([a-z0-9\]\[_-]+)\[([0-9]+)\]/gi, '$1[]');
        }

        input.attr('name', new_name);

        //new_content.
        $(what).after(clone);

        if (button.hasClass('small_add')) {
            button.removeClass('small_add');
            button.addClass('small_del');
        } else {
            button.removeClass('add');
            button.addClass('del');
        }

        button_new.click(function() {
            JZ.form.cloneInput($(this).parent());
        });

        button.unbind();

        button.click(function() {
            what.remove();
            return false;
        });
    },

    /*
     >>>>>>> 315d9d798b16c5b525f0a981d0dbb11060f157c6
     * form::cloneSelect
     *
     * clone select row
     *
     * @param: what object
     */

    cloneSelect: function(what) {
        what = $(what);
        var clone = what.clone();
        var select = clone.find('select').clone();
        var button = what.find('.button,.button_small');
        var button_new = clone.find('.button,.button_small');

        var new_name = select.attr('name');
        // if the select field's name does not contain a digital id, nothing happens here.
        // special case with `workxp[0]branches[]`
        if (new_name.match(/([a-z_-]+)\[([0-9]+)\]([a-z0-9\]\[_-]+)\[([0-9]*)\]/gi)) {
            new_name = new_name.replace(/([a-z_-]+)\[([0-9]+)\]([a-z0-9\]\[_-]+)\[([0-9]+)\]/gi, '$1[$2]$3[]');
        } else {
            // normal case with `branches[0]`
            new_name = new_name.replace(/([a-z0-9\]\[_-]+)\[([0-9]+)\]/gi, '$1[]');
        }
        select.attr('name', new_name);

        what.after(clone);

        if (button.hasClass('small_add')) {
            button.removeClass('small_add');
            button.addClass('small_del');
        } else {
            button.removeClass('add');
            button.addClass('del');
        }

        button_new.click(function(e) {
            e.preventDefault();

            if (what.find('td').html()) {
                JZ.form.cloneSelect($(this).parents('tr'));
            } else {
                JZ.form.cloneSelect($(this).parent());
            }
        });

        button.unbind();
        button.click(function(e) {
            e.preventDefault();
            what.remove();
        });
    },

    /*
     * form::cloneSelectFormbuilder
     *
     * clone select row FORMBUILDER!!!
     *
     * Alias to cloneSelect, but no event is set after this function!
     *
     * @param: what object
     */
    cloneSelectFormbuilder: function(what) {
        what = $(what);
        var clone = what.clone();
        var select = clone.find('select').clone();
        var button = what.find('a.button,a.button_small');
        var button_new = clone.find('a.button,a.button_small');

        var new_name = select.attr('name');
        // if the select field's name does not contain a digital id, nothing happens here.
        // special case with `workxp[0]branches[]`
        if (new_name.match(/([a-z_-]+)\[([0-9]+)\]([a-z0-9\]\[_-]+)\[([0-9]*)\]/gi)) {
            new_name = new_name.replace(/([a-z_-]+)\[([0-9]+)\]([a-z0-9\]\[_-]+)\[([0-9]+)\]/gi, '$1[$2]$3[]');
        } else {
            // normal case with `branches[0]`
            new_name = new_name.replace(/([a-z0-9\]\[_-]+)\[([0-9]+)\]/gi, '$1[]');
        }
        select.attr('name', new_name);

        what.after(clone);

        if (button.hasClass('small_add')) {
            button.removeClass('small_add');
            button.addClass('small_del');
        } else {
            button.removeClass('add');
            button.addClass('del');
        }

        //    button_new.click(function(e) {
        //      e.preventDefault();
        //
        //      if(what.find('td').html()) {
        //        JZ.form.cloneSelect($(this).parents('tr'));
        //      } else {
        //        JZ.form.cloneSelect($(this).parent());
        //      }
        //    });

        button.unbind();
        //    button.click(function(e) {
        //      e.preventDefault();
        //      what.remove();
        //    });
    },

    /*
     * form::cloneFileInput
     *
     * clone file input field
     *
     * @param: what object
     */
    cloneFileInput: function(what) {
        what = $(what);
        var clone = what.clone(false);
        var input = clone.find('input[type=file]').clone(false);
        var button = what.find('a.button,a.button_small');
        var button_new = clone.find('a.button,a.button_small');

        clone.find('div').remove();
        clone.find('input').remove();
        input.val('');
        input.attr('style', '');

        button_new.before(input);

        input.filestyle({
            image: "/media/img/site/form/choose-file.gif",
            imageheight : 24,
            imagewidth : 94,
            width : 287
        });


        what.after(clone);

        if (button.hasClass('small_add')) {
            button.removeClass('small_add');
            button.addClass('small_del');
        } else {
            button.removeClass('add');
            button.addClass('del');
        }

        button_new.click(function() {
            JZ.form.cloneFileInput($(this).parent());
        });

        button.attr('onClick', '');
        button.unbind();
        button.click(function() {
            what.remove();
            return false;
        });

        return false;
    },

    getGrades: function(what, index, type) {
        what = $(what);
        var value = what.val();

        var id = type + '_grades_' + index;
        var select = $('select#' + id);

        if ($('select#All' + id).length == 0) {
            var cloned = select.clone();
            cloned.attr("id", "All" + id).removeAttr("name").css({
                display: "none"
            });
            select.after(cloned);
        }

        if (value && value.length > 0) {
            // delete all current entries, add empty row, then all matching highschools
            var matchingGrades = $("select#All" + id + " option.country_" + value).clone();
            select.find("option").remove();
            select.append('<option class="emptyrow" value=""></option>').append(matchingGrades);
        } else {
            select.find("option").remove();
            select.append($("select#All" + id + " option").clone());
        }
    },

    /*
     * form::cloneFieldset
     *
     * clone a complete fieldset
     *
     * @param: what object, type string
     * @response: fieldset
     *
     * Update 17.11.2010 (Jan-Erik)
     *   I'm not 100% sure the whole cloning thing is the best approach.
     *   Will look into this later.
     *   FIXME: comments?!
     */
    cloneFieldset: function(what) {
        var fieldset_array = $(what).parent('div').children('fieldset');

        var search_for = 'input, select, textarea';

        var first_fieldset = fieldset_array.first();
        var last_fieldset = fieldset_array.eq(-1);

        // NEW APPROACH FOR PREVENTING IE7 PROBLEMS: clone first fieldset
        // FIXME: Is this still valid for IE7?
        var clone = first_fieldset.clone();

        var originals = first_fieldset.find(search_for);
        var replacements = clone.find(search_for);

        var counterIndex;
        if ($(what).attr('name')) {
            counterIndex = $(what).attr('name');
        } else { // if fieldset has no name, choose one
            counterIndex = "rnd_name_" + (Math.random() * 10000 | 0)
            $(what).attr('name', counterIndex);
        }

        // if not yet done, set counter variable
        if (!FieldSetCounter[counterIndex]) {
            // get name of first element for extracting the counter
            var inputs = last_fieldset.find(search_for);

            if (inputs.length > 0) {
                var n = inputs.first().attr('name');
                FieldSetCounter[counterIndex] = parseInt(n.replace(/[a-z_]+\[([0-9]+)\][^*]+/gi, '$1'));
            } else {
                FieldSetCounter[counterIndex] = 0;
                FirstFieldSetCounter[counterIndex] = FieldSetCounter[counterIndex];
            }
        }

        FieldSetCounter[counterIndex]++;

        replacements.each(function() {
            var count = FieldSetCounter[counterIndex];

            var element = $(this);
            var name = element.attr('name');
            var id = element.attr('id');
            // increment counter in name
            var new_name = name.replace(/^(.+?)\[([0-9]+)\]/gi, '$1[' + count + ']');
            // `id` is `name` with '[' and ']' replaced by '_'
            // atleast in some templates, sometimes it's `name` == `id` and
            // sometimes it's just some weird combo.
            // -> nasty workaround needed:
            // just replace first occurence of digit with a new.
            var new_id = id.replace(/(\d+)/, '' + count);

            element.val('');
            element.attr('name', new_name);
            element.attr('id', new_id);

            // if a label exist, set new name
            if ((lab = clone.find("label[for='" + id + "']")).length > 0) {
                $(lab).each(function() {
                    $(this).attr('for', new_id);
                });
            }
        });

        // add autocompleter to new field
        var autocompleter = clone.find('input.autocompleter');
        autocompleter.each(function() {
            $(this).autocomplete({
                source: JZ.autocompleter.fetchSource("/ajax/get_high_schools.html", "country"),
                select: JZ.autocompleter.onSelect,
                minLength: 2,
                delay: 15
            });
        });

        var coursesAutocompler = clone.find('input.autocompleterSC');
        coursesAutocompler.each(function() {
            $(this).autocomplete({
                source: JZ.autocompleter.fetchSource("/ajax/get_study_courses.html"),
                select: JZ.autocompleter.onSelect,
                minLength: 2,
                delay: 15
            });
        });

        // hide "remove" button in cloned fieldset
        clone.find("a.delete.formbutton").removeClass("hidden");

        // add 'to this day' script to checkbox
        var to_this_day = clone.find("input[type='checkbox']");

        /*to_this_day.click(function() {
         JZ.form.toggleDateToSelectVisibility();
         });*/

        $("form[name='cvgen'] input[type='checkbox']").click(function() {
            JZ.form.toggleDateToSelectVisibility();
        });

        $(last_fieldset).after(clone);
    },

    deleteFieldset: function(what) {
        $(what).parent('fieldset').remove();
        return false;
    },

    /*
     * form::editCVTitle
     *
     * clear high school fields as soon as
     * the corresponding country changed
     *
     */
    clearHighSchoolFields: function(what) {
        var index = $(what).attr('name').replace(/([a-z_]+)\[([0-9]+)\]([^*]+)/gi, '$2');

        var ac_field = $('#high_schools_' + index + '_ac');
        var title_field = $('#high_schools_' + index + '_title');

        if (ac_field) {
            ac_field.value = "";
        }

        if (title_field) {
            title_field.value = "";
        }

        return true;
    },

    toggleDateToSelectVisibility: function(what) {
        var spacer = $(what).parent('span').next('span').next('div.time_span_selector_spacer_container');
        var par = $(what).parent();


        var text_to = par.find('div.from_to_container');
        var select_month = $(text_to).next("select");
        var select_year = $(select_month).next("select");

        spacer.toggleClass('hidden');
        text_to.toggleClass('hidden');
        select_month.toggleClass('hidden');
        select_year.toggleClass('hidden');

        return true;
    },


    toggleFreeFromSelectVisibility: function(what) {
        var select_year = $(what).prev('select');
        var select_month = select_year.prev('select');
        var select_day = select_month.prev('select');

        select_year.toggleClass('hidden');
        select_month.toggleClass('hidden');
        select_day.toggleClass('hidden');

        return true;
    },


    /*
     * form::editCVTitle
     *
     * clone a complete fieldset
     *
     * @param: what object, type string
     * @response: fieldset
     */
    editCVTitle: function(what) {
        what = $(what);

        if (what.attr('href')) {
            $.get('/ajax' + what.attr('href'), function(data) {
                what.parent().html(data);
            });
        }
    },

    editCVLanguage: function(what) {
        what = $(what);

        if (what.attr('href')) {
            $.get('/ajax' + what.attr('href'), function(data) {
                what.parent().html(data);
            });
        }
    },

    saveCVTitle: function(what) {
        what = $(what);

        if (what.parent().attr('action')) {
            $.post(what.parent().attr('action'), {
                title: what.parent().find("input[name='title']").attr('value')
            }, function(data) {
                what.parent().parent().html(data);
            });
        }
    },

    saveCVLanguage: function(what) {
        what = $(what);

        if (what.parent().attr('action')) {
            $.post(what.parent().attr('action'), {
                language: what.parent().find("select[name='language']").attr('value')
            }, function(data) {
                what.parent().parent().html(data);
            });
        }
    },


    selectCVImage: function(img) {
        img = $(img);
        var id = img.attr('id');

        img.after('<img src="/media/img/site/form/selected.gif" class="selected">');
        img.parent().addClass('selected');
        $("input[name='image_id']").val(id);
    },

    /*
     * display the available packages for a selected work type
     *
     * used for companies inserting new jobs, i.e. /jobs/add_pdf.html
     **/
    adaptPackageDropdown: function(what) {
        var value = $(what).val();
        //console.log(value);
        if (value && value.length > 0) {
            var selectedWorkType = $(what).find("option[value='" + value + "']")

            var matchingPackages = $("select#allPackages option.department_" + value).clone();
            var allPackages = $("select#allPackages option");

            var select = $("select#order");
            select.find("option").remove();
            select.append('<option class="emptyrow" value=""></option>');

            if (selectedWorkType.hasClass('category_job')) {
                select.append($("select#allPackages option.booking_category_job").clone());
            } else if (selectedWorkType.hasClass('category_internship')) {
                select.append($("select#allPackages option.booking_category_internship").clone());
            } else if (selectedWorkType.hasClass('category_study_project')) {
                select.append($("select#allPackages option.booking_category_study_project").clone());
            }
        } else {
            // this should never happen. User can't select an empty row,
            // but if he manages to do this: prevent any harm
            // by just removing possible package options
            var select = $("select#order");
            select.find("option").remove();
            select.append('<option class="emptyrow" value=""></option>');
        }

        return false;
    },

    handleInputCloning: function(what) {
        if ($(what).hasClass('add')) {
            JZ.form.cloneInput($(what).parents('div.row'));
        } else {
            $(what).parents('div.row').remove();
        }
    },

    handleSelectCloning: function(what) {
        if ($(what).hasClass('add')) {
            JZ.form.cloneSelect($(what).parents('div.row'));
        } else {
            $(what).parents('div.row').remove();
        }
    },


    /*
     * selectionBasedOptions(base, selected, class_prefix)
     *
     * Observes a <select> tag for changes and
     * shows only the matching options in another <select>
     * based on the class_prefix + base.value
     *
     * See example usage in confirm_gtc.tpl.
     *
     * TODO: needs similar method for autocompletion-fields
     *
     * base         - ID of the selection to be observed.
     * selected     - ID of the select tag to change.
     * class_prefix - Class name prefix to match options with.
     *
     * Example:
     *
     *   // when #department_id is changed,
     *   // all matching "department_<value>" options in
     *   // #allinstitute_id are moved to the new <select>.
     *   JZ.form.selectionBasedOptions("departmend_id", "institute_id", "department_");
     **/
    selectionBasedOptions: function(base, selected, class_prefix) {
        var changeableSelection = $("select#" + selected);
        var cloned = changeableSelection.clone();
        var allId = "all" + selected;
        cloned.attr("id", allId).removeAttr("name").css({
            display: "none"
        });
        changeableSelection.after(cloned);

        $("select#" + base).change(function() {
            var value = $(this).val();
            if (value && value.length > 0) {
                // delete all current entries,
                // add empty row if needed, then append all matching elements
                var matching = $("select#" + allId + " option." + class_prefix + value).clone();

                var select = $("select#" + selected);
                select.find("option").remove();
                if (matching.length > 1) {
                    select.append($("select#" + allId + " option.emptyrow").clone())
                }
                select.append(matching);
                select.find("option").removeClass('hidden');
            } else {
                // delete all current entries
                // and append all institutes again
                var select = $("select#" + selected);
                select.find("option").remove();
                select.append($("select#" + allId + " option").clone());
            }
        });

    }
};

/*
 * The new autocompleter is bundled with jquery.ui.
 * The server now responds with correct json-encoded data,
 * therefore its use is nearly as easy as
 *   $.get(url, function(data) { resp(data); });
 * as the source property.
 *
 * But for all the comfort, use JZ.autocompleter.fetchSource,
 * which returns a proper function (see docu down there)
 *
 * A complete usecase should look like this:
 *
 *    $("input.autocompleter").autocomplete({
 *      source: JZ.autocompleter.fetchSource("url"),
 *      select: JZ.autocompleter.onSelect,
 *      minLength: 2, // autocomplete after atleast 2 chars
 *      delay: 300    // in ms, wait before activating,
 *                    // 300 is the default and works fine
 *    });
 */
space.autocompleter = {
    /**
     *  autocomplete(elem, url, extra)
     *
     *  elem       - A string containing a selector expression.
     *               This must be an input field.
     *  url        - A string containing the source url
     *               See 'JZ.autocompleter.fetchSource'
     *  extra      - (optional) The extra argument passed to fetchSource
     *               Quoted:
     *               > Add an additional parameter to the url,
     *               > the value is fetched from the previous select field.
     *  settings   - (optional) An object containing extra settings for the autocompleter
     *               Defaults:
     *                 minLength: 2
     *                 delay:     15
     *               You may pass an "select" property, which is applied as a callback
     *               for the autocompleter "select" event
     *               (called instead of JZ.autocompleter.onSelect)
     *
     *  It wraps around the default jQuery autocompleter.
     *  Internally it sets the source callback to `JZ.autocompleter.fetchSource`
     *  and the select callback to `JZ.autocompleter.onSelect`.
     *  It also creates callbacks, so that the input field is cleared
     *  when no item is selected.
     *
     *  Example:
     *
     *    JZ.autocompleter.autocomplete("input.autocompleter", "/ajax/get_high_schools.html", "country");
     *    JZ.autocompleter.autocomplete("input.autocompleterSC", "/ajax/get_study_courses.html");
     *
     **/
    autocomplete: function(elem, url, extra, settings) {
        if (typeof url == "undefined") return; // fail early.

        var minLength = 2
            , delay = 15
            , onselect = JZ.autocompleter.onSelect;

        if (typeof settings == "undefined" && typeof extra == "object") {
            settings = extra;
        }

        if (typeof settings == "object") {
            minLength = settings.minLength || 2;
            delay = settings.delay || 15;

            if (settings.select) {
                onselect = settings.select;
            }
        }

        // if element is focused and value and id are set,
        // save them for later use.
        $(elem).focus(function(ev) {
            var input = $(ev.target);
            var val = input.val();
            var id = input.next().val();

            if (val.length > 0 && id.length > 0) {
                input.data('last-input-val', val);
                input.data('last-input-id', id);
            }
        });

        // when autocompletion dropdown closes,
        // input value is changed, but nothing select
        // remove id in the next field
        // (ID is only set if user selects from dropdown
        var close = function(ev, ui) {
            var input = $(ev.target);
            var val = input.val();
            var id = input.next().val();
            var oldVal = input.data('last-input-val');
            var oldId = input.data('last-input-id');

            if (val != oldVal) {
                if (id == oldId) {
                    input.next().val('');
                }
            }

            // save the latest values
            input.data('last-input-val', val);
            input.data('last-input-id', '');
        };

        // unset value if no id is given
        // and focus is lost.
        $(elem).blur(function(ev) {
            var input = $(ev.target);
            var id = input.next().val();
            if (id == '') input.val('');
        });

        $(elem).autocomplete({
            close: close,
            source: JZ.autocompleter.fetchSource(url, extra),
            select: onselect,
            minLength: minLength,
            delay: delay
        });
    },

    autocompleteFormbuilder: function(elem, url, extra, settings) {
        if (elem == "input.autocompleterUD")
            if (typeof url == "undefined") return; // fail early.
        var minLength = 2
            , delay = 15
            , onselect = JZ.autocompleter.onSelectFormbuilder;

        if (typeof settings == "undefined" && typeof extra == "object") {
            settings = extra;
        }

        if (typeof settings == "object") {
            minLength = settings.minLength || 2;
            delay = settings.delay || 15;

            if (settings.select) {
                onselect = settings.select;
            }
        }
        // 
        // if element is focused and value and id are set,
        // save them for later use.
        $(elem).focus(function(ev) {
            var input = $(ev.target);
            var val = input.val();
            var id = input.parent().next('div').find('input').val();

            if (val.length > 0 && id.length > 0) {
                input.data('last-input-val', val);
                input.data('last-input-id', id);
            }
        });

        // when autocompletion dropdown closes,
        // input value is changed, but nothing select
        // remove id in the next field
        // (ID is only set if user selects from dropdown)
        var close = function(ev, ui) {
            var input = $(ev.target);
            var val = input.val();
            var id = input.parent().next('div').find('input').val();
            var oldVal = input.data('last-input-val');
            var oldId = input.data('last-input-id');

            if (val != oldVal) {
                if (id == oldId) {
                    input.parent().next('div').find('input').val('');
                }
            }

            // save the latest values
            input.data('last-input-val', val);
            input.data('last-input-id', '');
        };

        // unset value if no id is given
        // and focus is lost.
//        $(elem).blur(function(ev) {
//            var input = $(ev.target);
//            var id = input.parent().next('div').find('input').val();
//            if (id == '') input.val('');
//        });

        $(elem).autocomplete({
            close: close,
            source: JZ.autocompleter.fetchSourceFormbuilder(url, extra),
            select: onselect,
            minLength: minLength,
            delay: delay
        });
    },

    /*
     * onSelect(ev, ui)
     *
     * This function sets the value of the next input field to the given
     * item id.
     * This function MUST NOT be called directly!
     * Pass it to the "select" property of the autocompleter function
     * as shown above.
     */
    onSelect: function(ev, ui) {
        if (ui.item && ui.item.id) {
            $(ev.target).next().val(ui.item.id);
        }
    },
    onSelectFormbuilder: function(ev, ui) {
        if (ui.item && ui.item.id) {
            $(ev.target).parent().next('div').find('input').val(ui.item.id);
        }
    },

    /*
     * fetchSource(ajax_url, extra)
     *
     * ajax_url - An absolute url pointing to the location,
     *            the controller MUST return json data.
     * extra    - (optional) Add an additional parameter to the url,
     *            the value is fetched from the previous select field.
     *
     * returns function for use as "source" property for the autocompleter.
     */

    fetchSource: function(ajax_url, extra) {
        if (extra) {
            return function(req, resp) {
                var extra_val = $(this.element).prev('').val();
                if (extra_val && extra_val.length > 0) {
                    var url = ajax_url + "?" + extra + "=" + encodeURIComponent(extra_val);
                    url += "&q=" + encodeURIComponent($(this.element).val());
                    $.get(url, function(data) {
                        resp(data);
                    });
                }
            };
        } else {
            return function(req, resp) {
                var url = ajax_url;
                url += "?q=" + encodeURIComponent($(this.element).val());
                $.get(url, function(data) {
                    resp(data);
                });
            };
        }
    },

    fetchSourceFormbuilder: function(ajax_url, extra) {
        if (extra) {
            return function(req, resp) {
                var extra_val = $(this.element).parent().prev('div').find('select').val();

                if (!extra_val || extra_val.length <= 0)
                    extra_val = $(this.element).parent().prev('div').find('input').val();

                if (extra_val && extra_val.length > 0) {
                    var url = ajax_url + "?" + extra + "=" + encodeURIComponent(extra_val);
                    url += "&q=" + encodeURIComponent($(this.element).val());
                    $.get(url, function(data) {
                        resp(data);
                    });
                }
                else {
                    //console.log("extra_val not present");
                }
            };
        } else {
            return function(req, resp) {
                var url = ajax_url;
                url += "?q=" + encodeURIComponent($(this.element).val());
                $.get(url, function(data) {
                    resp(data);
                });
            };
        }
    }
};

$(document).ready(function() {
    // 
    // clear input function
    //  $("input").focus(function() {
    //    str = $(this).attr("name");
    //    if(FormDefaults[str]) {
    //      if($(this).val() == FormDefaults[str]) $(this).val('');
    //      // create new password input
    //      if(str == "password" || str == "password_confirm") {
    //        new_input = $(this).clone();
    //        new_input.attr("type","password");
    //        $(this).replaceWith(new_input);
    //        new_input.focus();
    //      }
    //    }
    //  });

    $("input").blur(function() {
        str = $(this).attr("name");

        if (FormDefaults[str] && $(this).val() == '')
            $(this).val(FormDefaults[str]);
    });

    $("div.row a.add, div.row a.small_add").click(function(e) {
        e.preventDefault();
        if ($(this).parents('div.row').find('select').length > 0) {
            JZ.form.cloneSelect($(this).parents('div.row'));
        } else {
            JZ.form.cloneInput($(this).parents('div.row'));
        }
    });

    $("div.row a.del, div.row a.small_del").click(function(e) {
        $(this).parents('div.row').remove();
        e.preventDefault();
    });

    // questionmark icons
    $("img.questionmark").tooltip({
        bodyHandler: function() {
            return $(this).attr('name');
        },
        showURL: false
    });

});

