﻿var $j = jQuery.noConflict();

// Detecting browser version.
// [MB]
var isFF = (navigator.userAgent.indexOf("Firefox") > 0);
var isChrome = (navigator.userAgent.indexOf("Chrome") > 0);
var isIE6 = false;
var isIE7 = false;
var isIE8 = false;

// Matching MSIE string for IE version detection.
// [MB]
if (!isFF && !isChrome) {
    if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
        var ieversion = new Number(RegExp.$1)
        if (ieversion >= 8) {
            isIE7 = true; // Use IE7 behavior for IE8 [MB]
            isIE8 = true;
        }
        else if (ieversion >= 7) {
            isIE7 = true;
        }
        else if (ieversion >= 6) {
            isIE6 = true;
        }
    }
}

var isIE = isIE6 || isIE7 || isIE8;

function SetById(controlId, value) {
    var controls = $j("#" + controlId);

    if (controls.length > 0)
        controls.get(0).value = value;
}

function Uncheck(checkBoxKey) {
    var cb = $j("#" + GetControlId(checkBoxKey)).get(0);

    if (cb)
        cb.src = "/Images/CheckboxUnchecked.png";
}

function Check(checkBoxKey) {
    var cb = $j("#" + GetControlId(checkBoxKey)).get(0);

    if (cb)
        cb.src = "/Images/CheckboxChecked.png";
}

function IsChecked(checkBoxKey) {
    var cb = $j("#" + GetControlId(checkBoxKey)).get(0);

    if (cb) {
        var matched = cb.src.match(/CheckboxChecked/);

        if (matched)
            return true;
    }

    return false;
}

function Toggle(controlIdToShow, controlIdToHide, controlToMark, controlToUnmark) {
    $j("#" + controlIdToShow).css("display", "block");
    $j("#" + controlIdToHide).css("display", "none");

    if (controlToMark)
        $j("#" + controlToMark).addClass("TextWithBlueArrowKeepHovered");
        
    if (controlToUnmark)
        $j("#" + controlToUnmark).removeClass("TextWithBlueArrowKeepHovered");

    RebindLinkHovers();
}

function FindParentOrSelfWrapped(e, className) {
    var foundElement = null;

    if (e) {
        if (e.srcElement)
            foundElement = FindParentOrSelfByClassName(e.srcElement, className);

        if (isFF || isChrome) {
            if (!foundElement && e.currentTarget) {
                foundElement = FindParentOrSelfByClassName(e.currentTarget, className);
            }

            if (!foundElement && e.originalTarget) {
                foundElement = FindParentOrSelfByClassName(e.originalTarget, className);
            }

            if (!foundElement && e.relatedTarget) {
                foundElement = FindParentOrSelfByClassName(e.relatedTarget, className);
            }
        }
    }

    return foundElement;
}

function GetBrowserSpecificTarget(e) {
    if (e) {
        return (isFF || isChrome) ? e.currentTarget : e.srcElement;
    }

    return null;
}

function FindParentOrSelfByClassName(currentItem, className) {
    var cnRegExp = new RegExp(className);

    while (currentItem) {
        if (cnRegExp.test(currentItem.className)) {
            return currentItem;
        }

        currentItem = currentItem.offsetParent;
    }

    return null;
}

function SwitchToDetailsTab(number, clickedControl) {
    $j(".DetailsTab").each(function(idx, e) {
        if (idx != (number - 1))
            $j(e).css("display", "none");
    });

    $j(".DetailsTabControl").each(function(idx, e) {
        $j(e).removeClass("TextWithBlueArrowKeepHovered");
    });

    $j("#DetailsTab" + number).css("display", "block");
//    $j(clickedControl).removeClass("TextWithGrayArrow");
    $j(clickedControl).addClass("TextWithBlueArrowKeepHovered");
}

function CompareValues(val1, val2) {
    if (val1 > val2)
        return 1;
    if (val1 < val2)
        return -1;

    return 0;
}

