var google_adnum = 0;

// check if element exists in page
// if ($(selector).exists()) { ... }
jQuery.fn.exists = function() {
    return jQuery(this).length > 0;
}

function init_salesobject_inputpage_categories() {

    mainCategorySelect.append(mainChoose);

    // initialize maincategory values
    $.each(parentArr, function() {
        var optionName = this.split(';')[1];
        var optionValue = this.split(';')[0];
        var option = $('<option/>').attr('value', optionValue).text(optionName);
        mainCategorySelect.append(option);
    });
    // select main category if already set. + trigger update event
    if (selectedMainCategoryId) {
        mainCategorySelect.val(selectedMainCategoryId);
        salesobject_inputpage_change_maincategory();
    }
    else {
        subCategorySelect.append(subChooseMain);
        thirdCategorySelect.append(thirdChooseMain);
        mainCategorySelect.val('');
    }

}

function salesobject_inputpage_change_maincategory() {

    // update values of the sub category
    //var newMainCategoryIndex = mainCategorySelect.attr('selectedIndex') - 1;    // is sometimes undefined: debug
    var newMainCategoryIndex = document.getElementById("attributes.CATEGORY/MAINCATEGORY").selectedIndex - 1;

    // remove all options
    while ($('option', subCategorySelect).length > 0)
        $('option:last', subCategorySelect).remove();
    while ($('option', thirdCategorySelect).length > 0)
        $('option:last', thirdCategorySelect).remove();

    // main category selected
    if (newMainCategoryIndex != -1) {
        subCategorySelect.append(subChoose);

        // insert new options
        var subCats = childArr[newMainCategoryIndex];
        $.each(subCats.split('|'), function() {
            var optionName = this.split(';')[1];
            var optionValue = this.split(';')[0];
            var option = $('<option/>').attr('value', optionValue).text(optionName);
            subCategorySelect.append(option);
        });
        // udpate selected subcategory if alread1y set + trigger update event
        if (selectedSubCategoryId) {
            subCategorySelect.val(selectedSubCategoryId);
            salesobject_inputpage_change_subcategory();
        }
        else {
            thirdCategorySelect.append(thirdChooseSub);
        }
    }
    // no main category selected
    else {
        subCategorySelect.append(subChooseMain);
        thirdCategorySelect.append(thirdChooseMain);
        subCategorySelect.val('');
    }

    return false;
}
function salesobject_inputpage_change_subcategory() {
    //var filterDependentAttributeValueId = $('option:selected:first', subCategorySelect).attr('value');
    var filterDependentAttributeValueId = subCategorySelect.val();

    // update values of the filter category
    while ($('option', thirdCategorySelect).length > 0)
        $('option:last', thirdCategorySelect).remove();

    if (filterDependentAttributeValueId) {
        var myFilter = filter[filterDependentAttributeValueId];
        var myFilterValues = filterValues[filterDependentAttributeValueId];

        // set form name of fitler category select
        thirdCategorySelect.attr('name', 'attributes.' + myFilter.xmlName);

        // add values
        thirdCategorySelect.append(thirdChoose);
        $.each(myFilterValues, function() {
            var option = $('<option/>').attr('value', this.id).text(this.value);
            thirdCategorySelect.append(option);
        });

        // set selected third level if already set for ad +
        if (selectedThirdCategoryId) {
            thirdCategorySelect.val(selectedThirdCategoryId);
            salesobject_inputpage_change_thirdlevelfiltercategory();
        }
        else {
            thirdCategorySelect.val('');
        }

    }
    else {
        thirdCategorySelect.append(thirdChooseSub);
    }

    return false;
}
function salesobject_inputpage_change_thirdlevelfiltercategory() {
    thirdCategoryInput.attr('value', thirdCategorySelect.attr('name') + '=' + thirdCategorySelect.val());
    return false;
}


function searchAll(radioObject, form1) {
    if (radioObject[1].checked) {
        document.forms['hiddenform'].elements['keyword'].value = form1.elements['keyword'].value;
        document.forms['hiddenform'].elements['sort'].value = form1.elements['sort'].value;
        document.forms['hiddenform'].submit();
        return false;
    }
    else {
        form1.submit();
        return true;
    }
}
/* facebook share button */
function fbs_click() {
    u = location.href;
    t = document.title;
    window.open('http://www.facebook.com/sharer.php?u=' + encodeURIComponent(u) + '&t=' + encodeURIComponent(t), 'sharer', 'toolbar=0,status=0,width=626,height=436');
    return false;
}
/* not in use
 function swapCurrency( formname, tofield, fromfield, selectedNo) {
 document.forms[formname].elements[tofield].value = document.forms[formname].elements[fromfield].options[selectedNo].text;
 }
 */

function expandCollapse() {
    for (var i = 0; i < expandCollapse.arguments.length; i++) {
        var element = document.getElementById(expandCollapse.arguments[i]);
        element.style.display = (element.style.display == "none") ? "block" : "none";
    }
}

/* not in use ON THE SITE - expl needed!   */
function expandCollapseInitiallyHidden() {
    for (var i = 0; i < expandCollapseInitiallyHidden.arguments.length; i++) {
        var element = document.getElementById(expandCollapseInitiallyHidden.arguments[i]);
        element.style.display = (element.style.display == "block") ? "none" : "block";
    }
}


function hideIfEmpty(emptyTag, hideTag) {
    // if no hide tag i specified, hide the empty tag.
    if (hideTag === null) {
        hideTag = emptyTag;
    }

    // find tag which might be empty
    var e = document.getElementById(emptyTag);
    if (isEmpty(e)) {
        hide(hideTag);
    }
}

function isEmpty(element) {
    if (element !== null && element.childNodes !== null && element.childNodes.length <= 1) {
        if (!element.childNodes.length) {
            // element has no children
            return 1;
        } else if (element.childNodes.length == 1 && element.childNodes[0].data !== null && !element.childNodes[0].data.match("[^ \t\n]")) {
            // element has one child, a the child contains only space, tabs and newlines.
            return 1;
        }
    }

    // the tag contains data
    return null;
}

