var WM_acceptsCookies = false;
if(document.cookie == '') {
    document.cookie = 'WM_acceptsCookies=yes';// Try to set a cookie.
    if(document.cookie.indexOf('WM_acceptsCookies=yes') != -1) {
	WM_acceptsCookies = true;
    }// If it succeeds, set variable
} else { // there was already a cookie
  WM_acceptsCookies = true;
}


function WM_setCookie (name, value, hours, path, domain, secure) {
    //alert(name+"="+value);
    if (WM_acceptsCookies) { // Don't waste your time if the browser doesn't accept cookies.
	var not_NN2 = (navigator && navigator.appName
		       && (navigator.appName == 'Netscape')
		       && navigator.appVersion
		       && (parseInt(navigator.appVersion) == 2))?false:true;

	if(hours && not_NN2) { // NN2 cannot handle Dates, so skip this part
	    if ( (typeof(hours) == 'string') && Date.parse(hours) ) { // already a Date string
		var numHours = hours;
	    } else if (typeof(hours) == 'number') { // calculate Date from number of hours
		var numHours = (new Date((new Date()).getTime() + hours*3600000)).toGMTString();
	    }
	}
	document.cookie = name + '=' + escape(value) + ((numHours)?(';expires=' + numHours):'') + ((path)?';path=' + path:'') + ((domain)?';domain=' + domain:'') + ((secure && (secure == true))?'; secure':''); // Set the cookie, adding any parameters that were specified.
    }
} // WM_setCookie


function WM_readCookie(name) {
    if(document.cookie == '') { // there's no cookie, so go no further
	return false;
    } else { // there is a cookie
	var firstChar, lastChar;
	var theBigCookie = document.cookie;
	firstChar = theBigCookie.indexOf(name);	// find the start of 'name'
	var NN2Hack = firstChar + name.length;
	if((firstChar != -1) && (theBigCookie.charAt(NN2Hack) == '=')) { // if you found the cookie
	    firstChar += name.length + 1; // skip 'name' and '='
	    lastChar = theBigCookie.indexOf(';', firstChar); // Find the end of the value string (i.e. the next ';').
	    if(lastChar == -1) lastChar = theBigCookie.length;
	    return unescape(theBigCookie.substring(firstChar, lastChar));
	} else { // If there was no cookie of that name, return false.
	    return false;
	}
    }
} // WM_readCookie

function WM_killCookie(name, path, domain) {
  var theValue = WM_readCookie(name); // We need the value to kill the cookie
  if(theValue) {
      document.cookie = name + '=' + theValue + '; expires=Fri, 13-Apr-1970 00:00:00 GMT' + ((path)?';path=' + path:'') + ((domain)?';domain=' + domain:''); // set an already-expired cookie
  }
}

function execStrutsAction(action, params) {
    var url = action + "?exec";
    for (key in params) {
        url+='&'+key+'='+params[key];
    }
    //alert( url );
    document.location.href = url;

}

function execStrutsActionNewWindow(action, params) {
    var url = action + "?exec";
    for (key in params) {
        url+='&'+key+'='+params[key];
    }
    window.open( url, "_blank" );

}

function viewWorkOrder(workOrderID) {
    execStrutsAction('tenant!viewWorkOrder.action', {'workOrderID': workOrderID});
}

function newWorkOrder( returnURL ) {
    execStrutsAction('tenant!editWorkOrder.action', { 'returnTo' : returnURL } );
}

function attachDocument(workOrderID){
    execStrutsAction('tenant!viewAttachServiceRequestDocument.action', {'workOrderID': workOrderID});
}

function removeDocument( workOrderID, workOrderDocumentID ){
    var del = confirm("Are you sure you want to delete this document?");
    if( del ){
        execStrutsAction('tenant!deleteServiceRequestDocument.action', {'workOrderID': workOrderID, 'workOrderDocumentID': workOrderDocumentID});
    }
}

function cancelAttachDocument(workOrderID){
    execStrutsAction('tenant!viewWorkOrder.action', {'workOrderID': workOrderID});
}

function addComment(workOrderID){
    /*    document.forms['tenant!addComment.action'].action.value = "AddComment" ;
    document.forms['tenant!addComment.action'].submit();*/
    execStrutsAction('tenant!addWorkOrderComment.action', {'workOrderID': workOrderID});
}