var controls = {};
function RegisterControlId(key, clientId) {
    controls[key] = clientId;
}

function GetControlId(key) {
    return controls[key];
}

function GetControlKeyByClientId(clientId) {
    while (clientId.search(/\$/) != -1) {
        clientId = clientId.replace(/\$/, "_");
    }

    for (var controlKey in controls) {
        if (controls[controlKey] == clientId)
            return controlKey;
    }
}

function CreateGermanPrice(number) {
    var numberString = number + "";

    var run = 1;
    var output = "";
    for (var charNum = numberString.length - 1; charNum >= 0; charNum--) {
        output = numberString.substr(charNum, 1) + output;

        if (run == 3 && (charNum > 0)) {
            run = 0;
            output = "." + output;
        }
        
        run++;
    }

    return output;
}

function ClearDropdownList(dropdownList, skipDefaultOption) {
    if (dropdownList) {
        while (dropdownList.firstChild) {
            dropdownList.removeChild(dropdownList.firstChild);
        }
    }

    if (!skipDefaultOption)
        AddDropdownOption(dropdownList, "", "Alle anzeigen");
}

function AddDropdownOption(dropdownList, key, value, selected) {
    if (dropdownList) {
        var elOptNew = document.createElement('option');
        elOptNew.text = value;
        elOptNew.value = key;
        dropdownList.options[dropdownList.options.length] = elOptNew;

        if (selected)
            dropdownList.selectedIndex = (dropdownList.options.length - 1);
    }
}

function ToggleLoginBox() {
    ToggleSideBox('LoginBox', 200, _ToggleLoginBoxClosed);
}

function ToggleSideBox(boxId, targetHeight, callback) {
    var targetBox = $j("#" + boxId);

    if (targetBox && (targetBox.length > 0)) {
        if (targetBox.css("display") != "block") {
            targetBox.css("height", "0px");
            targetBox.css("display", "block");
            
            targetBox.stop().animate({ height: targetHeight }, 500);
        }
        else {
            targetBox.stop().animate({ height: 0 }, 500, callback);
        }
    }
}

function _ToggleLoginBoxClosed() {
    var targetBox = $j("#LoginBox");
    
    if (targetBox) {
        $j(targetBox).css("display", "none");
    }
}

function ValidatePW() {
    var field1 = $j("#" + GetControlId("TbNewPassword"));
    var field2 = $j("#" + GetControlId("TbNewPasswordConfirm"));
    var okIndicator = $j("#" + GetControlId("ConfirmationField"));

    if ((field1.length > 0) && (field2.length > 0) && (okIndicator.length > 0)) {
        okIndicator.css("display", ((field1.get(0).value) && (field1.get(0).value == field2.get(0).value)) ? "block" : "none");
    }
}

function PostTo(path) {
    $get("HfRedirectHack").value = path;
    __doPostBack();
}

function LoginEnterKey(e) {
    if (e && (e.keyCode == 13)) {
        e.stopPropagation();
        e.preventDefault();

        var loginButton = $get(GetControlId("IbLogin"));
        loginButton.click();
    }
}

function GetCurrentRssFeed()
{
    return GetCurrentURL() + "/Search/RESTService.svc/SearchRSS/" + $get("SbFragments").value;
}

function OpenPopupType(key, parameter) {
    switch (key)
    {
        case "PrivacyPolicy":
            OpenPopup(GetCurrentURL() + "/ContentPopup/PrivacyPolicy.aspx", key);
            break;
        case "RssFeed":
            OpenPopup(GetCurrentRssFeed(), key);
            break;
        case "CustomRssFeed":
            OpenPopup(GetCurrentURL() + "/Search/RESTService.svc/SearchRSS/" + parameter, key);
            break;
//        case "Budget":
//            OpenPopup("http://rechner.sparkasse.de/templates/tr51/allgemein1/tr51.php?c_nominalzins=4.50", key, 630, 700);
//            break;
        case "PrintLayout":
            // alert("Nach der Bestätigung dieser Meldung wird die Druckansicht für Sie erstellt. Da hierfür Live-Daten abgerufen werden, kann es bis zu 30 Sekunden dauern, bis das Fenster vollständig geöffnet ist.");
            OpenPopup(GetCurrentURL() + "/Search/ExposePrintLayout.aspx?id=" + requestHelper.GetCurrentRealtyId(), key, 680, 835);
            break;
    }
}