/**
 *  Add an event listener to a DOM element.
 *
 *  @param element    DOM element, ie. "window"
 *  @param eventName  name of the event, ie. "'submit'", which is the onsubmit-event
 *  @param func       a reference to the function that should be called when the event fires
 **/
function _addEventListener(element, eventName, func) {
    if (element.addEventListener) {
        element.addEventListener(eventName, func, false); // W3C
    } else if (element.attachEvent) {
        element.attachEvent('on' + eventName, func); // IE
    } else {
        element['on' + eventName] = func; // warning! removes existing event handler(s)
    }
}

function show(object) {
    if (document.getElementById && document.getElementById(object) !== null) {
        document.getElementById(object).style.visibility = 'visible';
        document.getElementById(object).style.display = 'block';
    } else if (document.layers && document.layers[object] !== null) {
        document.layers[object].visibility = 'visible';
    } else if (document.all) {
        document.all[object].style.zIndex = 100;
        document.all[object].style.visibility = 'visible';
    }
}

function hide(object) {
    if (document.getElementById && document.getElementById(object) !== null) {
        document.getElementById(object).style.visibility = 'hidden';
        document.getElementById(object).style.display = 'none';
    } else if (document.layers && document.layers[object] !== null) {
        document.layers[object].visibility = 'hidden';
    } else if (document.all) {
        document.all[object].style.visibility = 'hidden';
    }
}
/* WHAT IS THIS ? */
if (document.getElementById) {
    document.write('<style>.contractArticle {position:absolute;visibility:hidden;display:none}</style>');
}

// Prevent double form submits by using this function as an input submit button's onclick handler.
// Example usage: <input:submit functionString="disableButton(this, 'Processing...', 'smallbuttonDisabled')" ... />
function disableButton(button, disabledButtonText, disabledStyle) {
    if (!disabledButtonText) {
        disabledButtonText = '   Bitte warten   ';
    }
    button.onclick = preventDefaultAction;
    button.value = disabledButtonText;
    if (disabledStyle) {
        button.className = disabledStyle;
    } else if (button.style) {
        button.style.color = '#BBBBBB';
    }
}

// Prevents the default action for this event from being performed.
function preventDefaultAction(event) {
    if (!event) {
        event = window.event;
        /* does not work with Mozilla 1.75 and Netscape 4 */
    }
    if (event) {
        if (event.preventDefault) {
            event.preventDefault(); // W3C
        } else {
            event.returnValue = false; // IE
        }
    }
    return false;
}

function submitForm(formName) {
    document[formName].submit();
}

function setFormAction(formName, actionValue) {
    document[formName].action = actionValue;
}

function setUserAction(formName, actionField, actionValue) {
    document[formName].elements[actionField].value = actionValue;
}

function setNextStep(formName, value) {
    document[formName].nextStep.value = value;
}

function changeImage(name, text) {
    document.images["main"].src = name;
    document.all.imagetext.innerText = text;
}

// Submit a form to a new popup window. Send all form elements, except files.
// Side effects: all input elements of type "file" will have the disabled-attribute set to false.
function submitToNewWindow(form, action, width, height) {
    function disableFileUpload(disable) {
        for (elemName in form.elements) {
            var elem = form.elements[elemName];
            if (elem !== null && elem.type == 'file') {
                elem.disabled = disable;
            }
        }
    }

    // Default values
    if (!width) {
        width = 740;
    }
    if (!height) {
        height = 540;
    }
    if (!action) {
        action = form.action;
    }

    // Remember old values
    var oldTarget = form.target;
    var oldAction = form.action;

    var windowName = "popupwindow";
    openWindow('', width, height, windowName);
    form.target = windowName;
    form.action = action;

    disableFileUpload(true);
    form.submit();
    disableFileUpload(false);

    // Restore original values
    form.target = oldTarget;
    form.action = oldAction;
    return false;
}

function openWindow(url, width, height, name) {
    if (!name) {
        name = "";
    }
    var win;
    win = window.open(url, name, "toolbar=no,location=no,directories=no,status=no,menubar=0,resizable=0,copyhistory=no,width=" + width + ",height=" + height + ",scrollbars=1");
    if (((navigator.appName.indexOf("Netscape") != -1) && (parseInt(navigator.appVersion) >= 3)) || ((navigator.userAgent.indexOf("MSIE") != -1) && (parseInt(navigator.appVersion) >= 4))) {
        win.focus();
    }
}

function openMapWindow(url) {
    mapwin = window.open(url, "Kart", "toolbar=no,location=no,directories=no,status=no,menubar=0,resizable=1,copyhistory=no,width=805,height=800,screenX=0,screenY=0,scrollbars=yes");
    if (((navigator.appName.indexOf("Netscape") != -1) && (parseInt(navigator.appVersion) >= 3)) || ((navigator.userAgent.indexOf("MSIE") != -1) && (parseInt(navigator.appVersion) >= 4))) {
        mapwin.focus();
    }
}

/* used in the next function */
function checkTextareaMaxLength(textarea, evt, maxLength) {
    if (textarea.selected && evt.shiftKey) {
        // ignore shift click for select
        return true;
    }
    var allowKey = false;
    if (textarea.selected && textarea.selectedLength > 0) {
        allowKey = true;
    } else {
        var keyCode =
            evt.which ? evt.which : evt.keyCode;
        if (keyCode < 48 && keyCode != 13 && keyCode != 32) {
            allowKey = true;
        } else {
            allowKey = textarea.value.length < maxLength;
        }
    }
    textarea.selected = false;
    if (!allowKey) {
        evt.returnValue = false;
        if (evt.preventDefault) {
            evt.preventDefault();
        }
    }
    return allowKey;
}

/**
 * Adds a counter to a textarea and limits its number of charaters to maxLength.
 */
