﻿function MO() { }

function isIE(){
   return /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);
}

// Browser Detection Javascript
// copyright 1 February 2003, by Stephen Chapman, Felgall Pty Ltd

// You have permission to copy and use this javascript provided that
// the content of the script is not changed in any way.

function whichBrs() {
    var agt = navigator.userAgent.toLowerCase();
    if (agt.indexOf("opera") != -1) return 'Opera';
    if (agt.indexOf("staroffice") != -1) return 'Star Office';
    if (agt.indexOf("webtv") != -1) return 'WebTV';
    if (agt.indexOf("beonex") != -1) return 'Beonex';
    if (agt.indexOf("chimera") != -1) return 'Chimera';
    if (agt.indexOf("netpositive") != -1) return 'NetPositive';
    if (agt.indexOf("phoenix") != -1) return 'Phoenix';
    if (agt.indexOf("firefox") != -1) return 'Firefox';
    if (agt.indexOf("safari") != -1) return 'Safari';
    if (agt.indexOf("skipstone") != -1) return 'SkipStone';
    if (agt.indexOf("msie") != -1) return 'Internet Explorer';
    if (agt.indexOf("netscape") != -1) return 'Netscape';
    if (agt.indexOf("mozilla/5.0") != -1) return 'Mozilla';
    if (agt.indexOf('\/') != -1) {
        if (agt.substr(0, agt.indexOf('\/')) != 'mozilla') {
            return navigator.userAgent.substr(0, agt.indexOf('\/'));
        }
        else return 'Netscape';
    } else if (agt.indexOf(' ') != -1)
        return navigator.userAgent.substr(0, agt.indexOf(' '));
    else return navigator.userAgent;
}
// END Browser Detection Javascript

AdditionalHeight = isIE() ? 2 : 0;

MO.RegisterFormID = '';

MO.RegisterFormShow = function() {
    var modal = $find(MO.RegisterFormID);
    if (modal) modal.show();
}

MO.GetFrame = function(doc, framepid) {
    var frameParent = doc.getElementById(framepid);
    if (frameParent.tagName.toUpperCase() == 'IFRAME')
        return frameParent;
    return frameParent.getElementsByTagName('iframe')[0];
}

MO.SetCssClass = function(frame, attrElem, attrClass) {
    var elem = frame.ownerDocument.getElementById(frame.attributes[attrElem].value);
    if (elem) elem.className = frame.attributes[attrClass].value;
}

MO.ShowFrame = function(framepid, params, parentFrame) {
    //alert("show frame");
    var frame = MO.GetFrame(document, framepid);
    if (frame == null)
        return;
        
    frame.parentFrame = parentFrame;
    MO.Disability(frame, 'viewElem', true);
    MO.SetCssClass(frame, 'editElem', 'editHideClass');
    MO.SetCssClass(frame, 'loadingElem', 'loadingShowClass');
    frame.className = frame.attributes['frameShowClass'].value;
    if (frame.src == 'about:blank') {
        var editUrl = frame.attributes['editUrl'];
        editUrl = editUrl ? unescape(editUrl.value) : "";
        frame.src = editUrl;
    }
    else {
        MO.ShowLoadedFrame(frame);
    }
}

function ExtendFrame(frame) {
    //alert("extend frame on");
    if (!frame) return;
    //alert("frame exist");
    var deltaHeight = parseInt(frame.frameWindow.document.body.offsetHeight) + 'px';    
    $(frame).animate({
        height: deltaHeight
    }, 300, "swing", function() {
        frame.style.height = parseInt(frame.frameWindow.document.body.offsetHeight) + 'px';
    });
    if (frame.parentFrame) {
        //alert("parent frame exist");
        ExtendFrame(frame.parentFrame);
    }
}

function ExtendFrameOn(frame, deltaHeight) {
    //alert("extend frame on");
    if (!frame) return;
    //alert("frame exist");
    
    $(frame).animate({
        height: "+=" + deltaHeight
    }, 300, "swing", function() {
        //frame.style.height = parseInt(frame.frameWindow.document.body.scrollHeight) + AdditionalHeight + 'px';
    });
    if (frame.parentFrame) {
        //alert("parent frame exist");
        ExtendFrameOn(frame.parentFrame, deltaHeight);
    }
}

function RollUpFrame(frame, ok, dontResetUrl) {
    if (!frame) return;

    var deltaHeight = parseInt(frame.frameWindow.document.body.offsetHeight) + 'px';
    $(frame).animate({
        height: "0px"
    }, 300, "swing", function() {
        RollUpComplete(frame, ok, dontResetUrl);
    });
    if (frame.parentFrame) {
        RollUpFrameOn(frame.parentFrame, deltaHeight);
    }
}

