/// <reference path="jquery-vsdoc.js" />

Object.extend = function(dest, source, replace) {
    for (var prop in source) {
        if (replace == false && dest[prop] != null) { continue; }
        dest[prop] = source[prop];
    }
    return dest;
};

var IwAG = {
    Base: {}
}

var globalDialog = null;
var marginLeft = null;
var marginTop = null;
var IsPrintSite = false;
var ModalBackButtonCounter = 0;
var ModalDialogonOpenFunction = null;
var ModalDialogonShowFunction = null;
var ModalDialogOnCloseFunction = null;
// Überprüfungen auf die Globalen vars
if (typeof IWhost == 'undefined') { IWhost = '' };
if (typeof mid == 'undefined') mid = 0;

jQuery.extend({

    hasURLParam: function(url, strParamName) {
        /// <summary>
        /// Überprüft die Url auf den benötigeten paramter
        /// </summary>
        /// <returns type='jQuery'></returns>
        /// <param name=url>url</param>
        /// <param name=strParamName>strParamName</param>
        /// <autor>AME</autor>
        /// <datum>26.11.2008</datum>
        return ($.getURLParam(url, strParamName) != "");
    },

    getURLParam: function(url, strParamName) {
        /// <summary>
        /// getURLParam
        /// </summary>
        /// <returns type='jQuery'></returns>
        /// <param name=url>url</param>
        /// <param name=strParamName>strParamName</param>
        /// <autor>AME</autor>
        /// <datum>26.11.2008</datum>
        var strReturn = "";
        var strHref = (url != undefined && url != null) ? url : window.location.href;
        if (strHref.indexOf("?") > -1) {
            var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
            var aQueryString = strQueryString.split("&");
            for (var iParam = 0; iParam < aQueryString.length; iParam++) {
                var keyVal = aQueryString[iParam].split("=");
                if (keyVal[0] == strParamName) {
                    strReturn = keyVal[1];
                    break;
                }
            }
        }
        return strReturn;
    },

    getURLFileName: function (str) {
        var slash = '/'
        if (str.match(/\\/)) {
            slash = '\\'
        }
        return str.substring(str.lastIndexOf(slash) + 1, str.lastIndexOf('.'))
    } 
    
    
});

// --------------------------------------------------------------------------------------------------------------------------
// ToDo: Muss sobald etwas gefunden wurde zum richtigen Eventhandling wieder in die js events verschoben werden!!
// Der Aufruf dieses NS passiert in Address.v4/LoginForm.ascx -- hier natürlich dann auch entfernen wenn es soweit ist!!
IwAG.Events = {};
IwAG.Events.Authentication = (function() {
    var uniqueInstance;

    function Authentication() {
        var $txtPassword = $("#txtPassword");
        var $lbtnLogin = $("a[id$=lbtnLogin]");
        if (typeof $lbtnLogin.get(0) == 'undefined')
            return;
        function Loggin_keydown(e) {
            e = e || window.event;
            var code = e.keyCode || e.which;
            if (code == 13) eval($lbtnLogin.attr('href').replace('javascript:', ''));
        }

        $txtPassword.keydown(function(e) {
            Loggin_keydown(e);
        });
    }

    return {
        getInstance: function() {
            if (!uniqueInstance) {
                uniqueInstance = Authentication();
            }

            return uniqueInstance;
        }
    }
})();
// --------------------------------------------------------------------------------------------------------------------------