/* seems to be used only in ADMIN */
function addTextAreaCounter(textareaName, maxLength, alertMessage) {
    var textarea = document.getElementById(textareaName);
    var textareaCounterName = textareaName + 'Counter';

    function updateCounter() {
        var value = maxLength - textarea.value.length;
        var counter = textarea.form[textareaCounterName];
        counter.value = value;
    }

    function onKeyPressHandler(evt) {
        if (!evt) {
            evt = window.event;
        }
        return checkTextareaMaxLength(textarea, evt, maxLength);
    }

    function onBlurHandler() {
        if (textarea.value.length > maxLength && alertMessage) {
            alert(alertMessage);
            if (textarea.focus) {
                textarea.focus();
            }
        }
    }

    if (!textarea.form[textareaCounterName]) {
        document.writeln('<input disabled type="text" name="' + textareaCounterName + '" size="3" maxlength="3" value=""> Zeichen frei');
        updateCounter();
        textarea.onkeypress = onKeyPressHandler;
        textarea.onkeyup = textarea.onkeydown = updateCounter;
        textarea.onblur = onBlurHandler;
    } else {
        alert('Error in addTextAreaCounter(): Form already contains a child node named "' + textareaCounterName + '".');
    }
}
function setSelected(form, field) {
    if (document.forms[form].elements[field].options) {
        var length = Number(document.forms[form].elements[field].options.length);
        for (var i = 0; i < length; i++) {
            document.forms[form][field][i].selected = true;
        }
    }
}

function unselectAll(form, field) {
    if (document.forms[form].elements[field].options) {
        var length = Number(document.forms[form].elements[field].options.length);
        for (var i = 0; i < length; i++) {
            document.forms[form][field][i].selected = false;
        }
    }
}

function copy(form, from, to) {
    var length = Number(document.forms[form].elements[from].options.length);
    for (var i = 0; i < length; i++) {
        if (document.forms[form][from][i].selected) {

            var valuefrom = document.forms[form][from][i].value;
            var textfrom = document.forms[form][from][i].text;

            var exists = false;

            var tolength = Number(document.forms[form].elements[to].options.length);
            for (var j = 0; j < tolength; j++) {
                var valueto = document.forms[form][to][j].value;
                var textto = document.forms[form][to][j].text;

                if (valueto == valuefrom && valueto || (textto == textfrom)) {
                    exists = true;
                }
            }

            if (!exists) {
                var l = document.forms[form].elements[to].options.length;
                document.forms[form][to][l] = new Option(document.forms[form][from][i].text, document.forms[form][from][i].value);
            }
            document.forms[form][to][l].selected = true;
        }
    }
}

function copyChild(form, parent, from, to, parentfield, insertparenttext) {
    var parentLenght = Number(document.forms[form].elements[parent].options.length);
    var parentText = "";
    var parentValue = "";

    for (var p = 0; p < parentLenght; p++) {
        if (document.forms[form].elements[parent].options[p].selected) {
            parentText = document.forms[form].elements[parent].options[p].text;
            parentValue = document.forms[form].elements[parent].options[p].value;
        }
    }
    var length = Number(document.forms[form].elements[from].options.length);
    for (var i = 0; i < length; i++) {
        if (document.forms[form][from][i].selected) {

            var valuefrom = document.forms[form][from][i].value;
            var textfrom = parentText + " " + document.forms[form][from][i].text;
            var all = false;
            if (valuefrom == '0') {
                all = true;
            }
            var exists = false;

            var tolength = Number(document.forms[form].elements[to].options.length);
            for (var j = 0; j < tolength; j++) {
                var valueto = document.forms[form][to][j].value;
                var textto = document.forms[form][to][j].text;

                if (valueto == valuefrom && valueto || (textto == textfrom)) {
                    exists = true;
                }
            }

            if (!exists) {
                if (!insertparenttext) {
                    parentText = "";
                }
                var l = document.forms[form].elements[to].options.length;
                if (all) {
                    document.forms[form][to][l] = new Option(parentText + " " + document.forms[form][from][i].text, parentValue);
                } else {
                    document.forms[form][to][l] = new Option(parentText + " " + document.forms[form][from][i].text, document.forms[form][from][i].value);
                }
                document.forms[form][to][l].selected = true;
            }
        }
    }
}


function deleteChild(form, from, all, parentfield) {
    var i, length = Number(document.forms[form].elements[from].options.length);
    if (!all) {
        for (i = length - 1; i >= 0; i--) {
            if (document.forms[form][from][i].selected) {
                if (navigator.appName.indexOf("Netscape") != -1) {
                    document.forms[form].elements[from].options[i] = null;
                } else if (navigator.userAgent.indexOf("Opera") != -1) {
                    document.forms[form].elements[from].options.remove(i);
                } else if ((navigator.userAgent.indexOf("MSIE") != -1) && (parseInt(navigator.appVersion) >= 4)) {
                    document.forms[form].elements[from].options.remove(i);
                } else if ((navigator.userAgent.indexOf("MSIE") != -1) && (parseInt(navigator.appVersion) < 4)) {
                    document.forms[form].elements[from].options[i].selected = false;
                } else {
                    document.forms[form].elements[from].options[i].selected = false;
                }
            } else {
                document.forms[form].elements[from].options[i].selected = true;
            }
        }
    } else {
        if (navigator.appName.indexOf("Netscape") != -1) {
            for (i = (length); i >= 0; i--) {
                document.forms[form].elements[from].options[i] = null;
            }
        } else if (navigator.userAgent.indexOf("Opera") != -1) {
            for (i = (length); i >= 0; i--) {
                document.forms[form].elements[from].options.remove(i);
            }
        } else if ((navigator.userAgent.indexOf("MSIE") != -1) && (parseInt(navigator.appVersion) >= 4)) {
            for (i = (length); i >= 0; i--) {
                document.forms[form].elements[from].options.remove(i);
            }
        } else if ((navigator.userAgent.indexOf("MSIE") != -1) && (parseInt(navigator.appVersion) < 4)) {
            for (i = (length - 1); i >= 0; i--) {
                document.forms[form].elements[from].options[i].selected = false;
            }
        } else {
            for (i = (length - 1); i >= 0; i--) {
                document.forms[form].elements[from].options[i].selected = false;
            }
        }
    }

}