function addLeaseComment(conversationID){
    execStrutsAction('tenant!addLeaseComment.action', {'conversationID':conversationID});
}

function saveLeaseConversation(){
    execStrutsAction('tenant!saveLeaseConversation.action');
}

function viewLeaseConversation(conversationID){
    execStrutsAction('tenant!viewLeaseConversation.action', {'conversationID':conversationID});
}
function closeConversation(conversationID){
    var conf = confirm("Do you truly wish to close this conversation? It will no longer be visible to you if it " +
                       "is closed.");
    if (conf){
    execStrutsAction('tenant!closeConversation.action', {'conversationID':conversationID});
    }
}
function openConversation(conversationID){
    execStrutsAction('tenant!openConversation.action', {'conversationID':conversationID});
}

function overConversation(o, pk){
    var actionButtons = 'actionButtons_'+ pk;
    var oActionButtons = document.getElementById(actionButtons);
    o.style.backgroundColor = "#FFFFFF";
    o.style.border = "1px solid #CCCCCC";

    if (oActionButtons != null)
        oActionButtons.style.display = "block";
}

function outConversation(o, pk){
    var actionButtons = 'actionButtons_'+ pk;
    var oActionButtons = document.getElementById(actionButtons);
    o.style.backgroundColor = "";
    o.style.border = "";
    o.style.borderBottom = "1px solid #CCCCCC";
    if (oActionButtons != null){
        oActionButtons.style.display = "none";
    }
}

function editWorkOrder(workOrderID) {
    execStrutsAction('tenant!editWorkOrder.action', {'workOrderID': workOrderID});
}

function cancelWorkOrder(workOrderID) {
    execStrutsAction('tenant!cancelWorkOrder.action', {'workOrderID': workOrderID});
}

function viewLease(leaseID) {
    execStrutsAction('tenant!viewLease.action', {'leaseID': leaseID});
}

function editPayment(leaseID) {
    execStrutsAction('tenant!editPayment.action', {'leaseID': leaseID});
}

function viewAutoPayment(autoPaymentID) {
    execStrutsAction('tenant!viewAutoPayment.action', {'autoPaymentID': autoPaymentID});
}

function editAutoPayment(autoPaymentID) {
    execStrutsAction('tenant!editAutoPayment.action', {'autoPaymentID': autoPaymentID});
}

function deleteAutoPayment(autoPaymentID) {
    if (confirm("Are you sure you want to delete this Auto ePayment?"))
        execStrutsAction('tenant!deleteAutoPayment.action', {'autoPaymentID': autoPaymentID});
}

function printTenantLedger(leaseID){
    execStrutsAction('tenant!printTenantLedger.action', {'leaseID': leaseID});

    /*popUp('lease_view_print_view.jsp');*/
}

function formatCurrencyMax(item, max) {
    var num = item.value;
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
        cents = "0" + cents;

    if (max > 0)
        num = num.substring(0, max-2);

    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
        num = num.substring(0,num.length-(4*i+3))+','+
              num.substring(num.length-(4*i+3));
    item.value = (((sign)?'':'-') + '$' + num + '.' + cents);
}

function formatCurrency(item) {
    formatCurrencyMax(item, 0);
}

function formatPhone (field) {
    //alert(field.value)
    field.value = trim(field.value);

    var ov = field.value;
    var v = "";
    var x = -1;

    // is this phone number 'escaped' by a leading plus?
    if (0 < ov.length && '+' != ov.charAt(0)) { // format it
        // count number of digits
        var n = 0;
        if ('1' == ov.charAt(0)) {  // skip it
            ov = ov.substring(1, ov.length);
        }

        for (i = 0; i < ov.length; i++) {
            var ch = ov.charAt(i);

            // build up formatted number
            if (ch >= '0' && ch <= '9') {
                if (n == 0) v += "(";
                else if (n == 3) v += ") ";
                else if (n == 6) v += "-";
                v += ch;
                n++;
            }
            // check for extension type section;
            // are spaces, dots, dashes and parentheses the only valid non-digits in a phone number?
            if (! (ch >= '0' && ch <= '9') && ch != ' ' && ch != '-' && ch != '.' && ch != '(' && ch != ')') {
                x = i;
                break;
            }
        }
        // add the extension
        if (x >= 0) v += " " + ov.substring(x, ov.length);

        // if we recognize the number, then format it
        if (n == 10 && v.length <= 40) {
            //alert(v);
            field.value = v
        };
    }
    return true;
}