function OpenPopup(address, key, overrideWidth, overrideHeight) {
    var height = 600;
    var width = 790;

    if (overrideWidth)
        width = overrideWidth;
    if (overrideHeight)
        height = overrideHeight;

    window.open(address, key, "dependent=no,height=" + height + ",left=0,location=no,menubar=no,resizeable=yes,screenX=0,screenY=0,scrollbars=yes,status=no,toolbar=no,top=0,width=" + width);
}

function GetControlContextIndependent(controlId) {
    if (controlId) {    
        var foundControl = $j("#" + controlId);

        // First search the control in the current window.
        // [MB]
        if (!foundControl || (foundControl.length == 0))
            foundControl = $j("#" + controlId, top.window.document);

        if (!foundControl || (foundControl.length == 0))
            foundControl = $j("#" + top.GetControlId(controlId), top.window.document);

        // If we coudn't find the control, try to search for it inside of the iframe.
        // [MB]
        if ((!foundControl || (foundControl.length == 0)) && window.frames.DetailsIframe) {
            foundControl = $j("#" + controlId, window.frames.DetailsIframe.document);
        }

        if ((!foundControl || (foundControl.length == 0)) && window.frames.DetailsIframe && window.frames.DetailsIframe.GetControlId) {
            var controlKeyInIframe = window.frames.DetailsIframe.GetControlId(controlId);
            foundControl = $j("#" + controlKeyInIframe, window.frames.DetailsIframe.document);
        }
        
        // Workaround for Firefox.
        // [MB]
        if ((!foundControl || (foundControl.length == 0)) && window.frames[0]) {
            foundControl = $j("#" + controlId, window.frames[0].document);
        }

        if ((!foundControl || (foundControl.length == 0)) && window.frames[0] && window.frames[0].GetControlId) {
            var controlKeyInIframe = window.frames[0].GetControlId(controlId);
            foundControl = $j("#" + controlKeyInIframe, window.frames[0].document);
        }

        if (foundControl && (foundControl.length > 0)) {
            return foundControl.get(0);
        }
    }

    return null;
}

function RebindLinkHovers() {
    $j(".TextWithGrayArrow").mouseover(function(e) {
        $j(this).addClass("TextWithBlueArrow");
    });
    $j(".TextWithGrayArrowToLeft").mouseover(function(e) {
        $j(this).addClass("TextWithBlueArrowToLeft");
    });
    $j(".TextWithGrayArrow").mouseout(function(e) {
        $j(this).removeClass("TextWithBlueArrow");
    });
    $j(".TextWithGrayArrowToLeft").mouseout(function(e) {
        $j(this).removeClass("TextWithBlueArrowToLeft");
    });
}