function fillChilds(form, name1, name2, allchilds, allparents) {
    emptySelectBox(form, name1, allchilds);
    var childid = 0;
    var start = 1;
    var name2Length = document[form][name2].length;
    if (allchilds) {
        childid = 1;
    }
    if (!allparents) {
        start = 0;
    }
    var selectedvalue = 0;
    for (var i = start; i < name2Length; i++) {
        if (document[form][name2][i].selected) {

            selectedvalue = parentArr[i - start].split(";")[0];
            var tmpArr = childArr[i - start].split("|");
            for (var j = 0; j < tmpArr.length; j++) {
                var tmpArr2 = tmpArr[j].split(";");
                document[form].elements[name1].options[childid] = new Option(tmpArr2[1], tmpArr2[0]);
                childid++;
            }
        }
    }
    if (allchilds) {
        document[form].elements[name1].options[0].value = '0';
    }
}

function fillChilds_FirstEntryCustomised(form, name1, name2, allparents, value, text) {
    var childid = 0;
    var start = 1;
    var name2Length = document[form][name2].length;

    if (!allparents) {
        start = 0;
    }
    var selectedvalue = 0;
    for (var i = start; i < name2Length; i++) {
        if (document[form][name2][i].selected) {
            document[form].elements[name1].options.length = 0;
            document[form].elements[name1].options[childid] = new Option(text, value);
            childid++;
            selectedvalue = parentArr[i - start].split(";")[0];
            var tmpArr = childArr[i - start].split("|");
            for (var j = 0; j < tmpArr.length; j++) {
                var tmpArr2 = tmpArr[j].split(";");
                document[form].elements[name1].options[childid] = new Option(tmpArr2[1], tmpArr2[0]);
                childid++;
            }
        }
    }
}

function fillChildsLocation(form, name1, name2, allchilds, allparents) {
    emptySelectBox(form, name1, allchilds);
    var childid = 0;
    var start = 1;
    var name2Length = document[form][name2].length;
    if (allchilds) {
        childid = 1;
    }
    if (!allparents) {
        start = 0;
    }
    var selectedvalue = 0;
    for (var i = start; i < name2Length; i++) {
        if (document[form][name2][i].selected) {

            selectedvalue = parentArrLocation[i - start].split(";")[0];
            var tmpArr = childArrLocation[i - start].split("|");
            for (var j = 0; j < tmpArr.length; j++) {
                var tmpArr2 = tmpArr[j].split(";");
                document[form].elements[name1].options[childid] = new Option(tmpArr2[1], tmpArr2[0]);
                childid++;
            }
        }
    }
    if (allchilds) {
        document[form].elements[name1].options[0].value = '0';
    }
}

// Used by the <input:select> tag to remember options when the user navigates back in history
function rememberoptions_load(inputSelect) {
    if (inputSelect && inputSelect.form && inputSelect.options) {
        var hValues = inputSelect.form[inputSelect.name + '_values'];
        var hText = inputSelect.form[inputSelect.name + '_text'];
        var hSelected = inputSelect.form[inputSelect.name + '_selected'];
        if (hValues && hText && hSelected && hValues.value.length > 0) {
            // deserialize the arrays from the hidden fields
            var optionValues = hValues.value.split(';');
            var optionText = hText.value.split(';');
            var optionSelected = hSelected.value.split(';');

            // Delete all existing options.
            emptySelectBox(inputSelect.form.name, inputSelect.name, true);

            for (var i = 0; i < optionValues.length; ++i) {
                // Create a new option
                var option = new Option(optionText[i], optionValues[i]);
                // Add the option to the select tag
                inputSelect.options[i] = option;
                // Mark the option as selected if it should be
                for (var j = 0; j < optionSelected.length; ++j) {
                    if (option.value == optionSelected[j]) {
                        option.selected = true;
                    }
                }
            }
        }
    }
}

// Used by the <input:select> tag to remember options when the user navigates back in history
function rememberoptions_save(inputSelect) {
    if (inputSelect && inputSelect.form && inputSelect.options) {
        var options = inputSelect.options;
        var optionValues = new Array(), optionText = new Array(), optionSelected = new Array();

        // Store options to arrays
        for (var i = 0; i < options.length; ++i) {
            var option = options[i];
            optionValues.push(option.value);
            optionText.push(option.text);
            if (option.selected) {
                optionSelected.push(option.value);
            }
        }

        // Serialize the arrays to hidden fields
        inputSelect.form[inputSelect.name + '_values'].value = optionValues.join(';');
        inputSelect.form[inputSelect.name + '_text'].value = optionText.join(';');
        inputSelect.form[inputSelect.name + '_selected'].value = optionSelected.join(';');
    }
}

// Used by the <input:select> tag to remember options when the user navigates back in history
function rememberoptions_registerEventHandlers(formName, selectTagName) {
    // Find formName if it's missing.
    if (!formName || !formName.length) {
        var tags = document.getElementsByName(selectTagName);
        if (tags.length > 0 && tags[0] && tags[0].form && tags[0].form.name) {
            formName = tags[0].form.name;
        }
    }
    var form = document.forms[formName];
    if (form) {
        var selectTag = form[selectTagName];
        if (selectTag) {
            _addEventListener(form, 'submit', function() {
                rememberoptions_save(selectTag);
            });
            _addEventListener(window, 'load', function() {
                rememberoptions_load(selectTag);
            });
        }
    }
}

function emptySelectBox(form, boxname, allchilds) {
    var i, length = Number(document.forms[form].elements[boxname].options.length);

    if (navigator.appName.indexOf("Netscape") != -1) {
        for (i = (length); i > 0; i--) {
            document.forms[form].elements[boxname].options[i] = null;
        }
    } else if (navigator.userAgent.indexOf("Opera") != -1) {
        for (i = (length); i > 0; i--) {
            document.forms[form].elements[boxname].options.remove(i);
        }
    } else if ((navigator.userAgent.indexOf("MSIE") != -1) && (parseInt(navigator.appVersion) >= 4)) {
        for (i = (length); i > 0; i--) {
            document.forms[form].elements[boxname].options.remove(i);
        }
    } else if ((navigator.userAgent.indexOf("MSIE") != -1) && (parseInt(navigator.appVersion) < 4)) {
        for (i = (length - 1); i > 0; i--) {
            document.forms[form].elements[boxname].options[i].selected = false;
        }
    } else {
        for (i = (length - 1); i > 0; i--) {
            document.forms[form].elements[boxname].options[i].selected = false;
        }
    }
    if ((navigator.appName.indexOf("Netscape") == -1) || ((navigator.appName.indexOf("Netscape") != -1) && (parseInt(navigator.appVersion) > 4))) {
        if (allchilds) {
            document.forms[form].elements[boxname].options[0] = new Option("Alle", "0", true, true);
        } else {
            document.forms[form].elements[boxname].options[0] = new Option("", "0", true, true);
        }
        document.forms[form].elements[boxname].options[0].selected = true;
    }
}

