// Namespacing method http://blogger.ziesemer.com/2008/05/javascript-namespace-function.html
var namespace = function (name, separator, container) {
    var ns = name.split(separator || '.'),
    o = container || window,
    i,
    len;
    for (i = 0, len = ns.length; i < len; i++) {
        o = o[ns[i]] = o[ns[i]] || {};
    }
    return o;
};

// generell functions
var selectDisabled = 'select-disabled';
var inputDisabled = 'input-disabled';
var labelDisabled = 'label-disabled';

function AddCssClassToItem(cssclass, item) {
    RemoveCssClassFromItem(cssclass, item);
    item.className = (item.className + ' ' + cssclass).replace(/^\s+|\s+$/, "");
}
function RemoveCssClassFromItem(cssclass, item) {
    item.className = (item.className.replace(cssclass, '')).replace(/^\s+|\s+$/, "");
}

function gE(id) {
    return document.getElementById(id);
}

function defaultTextFocus(elem, cssclass) {
    var newElem;
    if (elem && elem.currentTarget)
        elem = elem.currentTarget;
    if (!elem && window.event && window.event.srcElement)
        elem = window.event.srcElement;
    if (!elem)
        return;

    if (!elem.defaultText && elem.attributes["defaulttext"])
        elem.defaultText = elem.attributes["defaulttext"].value;
    if (!elem.defaultTextCssClass && elem.attributes["defaulttextcssclass"])
        elem.defaultTextCssClass = elem.attributes["defaulttextcssclass"].value;
    try {
        if (elem.defaultText == elem.value) elem.value = '';
    } catch (e) { }
    if (elem.defaultTextCssClass) {
        setPassword = elem.attributes["isPassword"] != null ? elem.attributes["isPassword"].value : true;
        if (elem.id && (elem.id.indexOf('password') >= 0 || elem.id.indexOf('Password') >= 0) && setPassword == true && elem.getAttribute) {

            try {
                var passId = elem.id.substring(0, elem.id.length - 3);
                var passBox = $('#' + passId);
                if (passBox.length == 1) {
                    $('#' + elem.id).hide();
                    passBox.css('display', 'inline');
                    passBox.focus();
                }
            } catch (e) {
            }
        }
        RemoveClassName(elem, elem.defaultTextCssClass);
    } else if (cssclass) {
        elem.className = cssclass;
    }
}

function replaceChild(parent, oldelem, newElem) {
    if (!parent || !parent.children || !parent.children.length || !parent.removeChild || !parent.appendChild
    || !oldelem || !newElem || !oldelem.id) {
        return;
    }
    for (var i = 0; i < parent.children.length; i++) {
        if (parent.children[i].id == newElem.id) {
            parent.replaceChild(newElem, oldelem);
            break;
        }
    }
}

function defaultTextBlur(elem, evt, cssclass) {
    if (elem && elem.currentTarget)
        elem = elem.currentTarget;
    if (!elem && window.event)
        elem = window.event.srcElement;
    if (!elem)
        return;
    try {
        if (elem.value == '') {
            if (elem && elem.getAttribute && elem.getAttribute('type') == 'password') {
                elem.defaultText = '';
            } else {
                elem.value = elem.defaultText;
            }
            if (typeof (elem.onchange) == 'function' && evt) elem.onchange(evt);
            if (elem.defaultTextCssClass) {
                AddClassName(elem, elem.defaultTextCssClass);
            } else if (cssclass) {
                elem.className = cssclass;
            }
        }
    } catch (e) { }
}

function popUp(theUrl, theName, props) {
    var popupwin = window.open(theUrl, theName, props);
    if (popupwin.focus) popupwin.focus();
}

function trim(str) {
    // trim spaces from string
    return str.replace(/^\s+|\s+$/, "");
}

function AddClassName(elem, className) {
    if (elem.className.indexOf(className) == -1) {
        RemoveClassName(elem, className);
        elem.className = trim(elem.className + ' ' + className);
    }
}

function RemoveClassName(elem, className) {
    elem.className = trim(elem.className.replace(className, ''));
}

function ContainsClassName(elem, className) {
    return (elem.className == elem.className.replace(className, ''));
}

// handling dom
function removeElements(id) {
    var elem = gE(id);
    try {
        elem.innerHTML = '';
        for (cn in elem.childNodes) {
            elem.removeChild(cn);
        }
    }
    catch (e) { }
}

function createElement(parentElement, newElem) {
    var newNode = document.createElement(newElem);
    parentElement.appendChild(newNode);
    return newNode;
}

function createP(parentElement, css, text) {
    var newNode = document.createElement('p');
    newNode.className = css;
    if (text) createText(newNode, text);
    parentElement.appendChild(newNode);
    return newNode;
}

function createH2(parentElement, css) {
    var newNode = document.createElement('H2');
    newNode.className = css;
    if (parentElement) parentElement.appendChild(newNode);
    return newNode;
}

function createDiv(parentElement, css, text) {
    var newNode = document.createElement('div');
    newNode.className = css;
    if (parentElement) parentElement.appendChild(newNode);
    if (text) createText(newNode, text);
    return newNode;
}

function createSpan(parentElement, css, text) {
    var newNode = document.createElement('span');
    newNode.className = css;
    if (parentElement) parentElement.appendChild(newNode);
    if (text) createText(newNode, text);
    return newNode;
}

function createText(parentElement, text) {
    var newNode = document.createTextNode(text);
    parentElement.appendChild(newNode);
}

function createCheckbox(parentElement, id) {
    var newNode = document.createElement('input');
    newNode.type = 'checkbox';
    newNode.id = id;
    parentElement.appendChild(newNode);
    return newNode;
}