function RollUpFrameOn(frame, deltaHeight) {
    if (!frame) return;

    $(frame).animate({
        height: "-=" + deltaHeight
    }, 300, "swing", function() {
    });
    if (frame.parentFrame) {
        RollUpFrameOn(frame.parentFrame.frameElement, deltaHeight);
    }
}

MO.ShowLoadedFrame = function(frame) {
    //alert("show loaded frame");
    MO.SetCssClass(frame, 'viewElem', 'viewHideClass');
    MO.SetCssClass(frame, 'loadingElem', 'loadingHideClass');
    frame.style.display = "block";
    frame.parentNode.style.display = "block";
    //var deltaHeight = parseInt(frame.frameWindow.document.body.offsetHeight) + AdditionalHeight + 'px';
    //alert(deltaHeight);
    ExtendFrame(frame);
}

MO.UpdateTimeStamp = null;

MO.FrameLoaded = function(frameWindow) {
    //alert("frame loaded");
    var frame = frameWindow.frameElement;
    frame.frameWindow = frameWindow;
    //alert("frame loaded m");

    var requestManager = Sys.WebForms.PageRequestManager.getInstance();
    if (requestManager) {
        requestManager.add_endRequest(UpdateHeight);
    }

    if (typeof(ValidatorUpdateDisplay) != "undefined") {
        var oldValidatorUpdateDisplay = ValidatorUpdateDisplay;
        ValidatorUpdateDisplay = function(val) {
            oldValidatorUpdateDisplay(val);
            MO.UpdateTimeStamp = new Date();
            setTimeout("UpdateHeightByTimeOut(1000)", 1000);
        }

    }

    MO.ShowLoadedFrame(frame);
}

function OnCalendarShown(sender, args){
    var frame = window.frameElement;
    var frameHeight = parseInt(frame.frameWindow.document.body.offsetHeight);
    var calendarBottomPoint = parseInt(sender._container.offsetTop) + parseInt(sender._container.offsetHeight) + 10;
    //alert('frame height: ' + frameHeight + '; calendar bottom: ' + calendarBottomPoint);
    if (calendarBottomPoint > frameHeight) {
        var deltaHeight = (calendarBottomPoint - frameHeight) + 'px';
        if (whichBrs() == "Firefox") {
            frame.style.height = calendarBottomPoint + 'px';
        }
        else {
            ExtendFrameOn(frame, deltaHeight);
        }
    }    
}

function OnCalendarHidden(sender, args){
    UpdateHeight(null, null);
}

function UpdateHeightByTimeOut(timeout) {
    if (new Date() - MO.UpdateTimeStamp >= timeout) {
        UpdateHeight(null, null);
    }
}

function UpdateHeight(sender, args) {
    var frame = window.frameElement;
    if (whichBrs() == "Firefox") {
        var frameHeight = parseInt(frame.frameWindow.document.body.offsetHeight);
        frame.style.height = frameHeight + 'px';
        
    }
    else {
        ExtendFrame(frame);  
    }  
}


function RollUpComplete(frame, ok, dontResetUrl) {    
    frame.style.height = '0px';
    frame.className = frame.attributes['frameHideClass'].value;
    if (!dontResetUrl) {
        frame.src = 'about:blank';
    }
    MO.Disability(frame, 'viewElem', false);
    MO.SetCssClass(frame, 'viewElem', 'viewShowClass');
    MO.SetCssClass(frame, 'editElem', 'editShowClass');
    frame.style.display = "none";
    frame.parentNode.style.display = "none";
    if (ok) eval(frame.attributes['submitScript'].value);
}

MO.Disability = function(frame, attrElem, disability) {
   	var elem = frame.ownerDocument.getElementById(frame.attributes[attrElem].value);
   	if (elem) {
   		if (elem.type == "checkbox") {
   			elem.disabled = disability;
   		}
   	}
   }

MO.HideFrame = function(frameWindow, ok, dontResetUrl) {   
   var frame = frameWindow.frameElement;
   RollUpFrame(frame, ok, dontResetUrl);
}