function removeNonDigits(inputObject) {
    inputObject.value = inputObject.value.replace(/[\.,:]-$/, '');
    inputObject.value = inputObject.value.replace(/[\.,:][0-9][0-9]$/, '');
    inputObject.value = inputObject.value.replace(/[^0-9]/g, '');
}

function removeNonDigitsAllowDecimal(inputObject) {
    inputObject.value = inputObject.value.replace(/[\.,:]-$/, '');
    inputObject.value = inputObject.value.replace(/[\.:][0-9][0-9]$/, '');
    inputObject.value = inputObject.value.replace(/[^0-9,]/g, '');
}

function removeNonDigitsNonComma(inputObject) {
    inputObject.value = inputObject.value.replace(/[^0-9,]/g, '');
}

function removeZeroValue(inputObject) {
    inputObject.value = inputObject.value.replace(/^[^1-9]*0$/, '');
}

function removePrecedingZeros(inputObject) {
    inputObject.value = inputObject.value.replace(/^0+/, '');
}

function swapImage(intImage) {
    var filenamePosition = document.getElementById("image" + intImage).src.indexOf('collapse.gif');
    var originalSrc = document.getElementById("image" + intImage).src;
    if (filenamePosition > 0) {
        document.getElementById("image" + intImage).src = originalSrc.substring(0, filenamePosition) + 'expand.gif';
    } else {
        filenamePosition = document.getElementById("image" + intImage).src.indexOf('expand.gif');
        document.getElementById("image" + intImage).src = originalSrc.substring(0, filenamePosition) + 'collapse.gif';
    }
    return(false);
}

// Merge two or more collections.
// Example usage: var result = concat_collections(divTag.getElementsByTagName('input'), divTag.getElementsByTagName('textarea'))
function concat_collections() {
    var result = new Array();
    for (var i = 0; i < concat_collections.arguments.length; ++i) {
        var collection = concat_collections.arguments[i];
        for (var j = 0; j < collection.length; ++j) {
            result.push(collection[j]);
        }
    }
    return result;
}

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}
/*
 * Copied from Hebbes/Kalaydo as variaPriceFieldCheck
 */
function longPriceFieldCheck(inputObject) {
    var temp = inputObject.value;
    temp = temp.replace(/[,]$/, '');
    temp = temp.replace(/[^0-9,]/g, '');
    if (temp != inputObject.value) {
        alert('Must use comma in price field');
        inputObject.value = '';
    }
}

/**
 * Unobtrusive windows.onload replacement. Will keep existing onload events.
 **/
function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            oldonload();
            func();
        }
    }
}

/**
 * overrides all the selections (comboboxes) on the bulk-rejection page with the selection of the first combobox (select) element
 **/
function overrideSelections() {
    if (document.getElementsByTagName) {
        var comboboxes = document.getElementsByTagName('select');
        var overrider = comboboxes[0]; // defining the first combobox as the overrider
        var selectedIndexForAll = overrider.selectedIndex;

        if (comboboxes) {
            for (var index = comboboxes.length - 1; index > 0; index--) // no need to process index 0, its the overrider
            {
                var combobox = comboboxes[index];
                combobox[selectedIndexForAll].selected = true;
            }
        }
    }
}

function adjustImageSize(myAnchor, myMaxWidth, myMaxHeight) {
    var myAnchorElement = document.getElementById(myAnchor);
    if (myAnchorElement) {
        var myImages = myAnchorElement.getElementsByTagName("img");
        if (myImages) {
            for (var x = 0; x < myImages.length; x++) {

                // A "hack" to avoid rescaling of the google ads that is included in the resultlists for Willhaben.
                // Don't rescale images that has a parent with classname "googleAd". See eJ-1894505.
                var isGoogleAd = false;
                var parent = myImages[x].parentNode;
                while (!isGoogleAd && parent) {
                    if (parent.className == "googleAd") {
                        isGoogleAd = true;
                    }
                    parent = parent.parentNode;
                }

                if (!isGoogleAd) {
                    if (myImages[x].width > myMaxWidth) {
                        myImages[x].width = myMaxWidth;
                    }
                    if (myImages[x].height > myMaxHeight) {
                        myImages[x].height = myMaxHeight;
                    }
                }
            }
        }
    }
}
// resizes images in result lists (if they are too big)
function resizeImage(imageObject, maxWidth, maxHeight) {
    var image = imageObject;
    var setwidth = maxWidth;
    var setheight = maxHeight;

    if (image.width() > setwidth) {
        image.css('width', setwidth);
    }
    if (image.height() > setheight) {
        image.css('height', setheight);
    }
    image.css('visibility', 'visible');
}

/**
 * Update selected products. Will return html, and insert it to div#order.
 *
 * @param form
 * @param ajaxUrl
 */
function updateOrder(form, ajaxUrl) {
    var $j = jQuery.noConflict();
    var parameters = $j(form).serialize();
    $j.ajax({
        url: ajaxUrl, type: 'POST', dataType: 'html', timeout: 2000,
        data: parameters,
        error:   function() {/* If error then no changes will occur. */
        },
        success: function(html) {
            $j("div#order").html(html);
        }
    });
}

/**
 * Script that will format an input field with . as 1000 separator
 * and remove all non-numerig chars
 * Usage: <input name="price_from" type="text" onkeyup="formatWithThousandSeparator(this)" onchange="formatWithThousandSeparator(this)">
 **/