function createAnchor(parentElement, css, href, text, onclick) {
    var newNode = document.createElement('a');
    if (text) createText(newNode, text);
    newNode.href = href;
    newNode.className = css;
    parentElement.appendChild(newNode);
    if (onclick) {
        try { newNode.onclick = onclick; newNode.setAttribute('onclick', onclick); } catch (e) { }
    }
    return newNode;
}

function createAnchorWithoutHREF(parentElement, articleId, text, onclick) {
    var newNode = document.createElement('a');
    if (text) createText(newNode, text);
    newNode.className = articleId;
    parentElement.appendChild(newNode);
    if (!onclick) {
        onclick = 'jQuery.as24.parkdeck.addCar(this, "' + car.ArticleId + '")';
    }

    try { newNode.onclick = onclick; newNode.setAttribute('onclick', onclick); } catch (e) { };

    return newNode;
}

function createImage(parentElement, css, src, alt) {
    var newNode = document.createElement('img');
    newNode.src = src;
    newNode.alt = alt;
    newNode.title = alt;
    newNode.className = css;
    parentElement.appendChild(newNode);
    return newNode;
}

function createRow(parentElement, css) {
    var newNode = document.createElement('tr');
    newNode.className = css;
    parentElement.appendChild(newNode);
    return newNode;
}

function createCell(parentElement, css, text) {
    var newNode = document.createElement('td');
    newNode.className = css;
    if (text) createText(newNode, text);
    parentElement.appendChild(newNode);
    return newNode;
}

/* For checkbox labels in wevi listgn.aspx */
function createLabel(parentElement, forElement, css, text) {
    var newNode = document.createElement('label');
    newNode.className = css;
    newNode.setAttribute('for', forElement);
    if (parentElement) parentElement.appendChild(newNode);
    if (text) createText(newNode, text);
    return newNode;
}

// cookie handling
function getCookieValue(name, defaultValue) {
    var arg = name + '=';
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while (i < clen) {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg) {
            var endstr = document.cookie.indexOf(';', j);
            if (endstr == -1) endstr = document.cookie.length;
            return unescape(document.cookie.substring(j, endstr));
        }
        i = document.cookie.indexOf(' ', i) + 1;
        if (i == 0) break;
    }
    return defaultValue;
}

function setCookieValue(name, value, persistent) {
    var a = new Date();
    var expDate = new Date(a.getFullYear() + 1, a.getMonth(), a.getDay(), 1, 0, 0);
    var domain = document.domain;
    var path = '/';
    if (domain.indexOf('.') > -1) domain = domain.substring(domain.indexOf('.'));
    document.cookie = name + '=' + value + ';path=' + path + (persistent ? ';domain=' + domain + ';expires=' + expDate.toGMTString() : '');
}


// handling urls
function changeUrlParameter(url, param, val) {
    var anchorIndex = url.indexOf('#');
    var hasAnchor = anchorIndex > 0;
    var anchor = '';
    if (hasAnchor) {
        anchor = url.substring(anchorIndex);
        url = url.substring(0, anchorIndex);
    }
    var start = url.indexOf('?' + param);
    if (start == -1) start = url.indexOf('&' + param);
    if (start == -1) {
        if (url.indexOf('?') == -1)
            url += '?';
        else
            url += '&';
        url = url + param + '=' + escape(val);
        if (hasAnchor) { url += anchor; }
        return url;
    }
    var end = url.indexOf('&', start + 1);
    if (end == -1) end = url.length;
    url = url.substring(0, start + 1) + param + '=' + escape(val) + url.substring(end, url.length);
    if (hasAnchor) {
        url += anchor;
    }
    return url;
}

function changeMultipleUrlParameter(url, param, val) //val can be comma separated
{
    url = removeExistingUrlParameter(url, param);
    var a = val.split(',');
    for (var i = 0; i < a.length; i++) {
        if (url.indexOf('=')) {
            //already has parameters
            url = url.concat('&' + param + '=' + escape(a[i]));
        }
        else {
            url = url.concat('?' + param + '=' + escape(a[i]));
        }
    }
    return url;
}

function removeUrlParameter(url, param) {
    var start = url.indexOf('?' + param);
    if (start == -1) start = url.indexOf('&' + param);
    if (start == -1) return url;
    var end = url.indexOf('&', start + 1);
    if (end == -1) end = url.length;
    return url.substring(0, start + 1) + url.substring(end, url.length);
}

function removeExistingUrlParameter(url, param) {
    //parameters not at the end
    var regex = new RegExp(param + '=[^&]*&');
    var found = regex.exec(url);
    while (found) {
        url = url.replace(found[0], '');
        found = regex.exec(url);
    }
    //rightmost parameter
    regex = new RegExp('[?&]' + param + '=[^&]*');  //no ampersand
    found = regex.exec(url);
    if (found) {
        url = url.replace(found[0], '');
    }
    return url;
}

function getUrlParameter(url, param) {
    var start = url.indexOf('?' + param);
    if (start == -1) start = url.indexOf('&' + param);
    if (start == -1) return null;
    var end = url.indexOf('&', start + 1);
    if (end == -1) end = url.length;
    return url.substring(start + 1, end);
}

// makemodel selection
function onSelectionChanged(selList, hdVal, versionboxId) {
    var oSelList = gE(selList);
    gE(hdVal).value = oSelList.options[oSelList.selectedIndex].value;
    if (versionboxId != '') {
        var oVersionValue = gE(versionboxId);
        if (oVersionValue != null) {
            oVersionValue.value = '';
            if (gE(hdVal).value == 0) {
                oVersionValue.disabled = 'disabled';
                AddCssClassToItem(inputDisabled, oVersionValue);
            }
            else {
                oVersionValue.disabled = '';
                RemoveCssClassFromItem(inputDisabled, oVersionValue);
            }
        }
    }
}