$(document).ready(function () {

    var backButton = new Array();
    var resizeTimer = null;

    $.fn.SetDefaultModalPopupFunctions = function (onOpen, onShow, onClose) {
        ModalDialogonOpenFunction = (onOpen != undefined && onOpen != null ? onOpen : null);
        ModalDialogonShowFunction = (onShow != undefined && onShow != null ? onShow : null);
        ModalDialogOnCloseFunction = (onClose != undefined && onClose != null ? onClose : null);
    }

    $.fn.SetDefaultModalPopupCorners = function (ModalPopUpHeaderImage, mid, bgImageIsSet) {
        var _bg = "";
        if (typeof ModalPopUpHeaderImage != 'undefined' && ModalPopUpHeaderImage != null && mid != undefined && mid != null && mid > 0 && mid != 114 && mid != 115) // immowelt.ch & immowelt.at
            _bg = ModalPopUpHeaderImage;
        else {
            var _backgroundImage2 = "_Images/V3/layout_head/header_bg.gif";
            if (typeof PopUpImageDomain != 'undefined' && PopUpImageDomain != null) {
                _bg = PopUpImageDomain + "/" + _backgroundImage2;
                if (PopUpImageDomain.lastIndexOf("/") == PopUpImageDomain.length - 1)
                    _bg = PopUpImageDomain + _backgroundImage2;
            }
            else {
                _bg = IWhost + "/" + _backgroundImage2;
                if (IWhost.lastIndexOf("/") == IWhost.length - 1)
                    _bg = IWhost + _backgroundImage2;
            }
        }

        var bgUrl = "url(" + _bg + ")";
        if (!bgImageIsSet)
            bgUrl = '';

        jQuery.fn.corner = function (options) {
            var settings = {
                tl: { radius: 10 },
                tr: { radius: 10 },
                bl: { radius: 10 },
                br: { radius: 10 },
                backgroundImage2: bgUrl,
                antiAlias: true,
                autoPad: true,
                validTags: ["div"]
            };
            if (options && typeof (options) != 'string')
                jQuery.extend(settings, options);

            return this.each(function () {
                new curvyObject(settings, this).applyCorners();
                //new curvyCorners(settings, this ).applyCornersToAll();
            });
        };
    }

    $.fn.SetDefaultModalPopupStyle = function (width, height, backgroundColor, cssDialog, backgroundImage, corners) {
        var o = $(this);
        var bgImageIsSet = true;

        var ModalPopUpHeaderImage = "_Images/V3/layout_head/header_small_long_{0}.gif";

        if (typeof backgroundImage != 'undefined' && backgroundImage != null && backgroundImage != '') {
            if (backgroundImage.indexOf('/') == 0) {
                backgroundImage = backgroundImage.substring(1, backgroundImage.length);
            }
            ModalPopUpHeaderImage = backgroundImage;
            bgImageIsSet = backgroundImage != ' ';
        }

        if (typeof PopUpImageDomain != 'undefined' && PopUpImageDomain != null) {
            if (PopUpImageDomain.lastIndexOf("/") == PopUpImageDomain.length - 1) {
                ModalPopUpHeaderImage = PopUpImageDomain + ModalPopUpHeaderImage;
            }
            else {
                ModalPopUpHeaderImage = PopUpImageDomain + "/" + ModalPopUpHeaderImage;
            }
        }
        else {
            ModalPopUpHeaderImage = IWhost + ModalPopUpHeaderImage;
        }

        if (typeof mid != 'undefined' && mid != null && mid > 0) {
            ModalPopUpHeaderImage = ModalPopUpHeaderImage.replace("{0}", mid);
            _backgroundImageMID = ModalPopUpHeaderImage;
        }
        else ModalPopUpHeaderImage = ModalPopUpHeaderImage.replace("_{0}", "");

        var bgUrl = " url(" + ModalPopUpHeaderImage + ") no-repeat";
        if (!bgImageIsSet)
            bgUrl = '';

        // Corner Settings
        if (corners != false) {
            o.SetDefaultModalPopupCorners(ModalPopUpHeaderImage, mid, bgImageIsSet);
        }

        if (backgroundColor == undefined)
            backgroundColor = "#fff";
        if (width != undefined) $(o).css("width", width + "px");
        if (height != undefined) $(o).css("height", height + (height != "auto" ? "px" : ""));

        $(o).css({
            "margin": "0 0 1px -" + o.width() / 2 + "px",
            "color": "#000000",
            "background": backgroundColor + bgUrl,
            "border-right": "1px solid #000000",
            "vertical-align": "top",
            "display": "none",
            "table-layout": "fixed",
            "font-size": "11px"
        });

        if (cssDialog != undefined && cssDialog != null) {
            $(o).css(cssDialog);
        }
    }


    $.fn.setTransparent = function () {
        return this.each(function (e) {
            var div = $("<DIV />");
            // zu debugg-Zwecke: 
            // var div = $("<DIV border='solid 1px #f00;'/>");
            // zeigt alle umgewandelten PNG-Grafiken mit einem roten Rahmen an.
            for (var n in this.attributes) {
                if (this[n] != "" && this[n] != null) {
                    if (n.substr(0, 2) == "on") {
                        div.bind(n.substr(2), this[n]);
                    } else if (n != "src") {
                        div.attr(n, this[n]);
                    }
                }
            }

            div.attr("style", this.style.cssText);
            div.css({
                width: this.width + "px",
                height: this.height + "px",
                filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + this.src + "', sizingMethod='scale')"
            });

            if (this.align == "left") { div.css("float", "left"); }
            if (this.align == "right") { div.css("float", "right"); }
            if (this.parentNode.href) { div.css("cursor", "hand"); }
            this.parentNode.replaceChild(div[0], this);
            div.css({ visibility: "visible" });
        });
    }

    ///	<summary>
    ///	    Use to resize images for given maximum height and widht
    ///	</summary>
    ///	<param name="settings" type="String">
    ///		1: settings: collection of various settings
    ///        possible are:
    ///         - height
    ///         - width
    ///         - validTags
    ///        var settings = {
    ///             height: 200,
    ///             width: 300,
    ///             validTags: ["img"]
    ///        };
    ///	</param>
    ///	<autor>MHEI</autor>
    /// <datum>08.12.2008</datum>
    ///	<returns type="jQuery" />
    //    $.fn.ImageResize = function(options) {

    //        var settings = {
    //            height: 200,
    //            width: 300,
    //            validTags: ["img"]
    //        };
    //        if (options && typeof (options) != 'string')
    //            jQuery.extend(settings, options);

    //        return this.each(function() {
    //            var height = this.height;
    //            var width = this.width;
    //            var ratio = width / height;

    //            if (height >= settings.height && height >= width) {
    //                var factor = height / settings.height;
    //                width = width / factor;
    //                this.height = settings.height;
    //                this.width = width;
    //            } else if (width > settings.width && height < width) {
    //                var factor = width / settings.width;
    //                height = height / factor;
    //                this.width = settings.width;
    //                this.height = height;
    //            }
    //        });
    //    }

    $.fn.ImageResize = function (options) {

        var settings = {
            height: 200,
            width: 300,
            validTags: ["img"]
        };
        if (options && typeof (options) != 'string') {
            jQuery.extend(settings, options);
        }

        var img = null;
        if ($.browser.msie) {
            img = $(this);
        } else {
            img = $(this).get(0);
        }
        if (img == null || img == NaN)
            return;
        var height = 0;

        var width = 0;
        if ($.browser.msie) {
            height = img.height();
            width = img.width();
        } else {
            height = img.height;
            width = img.width;
        }
        var ratio = width / height;

        if (height >= settings.height && height >= width) {
            var factor = height / settings.height;
            width = width / factor;
            $(this).height(settings.height);
            $(this).width(width);
        } else if (width > settings.width && height < width) {
            var factor = width / settings.width;
            height = height / factor;
            $(this).width(settings.width);
            $(this).height(height);
        }

        $(this).show();

        return this;
    }

    ///	<summary>
    ///	    Use to set the Image to middle of container
    ///	</summary>
    ///	<param name="container" type="jQuery-Object">
    ///	</param>
    ///	<autor>MVO</autor>
    /// <datum>29.01.2009</datum>
    $.fn.MiddleImage = function (jContainer) {

        var image = this.get(0);

        if (jContainer != null && jContainer != NaN && image != null && image != NaN) {
            var containerHeight = parseInt(jContainer.css('height'));
            var imageHeight = parseInt(this.css('height'));
            var marginTop = (containerHeight - imageHeight) / 2;
            if (marginTop <= 0)
                return;

            image.style.marginTop = marginTop + 'px';
        }

        $(this).show();
    }

    //tooltip für html-container mit der ID "box_tooltip"
    $.fn.tooltip = function (html, options) {
        var defaults = {
            background: "#444",
            color: "#f1f1f1",
            padding: "5px 0px",
            opacity: 0.95,
            rounded: true
        }
        if ($.browser.msie) {
            defaults.opacity = 1;
        }

        var settings = $.extend({}, defaults, options);

        var showTooltip = function (text, top, left, width) {
            $('#box_tooltip').remove();
            $('<div id="box_tooltip" style="z-index: 3000;">' +
            '<div class="box_tooltip_start"></div>' +
            '<div class="box_tooltip_body"></div>' +
		    '<div class="box_tooltip_end"></div>' +
	        '</div>')
            .prependTo('body')
            .hide()
            .css({
                top: top + 5,
                left: left + width + 15
            });
            $('.box_tooltip_body').html(text);
            $("#box_tooltip").show();
        }

        var removeTooltip = function () {
            $('#box_tooltip').remove();
        }

        this.each(function () {
            var $this = $(this);
            var title = this.title;
            if ($this.attr('title') != '') {
                this.title = '';

                $this.hover(function (e) {
                    var offset = $this.offset();
                    showTooltip(title, e.pageY, e.pageX, 0);
                }, function () {
                    removeTooltip();
                });

                $this.mousemove(function (e) {
                    $('#box_tooltip').css({
                        top: e.pageY + 5,
                        left: e.pageX + 15
                    });
                });
            }
        });

        return this;
    }

    $.fn.enterHere = function (target) {
        $(this).attr('target', target);
        $(this).keydown(function (e) {
            e = e || window.event;
            var code = e.keyCode || e.which;
            if (code == 13) {
                var id = $(this).attr('target');
                if ($('#' + id).attr('onclick') != null && $('#' + id).attr('onclick') != '') {
                    $('#' + id).trigger('click');
                } else if ($('#' + id).attr('href') != null && $('#' + id).attr('href') != '') {
                    eval($('#' + id).attr('href'));
                } else {
                    __doPostBack(id, '');
                }
            }
        });
        return this;
    }

    $(window).resize(function () {
        marginLeft = $(window).width() / 2;

        if (resizeTimer) clearTimeout(resizeTimer);
        resizeTimer = setTimeout(function () { }, 100);

        if ($(window).height() < 600 || $(window).width() < 600) {
            $("#ModalContainer").css("position", "absolute");
        } else {
            $("#ModalContainer").css("position", "fixed");
        }
    });

    // Load Default Popup Style
    // Default Style beim Modalen PoPup wird dann nachfolgenden überschrieben
    if ($('#modalContent') != undefined && $('#modalContent') != null)
        $('#modalContent').SetDefaultModalPopupStyle(10, 10);

    Object.extend(IwAG.Base, {
        adjustHeight: function (body) {
            /// <summery>Passt die Höhe des <body>-Tags an eine neue Anzeige an</summary>
            body.height($(window).height()).height($(document).height());
        },

        LoadPagePartsIntoModalContentPanel: function (Pageurl, PageStringStartIndex, PageStringEndIndex, panel, width, height, top) {
            panel = (panel != undefined && panel != null ? panel : "#DataContentPopup");

            if ($.browser.msie && $.browser.version == "6.0") {
                w2 = window.open(Pageurl, 'Window2', 'scrollbars=yes,height=' + height + ', width=' + width + ', left=0, top=0, toolbar=no,menubar=no');
            }
            else {
                /********************************************* 
                * Methode zum Laden von html aus aspx Seiten in ein Modales Panel
                *
                * @param {string} Pageurl der Seite
                * @param {string} PageStringStartIndex
                * @param {string} PageStringEndIndex
                * @param {string} panel also html control das befüllt werden soll
                (damit das Modale Popup auch richtige größe hat sind folgende paramter notwendig)
                diese sollten über den link im Modalen Popup gesetzt werden so z.b url?width=100&height=100&top=10%
                * @param {string} [optional] width 
                * @param {string} [optional] height
                * @param {string} [optional] top
                *
                * Bsp:
                *   $("#lnkOpen").click(function(e){
                *       IwAG.Base.LoadPagePartsIntoModalContentPanel(
                *           "~/MeineImmowelt/Seite.aspx?type=2",
                *           "<!--Modal Start-->",
                *           "<!--Modal Ende-->",
                *           "#DataContentPopup");
                *       ); 
                *   });
                *
                *********************************************/
                // LoadPagePartsIntoPanel
                IwAG.Base.LoadPagePartsIntoPanel(
                   Pageurl,
                    (PageStringStartIndex != undefined && PageStringStartIndex != null ? PageStringStartIndex : "<!--Modal Start-->"),
                    (PageStringEndIndex != undefined && PageStringEndIndex != null ? PageStringEndIndex : "<!--Modal Ende-->"),
                    panel,
                    width,
                    height,
                    top
                );
                //                 var parentEls = ("."+$(panel).parents("div")
                //                            .map(function () { 
                //                                if(this.className.length > 0)
                //                                    return this.className; 
                //                              })
                //                            .get().join(" .")).split(" ").reverse().join(" ");


                $('#modalContent').SetDefaultModalPopupFunctions(
                                                                ModalDialogonOpenFunction != null ? ModalDialogonOpenFunction : null,
                                                                ModalDialogonShowFunction != null ? ModalDialogonShowFunction : null,
                                                                ModalDialogOnCloseFunction != null ? ModalDialogOnCloseFunction : null
                                                                );
                $('#modalContent').SetDefaultModalPopupStyle(width, height);

                // Statistik auswertungen
                $(panel).after("<iframe id='_statsCounter' src='" + Pageurl + "' style='display:none;' />");

                // Default ModalPopup
                IwAG.Base.showModalDialog(
                    "#modalContent",
                    "#lbtnCloseModal",
                    "#img2",
                    null,
                    null,
                    true
                );
            }
        },

        LoadPagePartsIntoPanel: function (Pageurl, PageStringStartIndex, PageStringEndIndex, panel, width, height, top, RefreshContentInside) {
            $(panel).html("");
            var refreshContentInside = typeof RefreshContentInside != 'undefined' && RefreshContentInside != null ? RefreshContentInside : true;

            /********************************************* 
            * Methode zum Laden von html aus aspx Seiten in ein html Control
            *
            * @param {string} Pageurl der Seite
            * @param {string} PageStringStartIndex
            * @param {string} PageStringEndIndex
            * @param {string} panel also html control das befüllt werden soll
            (damit das Modale Popup auch richtige größe hat sind folgende paramter notwendig)
            diese sollten über den link im Modalen Popup gesetzt werden so z.b url?width=100&height=100&top=10%
            * @param {string} [optional] width 
            * @param {string} [optional] height
            * @param {string} [optional] top
            * @param {bool}   [optional] RefreshContentInside
            *
            * Bsp:
            *   $("#lnkOpen").click(function(e){
            *       IwAG.Base.LoadPagePartsIntoPanel(
            *           "~/MeineImmowelt/Seite.aspx?type=2",
            *           "<!--Modal Start-->",
            *           "<!--Modal Ende-->",
            *           "#DataContentPopup");
            *       ); 
            *   });
            *
            *********************************************/
            $.post(Pageurl, function (data) {
                // Für das Modale Popup
                if (width != undefined && height != undefined && top != undefined) {
                    $("#modalContent").height(height + "px");
                    $("#modalContent").width(width + "px");
                    $("#ModalContainer").css("top", top);
                    $(panel).height(height - 50 + "px");
                    $(panel).width(width - 20 + "px");
                    $(panel).css("overflow", "hidden");
                }

                var start = data.indexOf(PageStringStartIndex);
                var ende = data.indexOf(PageStringEndIndex);

                // Zurück Button für das Modale Popup
                var back = "";
                if (backButton != null && backButton.length < ModalBackButtonCounter + 1)
                    backButton[ModalBackButtonCounter] = "<div id='pModalBack'><a href=\"javascript:ModalBackButtonCounter--;IwAG.Base.LoadPagePartsIntoPanel('" + Pageurl + "','" + PageStringStartIndex + "' ,'" + PageStringEndIndex + "','" + panel + "','" + width + "',' " + height + "', '" + top + "');\"  style=\"float:left;color:Black;text-decoration:none;\" onMouseover=\"this.style.color='#FF6600'\" onMouseout=\"this.style.color='#000'\">&lt;&lt; <b>zur&uuml;ck</b> &gt;&gt;</a></div>";

                //var closeButton = "<a href='#' id='lbtnCloseModal' class='modClose'>schlie&szlig;en<img id='img2' src='http://www.immowelt.de/_Images/V3/icons/icon_close.gif' border='0' alt='' /></a><br /><br /><br />"

                if (ModalBackButtonCounter == 0) back = "";
                else back = backButton[ModalBackButtonCounter - 1];

                $(panel).html("<div style='overflow:auto;height:" + (height - 60) + "px;'>" + data.substring(start, ende) + "</div>");
                $('#pModalBack').remove();
                if (back != "") $(panel).before(back);

                $(panel + " a").each(function (e) {
                    var href = $(this).attr("href");
                    if (refreshContentInside && href != undefined && href.indexOf("javascript:") == -1 && href.length > 5 && href.toLowerCase().indexOf(".pdf") == -1) {
                        $(this).click(function () {
                            ModalBackButtonCounter++;
                            //alert(href);

                            $("#_statsCounter").attr("src", href);
                            if ($.hasURLParam(href, "width") &&
                                    $.hasURLParam(href, "height") &&
                                    $.hasURLParam(href, "top")) {
                                IwAG.Base.LoadPagePartsIntoPanel(
                                        href,
                                        PageStringStartIndex,
                                        PageStringEndIndex,
                                        panel,
                                        $.getURLParam(href, "width"),
                                        $.getURLParam(href, "height"),
                                        $.getURLParam(href, "top"),
                                        RefreshContentInside);
                            }
                            else {
                                IwAG.Base.LoadPagePartsIntoPanel(
                                        href,
                                        PageStringStartIndex,
                                        PageStringEndIndex,
                                        panel,
                                        width,
                                        height,
                                        top,
                                        RefreshContentInside);
                            }

                            return false;

                        });
                    }
                    else $("#_statsCounter").attr("src", Pageurl);
                })
            });
        },

        showModalDialog: function (dialog, closeBtn, closeIcon, cssDialog, cssOverlay, roundedCorners) {
            /********************************************* 
            * Methode zum Öffnen eines modalen Fensters
            *
            * @param {string} ID des modalen Fensters
            * @param {string} ID des close-Links
            * @param {string} ID des close-Icons
            * @param {array} [optional] css-Parameterliste des Dialogfensters
            * @param {array} [optional] css-Parameterliste des Overlays
            *
            * Bsp:
            *   $("#lnkOpen").click(function(e){
            *       IwAG.Base.showModalDialog(
            *           ".ModalContainer",
            *           "#lnkClose",
            *           "#imgClose", 
            *           {   background : "#fff", 
            *               border : "1px solid #666", 
            *               height : "auto", 
            *               width : "590px", 
            *               left : "50%", 
            *               top : "15%", 
            *               margin : "0 0 0 -295px" }, 
            *           {   background : "#000",
            *               opacity : "0.7", 
            *               cursor : "auto" }
            *       ); 
            *   });
            *
            *********************************************/
            globalDialog = dialog;

            if (roundedCorners != undefined && roundedCorners) {
                if (!(dialog == "#geoPopup" && $.browser.msie && $.browser.version == "6.0")) //blöder IE6 und Slide-Effekt!!!
                {
                    $(dialog).corner();
                }
            }

            if ($.browser.msie && $.browser.version == "6.0") {

                if (cssDialog != undefined) {
                    $("#ModalContainer").css(cssDialog);
                }

                $(dialog).modal({
                    appendTo: '#aspnetForm',
                    overlayId: 'ModalOverlay',
                    containerId: 'ModalContainer',
                    onOpen: ModalDialogonOpenFunction != null ? function () { eval(ModalDialogonOpenFunction) } : null,
                    onShow: function () { IwAG.Base.SetModalFocus(closeBtn); ModalDialogonShowFunction != null ? eval(ModalDialogonShowFunction) : null; },
                    onClose: ModalDialogOnCloseFunction != null ? function () { eval(ModalDialogOnCloseFunction) } : null
                });

                $("select:visible").addClass("hiddenByModal").hide();
                $('object').hide();
                $(dialog + " select").show();
                $('#ModalOverlay').css("height", $(document).height() + "px");
                $('#ModalOverlay').css("width", $(document).width() + "px");
                $('#ModalOverlay').css("background", "#000");

                // Fix für verschobene Darstellung
                $('#ModalContainer').css('witdh', $(dialog).width() + 'px');
                $(dialog).css({ marginLeft: "0px" });
            }
            else {
                $('object').hide();
                $(dialog).modal({
                    appendTo: '#aspnetForm',
                    close: true,
                    overlayId: 'ModalOverlay',
                    containerId: 'ModalContainer',
                    persist: true,
                    onOpen: ModalDialogonOpenFunction != null ? function () { eval(ModalDialogonOpenFunction) } : null,
                    onShow: function () { IwAG.Base.SetModalFocus(closeBtn); ModalDialogonShowFunction != null ? eval(ModalDialogonShowFunction) : null; },
                    onClose: ModalDialogOnCloseFunction != null ? function () { eval(ModalDialogOnCloseFunction) } : null
                });

                if (cssOverlay != undefined) {
                    $('#ModalOverlay').css(cssOverlay);
                } else {
                    $('#ModalOverlay').css({ background: '#000', opacity: '0.7', cursor: 'auto' });
                }

                if (cssDialog != undefined) {
                    $(dialog).css(cssDialog);
                }

                if ($(window).height() < 600 || $(window).width() < 600) {
                    window.scrollTo(0, 0);
                    var offset = $(dialog).attr("offsetTop");

                    if ($(window).height() > $(dialog).height()) {
                        marginTop = ($(window).height() - $(dialog).height()) / 2;
                    } else {
                        marginTop = 10;
                    }
                    marginLeft = $(window).width() / 2;

                    $('#ModalContainer').css('position', 'absolute');
                    $('#ModalContainer').css('top', $(window).scrollTop() + marginTop - offset + 'px');
                    $('#ModalContainer').css('left', $(window).scrollLeft() + marginLeft + 'px');

                } else {
                    $('#ModalContainer').css('left', '50%');
                    $('#ModalContainer').css('top', '30%');
                }
            }

            if (closeBtn != undefined && closeBtn != null) {
                $(closeBtn).click(function (e) {
                    IwAG.Base.CloseModalDialog(closeBtn, closeIcon, dialog, roundedCorners);
                    return false;
                });
            }

            if (closeIcon != undefined && closeIcon != null) {
                $(closeIcon).click(function (e) {
                    IwAG.Base.CloseModalDialog(closeBtn, closeIcon, dialog, roundedCorners);
                    return false;
                });
            }

            // Added by AME Jetzt is es auch möglich ausserhalb des Popups dieses zu schließen!!!
            // Optimized by AME Jetzt können Bitte warten Modal Dialoge gestartet werden, mit der folgenden Bedingung:
            if (closeIcon != undefined && closeIcon != null && closeBtn != undefined && closeBtn != null) {
                $("#ModalOverlay").click(function (e) {
                    $(closeIcon).click();
                });
            }
        },
        SetModalFocus: function (element) {
            $(element).focus();
        },
        CloseModalDialog: function (closeBtn, closeIcon, dialog, roundedCorners) {
            if ($.browser.msie && $.browser.version == "6.0")
                $('select:hidden.hiddenByModal').removeClass("hiddenByModal").show();
            $('object').show();
            ModalBackButtonCounter = 0;
            backButton = new Array();
            if ($("#_statsCounter")) $("#_statsCounter").remove();
            if ($(dialog).length > 0) {
                while ($(dialog).get(0).style.display != 'none') {
                    $.modal.close();
                }
            } else {
                $.modal.close();
            }

            if (closeBtn !== undefined && closeBtn !== null) {
                $(closeBtn).unbind('click');
            }
            if (closeIcon !== undefined && closeIcon !== null) {
                $(closeIcon).unbind('click');
            }
            $("#ModalOverlay").unbind('click');
            if (roundedCorners !== undefined && roundedCorners !== null && roundedCorners && dialog !== undefined && dialog !== null) {
                $(dialog + '.simplemodal-data').children("div[class!='autoPadDiv'][class!='iwag']").remove();
            }
        },
        initOverlayMessageBox: function (initButton, container) {
            /********************************************* 
            * Methode zum Öffnen eines Overlay-Div-Containers
            *
            * @param {string} initButton - Selector, der das Overlay öffnen soll
            * @param {string} container - Selector des Overlays 
            *
            *********************************************/
            $(initButton).bind("click", function () {
                if ($(container).is(":hidden")) {
                    $(container).show();
                    $(document).one("click", function () {
                        $(container).hide();
                    });
                } else {
                    $(container).hide();
                }
                return false;
            });
        },

        parseACData: function (data) {
            var parsed = [];
            if (typeof data != 'undefined' && data != null && data.d != '') {
                var rows = jQuery.parseJSON(data.d);
                if (rows != null) {
                    for (var i = 0; i < rows.length; i++) {
                        var row = rows[i];
                        if (row) {
                            parsed[parsed.length] = {
                                data: row,
                                value: row.id,
                                result: row.suggest + " " + row.annotation
                            };
                        }
                    }
                }
            }
            return parsed;
        },

        autoCompleteForLocation: function (inputBox, servicePath, listHeight, listWidth, autoSubmit, postBack, addParams, autoFill) {
            /********************************************* 
            * Methode zum Aktivieren der AutoComplete-Fkt.
            *
            * @param {string} inputBox      - Selector, an den die Liste gebunden wird
            * @param {string} servicePath   - Pfad zur Seite, die die List-Einträge enthält
            * @param {int} listHeight       - Höhe der einzublendenden Liste
            * @param {int} listWidth        - Breite der einzublendenden Liste
            * @param {bool} autoSubmit      - wenn "true", wird bei <ENTER> ein Postback ausgeführt
            * @param {string} postBack      - Postback-Ziel
            * @param {string} addParams     - Additional Parameter (JSON)
            *
            * Dokumetation unter: http://docs.jquery.com/Plugins/Autocomplete
            *
            *********************************************/

            if (listHeight == undefined)
                listHeight = 300;
            if (listWidth == undefined)
                listWidth = 200;

            if (typeof servicePath != 'undefined' && servicePath != '') {
                var extraParams = {};

                if (typeof addParams != 'undefined' && addParams != undefined) {
                    $.each(addParams, function (key, param) {
                        extraParams[key] = typeof param == "function" ? param() : param;
                    });
                }

                if (extraParams.GeoID == undefined || extraParams.GeoID == null) {
                    extraParams = $.extend(extraParams, { GeoID: '108' });
                }
                if (extraParams.ValidOnly == undefined || extraParams.ValidOnly == null) {
                    extraParams = $.extend(extraParams, { ValidOnly: false });
                }
                if (extraParams.PLZ == undefined || extraParams.PLZ == null) {
                    extraParams = $.extend(extraParams, { PLZ: null });
                }

                $(inputBox).autocomplete(servicePath, {
                    width: listWidth,
                    max: 150,
                    highlight: false,
                    scroll: true,
                    highlight: false,
                    selectFirst: autoFill,
                    autoFill: autoFill,
                    scrollHeight: listHeight,
                    cacheLength: 0,
                    delay: 100,
                    multiple: false,
                    requestType: "POST",
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    extraParams: extraParams,
                    parse: function (data) { return IwAG.Base.parseACData(data); },
                    formatItem: function (row) { return row.suggest + " " + row.annotation; },
                    formatResult: function (row) { return row.suggest + " " + row.annotation; }
                });

                $(inputBox).result(function (event, data, formatted) {
                    var hidden = $(this).parent().find(">:hidden");
                    if (data != undefined && data != null) {
                        hidden.val(data.id);
                    }

                });

                if (autoSubmit == true && postBack != undefined) {
                    $(inputBox).result(function (e) {
                        e = e || window.event;
                        var code = e.keyCode || e.which;
                        if (code == 13) {
                            eval(postBack);
                        }
                        return true;
                    });

                    $(inputBox).keydown(function (e) {
                        e = e || window.event;
                        var code = e.keyCode || e.which;
                        if (code == 13) {
                            $(inputBox).hideautocomplete();
                            eval(postBack);
                        }
                        return true;
                    });
                }
            }

            return true;
        },
        serialize: function (o) {

            var m = {  // A character conversion map
                '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f',
                '\r': '\\r', '"': '\\"', '\\': '\\\\'
            },
                s = { // Map type names to functions for serializing those types
                    'boolean': function (x) { return String(x); },
                    'null': function (x) { return "null"; },
                    number: function (x) { return isFinite(x) ? String(x) : 'null'; },
                    string: function (x) {
                        if (/["\\\x00-\x1f]/.test(x)) {
                            x = x.replace(/([\x00-\x1f\\"])/g, function (a, b) {
                                var c = m[b];
                                if (c) {
                                    return c;
                                }
                                c = b.charCodeAt();
                                return '\\u00' +
                                    Math.floor(c / 16).toString(16) +
                                    (c % 16).toString(16);
                            });
                        }
                        return '"' + x + '"';
                    },
                    array: function (x) {
                        var a = ['['], b, f, i, l = x.length, v;
                        for (i = 0; i < l; i += 1) {
                            v = x[i];
                            f = s[typeof v];
                            if (f) {
                                v = f(v);
                                if (typeof v == 'string') {
                                    if (b) {
                                        a[a.length] = ',';
                                    }
                                    a[a.length] = v;
                                    b = true;
                                }
                            }
                        }
                        a[a.length] = ']';
                        return a.join('');
                    },
                    object: function (x) {
                        if (x) {
                            if (x instanceof Array) {
                                return s.array(x);
                            }
                            var a = ['{'], b, f, i, v;
                            for (i in x) {
                                v = x[i];
                                f = s[typeof v];
                                if (f) {
                                    v = f(v);
                                    if (typeof v == 'string') {
                                        if (b) {
                                            a[a.length] = ',';
                                        }
                                        a.push(s.string(i), ':', v);
                                        b = true;
                                    }
                                }
                            }
                            a[a.length] = '}';
                            return a.join('');
                        }
                        return 'null';
                    }
                };

            return s.object(o);
        },
        setAccordion: function (expandedIndex, iconExpand, iconCollapse) {
            /********************************************* 
            * Methode zum Aktivieren der Accordion-Fkt.
            * bei Verwendung muss "jquery.ddaccordion.js" implementiert werden
            *
            * @param {string} expandedIndex      - Header-Index, welcher Contentbereich initial dargestellt werden soll
            *
            * Dokumetation unter: http://www.dynamicdrive.com/dynamicindex17/ddaccordion.htm?technology=0,1,2
            *
            *********************************************/
            ddaccordion.init({
                headerclass: 'accordionhead',
                contentclass: 'accordionContent',
                revealtype: 'click',
                collapseprev: true,
                defaultexpanded: [expandedIndex],
                onemustopen: true,
                animatedefault: false,
                persiststate: true,
                toggleclass: ['', ''],
                togglehtml: ['suffix', iconExpand, iconCollapse],
                animatespeed: 'fast',
                oninit: function (headers, expandedindices) { },
                onopenclose: function (header, index, state, isuseractivated) { }
            });
            return false;
        }

    }, true);

    Object.extend(String, {

        Format: function () {
            /// <summary>Methode zur String-Formatierung analog zu C#</summary>
            /// <param name="argument[0]">Der zu formatierende String</param>
            /// <param name="argument[1...n]">Liste Argumenten, die im String ersetzt werden sollen</param>
            var s = arguments[0];
            for (var i = 0; i < arguments.length - 1; i++) {
                var reg = new RegExp("\\{" + i + "\\}", "gm");
                s = s.replace(reg, arguments[i + 1]);
            }
            return s;
        }
    });
});

/// <summary>
/// removeURLParam
/// Funktion zum Entfernen bestimmter Parameter aus dem Url-Querystring
/// </summary>
/// <returns type='string'>Url QueryString</returns>
/// <param name='strHref'>Url QueryString</param>
/// <param name='strParamName'>zu entfernender Parameter</param>
/// <autor>TBA</autor>
/// <datum>13.08.2009</datum>
function removeURLParam(strHref, strParamName) {
    var strReturn = '';
    if (strHref.indexOf('?') > -1) {
        var strQueryString = strHref.substr(strHref.indexOf('?'));

        if (strQueryString.indexOf('#&&') > -1) {
            // Url-Anhänge für den Scriptmanager zum Managen der History werden entfernt
            strQueryString = strQueryString.replace(strQueryString.slice(strQueryString.indexOf('#&&'), strQueryString.indexOf('==') + 2), '');
        }

        var aQueryString = strQueryString.split('&');
        var aNewQuery = new Array();
        for (var iParam = 0; iParam < aQueryString.length; iParam++) {
            if (aQueryString[iParam].toLowerCase().indexOf(strParamName.toLowerCase() + '=') < 0) {
                aNewQuery.push(aQueryString[iParam]);
            }
        }
        strReturn = aNewQuery.join('&');
        if (strReturn.indexOf('?') < 0) {
            strReturn = '?' + strReturn;
        }
    }
    return strReturn;
}

function ResizeODW(settings, img, div) {
    $(img).css({ visibility: 'hidden' })
          .removeAttr('height')
          .removeAttr('width')
          .show()
          .ImageResize(settings);
    $(div).width(settings.width)
          .height(settings.height + 3); 
    if ($(img).height() > settings.height) {
        settings.width = (settings.height / $(img).height()) * settings.width;
        $(img).ImageResize(settings);
    } else if ($(img).width() > settings.width) {
        settings.height = (settings.width / $(img).width()) * settings.height;
        $(img).ImageResize(settings);
    }
    $(img).css({
        marginTop: (settings.height - $(img).height()) / 2 + 'px',
        visibility: 'visible'
    });
}

// *******************************************************************
// HACK: Bug im FF, beim Zoomen in die Karte scrollt die Seite mit...
// *******************************************************************
function hookEvent(element, eventName, callback) {
    if (typeof (element) == "string")
        element = document.getElementById(element);
    if (element == null)
        return;
    if (element.addEventListener) {
        if (eventName == 'mousewheel')
            element.addEventListener('DOMMouseScroll', callback, false);
        element.addEventListener(eventName, callback, false);
    }
    else if (element.attachEvent)
        element.attachEvent("on" + eventName, callback);
}

function unhookEvent(element, eventName, callback) {
    if (typeof (element) == "string")
        element = document.getElementById(element);
    if (element == null)
        return;
    if (element.removeEventListener) {
        if (eventName == 'mousewheel')
            element.removeEventListener('DOMMouseScroll', callback, false);
        element.removeEventListener(eventName, callback, false);
    }
    else if (element.detachEvent)
        element.detachEvent("on" + eventName, callback);
}

function cancelEvent(e) {
    e = e ? e : window.event;
    if (e.stopPropagation)
        e.stopPropagation();
    if (e.preventDefault)
        e.preventDefault();
    e.cancelBubble = true;
    e.cancel = true;
    e.returnValue = false;
    return false;
}