$j(document).ready(function() {
    $j(".TextWithGrayArrow").mouseover(function(e) {
        $j(this).addClass("TextWithBlueArrow");
    });
    $j(".TextWithGrayArrowToLeft").mouseover(function(e) {
        $j(this).addClass("TextWithBlueArrowToLeft");
    });
    $j(".TextWithGrayArrow").mouseout(function(e) {
        $j(this).removeClass("TextWithBlueArrow");
    });
    $j(".TextWithGrayArrowToLeft").mouseout(function(e) {
        $j(this).removeClass("TextWithBlueArrowToLeft");
    });
    $j(".LeftArrowImg").mouseover(function(e) {
        $j(this).attr("src", $j(this).attr("src").replace(/Gray/, "Blue"));
    });
    $j(".LeftArrowImg").mouseout(function(e) {
        $j(this).attr("src", $j(this).attr("src").replace(/Blue/, "Gray"));
    });
    $j(".RightArrowImg").mouseover(function(e) {
        $j(this).attr("src", $j(this).attr("src").replace(/Gray/, "Blue"));
    });
    $j(".RightArrowImg").mouseout(function(e) {
        $j(this).attr("src", $j(this).attr("src").replace(/Blue/, "Gray"));
    });

    $j("#" + GetControlId("TbUsername")).keyup(function(e) {
        LoginEnterKey(e);
    });
    $j("#" + GetControlId("TbPassword")).keyup(function(e) {
        LoginEnterKey(e);
    });

    $j(".SearchRequestItem").mouseover(function(e) {
        $j(this).css("background-color", "#F4F2F3");
    });
    $j(".SearchRequestItem").mouseout(function(e) {
        $j(this).css("background-color", "");
    });

    $j(".UpdateOnEnterFieldStart").keydown(function(e) {
        HandleEnterFieldKey(e, "Start");
    });
    $j(".UpdateOnEnterFieldEnd").keydown(function(e) {
        HandleEnterFieldKey(e, "End");
    });
});

function HandleEnterFieldKey(e, type) {
    if ((e.keyCode == 13) || (e.keyCode == 9)) {
        if (e.keyCode == 13)
            e.preventDefault();

        if (isIE) {
            if (type == "Start") {
                filterHelper.UpdateStartValue(e.srcElement, tbToSliderRelation[e.srcElement.id]);
            }
            else if (type == "End") {
                filterHelper.UpdateEndValue(e.srcElement, tbToSliderRelation[e.srcElement.id]);
            }
        }
        else {
            // Dirty hack: Firefox fires button click events otherwise.
            // [MB]
            window.setTimeout("TriggerFirefoxDelayedUpdate('" + e.originalTarget.id + "', '" + type + "');", 100)
        }
    }
}

function TriggerFirefoxDelayedUpdate(srcId, type) {
    if (srcId) {
        if (type == "Start") {
            filterHelper.UpdateStartValue($j("#" + srcId).get(0), tbToSliderRelation[srcId]);
        }
        else if (type == "End") {
            filterHelper.UpdateEndValue($j("#" + srcId).get(0), tbToSliderRelation[srcId]);
        }
    }
}

var tbToSliderRelation = {};
function AssignValueField(relatedSlider, sourceControlId) {
    tbToSliderRelation[sourceControlId] = relatedSlider;
}

function GetCurrentURL() {
    var location = window.location.href;
    var locationParts = location.split(new RegExp("\/"));

    var protocolIndicator = new RegExp(":\/\/");
    var protocolfound = (location.search(protocolIndicator) > -1);

    if (locationParts.length >= 1) {
        if (protocolfound && (locationParts.length > 1)) {
            var domainToUse = locationParts[1];
            if (!domainToUse)
                domainToUse = locationParts[2];

            return locationParts[0] + "//" + domainToUse;
        }
        else if (!protocolfound) {
            return locationParts[0];
        }
    }
}

function RoundValue(startVal, roundSize) {
    var result = startVal / roundSize;
    result = Math.ceil(result);
    
    return result * roundSize;
}

// #################
// Trim operations.
// [MB]
// #################
function TrimBoth(value) {
    return TrimRight(TrimLeft(value));
}

function TrimLeft(value) {
    if (value) {
        while (value && (value.length > 0) && (value.search(/^\s/) != -1)) {
            value = value.replace(/^\s/, "");
        }
    }

    return value;
}

function TrimRight(value) {
    if (value) {
        while (value && (value.length > 0) && (value.search(/\s$/) != -1)) {
            value = value.replace(/\s$/, "");
        }
    }

    return value;
}