// makemodel selection
function onSelectionInit(selList, hdVal, versionboxId, singleVersion) {
    var oSelList = gE(selList);
    gE(hdVal).value = oSelList.options[oSelList.selectedIndex].value;
    if (versionboxId != '') {
        var oVersionValue = gE(versionboxId);
        if (oVersionValue != null && !singleVersion) {
            //oVersionValue.value = '';
            if (gE(hdVal).value == 0) {
                oVersionValue.disabled = 'disabled';
                AddCssClassToItem(inputDisabled, oVersionValue);
            }
            else {
                oVersionValue.disabled = '';
                RemoveCssClassFromItem(inputDisabled, oVersionValue);
            }
        }
    }
}

function onSelectionChangedSingleVersion(selList, hdVal, selList1, hdVal1, selList2, hdVal2, versionboxId) {
    var oSelList = gE(selList);
    var oSelList1 = gE(selList1);
    var oSelList2 = gE(selList2);
    gE(hdVal).value = oSelList.options[oSelList.selectedIndex].value;
    gE(hdVal1).value = oSelList1.options[oSelList1.selectedIndex].value;
    gE(hdVal2).value = oSelList2.options[oSelList2.selectedIndex].value;
    if (versionboxId != '') {
        var oVersionValue = gE(versionboxId);
        if (oVersionValue != null) {
            if (gE(hdVal).value == 0 && gE(hdVal1).value == 0 && gE(hdVal2).value == 0) {
                oVersionValue.value = '';
                oVersionValue.disabled = 'disabled';
                AddCssClassToItem(inputDisabled, oVersionValue);
            }
            else {
                oVersionValue.disabled = '';
                RemoveCssClassFromItem(inputDisabled, oVersionValue);
            }
        }
    }
}

