﻿/// <reference name="MicrosoftAjax.js"/>
/// <reference assembly="Controls" name="Lib.js"/>

// globals
var continueProgress = false;

var 
pageMessageError = null,
pageMessageWarning = null,
pageMessageInfo = null,
pageMessageDone = null;

var historyCanGoBack = false, historyCanGoForward = false;

var 
theConfirmPanelId, theConfirmPanelTextId, theConfirmPanelYesId, theConfirmPanelNoId, theConfirmLayerId;

// trigger client resize events
var theClientWidth = 0, theClientHeight = 0;

// also works without ASP.NET AJAX, i.e. without Sys namespace
function updateClientSize() {
    if (typeof (window.innerWidth) == 'number') {
        // W3C compliant
        theClientWidth = window.innerWidth;
        theClientHeight = window.innerHeight;
    } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        //IE 6+ in 'standards compliant mode'
        theClientWidth = document.documentElement.clientWidth;
        theClientHeight = document.documentElement.clientHeight;
    } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
        //IE 4 compatible
        theClientWidth = document.body.clientWidth;
        theClientHeight = document.body.clientHeight;
    }
}

// also works without ASP.NET AJAX, i.e. without having Sys namespace
function addResizeHandler(handler, onRequest) {
    if (typeof (handler) == 'function') {
        if (document.addEventListener) {
            window.addEventListener('resize', handler, false);
        } else { // IE
            window.attachEvent('onresize', handler);
        }

        // declare Sys = false if not having ASP.NET AJAX
        if (typeof Sys != 'undefined' && Sys && onRequest) {
            Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(handler);
            Sys.WebForms.PageRequestManager.getInstance().add_endRequest(handler);
        }
        handler();
    }
}


//function removeResizeEvent(handler) {
//  if (typeof(handler) == 'function') {
//	  if (document.addEventListener)
//	  {
//      window.removeEventListener('resize',handler,false);
//	  } else { // IE
//	    window.detachEvent('onresize',handler);
//	  }
//  }
//}


// custom postback methods
//
//  //  var theform = document.forms['form1'];
//  //  if (!theform) {
//  //      theform = document.form1;
//  //  }
//  //  function __dopostback(eventtarget, eventargument) {
//  //      if (!theform.onsubmit || (theform.onsubmit() != false)) {
//  //          theform.__eventtarget.value = eventtarget;
//  //          theform.__eventargument.value = eventargument;
//  //          theform.submit();
//  //      }
//  //  }
//
// __doPostBack is usually modified through ASP.NET AJAX

function aspPostBack(id, arg) {
    var sid = id.replace(/_/g, '$');
    if (!arg) arg = '';
    __doPostBack(sid, arg);
}

// postback to new window: avoid ajax action, i.e skip __doPostBack here
function aspPostBackToNew(id, arg, url) {
    var sid = id.replace(/_/g, '$');
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = sid;
        theForm.__EVENTARGUMENT.value = arg || '';
        var originalAction = theForm.action;
        var originalTarget = theForm.target;
        if (url) theForm.action = url;
        theForm.target = '_blank';
        theForm.submit();
        if (url) theForm.action = originalAction;
        theForm.target = originalTarget;
    }
}

// process webservice response
function updateMessageListRow(result) {
    if (result && result.update) {
        for (var i in result.update) {
            var id = result.update[i].id;
            var elem = $get(id);
            if (elem) {
                var c = result.update[i].className;
                if (typeof c == 'string')
                    elem.className = c;
                var t = result.update[i].title;
                if (typeof t == 'string')
                    elem.title = t;
            }
            else {
                // element not found!
            }
        }
    }
}

// HttpNet2.Webmail.Services.Messages.ChangeMessageFlag
function onMessageFlagChange(messageID, tableID, flagID, subjectID, addressID) {
    HttpNet2.Webmail.Services.ScriptService.ChangeMessageFlag(messageID, tableID, flagID, subjectID, addressID, updateMessageListRow);
}