function formatWithThousandSeparator(input) {
    var num = input.value.replace(/\./g, '');	// Remove dots
    if (!isNaN(num)) {
        num = num.toString().split('').reverse().join(''); // reverse the number, enabling us to find three and three numbers from the back
        num = num.replace(/(?=\d*\.?)(\d{3})/g, '$1.');	// group numbers and add dots
        num = num.split('').reverse().join('').replace(/^[\.]/, '');	// reverse again, and remove starting dot
        input.value = num;
    } else {
        input.value = input.value.replace(/[^\d\.]*/g, '');	// remove non-numeric stuff
    }
}

/**
 * Script that displays a window with the description texts and images
 * for the upselling products. used at ad-input shoppingcart pages.
 **/

function addon_description_window_show(imgfname, productname, productdesc, productpros, type, vertical) {
    var width;
    var height;
    var left = "100";
    var top = "100";
    var addonPopupUrl = "http://fast2.willhaben.apa.net/upselling_descriptions/";

    switch (type) {
        case "highlight":
            width = "850";
            switch (vertical) {
                case "realestate":
                    height = "445";
                    addonPopupUrl += "upselling_highlight_realestate.html";
                    break;
                case "car":
                    height = "445";
                    addonPopupUrl += "upselling_highlight_car.html";
                    break;
                case "job":
                    height = "445";
                    addonPopupUrl += "upselling_highlight_job.html";
                    break;
                case "bap":
                    height = "445";
                    addonPopupUrl += "upselling_highlight_bap.html";
                    break;
                default:
                    height = "700";
            }
            break;
        case "bold":
            width = "850";
            switch (vertical) {
                case "realestate":
                    height = "445";
                    addonPopupUrl += "upselling_bold_realestate.html";
                    break;
                case "car":
                    height = "445";
                    addonPopupUrl += "upselling_bold_car.html";
                    break;
                case "job":
                    height = "445";
                    addonPopupUrl += "upselling_bold_job.html";
                    break;
                case "bap":
                    height = "445";
                    addonPopupUrl += "upselling_bold_bap.html";
                    break;
                default:
                    height = "700";
            }
            break;
        case "topjob":
            width = "650";
            height = "440";
            addonPopupUrl += "upselling_topjob_job.html";
            break;
        case "topad1":
            width = "700";
            switch (vertical) {
                case "realestate":
                    height = "495";
                    addonPopupUrl += "upselling_topad_result_realestate.html";
                    break;
                case "car":
                    height = "520";
                    addonPopupUrl += "upselling_topad_result_car.html";
                    break;
                case "job":
                    height = "465";
                    addonPopupUrl += "upselling_topad_result_job.html";
                    break;
                case "bap":
                    height = "500";
                    addonPopupUrl += "upselling_topad_result_bap.html";
                    break;
                default:
                    height = "700";
            }
            break;
        case "topad2":
            width = "700";
            switch (vertical) {
                case "realestate":
                    height = "590";
                    addonPopupUrl += "upselling_topad_vertical_realestate.html";
                    break;
                case "car":
                    height = "490";
                    addonPopupUrl += "upselling_topad_vertical_car.html";
                    break;
                case "job":
                    height = "600";
                    addonPopupUrl += "upselling_topad_vertical_job.html";
                    break;
                case "bap":
                    height = "570";
                    addonPopupUrl += "upselling_topad_vertical_bap.html";
                    break;
                default:
                    height = "700";
            }
            break;
        default:
            width = "700";
            height = "700";
    }

    var new_window = window.open(addonPopupUrl, "_blank", "width=" + width + ",height=" + height + ",left=" + left + ",top=" + top + ", toolbar=no, menubar=no, status=no");

    new_window.focus();
    return(false);
}

// fix IE6 and IE7 bottom round corner
if ($.browser.msie && $.browser.version.substr(0, 1) < 8) {
    $(document).ready(fixIE);
    $(window).load(fixIE);
}
// IE hack for problematic elements (wrong display)
// dynamically add (and remove) the CSS attribute 'zoom' ('zoom' works only in IE!)
function fixIE() {
    $('.rounded-bottom').css('zoom', '').css('zoom', '1');
}

// global popup handler
// add class "popup"  to any link tag and it will be automatically opened in a popup window
// default size for the pop up is 500 x 500 pixel
// additionally to "popup" you can add class "big" to change the popup dimensions to 760 x 500
var popupwin = null;
var activatePopups = function() {
    var winwith, winheight;
    $('a.popup').click(function(event) {
        if ($(this).hasClass('big')) {
            winwith = 760;
            winheight = 500;
        } else {
            winwith = 500;
            winheight = 500;
        }

        var winleft = (screen.width - winwith) / 2;
        var wintop = (screen.height - winheight) / 2;
        var settings = 'height=' + winheight + ',';
        settings += 'width=' + winwith + ',';
        settings += 'top=' + wintop + ',';
        settings += 'left=' + winleft + ',';
        settings += 'scrollbars=yes' + ',';
        settings += 'status=yes' + ',';
        settings += 'resizable=yes';
        popupwin = window.open(this.href, 'willhabenpop', settings);
        popupwin.focus();
        event.preventDefault();
    });
}
$(document).ready(activatePopups);

// upselling popup handler
// this is a clone implementation of activatePopups() for the popups in the upselling pages
// (these upselling popups should be replaced with overlays at some point)
var upsellingwin = null;
var upsellingPopups = function() {
    var winwith = 660;
    var winheight = 560;
    var winleft = (screen.width - winwith) / 2;
    var wintop = (screen.height - winheight) / 2;
    var settings = 'height=' + winheight + ',';
    settings += 'width=' + winwith + ',';
    settings += 'top=' + wintop + ',';
    settings += 'left=' + winleft + ',';
    settings += 'scrollbars=yes' + ',';
    settings += 'status=yes' + ',';
    settings += 'resizable=yes';
    $('a.uppopup').click(function(event) {
        popupwin = window.open(this.href, 'upsellpop', settings);
        popupwin.focus();
        event.preventDefault();
    });
}