MO.ShowPanel = function(panelId) {
    var panel = $get(panelId);
    if (panel == null) {
        alert("panel has not found!");
        return;
    }

    //alert("OffsetHeight: " + panel.offsetHeight + "; ScrollHeight: " + panel.scrollHeight + ";");

    // determine deltaHeight
    setElementOpacity(panel, 0);
    panel.style["display"] = "block";
    panel.style["height"] = "";

    //alert("OffsetHeight: " + panel.offsetHeight + "; ScrollHeight: " + panel.scrollHeight + ";");
    var deltaHeight = parseInt(panel.offsetHeight) + 'px';
    
    // make visible with 0 height
    panel.style["height"] = "0px";
    setElementOpacity(panel, 1);

    $(panel).animate({
        height: "+=" + deltaHeight
    }, 300, "swing", function() {

    });
    if (window.frameElement) {
        ExtendFrameOn(window.frameElement, deltaHeight);
    }

    //alert("OffsetHeight: " + panel.offsetHeight + "; ScrollHeight: " + panel.scrollHeight + ";");
}

MO.HidePanel = function(panelId) {
    var panel = $get(panelId);
    if (panel == null) {
        alert("panel has not found!");
        return;
    }

    //alert("OffsetHeight: " + panel.offsetHeight + "; ScrollHeight: " + panel.scrollHeight + ";");
    var deltaHeight = parseInt(panel.offsetHeight) + 'px';

    $(panel).animate({
        height: "0px"
    }, 300, "swing", function() {
        panel.style["display"] = "none";
        panel.style["height"] = "0px";
    });
    if (window.frameElement) {
        RollUpFrameOn(window.frameElement, deltaHeight);
    }

    //alert("OffsetHeight: " + panel.offsetHeight + "; ScrollHeight: " + panel.scrollHeight + ";");
}

function setElementOpacity(elem, nOpacity) {
    var opacityProp = getOpacityProperty();
    
    if (!elem || !opacityProp) return; // Если не существует элемент с указанным id или браузер не поддерживает ни один из известных функции способов управления прозрачностью

    if (opacityProp == "filter")  // Internet Exploder 5.5+
    {
        nOpacity *= 100;

        // Если уже установлена прозрачность, то меняем её через коллекцию filters, иначе добавляем прозрачность через style.filter
        var oAlpha = elem.filters['DXImageTransform.Microsoft.alpha'] || elem.filters.alpha;
        if (oAlpha) oAlpha.opacity = nOpacity;
        else elem.style.filter += "progid:DXImageTransform.Microsoft.Alpha(opacity=" + nOpacity + ")"; // Для того чтобы не затереть другие фильтры используем "+="
    }
    else // Другие браузеры
        elem.style[opacityProp] = nOpacity;
}

function getOpacityProperty() {
    if (typeof document.body.style.opacity == 'string') // CSS3 compliant (Moz 1.7+, Safari 1.2+, Opera 9)
        return 'opacity';
    else if (typeof document.body.style.MozOpacity == 'string') // Mozilla 1.6 и младше, Firefox 0.8 
        return 'MozOpacity';
    else if (typeof document.body.style.KhtmlOpacity == 'string') // Konqueror 3.1, Safari 1.1
        return 'KhtmlOpacity';
    else if (document.body.filters && navigator.appVersion.match(/MSIE ([\d.]+);/)[1] >= 5.5) // Internet Exploder 5.5+
        return 'filter';

    return false; //нет прозрачности
}

function onCalendarShownBalance() {
    var cal = $find("calendarBalance");     //Setting the default mode to month    
    cal._switchMode("months", true);          //Iterate every month Item and attach click event to it    
    if (cal._monthsBody) {
        for (var i = 0; i < cal._monthsBody.rows.length; i++) {
            var row = cal._monthsBody.rows[i];
            for (var j = 0; j < row.cells.length; j++) {
                Sys.UI.DomEvent.addHandler(row.cells[j].firstChild, "click", call);
            }
        }
    }
}

function onCalendarHiddenBalance() {
    var cal = $find("calendarBalance");
    //Iterate every month Item and remove click event from it
    if (cal._monthsBody) {
        for (var i = 0; i < cal._monthsBody.rows.length; i++) {
            var row = cal._monthsBody.rows[i];
            for (var j = 0; j < row.cells.length; j++) {
                Sys.UI.DomEvent.removeHandler(row.cells[j].firstChild, "click", call);
            }
        }
    }
}

function call(eventElement) {
    var target = eventElement.target;
    switch (target.mode) {
        case "month":
            var cal = $find("calendarBalance");
            cal._visibleDate = target.date;
            cal.set_selectedDate(target.date);
            cal._switchMonth(target.date);
            cal._blur.post(true);
            cal.raiseDateSelectionChanged();
            break;
    }
}