// HttpNet2.Webmail.Services.ScriptService.SetMessageSeen
function onMessageView(pagerIndex, tableID, flagID, subjectID, addressID) {
    if ($find(tableID)) {
        HttpNet2.Webmail.Services.ScriptService.GetMessageID(pagerIndex - 1, function(result) {
            if (typeof result != 'undefined' && result != '') {
                var id = result;
                HttpNet2.Webmail.Services.ScriptService.SetMessageSeen(id, tableID, flagID, subjectID, addressID, function(result2) {
                    updateMessageListRow(result2);
                    var o = $find(tableID);
                    if (o) o.selectRows([id]);
                });
            }
        });
    }
}
function setMessageSeen(messageID, tableID, flagID, subjectID, addressID) {
    window.setTimeout(function() {
        if ($find(tableID)) {
            HttpNet2.Webmail.Services.ScriptService.SetMessageSeen(messageID, tableID, flagID, subjectID, addressID, function(result) {
                updateMessageListRow(result);
                $find(tableID).selectRows([messageID]);
            });
        }
    }, 1000);
}

// HttpNet2.Webmail.Services.ScriptService.GetFolderItem
function clientFetchFolders(onAddRow, onDone, tableID, columnID, idList, i) {
    if (!i) i = 0;
    HttpNet2.Webmail.Services.ScriptService.GetFolderItem(idList[i],
    function(result) { // onSuccess
        if (result && result.update) {
            var elem = document.createElement('div');
            elem.setAttribute('id', tableID + '_' + result.update.id + '_' + columnID + '_icon');
            var c = result.update.className;
            if (typeof c == 'string')
                elem.className = c; // elem.setAttribute('class',c); does not work in IE

            var t = result.update.title;
            if (typeof t == 'string')
                elem.setAttribute('title', t);
            var s = result.update.text;
            if (typeof s == 'string') {
                elem.appendChild(document.createTextNode(s));
            }


            if (i < idList.length - 1) {
                // fetch next folder
                window.setTimeout(function() {
                    onAddRow(result.update.id, [elem]);
                    clientFetchFolders(onAddRow, onDone, tableID, columnID, idList, i + 1);
                }, 10);
            } else {
                // finish
                window.setTimeout(function() {
                    onAddRow(result.update.id, [elem]);
                    if (typeof onDone == 'function') {
                        onDone();
                    }
                }, 10);
            }
        }
    }, function() { // onError
        // maybe IMAP server returned "STATUS failed (NO)" - skip it
        if (i < idList.length - 1) {
            // fetch next folder
            window.setTimeout(function() {
                clientFetchFolders(onAddRow, onDone, tableID, columnID, idList, i + 1);
            }, 10);
        } else {
            // finish
            window.setTimeout(function() {
                if (typeof onDone == 'function') {
                    onDone();
                }
            }, 10);
        }
    });
}

// HttpNet2.Webmail.Services.ScriptService.Acknowledge
function clientFoldersComplete() {
    HttpNet2.Webmail.Services.ScriptService.FoldersComplete();
}

// HttpNet2.Webmail.Services.ScriptService.Acknowledge
function clientAcknowledge() {
    HttpNet2.Webmail.Services.ScriptService.Acknowledge(function(result) { });
}