// splits a html list in 2 equal lists
// useful to display a list on 2 columns (where it's not possible to do this in the backend)
// example: from one UL with 10 LI elements it creates two ULs with 5 LIs each
var splitList = function(listClass) {
    var originalList = $(listClass);
    var originalItems = originalList.children('li');
    if (originalItems.length > 0) {
        var splitAt = Math.round(originalItems.length / 2);

        //clone it but hide it
        var cloneList = originalList.clone().insertAfter(originalList).css('display', 'none');
        var clonedItems = cloneList.children();

        //remove first half of LIs from clone list
        for (var i = 0; i < clonedItems.length; i++) {
            if (i < splitAt) {
                $(clonedItems[i]).remove();
            }
        }
        //remove last half of LIs from original list
        for (var i = 0; i < originalItems.length; i++) {
            if (i >= splitAt) {
                $(originalItems[i]).remove();
            }
        }
        //show it
        cloneList.css('display', 'block');
    }
}

// sorts a list alphabetically
// used where it's not possible to do this from the backend
// listClass must be a CSS selector (class or ID)
var sortList = function(listClass) {
    var mylist = $(listClass);
    var listitems = mylist.children('li').get();
    if (listitems.length > 0) {
        listitems.sort(function(a, b) {
            var compA = $(a).text().toUpperCase();
            var compB = $(b).text().toUpperCase();
            return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
        })
        $.each(listitems, function(idx, itm) {
            mylist.append(itm);
        });
    }
};

// render media icons on certain links attached to objects
// the scripts checks the extension of the link  and renders the appropiate icon by applying a certain class
// the default icon will be rendered when none of the extensions is found
var renderMediaIcons = function() {
    var videocount = 0;
    var documentcount = 0;
    $('.media-icons a').each(function() {
        // get link URL
        var link = $(this).attr('href');

        // get link extension
        var mediatype = link.split(".").pop();

        var mediaclass, linktext, docnumber;

        switch (mediatype) {
            // video extensions
            case 'avi':
            case 'asf':
            case 'dvx':
            case 'flv':
            case 'mp4':
            case 'mpe':
            case 'mpg':
            case 'mpeg':
            case 'wm':
            case 'wmv':
            case 'mov':
            case 'vid':
                mediaclass = 'video';
                linktext = "Video";
                videocount++;
                docnumber = videocount;
                break;
            // pdf extensions
            case 'pdf':
                mediaclass = 'pdf';
                linktext = "Dokument";
                documentcount++;
                docnumber = documentcount;
                break;
            // Word extensions
            case 'doc':
            case 'docx':
                mediaclass = 'word';
                linktext = "Dokument";
                documentcount++;
                docnumber = documentcount;
                break;
            // Excel extensions
            case 'xls':
            case 'xlsx':
                mediaclass = 'excel';
                linktext = "Dokument";
                documentcount++;
                docnumber = documentcount;
                break;
            // default behaviour
            default:
                mediaclass = 'default';
                linktext = "Dokument";
                documentcount++;
                docnumber = documentcount;
        }
        // add the class and update the anchor text
        $(this).addClass('media-link').addClass(mediaclass + '-link').text(linktext + ' ' + docnumber);
    });

};

// used in search\car\include\makemodel_navigator.jsp
// script written by finn
var dynamicCarMake = function() {
    // find out which car models to show. Show maximum 20, so hide the ones with fewer hits than the 20th
    var adsPerBrand = new Array();
    $("#make_navigator_head .car_make_item").each(function() {
        var adsInBrand = $(this).attr("rel");
        adsPerBrand.push(new Number(adsInBrand));
    });

    adsPerBrand.sort(function(a, b) {
        return (b < a);
    });
    var showCarMakeLimit = 0;

    // find the number of ads in the 20th
    showCarMakeLimit = adsPerBrand[Math.max(0, adsPerBrand.length - 20)];

    // mark all car make ids according to whether its count number is higer or lower than the limt
    $("#make_navigator_head .car_make_item").each(function() {
        if (new Number($(this).attr("rel")) < showCarMakeLimit) {
            $(this).addClass("rare_make");
        }
    });

    //show and hide brands
    $('#car_make_compander').toggle(
        function() {
            $('.rare_make').css('display', 'block');
            $(this).addClass("display-all");
        },
        function() {
            $(this).removeClass('display-all');
            $('.rare_make').css('display', 'none');
            $('.rare_make input').each(function() {
                $(this).attr('checked', '');
            });
            //scroll up
            var targetOffset = $($('#make_navigator_head')).offset().top - 10;
            $('html,body').animate({scrollTop: targetOffset}, 500);
        }
    );
};