function formatPercent(item){
    var num = item.value;
    num = num.replace('%','');
    if(isNaN(num) || num == "")
        num = "0";
	if (isNaN(num)){
		num = "0.0";
	}
    item.value = num + '%';
}

function ltrim(s) {
    return s.replace( /^\s*/, "" );
}

function rtrim(s) {
    return s.replace( /\s*$/, "" );
}

function trim(s) {
    return rtrim(ltrim(s));
}

function _popUp(url, popupWidth, popupHeight) {
    var x, y;
    if(!document.all) {
        x = window.screenX + 400 - (popupWidth/2);
        y = window.screenY + 300 - (popupHeight/2);
    } else {
        x = window.screenLeft + 400 - (popupWidth/2);
        y = window.screenTop + 300 - (popupHeight/2);
        y = y - 65    //IE does not include the top bars of the window in the screenTop value.
    }
    y = y - 16;       //account for the top bar of the popup
    var win = window.open(url, 'Propertyware', 'menubar=yes,toolbar=yes,location=no,directories=no,status=no,scrollbars=yes,resizable=yes,copyhistory=no,width='+popupWidth+',height='+popupHeight+',screenX='+x+',screenY='+y+',top='+y+',left='+x);
    //win.focus();
}

function popUp(url, leaseID) {

    _popUp(url, 750, 580);
}

//Owner Portal Functions


function addPortfolioComment(conversationID){
    execStrutsAction('owner!addPortfolioComment.action', {'conversationID':conversationID});
}

function removeWODocument( workOrderID, workOrderDocumentID ){
    var del = confirm("Are you sure you want to delete this document?");
    if( del ){
        execStrutsAction('owner!deleteWorkOrderDocument.action', {'workOrderID': workOrderID, 'workOrderDocumentID': workOrderDocumentID});
    }
}

function attachWODocument(workOrderID){
    execStrutsAction('owner!viewAttachWorkOrderDocument.action', {'workOrderID': workOrderID});
}

function addWOComment(workOrderID){
    execStrutsAction('owner!addComment.action', {'workOrderID': workOrderID});
}

function viewWorkOrderOP(workOrderID) {
    execStrutsAction('owner!viewWorkOrder.action', {'workOrderID': workOrderID});
}

function approveWorkOrderOP(workOrderID) {
    var del = confirm("Are you sure you want to approve this work order?");
    if( del ){
        execStrutsAction('owner!approveWo.action', {'workOrderID': workOrderID});
    }
}

function rejectWorkOrderOP(workOrderID) {
    var del = confirm("Are you sure you want to reject this work order?");
    if( del ){
        execStrutsAction('owner!rejectWo.action', {'workOrderID': workOrderID});
    }
}

function cancelAttachWODocument(workOrderID){
    execStrutsAction('owner!viewWorkOrder.action', {'workOrderID': workOrderID});
}

function savePortfolioConversation(){
    execStrutsAction('owner!savePortfolioConversation.action');
}

function viewPortfolioConversation(conversationID){

    execStrutsAction('owner!viewPortfolioConversation.action', {'conversationID':conversationID});
}

function closePortfolioConversation(conversationID){
    var conf = confirm("Do you truly wish to close this conversation? It will no longer be visible to you if it " +
                       "is closed.");
    if (conf){
        execStrutsAction('owner!closePortfolioConversation.action', {'conversationID':conversationID});
    }
}
function openPortfolioConversation(conversationID){
    execStrutsAction('owner!openPortfolioConversation.action', {'conversationID':conversationID});
}

function viewBill(billID) {
    execStrutsAction('owner!viewBill.action', {'billID': billID});
}

function refreshViewBill(type) {
    execStrutsAction('owner!viewBill.action', {'billType': type, 'billsDateFilter': document.getElementById('billsDateFilter').value});
}

function viewInvoice(billID){
    execStrutsActionNewWindow('owner!viewInvoice.action', {'billID': billID});
}