// This function is used to preselect make and model from URL parameters passed to 
// the home page.
function selectMakeAndModelByUrlParameter(makeListId, modelListId, modelValId, versionboxId, modelCaptionId, index, byValue, singleVersion) {
    if (!index || index < 0) {
        index = 0;
    }

    var makeList = $('#' + makeListId);
    var modelList = $('#' + modelListId);

    if (makeList.length > 0 && modelList.length > 0) {

        var makeParam, modelParam;

        var mmk0 = location.search.match(/[\?&]mmvmk0=([^&#]+)/);
        var mmk1 = location.search.match(/[\?&]mmvmk1=([^&#]+)/);
        var mmk2 = location.search.match(/[\?&]mmvmk2=([^&#]+)/);
        if (mmk0 == null && mmk1 == null && mmk2 == null)
            makeParam = location.search.match(/[\?&]make=([^&#]+)/);
        else {
            makeParam =
                mmk0 == null ? '0' : mmk0 + ',' +
                mmk1 == null ? '0' : mmk1 + ',' +
                mmk2 == null ? '0' : mmk2;
        }

        var mmd0 = location.search.match(/[\?&]mmvmd0=([^&#]+)/);
        var mmd1 = location.search.match(/[\?&]mmvmd1=([^&#]+)/);
        var mmd2 = location.search.match(/[\?&]mmvmd2=([^&#]+)/);
        if (mmd0 == null && mmd1 == null && mmd2 == null)
            modelParam = location.search.match(/[\?&]model=([^&#]+)/);
        else {
            modelParam =
                mmd0 == null ? '0' : mmd0 + ',' +
                mmd1 == null ? '0' : mmd1 + ',' +
                mmd2 == null ? '0' : mmd2;
        }

        var makeName = makeParam != null ? decodeURIComponent(makeParam[1]) : null;
        var modelName = modelParam != null ? decodeURIComponent(modelParam[1]) : null;

        if (makeName != null && isNaN(makeName)) {
            var makeNames = makeName.split(',');
            if (makeNames.length && index <= makeNames.length - 1) {
                makeList.val(makeNames[index]);
            }
            chooseMake(true, makeListId, modelListId, false, modelCaptionId);
        }
        if (modelName != null && isNaN(modelName)) {
            var models;
            if (modelName.indexOf(',') > -1) { models = modelName.split(','); }
            else { models = [modelName] };
            if (models.length && index <= models.length) {
                for (var i = 0; i < modelList[0].length; i++) {
                    for (var j = 0; j < models.length; j++) {
                        var compareValue = "";
                        if (byValue)
                            compareValue = fastTrim(modelList[0].options[i].value);
                        else
                            compareValue = fastTrim(modelList[0].options[i].text);

                        if (j <= models.length - 1 && compareValue == models[j]) {
                            modelList[0].selectedIndex = i;
                            onSelectionInit(modelListId, modelValId, versionboxId, singleVersion);
                            break;
                        }
                    }
                }
            }
        }
        if (modelName != null && !isNaN(modelName)) {
            var models = modelName; ;
            if (models.length && index <= models.length) {
                for (var i = 0; i < modelList[0].length; i++) {
                    var compareValue = "";
                    if (byValue)
                        compareValue = fastTrim(modelList[0].options[i].value);
                    else
                        compareValue = fastTrim(modelList[0].options[i].text);

                    if (compareValue == models) {
                        modelList[0].selectedIndex = i;
                        onSelectionInit(modelListId, modelValId, versionboxId, singleVersion);
                        break;
                    }
                }
            }
        }
    }
}

var _includeModelLine = true;
/**
* 
*/

function initTypeMakeModel(typeListId, makeListId, modelListId, modelValId, versionboxId, modelCaptionId, includeModelLine, index, byValue, singleVersion, selectedMake) {
    chooseType(true, typeListId, makeListId, modelListId);

    var oMakeSelect = gE(makeListId);

    for (var i = 0; i < oMakeSelect.options.length; i++) {
        if (oMakeSelect.options[i].value == selectedMake) {
            oMakeSelect.selectedIndex = i;
            break;
        }
    }

    initMakeModel(makeListId, modelListId, modelValId, versionboxId, modelCaptionId, includeModelLine, index, byValue, singleVersion);

}

function initMakeModel(makeListId, modelListId, modelValId, versionboxId, modelCaptionId, includeModelLine, index, byValue, singleVersion) {

    _includeModelLine = includeModelLine;
    chooseMake(true, makeListId, modelListId, false, modelCaptionId);
    var oModelSelect = gE(modelListId);
    var oModelValue = gE(modelValId).value;
    if (versionboxId != '') {
        var oVersionValue = gE(versionboxId);
        if (oVersionValue != null) {
            if (!singleVersion) {
                if (oModelValue == 0) {
                    oVersionValue.disabled = 'disabled';
                    AddCssClassToItem(inputDisabled, oVersionValue);
                }
                else {
                    oVersionValue.disabled = '';
                    RemoveCssClassFromItem(inputDisabled, oVersionValue);
                }
            }
            else {
                if (!oVersionValue.value && gE("selectedmodelvalue0").value == 0 && gE("selectedmodelvalue1").value == 0 && gE("selectedmodelvalue2").value == 0) {
                    oVersionValue.disabled = 'disabled';
                    AddCssClassToItem(inputDisabled, oVersionValue);
                }
            }
        }
    }

    for (var i = 0; i < oModelSelect.options.length; i++) {
        if (oModelSelect.options[i].value == oModelValue) {
            oModelSelect.selectedIndex = i;
            break;
        }
    }

    if (!singleVersion)
        selectMakeAndModelByUrlParameter(makeListId, modelListId, modelValId, versionboxId, modelCaptionId, index, byValue, singleVersion);
}

function initMultiControl(parent, make, model, version, caption, captionNr, singleVersion) {
    //initMakeModel(make, model, "","");
    setMultiControl(parent, make, model, version, caption, captionNr, singleVersion);
}

function setMultiControl(parent, make, model, version, caption, captionNr, singleVersion) {
    var oParent = gE(parent);
    var oMake = gE(make);
    var oModel = gE(model);
    var oVersion = gE(version);
    var oCaption = gE(caption);
    var oCaptionNr = gE(captionNr);

    oMake.disabled = ((oParent.selectedIndex == 0) ? 'disabled' : '');
    if (oMake.selectedIndex > 0) oMake.disabled = '';
    oModel.disabled = ((oMake.selectedIndex == 0) ? 'disabled' : '');
    if (!singleVersion)
        oVersion.disabled = ((oModel.selectedIndex == 0) ? 'disabled' : '');
    else {
        if (oVersion.disabled) oVersion.disabled = ((oModel.selectedIndex == 0) ? 'disabled' : '');
    }

    if (oMake.disabled) {
        AddCssClassToItem(selectDisabled, oMake);
        AddCssClassToItem(labelDisabled, oCaption);
        AddCssClassToItem(labelDisabled, oCaptionNr);
    }
    else {
        RemoveCssClassFromItem(selectDisabled, oMake);
        RemoveCssClassFromItem(labelDisabled, oCaption);
        RemoveCssClassFromItem(labelDisabled, oCaptionNr);
    }

    if (oModel.disabled) {
        AddCssClassToItem(selectDisabled, oModel);
    }
    else {
        RemoveCssClassFromItem(selectDisabled, oModel);
    }

    if (oVersion.disabled) {
        AddCssClassToItem(inputDisabled, oVersion);
    }
    else {
        RemoveCssClassFromItem(inputDisabled, oVersion);
    }
}

function chooseType(headContained, typeListId, makeListId, modelListId) {
    var oTypeSelect = gE(typeListId);
    var oMakeSelect = gE(makeListId);
    var oModelSelect = gE(modelListId);

    oModelSelect.selectedIndex = 0;
    oModelSelect.options.length = 1;
    oMakeSelect.selectedIndex = 0;
    oMakeSelect.options.length = 1;

    var offsetForAll = (headContained ? 1 : 0);

    if (oTypeSelect.selectedIndex >= offsetForAll) {

        var postfix = oTypeSelect.options[oTypeSelect.selectedIndex].value;
        eval("arrMakes = arrMakes" + postfix + ";");
        eval("arrModels = arrModels" + postfix + ";");
        oMakeSelect.options.length = arrMakes.length;
        for (var i = offsetForAll; i < arrMakes.length; i++) {
            oMakeSelect.options[i].value = arrMakes[i].split(',')[0];
            oMakeSelect.options[i].text = arrMakes[i].split(',')[1];
        }
    }

    if (headContained && oTypeSelect.selectedIndex == 0) {
        oMakeSelect.disabled = 'disabled';
        AddCssClassToItem(selectDisabled, oMakeSelect);
    }
    else {
        oMakeSelect.disabled = '';
        RemoveCssClassFromItem(selectDisabled, oMakeSelect);
    }

    oModelSelect.disabled = 'disabled';
    AddCssClassToItem(selectDisabled, oModelSelect);
}

function chooseMake(headContained, makeListId, modelListId, updateModel, modelCaption) {
    var oMakeSelect = gE(makeListId);
    var oModelSelect = gE(modelListId);
    var oModelCaption = gE(modelCaption);

    oModelSelect.selectedIndex = 0;
    oModelSelect.options.length = 1;
    var offsetForAll = (headContained ? 1 : 0);
    if (oMakeSelect.selectedIndex >= offsetForAll) {

        var modList = (arrModels[oMakeSelect.value]).split(';');
        oModelSelect.options.length = modList.length + 1;
        var index = 1;
        for (var i = 0; i < modList.length; i++) {
            if (_includeModelLine) {
                oModelSelect.options[index].value = modList[i].split(',')[0];
                oModelSelect.options[index].text = modList[i].split(',')[1];
            }
            else {
                var val = modList[i].split(',')[0];
                if (parseInt(val) < 0) {
                    oModelSelect.options.length--;
                    continue;
                }
                oModelSelect.options[index].value = val;
                oModelSelect.options[index].text = trim(modList[i].split(',')[1]);
            }
            index++;
        }
    }

    if (oModelSelect.options.length == (1 + offsetForAll)) oModelSelect.selectedIndex = offsetForAll;

    if (headContained && oMakeSelect.selectedIndex == 0) {
        oModelSelect.disabled = 'disabled';
        AddCssClassToItem(selectDisabled, oModelSelect);
        if (oModelCaption != null) {
            AddCssClassToItem(labelDisabled, oModelCaption);
        }
        setBlueDots('makeModelDots', false);
    }
    else {
        oModelSelect.disabled = '';
        RemoveCssClassFromItem(selectDisabled, oModelSelect);
        if (oModelCaption != null) {
            RemoveCssClassFromItem(labelDisabled, oModelCaption);
        }
        setBlueDots('makeModelDots', true);
    }

    if (updateModel) oModelSelect.onchange();
}

function setBlueDots(dotsDivId, active) {
    var dotsCtrl = gE(dotsDivId);
    if (dotsCtrl != null) {
        if (active) {
            RemoveCssClassFromItem("dots-grey", dotsCtrl);
            AddCssClassToItem("dots-blue", dotsCtrl);
        }
        else {
            RemoveCssClassFromItem("dots-blue", dotsCtrl);
            AddCssClassToItem("dots-grey", dotsCtrl);
        }
    }
}

/*Sets the text of the associated control. */
function setHoverLabelTxt(labelCtrlId, text) {
    var labelCtrl = gE(labelCtrlId); // $('#' + labelCtrlId).text(text)
    if (labelCtrl != null) {
        labelCtrl.innerHTML = text;
    }
}

function checkInputLength(elem, len) {
    if (elem.value.length > len) elem.value = elem.value.substring(0, len);
}

function SetZipSearchOnChange(countrySelect, radiusSelect, zipInput) {
    if ((countrySelect == null) || (radiusSelect == null) || (zipInput == null)) {
        return;
    }
    if (countrySelect.selectedIndex == 0) {
        radiusSelect.disabled = 'disabled';
        radiusSelect.selectedIndex = 0;
        zipInput.disabled = 'disabled';
        zipInput.value = zipInput.defaultText;

        // requested by PM - ticket 15158
        AddCssClassToItem(selectDisabled, radiusSelect);
        AddCssClassToItem(inputDisabled, zipInput);
    }
    else {
        radiusSelect.disabled = '';
        zipInput.disabled = '';

        // requested by PM - ticket 15158
        RemoveCssClassFromItem(selectDisabled, radiusSelect);
        RemoveCssClassFromItem(inputDisabled, zipInput);
    }
}

function SortImages(parent, intFirst, intSecond) {
    var objFirst = gE(parent + "_ImageCtr" + intFirst);
    var objSecond = gE(parent + "_ImageCtr" + intSecond);

    var objOldNumberFirst = gE(parent + "_OldIndex" + intFirst);
    var objOldNumberSecond = gE(parent + "_OldIndex" + intSecond);

    var strSRC = objFirst.src;
    objFirst.src = objSecond.src;
    objSecond.src = strSRC;

    var i = objOldNumberFirst.value;
    objOldNumberFirst.value = objOldNumberSecond.value;
    objOldNumberSecond.value = i;
}


function ShowDeleteLogoConfirmation() {
    showHideForm('confirmArea', 'block', null, null);
    activeForm = gE('confirmArea');
    var hei = activeForm.offsetHeight ? activeForm.offsetHeight : 150;
    centerForm(activeForm, hei);
    attachKeyDown();
    return false;
}

function Delete_Cancel() {
    showHideForm('confirmArea', 'none', null, null);
    return false;
}



var gparent;


function SetDeleteImages(parent, delIndex) {
    gparent = parent;
    var delButtonIndex = gE(parent + "_DeleteButtonIndex");
    delButtonIndex.value = delIndex;
    showHideForm('confirmArea', 'block', null, null);
    activeForm = gE('confirmArea');
    var hei = activeForm.offsetHeight ? activeForm.offsetHeight : 150;
    centerForm(activeForm, hei);
    attachKeyDown();
    return false;
}

function SetDeleteAllImages() {
    var delButtonIndex = gE(parent + "_DeleteButtonIndex");
    delButtonIndex.value = delIndex;
    showHideForm('confirmArea', 'block', null, null);
    return false;
}

function DeleteImage_Ok() {
    for (var i = 1; i < 15; i++) {
        var who = gE(gparent + "_fu" + i);
        var who2 = who.cloneNode(false);
        who2.onchange = who.onchange;
        who.parentNode.replaceChild(who2, who);
    }
}

function schwacke() {
    if (document.cookie.indexOf("zanox=1") >= 0)
        koop = '855D2A2961';
    else
        koop = '42FB6A6CEB';
    var link1 = escape('http://wli-de.eurotax.com/wli/dede/entry/welcome.php?koop_id=' + koop);
    var url = '/redir.asp?type=AC&eventdetail=SCEC&site=1&language=ger&name=az_ct_schwacke&link=' + link1;
    breite = 790;
    hoehe = 580;
    XX = screen.availWidth;
    YY = screen.availHeight;
    x = (XX - breite) / 2;
    y = (YY - hoehe) / 2;
    var win = window.open(url, 'schwacke', 'height=' + hoehe + ',width=' + breite + ',toolbar=no,location=no,menubar=no,scrollbars=yes,resizable=no,left=' + x + ',top=' + y);
    if (win && win.focus)
        win.focus();
}

/* z-index utility function*/

function SetZIndex(indexvalue, controlclass) {
    var control = $(controlclass);
    if (control.length > 0) {
        control[0].style.zIndex = indexvalue;
    }
}

function escapeHTML(str) {
    var replacements = { '<': '&lt;', '&': '&amp;', '>': '&gt;' };
    return str.replace(/[<&>]/g, function(c) { return replacements[c]; });
}

function measureString(cssClass, str) {
    var e = document.createElement('span');
    e.setAttribute('class', cssClass);
    e.style.whiteSpace = 'nowrap';
    e.style.visibility = 'hidden';
    var body = document.getElementsByTagName('body');
    if (body && body.length)
        body[0].appendChild(e);
    else
        return -1;
    e.innerHTML = str;
    var length = -1;
    if (e.offsetWidth)
        length = e.offsetWidth;
    body[0].removeChild(e);
    return length;
}

/* str - string to trim
* cssClass - css class of the string
* maxLengthPx - maximal allowed length in pixels
* maxLengthWorstCase - approximated maximal allowed length in characters ( worst case - if widest possible character is used W )
*/
function trimString(str, cssClass, maxLengthPx, maxLengthWorstCase) {
    if (!str || !cssClass || !maxLengthPx || !maxLengthWorstCase || maxLengthWorstCase <= 3) {
        return str;
    }
    if (navigator.appName.indexOf('Microsoft') >= 0) {
        maxLengthPx -= 10;
    }

    var length = measureString(cssClass, str);
    if (length < 0) {
        if (str && str.length && str.length > maxLengthWorstCase) {
            str = str.substring(0, maxLengthWorstCase - 3) + '...';
        }
    } else if (length > maxLengthPx) {
        while (length > maxLengthPx && str.length > maxLengthWorstCase) {
            str = str.substring(0, str.length - 2);
            length = measureString(cssClass, str + "...");
        }
        str += "...";
    }
    return str;
}

var lastRadiusValue = 0;
var isWeviCtrl = false;
function activateRadiusDropDown(textBox, id, fn, captionId) {
    var captionCtrl = gE(captionId);
    if (!textBox) return;
    if (!id) return;
    if (typeof fn != 'function') fn = validateNumber;
    var e = $('[id$=' + id + ']');
    if (e[0].className.indexOf("wevictrl") > -1) { isWeviCtrl = true; }
    if (!e) return;
    if (textBox.value && textBox.value.length && fn(textBox.value)) {
        if (!isWeviCtrl) {
            RemoveCssClassFromItem(selectDisabled, e[0]);
            if (e && e.attr('disabled')) {
                e.attr('disabled', false);
            }
            lastRadiusValue = e.attr('value');
            if (lastRadiusValue == 0) {
                e.attr('value', 100);
            }
            else {
                e.attr('value', lastRadiusValue);
            }
        }
        else {
            if (e[0].className == "wevictrl_disabled") { e[0].className = "wevictrl" }
            if (lastRadiusValue != 0) {
                e.val(lastRadiusValue);
            }
            else {
                e.val(100);
            }
        }
        setBlueDots("radiusDots", true);
        if (captionCtrl != null) {
            RemoveCssClassFromItem(labelDisabled, captionCtrl);
        }
    }
    else {
        if (!isWeviCtrl) {
            AddCssClassToItem(selectDisabled, e[0]);
            if (e && !e.attr('disabled')) {
                e.attr('disabled', true);
            }
            lastRadiusValue = e.attr('value');
        }
        else {
            if (e.val() != "") { lastRadiusValue = parseInt(e.text()); e.val(""); }
            if (e[0].className == "wevictrl") { e[0].className = "wevictrl_disabled"; }
        }
        setBlueDots("radiusDots", false);
        if (captionCtrl != null) {
            AddCssClassToItem(labelDisabled, captionCtrl);
        }
    }
}

function validateNumber(zip) {
    if (!zip || typeof zip != ('string') || !zip.length)
        return false;
    for (var i = 0; i < zip.length; i++) {
        if (zip[i] < '0' || zip[i] > '9') {
            return false;
        }
    }
    return true;
}

function validateZipD(zip) {
    var v = new RegExp('^[\\d]{5}$');
    var m = v.exec(zip);
    return (m != null);
}

fastTrim = function(str) {
    if (!str) return str;
    return str.replace( /^\s\s*/ , '').replace( /\s\s*$/ , '');
};

function vcmap_over() { $('[id^=vcml_]').css('text-decoration', 'none'); }
function vcmap_out() { $('[id^=vcml_]').css('text-decoration', 'underline'); }

bindHighlightEvent = function(ctrlId, lblId, nodeName) {
    var elm = $('#' + ctrlId + ' ' + nodeName);
    if (elm[0] != null) {
        elm.bind('focus', function() { $('#' + lblId).addClass('active') });
        elm.bind('blur', function() { $('#' + lblId).removeClass('active') });
    }
}

function isZipCodeValid(zipcode, country) {
    var pattern;

    if (country == undefined || country == null) country = "";

    var c = country.toString().toUpperCase();

    switch (c) {
        case "A":
        case "B":
        case "L":
            pattern = /^[0-9]{4}$/;
            break;
        case "D":
        case "S":
        case "I":
        case "HR":
            pattern = /^[0-9]{5}$/;
            break;
        case "F":
        case "E":
            pattern = /^[0-9]{4,5}$/;
            break;
        case "NL":
            pattern = /^[0-9]{4}\s?[a-z]{0,2}$/i;
            break;
        case "RUS":
            pattern = /^[0-9]{6}$/;
            break;
        default:
            pattern = /^[0-9]{5}$/;
            break;
    }

    return pattern.test(zipcode);
}

function validateZipCountries(zip) {
    return isZipCodeValid(zip, ctry);
}

(function($) {

    // old selectfix.js migrated to jquery
    $(document).ready(function() {
        if ($.browser.msie && parseInt($.browser.version) <= 6) {
            $('select').bind('focusin', function() {
                var eSrc = window.event.srcElement;
                if (eSrc) eSrc.tmpIndex = eSrc.selectedIndex;
            }).bind('focus', function() {
                var eSrc = window.event.srcElement;
                if (eSrc) eSrc.selectedIndex = eSrc.tmpIndex;
            });
        }
    });
} (jQuery));

// showHeadlineForMediumRectangle() sets up a timer which checks every 300ms if the div with the
// id="mediumRectangle" has an height greater than 30 px and if yes makes the label visible.
var showHeadlineForMediumRectangle = function() {
    $(document).ready(function() {
        var headline = $("#mediumRectangleHeadline")[0];
        if (typeof(headline) != "undefined")
        {
            headline.style.display = "none";
            
            var rectangle = $("#mediumRectangle")[0]; // exists only after $(document).ready
            rectangle.style.display = "none"; 
            
            var intervalId = window.setInterval(function() {
                if ($(rectangle).height() > 30) {
                    headline.style.visibility = "visible";
                    headline.style.display = "block";
                    rectangle.style.display = "block";
                    window.clearInterval(intervalId);
                }
            }, 300);
        }
    });
};

// Note: legacy - jQuery UI Slider modification to support styling for range sliders (separate css classes)
$(function () {
    $(document).bind('slidecreate', function (event) {
        var range = $(event.target).slider('option', 'range');
        var values = $(event.target).slider('option', 'values');
        if (range) {
            $(event.target).find('.ui-slider-handle:first').addClass('ui-slider-handle-left');
        }
        if (values && values.length) {
            $(event.target).find('.ui-slider-handle:gt(0)').addClass('ui-slider-handle-right');
        }
    });
});

// FeatureToggles for JavaScript - use only as a last resort
namespace("$.as24").isToggleEnabled = function(name) {
    return (typeof($.as24.toggles[name]) == "undefined") ? false: true;
};


// Hack for moving the Eurotax Wizard Pages to a different domain
// This functions is used to resize the iframe and post a message on the click 
// event of the "weiter" button
// It is implemented here so we don't have to change any asp pages
function resizeIframe() {
    if (!(window['postMessage'] && !$.browser.opera)) return;        

    var height = $(document).height() + 30;
    var parentUrl = window.location.protocol + '//' + window.location.host.replace('asp', 'www');

    $.postMessage(height.toString(), parentUrl, parent);
    $('button.button-emphasised[name^="action"]').click(function () {
        $.postMessage("weiter", parentUrl, parent);
    });

    // Old implementation for unmoved asp pages
    //    var iframe = parent.document.getElementById(iframeId);
    //    if (iframe) iframe.height = self.document.body.scrollHeight;
}

// this belongs to the above hack and is used only as a stub for
// old asp pages that we don't want to change
function checkAndResizeIframe(iframeId, parentUrl) {

    // Old implementation for unmoved asp pages
    //    if (parent.location.href.indexOf(parentUrl) == -1)
    //        location.href = parentUrl;
    //    else
    //        resizeIframe(iframeId);
}

/*!
* jQuery postMessage - v0.5 - 9/11/2009
* http://benalman.com/projects/jquery-postmessage-plugin/
* 
* Copyright (c) 2009 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/

// Script: jQuery postMessage: Cross-domain scripting goodness
//
// *Version: 0.5, Last updated: 9/11/2009*
// 
// Project Home - http://benalman.com/projects/jquery-postmessage-plugin/
// GitHub       - http://github.com/cowboy/jquery-postmessage/
// Source       - http://github.com/cowboy/jquery-postmessage/raw/master/jquery.ba-postmessage.js
// (Minified)   - http://github.com/cowboy/jquery-postmessage/raw/master/jquery.ba-postmessage.min.js (0.9kb)
// 
// About: License
// 
// Copyright (c) 2009 "Cowboy" Ben Alman,
// Dual licensed under the MIT and GPL licenses.
// http://benalman.com/about/license/
// 
// About: Examples
// 
// This working example, complete with fully commented code, illustrates one
// way in which this plugin can be used.
// 
// Iframe resizing - http://benalman.com/code/projects/jquery-postmessage/examples/iframe/
// 
// About: Support and Testing
// 
// Information about what version or versions of jQuery this plugin has been
// tested with and what browsers it has been tested in.
// 
// jQuery Versions - 1.3.2
// Browsers Tested - Internet Explorer 6-8, Firefox 3, Safari 3-4, Chrome, Opera 9.
// 
// About: Release History
// 
// 0.5 - (9/11/2009) Improved cache-busting
// 0.4 - (8/25/2009) Initial release

(function ($) {
    '$:nomunge'; // Used by YUI compressor.

    // A few vars used in non-awesome browsers.
    var interval_id,
    last_hash,
    cache_bust = 1,

    // A var used in awesome browsers.
    rm_callback,

    // A few convenient shortcuts.
    window = this,
    FALSE = !1,

    // Reused internal strings.
    postMessage = 'postMessage',
    addEventListener = 'addEventListener',

    p_receiveMessage,

    // I couldn't get window.postMessage to actually work in Opera 9.64!
    has_postMessage = window[postMessage] && !$.browser.opera;

    // Method: jQuery.postMessage
    // 
    // This method will call window.postMessage if available, setting the
    // targetOrigin parameter to the base of the target_url parameter for maximum
    // security in browsers that support it. If window.postMessage is not available,
    // the target window's location.hash will be used to pass the message. If an
    // object is passed as the message param, it will be serialized into a string
    // using the jQuery.param method.
    // 
    // Usage:
    // 
    // > jQuery.postMessage( message, target_url [, target ] );
    // 
    // Arguments:
    // 
    //  message - (String) A message to be passed to the other frame.
    //  message - (Object) An object to be serialized into a params string, using
    //    the jQuery.param method.
    //  target_url - (String) The URL of the other frame this window is
    //    attempting to communicate with. This must be the exact URL (including
    //    any query string) of the other window for this script to work in
    //    browsers that don't support window.postMessage.
    //  target - (Object) A reference to the other frame this window is
    //    attempting to communicate with. If omitted, defaults to `parent`.
    // 
    // Returns:
    // 
    //  Nothing.

    $[postMessage] = function (message, target_url, target) {
        if (!target_url) { return; }

        // Serialize the message if not a string. Note that this is the only real
        // jQuery dependency for this script. If removed, this script could be
        // written as very basic JavaScript.
        message = typeof message === 'string' ? message : $.param(message);

        // Default to parent if unspecified.
        target = target || parent;

        if (has_postMessage) {
            // The browser supports window.postMessage, so call it with a targetOrigin
            // set appropriately, based on the target_url parameter.
            target[postMessage](message, target_url.replace(/([^:]+:\/\/[^\/]+).*/, '$1'));

        } else if (target_url) {
            // The browser does not support window.postMessage, so set the location
            // of the target to target_url#message. A bit ugly, but it works! A cache
            // bust parameter is added to ensure that repeat messages trigger the
            // callback.
            target.location = target_url.replace(/#.*$/, '') + '#' + (+new Date) + (cache_bust++) + '&' + message;
        }
    };

    // Method: jQuery.receiveMessage
    // 
    // Register a single callback for either a window.postMessage call, if
    // supported, or if unsupported, for any change in the current window
    // location.hash. If window.postMessage is supported and source_origin is
    // specified, the source window will be checked against this for maximum
    // security. If window.postMessage is unsupported, a polling loop will be
    // started to watch for changes to the location.hash.
    // 
    // Note that for simplicity's sake, only a single callback can be registered
    // at one time. Passing no params will unbind this event (or stop the polling
    // loop), and calling this method a second time with another callback will
    // unbind the event (or stop the polling loop) first, before binding the new
    // callback.
    // 
    // Also note that if window.postMessage is available, the optional
    // source_origin param will be used to test the event.origin property. From
    // the MDC window.postMessage docs: This string is the concatenation of the
    // protocol and "://", the host name if one exists, and ":" followed by a port
    // number if a port is present and differs from the default port for the given
    // protocol. Examples of typical origins are https://example.org (implying
    // port 443), http://example.net (implying port 80), and http://example.com:8080.
    // 
    // Usage:
    // 
    // > jQuery.receiveMessage( callback [, source_origin ] [, delay ] );
    // 
    // Arguments:
    // 
    //  callback - (Function) This callback will execute whenever a <jQuery.postMessage>
    //    message is received, provided the source_origin matches. If callback is
    //    omitted, any existing receiveMessage event bind or polling loop will be
    //    canceled.
    //  source_origin - (String) If window.postMessage is available and this value
    //    is not equal to the event.origin property, the callback will not be
    //    called.
    //  source_origin - (Function) If window.postMessage is available and this
    //    function returns false when passed the event.origin property, the
    //    callback will not be called.
    //  delay - (Number) An optional zero-or-greater delay in milliseconds at
    //    which the polling loop will execute (for browser that don't support
    //    window.postMessage). If omitted, defaults to 100.
    // 
    // Returns:
    // 
    //  Nothing!

    $.receiveMessage = p_receiveMessage = function (callback, source_origin, delay) {
        if (has_postMessage) {
            // Since the browser supports window.postMessage, the callback will be
            // bound to the actual event associated with window.postMessage.

            if (callback) {
                // Unbind an existing callback if it exists.
                rm_callback && p_receiveMessage();

                // Bind the callback. A reference to the callback is stored for ease of
                // unbinding.
                rm_callback = function (e) {
                    if ((typeof source_origin === 'string' && e.origin !== source_origin)
            || ($.isFunction(source_origin) && source_origin(e.origin) === FALSE)) {
                        return FALSE;
                    }
                    callback(e);
                };
            }

            if (window[addEventListener]) {
                window[callback ? addEventListener : 'removeEventListener']('message', rm_callback, FALSE);
            } else {
                window[callback ? 'attachEvent' : 'detachEvent']('onmessage', rm_callback);
            }

        } else {
            // Since the browser sucks, a polling loop will be started, and the
            // callback will be called whenever the location.hash changes.

            interval_id && clearInterval(interval_id);
            interval_id = null;

            if (callback) {
                delay = typeof source_origin === 'number'
          ? source_origin
          : typeof delay === 'number'
            ? delay
            : 100;

                interval_id = setInterval(function () {
                    var hash = document.location.hash,
            re = /^#?\d+&/;
                    if (hash !== last_hash && re.test(hash)) {
                        last_hash = hash;
                        callback({ data: hash.replace(re, '') });
                    }
                }, delay);
            }
        }
    };

})(jQuery);