// renders the bookmark service links in the left column
// 
var bookmarkServices = function() {
    // get and encode URL of current page
    var url = encodeURIComponent(location.href);

    //get and encode title of current page
    var metatitle = encodeURIComponent(document.title);

    var container = $('#bookmarks');

    // add "Bookmarks" title
    container.append('<p class="box-title">Bookmarks</p>');

    // define bookmarks array
    // synax is:
    // [bookmark-id, bookmark short URL, bookmark complete URL]
    // the bookmark-ids are used in css for displaying the icons !
    var bookmarks = [
        ['oneview','oneview.de','http://www.oneview.de/quickadd/neu/addBookmark.jsf?URL=' + url + '&title=' + metatitle],
        ['delicious','delicious.com','http://delicious.com/post?v=4&noui&jump=close&url=' + url + '&title=' + metatitle],
        ['misterwong','mister-wong.de','http://www.mister-wong.de/index.php?action=addurl&bm_url=' + url + '&bm_notice=&bm_description=' + metatitle + '&bm_tags='],
        ['linkarena','linkarena.com','http://linkarena.com/bookmarks/addlink/?url=' + url + '&title=' + metatitle + '&desc=&tags='],
        ['googlebookmarks','google.com/bookmarks','http://www.google.com/bookmarks/mark?op=add&hl=de&bkmk=' + url + '&annotation=&labels=&title=' + metatitle],
        ['stumbleupon','stumbleupon.com','http://www.stumbleupon.com/submit?url=' + url + '&title=' + metatitle],
        ['digg','digg.com','http://digg.com/submit?phase=2&url=' + url + '&bodytext=&tags=&title=' + metatitle]
    ];
    // create a tags for each bookmark
    for (var i = 0; i <= bookmarks.length - 1; i++) {
        $('<a/>')
            .attr('id', bookmarks[i][0])
            .text(bookmarks[i][1])
            .attr('href', bookmarks[i][2])
            .attr('title', 'Diese Seite bei ' + bookmarks[i][1] + ' boomkarken')
            .attr('class', 'popup big')
            .attr('target', '_blank')
            .attr('rel', 'nofollow')
            .appendTo(container);
    }

    // add help button
    $('<span class="button-help">?</span>')
        // insert button into DOM
        .appendTo(container)
        // add click event (toggle between 2 functions)
        .toggle(
        // 1st function: show (or create) the bubble
        function() {
            // if bubble already exists in DOM, show it
            if ($('#bookmarkshelp').exists()) {
                $('#bookmarkshelp').fadeIn('fast');
            }
            // else create the bubble, then show it
            else {
                infoBubble();
                $('#bookmarkshelp').fadeIn('fast');
            }
        },
        // 2nd function: hide bubble
        function() {
            $('#bookmarkshelp').fadeOut('fast');
        }
    );

    // create help overlay
    var infoBubble = function() {
        //create help bubble
        var bubbleText = '' +
            '<p>Jede Seite auf willhaben.at können Sie für sich und für andere mit einem Klick als "Bookmark" (engl. Lesezeichen) speichern, wenn Sie eines der Symbole klicken. Das Besondere: Diese Lesezeichen werden nicht auf Ihrem eigenen Computer, sondern direkt im Internet auf der Webseite des jeweiligen Dienstes gespeichert. Je mehr Personen eine Seite dann dort gespeichert haben und dadurch im Prinzip auch anderen empfohlen haben, desto interessanter stuft der Dienst diese Seite ein.</p>' +
            '<p>Im Gegensatz zu den gängigen Suchmaschinen wie bspw. Google werden die empfohlenen Links also nicht durch spezielle Suchprogramme automatisch, sondern stets von anderen Menschen erstellt. Dies gewährleistet, dass die gefundenen Informationen wirklich genau dem Gesuchten entsprechen.</p>' +
            '<p>Achtung: Einzige Voraussetzung, unsere Seiten wie beschrieben zu "bookmarken" ist, dass Sie bei einem der vorgestellten Social Bookmark-Dienste registriert sind. Die Anmeldung ist bei allen Anbietern kostenlos.</p>';

        var bubbleHTML = $('<div class="bubbleContainer bubble-2" id="bookmarkshelp"><div class="bubbleTop"></div><div class="bubbleBody">' + bubbleText + '</div><div class="bubbleBottom"></div><span class="bubbleClose"></span></div>');
        bubbleHTML.appendTo(container);

        // activate close button of bubble
        // this simulates a click on the trigger button and will call the toggle function
        $('#bookmarkshelp .bubbleClose').click(function() {
            $('#bookmarks .button-help').trigger('click');
        });
    };

    // now show bookmarks box
    container.css('display', 'block');
};

//init tabs in form (on Immobilien Services)
var formTabs = function() {
    $('.form-tabs .tabs span').click(function() {
        //toggle tabs
        $('#tab-switch').removeClass().addClass('form-tabs').addClass("show-" + $(this).attr('class'));
    });
};

// init help labels on Immobilien Service forms
var formHelp = function() {
    // make help-labels disappear (by removing class 'has-help') when it's pair-input receives focus
    $('.has-help input').focus(function() {
        $(this).parent('.has-help').removeClass('has-help');
    });

    // if user clicks on the help-label, focus on it's pair-input (and hence make the label disappear)
    $('.has-help .input-help').click(function() {
        $(this).css('display', 'none').prev('input').focus();
    });
};

// init form validation on Immobilien Service
var formCheck = function() {
    $('#checkimmoform').submit(function(element) {
        var emptyFields = '';
        var searchScope1;
        var searchScope2 = '#checkimmoform .no-tabs input.mandatory';

        //check fileds under Dokumentdaten
        if ($('#tab-switch').hasClass('show-tab-1')) {
            searchScope1 = '#checkimmoform .tab-content-1 input.mandatory';
        } else if ($('#tab-switch').hasClass('show-tab-2')) {
            searchScope1 = '#checkimmoform .tab-content-2 input.mandatory';
        }

        //check fields under Rechnungsdaten
        $(searchScope1 + ',' + searchScope2).each(function() {
            var self = $(this);

            // if the input is empty, get the text from it's label-pair
            if (self.val() == '') {
                emptyFields = emptyFields + self.parent().prev('label').text() + '\n';
            }
        });

        // alert all empty fields (if any found)
        if (emptyFields != '') {
            alert('Bitte ausfüllen:\n' + emptyFields);
            return false;
        }
        else {
            return true;
        }
    });
};

// fix firefox iframe cache bug
$(document).load(function() {
    $('iframe').each(function() {
        var iframesrc = $(this).attr('src');
        $(this).attr('src', iframesrc);
    });
});

function checkPublishStatus(obj, adIdQuery, aggStatus, url) {
    if (obj.checked) {
        publicizeUnpublicize(obj, adIdQuery, aggStatus, url);
        obj.disabled = true;
    } else {
        publicizeUnpublicize(obj, adIdQuery, aggStatus, url);
        obj.disabled = true;
    }
}

function publicizeUnpublicize(obj, adIdQuery, aggStatus, url) {
    $.ajax({
        url: url,
        type: 'POST',
        dataType: 'json',
        timeout: 200000,
        data: {},
        contentType: "application/x-www-form-urlencoded;charset=UTF-8",
        success : function(json) {
            obj.disabled = false;
            $("#" + aggStatus).load(window.location.href + " #" + aggStatus + " > *", {'adIdQuery':adIdQuery, 'dontStoreSearchInSession': true});
        },
        error : function(err) {
            alert('AJAX Error:\n ' + err);
        }
    });
}

if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, '');
  }
}