function refreshViewWorkOrder() {
    execStrutsAction('owner!viewWorkOrder.action', {'maintenanceStatus': document.getElementById('status').value, 'maintenanceApproval': document.getElementById('approval').value});
}

function newContribution() {
    execStrutsAction('owner!newContribution.action');
}

function editContact() {
    execStrutsAction('owner!editContact.action');
}

function setDateRangeFunction(fn){
    if (fn == 'custom()') {
        document.getElementById('dateRangeFunction').value = 'custom()';
        showElement('withCustomDate');
        hideElement('noCustomDate');
    } else {
        document.getElementById('billsTabView.startDate').value = "";
        document.getElementById('billsTabView.endDate').value = "";
        if(document.getElementById('dateRangeFunction').value != 'custom()'){
            document.getElementById('billsTabView.dateRangeFunction').value = document.getElementById('dateRangeFunction').value;
            document.getElementById('dateRangeFunction').value = 'custom()';
        }
        showElement('noCustomDate');
        hideElement('withCustomDate');
    }
}

function showElement(elementID) {
    if (document.getElementById(elementID))
        document.getElementById(elementID).style.display = 'block';
}

function hideElement(elementID) {
    if (document.getElementById(elementID))
        document.getElementById(elementID).style.display = 'none';
}

function saveWOComment(){
    execStrutsAction('owner!saveComment.action', {'workOrderID': document.getElementById("owner_workOrderID").value, 'commentText': document.getElementById("owner_commentText").value});
}

function updatePortfolioFee() {
    execStrutsAction('owner!updatePortfolioFeeSelected.action', {'portfolioFeeSelectedID': document.getElementById("portfolioFeeSelectedID").value, 'contribution.amountAsString': document.getElementById("contribution.amountAsString").value, 'contribution.comments': document.getElementById("contribution.comments").value});
}

function editContribution() {
    execStrutsAction('owner!editContribution.action', {'portfolioFeeSelectedID': document.getElementById("portfolioFeeSelectedID").value, 'contribution.amount': document.getElementById("contribution.amount").value, 'contribution.comments': document.getElementById("contribution.comments").value});
}

/** Conversations **/
function showConvoDelete(cid, b){
    if (b){
        document.getElementById("cd_" + cid).style.display = 'block';
    }
    else {
        document.getElementById("cd_" + cid).style.display = 'none';
    }
}

function showCmtDelete(cid, b){
    if (b){
        document.getElementById("cmtd_" + cid).style.display = 'block';
    }
    else {
        document.getElementById("cmtd_" + cid).style.display = 'none';
    }
}

function fcb(cid){
    var elem = document.getElementById('fcb_' + cid);
    if (elem != null){
        elem.style.display = 'block';
    }
    var cbox = document.getElementById('cbox_' + cid);
    cbox.focus();
    typeCommentBox(cbox);
}

function cancelFcb(cid){
    var elem = document.getElementById('fcb_' + cid);
    elem.style.display = 'none';
    var cbox = document.getElementById('cbox_' + cid);
    cbox.blur();
}

function typeCommentBox(elem){
    if (elem.value == 'Write a comment...'){
        elem.value = '';
    }
    elem.style.height = 70;
    elem.style.color = '#000000';
    var elemId = elem.id;
    var cId = elemId.split("_")[1];
    document.getElementById('cbtns_' + cId).style.display = 'block';
}

function endTypeCommentBox(cid){
    var elem = document.getElementById('cbox_'+cid);
    elem.value = 'Write a comment...';
    elem.style.height = 30;
    elem.style.color = '#CCCCCC';
    document.getElementById('cbtns_' + cid).style.display = 'none';
}