// display fancy ajax confirm dialog
// requires:
// theConfirmPanelId, theConfirmPanelTextId, theConfirmPanelYesId, theConfirmPanelNoId, theConfirmLayerId
function _confirm(text, onConfirmed, onAborted, postbackArg) {
    var panel = $get(theConfirmPanelId);
    if (panel) {
        var layer = $get(theConfirmLayerId);
        $get(theConfirmPanelNoId).onclick = function() {
            panel.style.visibility = 'hidden';
            if (layer) {
                layer.style.visibility = 'hidden';
            }
            if (typeof onAborted == 'function')
                onAborted();
            return false;
        };
        $get(theConfirmPanelYesId).onclick = function() {
            panel.style.visibility = 'hidden';
            if (layer) {
                layer.style.visibility = 'hidden';
            }
            if (typeof onConfirmed == 'string') {
                // onConfirmed as postback ID
                aspPostBack(onConfirmed, postbackArg);
            } else if (typeof onConfirmed == 'function') {
                onConfirmed();
            }
            return false;
        };
        $get(theConfirmPanelTextId).innerHTML = text;
        updateClientSize();
        var b = Sys.UI.DomElement.getBounds(panel);
        panel.style.left = Math.round((theClientWidth - b.width) / 2) + 'px';
        panel.style.top = Math.round((theClientHeight) / 3) + 'px';
        if (layer) layer.style.visibility = 'visible';
        panel.style.visibility = 'visible';
        return false;
    }
    else return window.confirm(text);
}

// ajust message view
var messageViewItemID, messageViewIFrameID, messageViewPlainID,
  messageViewInnerID, messageViewHeaderID, messageViewRadioID;
function switchMessageView(isHTML) {
    var iframeElem = $get(messageViewIFrameID);
    var plainElem = $get(messageViewPlainID);
    if (isHTML) {
        // html view
        iframeElem.style.display = 'block';
        plainElem.style.display = 'none';
    } else {
        // plain view
        // display='none' avoids iframe content loading
        plainElem.style.display = 'block';
        iframeElem.style.display = 'none';
    }
    adjustMessageView();
}
function adjustMessageView() {

    var item = $find(messageViewItemID);
    if (item) {

        //alert('adjustMessageView: ' + contentWidth + '; ' + contentHeight);

        var width = item.get_innerWidth();
        var height = item.get_innerHeight();

        // due to a bug in Firefox we have to change the height to force an update
        $get(messageViewItemID).style.height = (height - 1) + 'px';

        $resize(messageViewHeaderID, width - 30, NaN);
        var headerHeight = $bounds(messageViewHeaderID).height + 8;

        var isHtml = $get(messageViewRadioID).checked;
        var contentWidth = 0, contentHeight = 0;
        if (isHtml) {
            // html view
            var doc = getIFrameDocument(messageViewIFrameID);
            if (doc) {
                contentWidth = doc.body.scrollWidth + 5;
                contentHeight = doc.body.scrollHeight + 5;
            }
        } else {
            // plain text view
            var b = $bounds(messageViewPlainID);
            contentWidth = b.width;
            contentHeight = b.height;
        }
        if (contentWidth < width - 18)
            contentWidth = width - 18;
        if (contentHeight < height - headerHeight - 40)
            contentHeight = height - headerHeight - 40;

        // adjust elements  
        $resize(messageViewInnerID, width - 18, contentHeight + headerHeight + 40);
        $set(messageViewBodyID, NaN, headerHeight + 4, contentWidth, NaN);

        if (isHtml) {
            // ajust iframe element
            $resize(messageViewIFrameID, contentWidth, contentHeight);
        }
        $resize(messageViewItemID, NaN, height);
        $show(messageViewItemID, true);

        //alert('adjustMessageView: ' + contentWidth + '; ' + contentHeight);
    }



}
function getIFrameDocument(iframeID) {
    var doc = null;
    var frame = $get(iframeID);
    // if contentDocument exists, W3C compliant (e.g. Mozilla) 
    if (frame.contentDocument)
        doc = frame.contentDocument;
    else if (frame.contentWindow)
        doc = frame.contentWindow.document;
    else // bad IE
        doc = document.frames[iframeID].document;
    if (doc && doc.body) return doc;
    else return null;
}

function enableInput(id, checked) {
    var el = $get(id);
    if (checked) {
        el.disabled = false;
        window.setTimeout('$get("' + id + '").focus()', 10);
    }
    else el.disabled = true;
}