function AjaxAction(actionFormName, actionURL) {
    var formName = actionFormName;
    var url = actionURL;
    var debug = false;
    var usePost = false;
    var async = true;
    this.changeButtonsState = true;

    this.setAction = function( action ) {
        document.forms[formName].action.value = action;
        return this;
    };

    this.setUsePost = function() {
        this.usePost = true;
        return this;
    };

    this.setAsync = function (pAsync) {
        this.async = pAsync;
        return this;
    };

    this.setChangeButtonsState = function () { // set it to false if postRequest = null after ajaxAction.sendAll();
        this.changeButtonsState = false;
        return this;
    };

    this.send = function() {
        try {
            document.forms[formName].ajaxMode.value = true;
            var ajaxRequest = new AjaxRequest(url);
            if (this.debug) ajaxRequest.setEchoDebugInfo();
            ajaxRequest.addFormElementsById(formName +'.action');
            ajaxRequest.addFormElementsById(formName +'.ajaxMode');

            if (document.getElementById(formName +'.entityID') != null) {
                ajaxRequest.addFormElementsById(formName +'.entityID');
            }

            for ( i = 0; i < arguments.length; i++){
                ajaxRequest.addFormElementsById(arguments[i]);
            }
            ajaxRequest.setPreRequest(this.buttonsOff);
            ajaxRequest.setPostRequest(this.buttonsOn);
            ajaxRequest.setAsync(this.async);
            ajaxRequest.sendRequest();
        } catch (e)  {
            this.handleAjaxException(e);
        }
    };

    this.sendArray = function(arg) {
        /*
         try {
         */
        document.forms[formName].ajaxMode.value = true;
        var ajaxRequest = new AjaxRequest(url);
        ajaxRequest.setUsePOST();
        if (this.debug) ajaxRequest.setEchoDebugInfo();
        ajaxRequest.addFormElementsById(formName +'.action');
        ajaxRequest.addFormElementsById(formName +'.ajaxMode');
        for ( i = 0; i < arg.length; i++){
            var elemId = arg[i];
            try {
                ajaxRequest.addFormElementsById(elemId);
            } catch(ex) {
                //alert(ex + elemId);
            }
        }
        ajaxRequest.setPreRequest(this.buttonsOff);
        ajaxRequest.setPostRequest(this.buttonsOn);
        ajaxRequest.setAsync(this.async);
        ajaxRequest.sendRequest();
        /*
         } catch (e)  {
         this.handleAjaxException(e);
         }
         */
    }

    this.sendAll = function() {
        /*
         try {
         */
        // alert('ajax');

        document.forms[formName].ajaxMode.value = true;
        var ajaxRequest = new AjaxRequest(url);
        if (this.debug) ajaxRequest.setEchoDebugInfo();
        if (this.usePost) ajaxRequest.setUsePOST();
        if (this.changeButtonsState){
            ajaxRequest.setPreRequest(this.buttonsOff);
            ajaxRequest.setPostRequest(this.buttonsOn);
        }
        // always reset to true, so subsequent requests disable the buttons
        this.changeButtonsState = true;
        ajaxRequest.addFormElements(formName);
        ajaxRequest.setAsync(this.async);
        ajaxRequest.sendRequest();
        /*
         } catch (e)  {
         this.handleAjaxException(e);
         }
         */
    }

    this.handleAjaxException = function(e) {
        alert('Error:' + e);
    }

    this.buttonsOn = function(){
        var theForm = document.forms[formName];
        for(i=0; i<theForm.elements.length; i++){
            if(theForm.elements[i].type == "button"){
                theForm.elements[i].disabled = false;
                theForm.elements[i].style.color = '#333333';
            }
        }
    }

    this.buttonsOff = function(){
        var theForm = document.forms[formName];
        for(i=0; i<theForm.elements.length; i++){
            if(theForm.elements[i].type == "button"){
                theForm.elements[i].disabled = true;
                theForm.elements[i].style.color = 'e7e7e7';
            }
        }
    }

}

function saveTenantComment(cid){
    var ajaxAction = new AjaxAction('conversationForm', 'tenant!saveComment.action');
    document.forms['conversationForm'].action.value = 'SaveComment';
    document.forms['conversationForm'].conversationID.value = cid;
    document.forms['conversationForm'].commentText.value = document.getElementById('cbox_'+cid).value;
    ajaxAction.send('conversationID', 'commentText');
}

function saveOwnerComment(cid){
    var ajaxAction = new AjaxAction('conversationForm', 'owner!saveComment.action');
    document.forms['conversationForm'].action.value = 'SaveComment';
    document.forms['conversationForm'].conversationID.value = cid;
    document.forms['conversationForm'].commentText.value = document.getElementById('cbox_'+cid).value;
    ajaxAction.send('conversationID', 'commentText');
}

