if (typeof redrata == "undefined") {
    // if logging is not setup, then define a no-op, do nothing logger
    redrata = {};
}

if (typeof redrata.log == "undefined") {
    log_enabled = false;
    // if logging is not setup, then define a no-op, do nothing logger
    dojo.declare("redrata.log", redrata.log, {
        constructor : function(arguments) {
            dojo.mixin(this, arguments);
        }
    });

    redrata.logging = {
        hideLogs : function() {
        },
            
        log : function(divId, logMessage, groupById, separator) {
        },

        outputLogs : function() {
        },

        outputLog : function(divId, logMessage, groupById, separator) {
        }
    };    
}

//redrata.logging.log("redrataJsStart", "Logs from initial processing of redrata.js - START", false, true);

redrata.sid = Math.floor(Math.random() * 1000000);

redrata.focus = "";

redrata.constants = (function() {
    var list = {
        'MAIL_TEXT_AREA_MIN_ROWS': 7,
        'MAIL_TEXT_AREA_MIN_COLS': 50,
        'MAIL_TEXT_AREA_MAX_ROWS': 20,
        'MAIL_TEXT_AREA_MAX_COLS': 150,
        'MAIL_TEXT_AREA_STEP' : 0
    };

    return {
       get: function(name) { return list[name]; }
   };
})();

redrata.util = {
/**
 * function to trim CDATA from string
 */ 
trimCDATA : function(str) {
    str = str.replace("<!--[CDATA[", "");
    str = str.replace("]]-->", "");
    str = str.replace("<![CDATA[", "");
    str = str.replace("]]>", "");
    return str;
},

/**
 * function to trim ja script tag from string
 */ 
trimJSScriptTag : function(str) {
    str = str.replace("<script type='text/javascript'>", "");
    str = str.replace('<script type="text/javascript">', "");
    str = str.replace("</script>", "");
    return str;
},

/**
 * functions to get appropriate value from matrix params from url
 */ 
getValueFromMatrixParam : function(paramName) {
    if (window.location.href.match(paramName + "=")) {
        var urlFromParamValueTillTheEnd = window.location.href.split(paramName + "=")[1];
        var urlFromParamValueWithoutHash = urlFromParamValueTillTheEnd.split("#")[0];
        return decodeURIComponent(urlFromParamValueWithoutHash.substring(0, urlFromParamValueWithoutHash.indexOf(";") == -1?urlFromParamValueWithoutHash.length: urlFromParamValueWithoutHash.indexOf(";")));
    } else return "";
},

getCheckedFromMatrixParam : function(paramName, value) {
    if (value != null && window.location.href.match(paramName + "=" + value)) {
        return true;
    } else if (value == null && window.location.href.match(paramName + "=")) {
        return true
    } else {
        return false;
    } 
},

getCheckedIdFromMatrixParam : function(paramName, fieldIdPrefix, fieldIdPostfix) {
    if (window.location.href.match(paramName + "=")) {
        if (window.location.href.match(paramName + "=Y")) {
            return (fieldIdPrefix + 'Y' + fieldIdPostfix);
        } else if (window.location.href.match(paramName + "=N")) {
            return (fieldIdPrefix + 'N' + fieldIdPostfix);
        }
    } else {
        return (fieldIdPrefix + 'NULL' + fieldIdPostfix);
    }
},

/**
 * functions to create matrix params based on values
 */ 
createMatrixParamFromValue : function(paramName, fieldId, value) {
    if (fieldId != null && dojo.byId(fieldId) != null && dojo.byId(fieldId).value != null && dojo.byId(fieldId).value.length != 0) {
        return (';' + paramName + '=' + encodeURIComponent(dojo.byId(fieldId).value));
    } else if (value != null && value.length != 0) {
        return (';' + paramName + '=' + encodeURIComponent(value));
    } else return "";
},

createMatrixParamFromCheckBox : function(paramName, fieldId, value) {
    if (fieldId != null && dojo.byId(fieldId) != null && dojo.byId(fieldId).checked) {
        return (';' + paramName + '=' + encodeURIComponent((value != null)?value:"Y"));
    } else return "";
},

createMatrixParamFromRadio : function(paramName, fieldIdPrefix, fieldIdPostfix) {
    var val;
    if (dojo.byId(fieldIdPrefix + 'N' + fieldIdPostfix) && dojo.byId(fieldIdPrefix + 'N' + fieldIdPostfix).checked) {
        val = 'N';
    } else if (dojo.byId(fieldIdPrefix + 'Y' + fieldIdPostfix) && dojo.byId(fieldIdPrefix + 'Y' + fieldIdPostfix).checked) {
        val = 'Y';
    } else return "";
    return (';' + paramName + '=' + val);
},

/**
 * function to set hash, if desired, stays on page position before changing the hash
 */ 
setHash : function(newHash, keepYScroll) {
    var scrOfY = 0;
    if( typeof( window.pageYOffset ) == 'number' ) {
        //Netscape compliant
        scrOfY = window.pageYOffset;
    } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
        //DOM compliant
        scrOfY = document.body.scrollTop;
    } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
        //IE6 standards compliant mode
        scrOfY = document.documentElement.scrollTop;
    }
    if (newHash == "") {
        newHash = "#";
    }
    window.location.hash = newHash;
    if (keepYScroll) {
        window.scroll(0, scrOfY);
    }
},

/**
 * adds subview to hash, separated by comma, gets rid of all subviews from hash containing expression from subviewToGedRidOf field items, keeps scroll
 */ 
addSubviewToHash : function (subview, subviewsToGetRidOf) {
    var hash = window.location.hash;
    if (subviewsToGetRidOf) {
        if (!dojo.isArray(subviewsToGetRidOf)) {
            subviewsToGetRidOf = [ subviewsToGetRidOf ];
        }
        var subviews = hash.split(',');
        dojo.forEach(subviews, function(s) {
            dojo.forEach(subviewsToGetRidOf, function(sToDel) {
                if (s.match(sToDel)) {
                    if (hash.match(s + ',') != null) s = s + ',';
                    hash = hash.replace(s, '');
                    if (hash.charAt(hash.length - 1) == ',') {
                        hash = hash.substring(0, hash.length - 1);
                    }
                }
            });
        });
    }
    if (hash == '' || hash == '#') {
        redrata.util.setHash('#' + subview);
        return;
    }
    if (hash.match(subview) == null) {
        redrata.util.setHash(hash + ',' + subview, true);
    } else {
        redrata.util.setHash(hash, true);
    }
},

/**
 * deletes subview from hash, separated by comma, gets rid of all subviews from hash containing expression from subviewToGedRidOf field items, keeps scroll
 */
deleteSubviewFromHash : function(subview, subviewsToGetRidOf) {
    redrata.util.setHash(redrata.util.deleteSubviewFromString(window.location.hash, subview, subviewsToGetRidOf), true);
},

/**
 * deletes subview string, subview are separated by comma, gets rid of all subviews from hash containing expression from subviewToGedRidOf field items, returns modified string
 */
deleteSubviewFromString : function(string, subview, subviewsToGetRidOf) {
    var hash = string;
    if (subview != "" && hash.match(subview + ',') != null) subview = subview + ',';
    hash = hash.replace(subview, '');
    if (hash.charAt(hash.length - 1) == ',') {
        hash = hash.substring(0, hash.length - 1);
    }
    if (subviewsToGetRidOf) {
        if (!dojo.isArray(subviewsToGetRidOf)) {
            subviewsToGetRidOf = [ subviewsToGetRidOf ];
        }
        var subviews = hash.split(',');
        dojo.forEach(subviews, function(s) {
            dojo.forEach(subviewsToGetRidOf, function(sToDel) {
                if (s.match(sToDel)) {
                    if (hash.match(s + ',') != null) s = s + ',';
                    hash = hash.replace(s, '');
                    if (hash.charAt(hash.length - 1) == ',') {
                        hash = hash.substring(0, hash.length - 1);
                    }
                }
            });
        });
    }
    return hash;
},

/**
 * scrolls into node view, currently usin default js implementation ...
 * @Peter replace with whatever implementation u wanna have ...
 */
scrollIntoView : function(node) {
    node.scrollIntoView();
},

/**
 * highlights element identified by id by applying given class for given period
 * if scrollIntoView set to true, also scrolls into view of element identified by id
 */
highlightId : function(id, scrollIntoView, clzzz, period) {
    if (!id || !dojo.byId(id)) {
        console.error("No such id " + id);
        return;
    }
    if (!clzzz) {
        clzzz = 'rr-subview-manager-highlight';
    }
    if (!period) {
        period = 1000;
    }
    dojo.query('#' + id).addClass(clzzz);
    setTimeout(function() {dojo.query('#' + id).removeClass(clzzz)}, period);
    if (scrollIntoView) {
        redrata.util.scrollIntoView(dojo.byId(id));
    }
},

/** 
 * finds the uri part in the location header that contains the ci item type and its oid, e.g. email-93736 
 */
extractCiUriPartFromLocationUri : function(location) {
    if (!location) {
        return;
    }
    var elements = location.split("/");
    for (var i=0; i<elements.length; i++) {
        if ((elements[i].indexOf("email-") == 0) || (elements[i].indexOf("message-") == 0) || (elements[i].indexOf("todo-list-") == 0)) {
            return elements[i];
        }
    }
},

/** 
 * selects all contents of textfield defined by id
 */
selectAllContentsOfTextfield : function(id) {
    if (dojo.byId(id)) {
        dojo.byId(id).focus();
        dojo.byId(id).select();
    }
},

/** 
 * extracts the oid from either the location header or the partial uri (see: redrata.util.extractCiUriPartFromLocationUri)
 */
extractCiIdFromLocationUri : function(location, isPartialUri) {
    if (!isPartialUri) { // delegate to extract the partial uri
        location = redrata.util.extractCiUriPartFromLocationUri(location);
    }
    if (!location) return;
    return location.substr(location.lastIndexOf("-") + 1, location.length);
},

/**
 * creates array from object and returns it
 */
createArrayFromObject : function(object) {
    if (object == null) {
        return [];
    } else
    if (!dojo.isArray(object)) {
        return [object];
    } else {
        return object;
    }
},

/**
 * replaces every occurence of key by value in string or field of strings
 */
replaceAttribute : function(str, key, value) {
    if (str == null) {
        return null;
    }
    var regexp = new RegExp(key,"g");
    if (!dojo.isArray(str)) {
        return str.replace(regexp, value);
    } else {
    	var a = [];
        dojo.forEach(str, function(s, index, array) {
            a[index] = s.replace(regexp, value);
        });
        return a;
    }
},

/**
 * returns field of conversation items ids which are on page
 */ 
getIdsOfCisOnPage : function() {
	var cis = dojo.query(".rrca-conversation-item");
	var ids = [];
	dojo.forEach(cis, function(s, index, array) {
        ids[index] = s.id.split("-")[s.id.split("-").length - 1];
    });
	return ids;
},

/**
* returns caret position of focused element
*/ 
getCaretPosition : function(focusedEl) {
	var caretPos = 0;
	try {
    	if (focusedEl != null) {
    		if (document.selection) {// IE Support
    			focusedEl.focus();
    			var sel = document.selection.createRange();
    			sel.moveStart ('character', -ctrl.value.length);
    			caretPos = sel.text.length;
    		}
    		else if (focusedEl.selectionStart || focusedEl.selectionStart == '0') { // Firefox support
    			caretPos = focusedEl.selectionStart;
    		}
    	}
	} catch(err) {}
	return caretPos;
},

/**
* sets caret position of focused element
*/ 
setCaretPosition : function(focusedEl, pos){
	if (focusedEl != null) {
	    try {
    		if(focusedEl.setSelectionRange)
    		{
    			focusedEl.focus();
    			focusedEl.setSelectionRange(pos,pos);
    		}
    		else if (focusedEl.createTextRange) {
    			var range = focusedEl.createTextRange();
    			range.collapse(true);
    			range.moveEnd('character', pos);
    			range.moveStart('character', pos);
    			range.select();
    		}
	    } catch(err) {}
	}
},

/**
 * sometimes after we submit form, we want it to go away and display message, this function hides the form identified by formId, clears its values (if desired) and displays message
 */
formToMessage : function(formId, messageId, messageHTML, clearForm, idsToExclude) {
	var form = dojo.byId(formId);
	var message = dojo.byId(messageId);
	if (!form || !message) {
		console.log('There is no element with ' + formId + ' id.');
		return;
	}
	if (clearForm) {
		redrata.util.clearFormFields(formId, idsToExclude);
	}
	if (messageHTML) {
	    message.innerHTML = messageHTML;
	}
	dojo.addClass(form, 'rr-is-hidden');
	dojo.removeClass(message, 'rr-is-hidden');
},

/**
 * if you call dojo.behavior.add multiple times using the same selector, you get multiple events. this can happen, e.g. if we add behaviors when the document changes. This method helps us adding the event handlers more than once. by us passing in a unique key. We will only add the event handlers if we have not seen this unique key before on this page. Using dojo.behavior.add? chance that the dojo.behavior.add code can be called more than once? e.g. after a doc refresh or in a rr-on-resource-load-js block? Then use redrata.util.addBehavior instead. That will just check we have not already added the behavior yet (quick return) else call dojo.behavior.add
 */
addBehavior : function(uniqueKey, /** array of selector to actions. same as per dojo.behavior.add */
mappedValues) {
    if (!redrata.behaviorSingleton) {
        redrata.behaviorSingleton = {};
    }
    if (redrata.behaviorSingleton[uniqueKey]) {
        //redrata.logging.log(uniqueKey, "ALREADY IN", true);
        return;
    }
    redrata.behaviorSingleton[uniqueKey] = uniqueKey;
    dojo.behavior.add(mappedValues);
    var a = dojo.behavior.apply();
    //redrata.logging.log(uniqueKey, "ADDED BEHAVIOR", true);
    return a;
},

/**
 * executes js contents of query for selector + .rr-on-resource-load-js
 */
executeOnResourceLoadJS : function(underThisSelector) {
    var scripts = dojo.query((underThisSelector ? underThisSelector : "") + " .rr-on-resource-load-js");
    if (scripts.length == 0) {
        return;
    }
    dojo.forEach(scripts, function(script) {
        var somejavascript = dojo.eval(redrata.util.trimCDATA(redrata.util.trimJSScriptTag(script.innerHTML)));
        if (somejavascript && typeof (somejavascript) == "function") {
            somejavascript();
        }
        if (somejavascript && somejavascript.init && typeof (somejavascript.init) == "function") {
            somejavascript.init();
        }
    });
}, 

/**
 * executes js contents of query for selector + .rr-on-resource-load-js and applies behavior
 */
onPageContentHasChanged : function(underThisSelector) {
    redrata.util.executeOnResourceLoadJS(underThisSelector);
    dojo.behavior.apply();
},

/**
 * sends a ajax request, if sucessful fires AjaxSuccessEvent, method successCallBack can be used for optional handling 
 */
doAjaxRequest : function(url, method, requestOptions, responseHandlingOptions) {
    requestOptions = dojo.mixin({
        formId /* optional (if submit of a form) */ : null,
        acceptType : "application/json",
        isSync : false,
        contentType : "application/x-www-form-urlencoded"
        
    }, requestOptions);
    responseHandlingOptions = dojo.mixin({
    }, responseHandlingOptions);
    if(responseHandlingOptions.formidprefix ==null && requestOptions.formId!=null && requestOptions.formId.match('rrid-ajax-form-') != null) {
        responseHandlingOptions.formidprefix = requestOptions.formId.substring('rrid-ajax-form-'.length);
    }
    if(responseHandlingOptions.messageDivSelector==null && requestOptions.formId!=null) {
        var selector = "#"+requestOptions.formId + " .rr-feedback-message";
        var ele = dojo.query(selector);
        if(ele && ele[0]) {
            responseHandlingOptions.messageDivSelector = selector;
        }
    }

    // preliminary checks
    if (typeof url !== 'string' || typeof method !== 'string') {
        console.warn('Ajax Call Aborted: At least one of the required paramters url and method has not been supplied or is of a wrong type.');
        return;
    }
    
    dojo.query('.rr-error-placeholder, .rr-error-message').forEach(dojo.empty);

    var html_headers = {
    "Accept" : requestOptions.acceptType,
    "Content-Type" : requestOptions.contentType,
    // rob->bry this is intended to address the double-message problem (message from local and the same message from server).
    // The RR-Id is sent as an html header to the server and gets returned as a response header in the dwr sent onajaxsuccessmessage.
    // It would be helpful of all ajax requests could go through a single method (there are currently several places).
    "RR-Id" : redrata.sid
    };

    var o = {
    url : url,
    sync : requestOptions.isSync,
    load : function(payload, data) {
        redrata.messagebus.fireAjaxSuccessEvent(new redrata.onajaxsuccessmessage( {
        formSelector : requestOptions.formId ? '#' + requestOptions.formId : null,
        method : method.toUpperCase(),
        messageDivSelector : responseHandlingOptions.messageDivSelector,
        resourceURL : url,
        xhr : data.xhr
        }));
        if (responseHandlingOptions.successCallBack) {
            responseHandlingOptions.successCallBack(payload);
        }
    },
    error : function(msg, error) {
        if (error.xhr.status == 0) {
            return;
        }
        if (redrata.util.parseXHRAndHandleJaxRSResponse(error.xhr, responseHandlingOptions)) {
            return;
        }
    	new redrata.feedBackLayer( {  
			message : "There was an error while performing this operation.",
			isError : true 
		});
    },
    headers : html_headers
    };

    // make it a form submit, otherwise a regular ajax call
    if (requestOptions.formId) {
        o.form = requestOptions.formId;
    }

    if (method.toUpperCase() == 'GET') {
        dojo.xhrGet(o);
    } else {
        dojo.xhr(method, o, true);
    }
},

/**
 * sends a ajax request via doAjaxRequest, useful when submitting a form
 */
doFormAjax : function(formId, method, requestOptions, responseHandlingOptions) {
    var form = dojo.byId(formId);

    if (!form) {
        console.warn('Ajax Call Aborted: There is no form with the given id.');
        return;
    }
    if(responseHandlingOptions==null) {
        responseHandlingOptions = {};
    }
    if(responseHandlingOptions.messageDivSelector==null) {
        var selector = "#"+formId + " .rr-feedback-message";
        var ele = dojo.query(selector);
        if(ele && ele[0]) {
            responseHandlingOptions.messageDivSelector = selector;
        }
    }

    // delegate
    redrata.util.doAjaxRequest(form.action, method, requestOptions, responseHandlingOptions);
},

/**
 * parses xhr and creates and return jaxrs_response
 */
getJaxRSResponseFromXHR : function(xhr) {
    if (!xhr) {
        console.warn('error, no xhr');
        return null;
    }
    if (xhr.xhr) {
        // e.g. if we passed in 'data' from load then we really want data.xhr
        xhr = xhr.xhr;
    }
    var ct = xhr.getResponseHeader("Content-Type");
    if (!xhr.responseText || !(ct && ct.indexOf("application/json") != -1)) {
        return null;
    }
    var response = dojo.eval("(" + xhr.responseText + ")");
    if (response.validation_errors) {
        response.jaxrs_response = {
        response_type : "ERROR",
        human_readable_message : "There were validation errors.",
        payload : {
            validation_errors : response.validation_errors
        }
        };
    }
    return response.jaxrs_response;
},

/**
 * does exactly those things after which it was named :)
 */
parseXHRAndHandleJaxRSResponse : function(xhr, responseHandlingOptions) {
    var jaxrsResponse = redrata.util.getJaxRSResponseFromXHR(xhr);
    if (!jaxrsResponse)
        return false;
    redrata.util.handleJaxRSResponse(jaxrsResponse, responseHandlingOptions);
    return true;
},

/**
 * handles jaxrs response
 */
handleJaxRSResponse : function(/** jaxrsresponse json object */
jaxr, /** string */
responseHandlingOptions
) {
    responseHandlingOptions = dojo.mixin({
        successCallBack : null,
        formidprefix : "", 
        feedbackmessage : null, /** instance of a feedbackmessage object */ 
        isHumanReadableMessageDisplayed : true,
        scrollFeedbackMessageIntoView : null,
        setFocusOnErrorField : true,
        messageDivSelector : null
    }, responseHandlingOptions);
    var msg = jaxr.human_readable_message ? jaxr.human_readable_message : "ERROR" == jaxr.response_type ? "Error" : "OK";
    if (responseHandlingOptions.feedbackmessage == null) {
        responseHandlingOptions.feedbackmessage = new redrata.feedbackmessage( {messageDivSelector : responseHandlingOptions.messageDivSelector});
    }
    if (jaxr.payload) {
        dojo.forEach(jaxr.payload.validation_errors, function(item) {
            var errMsgEle = dojo.byId(responseHandlingOptions.formidprefix + "errif" + item.field_name);
            if (errMsgEle) {
				responseHandlingOptions.inputId = responseHandlingOptions.formidprefix + "if" + item.field_name;
				// dojo.addClass(errMsgEle,
				// 'rr-error-message');
				redrata.formValidationMessage( {
					message : item.human_readable_message,
					inputId : responseHandlingOptions.formidprefix + "if"+ item.field_name
				});
				// dojo.attr(errMsgEle, "innerHTML",
				// item.human_readable_message);
            } else {
                // for fields where we can't find an input element, add to overall form message.
                if (msg) {
                    msg += "  ";
                }
                msg += item.full_error_message;
                new redrata.feedBackLayer({  
                	message : msg,
                	isError : "ERROR" == jaxr.response_type 
                });
            }
        });
        // set focus to the field with the first validation error
        if(jaxr.payload.validation_errors && jaxr.payload.validation_errors.length > 0 
            && (responseHandlingOptions.setFocusOnErrorField==null || responseHandlingOptions.setFocusOnErrorField)) {
            // e.g. on err mesg span id='v2order-errifserver_label'
            // e.g. on whole input id='rrid-input-whole-v2order-server_label
            var field_name = jaxr.payload.validation_errors[0].field_name;
            field_name = '#rrid-input-whole-'+responseHandlingOptions.formidprefix+ field_name+" * .rr-input-edit-controls";
            var els = dojo.query(field_name);
            if(els && els.length > 0 ) {
                els[0].focus();
                // no preference?  Then we'll say, no don't scroll into view, keep it on the focussed element
                if(responseHandlingOptions.scrollFeedbackMessageIntoView ==null) {
                    responseHandlingOptions.scrollFeedbackMessageIntoView = false;
                }
            }
        }

    }
    
    if (responseHandlingOptions.isHumanReadableMessageDisplayed && responseHandlingOptions.feedbackmessage != null) {
    	if("ERROR" == jaxr.response_type){
			new redrata.feedBackLayer({  message : msg,isError : true});
		}
		
    	//console.log(responseHandlingOptions);
    	/*
    	redrata.formValidationMessage( { 
    		message : msg,
			inputId : responseHandlingOptions.inputId,
			delay : 3000,
			isFormMsg:true
		})
		*/
        //responseHandlingOptions.feedbackmessage.setMessage(msg, "ERROR" == jaxr.response_type, jaxr.response_display_duration_type, {scrollFeedbackMessageIntoView : responseHandlingOptions.scrollFeedbackMessageIntoView});
    }
},

/**
 * called when page is loaded/reloaded, shows/hides things based on the hash ... this handles when we have subview open, that it stays open after reload
 */
initViewToggle : function() {
    if (window.location.hash.match('edit-view') != null) {
        dojo.query('.rr-read-only-view').addClass('rr-is-hidden');
        dojo.query('.rr-edit-view').removeClass('rr-is-hidden');
    } else {
        dojo.query('.rr-edit-view').addClass('rr-is-hidden');
        dojo.query('.rr-read-only-view').removeClass('rr-is-hidden');
    }
    var subviewName = window.location.hash.replace("edit-view","");
    subviewName = subviewName.replace("#","");
    var subviews = subviewName.split(',');
    dojo.forEach(subviews, function(subview) {
          //general handling
          dojo.query('.rr-' + subview + '-subview-div').removeClass('rr-is-hidden');
          dojo.query('.rr-' + subview + '-subview-hide-div').addClass('rr-is-hidden');
          //special handlings 4 subviews, only the case when we use class other that rr-is-hidden in switchers
          if ((window.location.href.match("needing-work") || window.location.href.match("inbox") ||  
        		  window.location.href.match("conversation-items") ||  
        		  window.location.href.match("-in-progress-items") || window.location.href.match("-finished-items") ||
        		  window.location.href.match("in-progress")  || window.location.href.match("my-tasks") || 
        		  window.location.href.match("unassigned")) 
        		  && subview.match("edit-attribs-")) { //hackie hack
              dojo.query('#rrcaid-attribs-for-' + subview.split("-")[2]).addClass('rrca-item-attribs');
          } 
          if (subview.match("no-filter-view")) { //hackie hack 2
              dojo.query('#rrcaid-conversation-display').removeClass('grid_9');
              dojo.query('#rrcaid-conversation-display').addClass('grid_12');
              dojo.query('#rrcaid-widget-bar-attribs-conversation').removeClass('grid_9');
              dojo.query('#rrcaid-widget-bar-attribs-conversation').addClass('grid_12');
          }
          if (subview.match("details")) {
              var id = subview.split('-')[1];
              dojo.query('#rrcaid-to-flow-over-' + id).removeClass('rrca-message-size-changer');
          }
          //function handling, when we have appropriate function for subview, we call it
          var functionName = subview.split('-')[0] + "SubviewFunction";
          var functionParam = subview.split('-').length > 1 ? subview.split('-')[1] : "no param";
          if (typeof window[functionName] == "function") {
              window[functionName](functionParam);
          }
    });
    if (window.location.hash.match('newMessage-fullscreen')) {
        dojo.query('.rrca-new-resource-creator').addClass('rr-is-fullscreen');
        dojo.query('body').addClass('rrca-remove-scroll');
    }
},

/**
 * uploads a file from input type file
 */
uploadFile : function(formId, url) {
    dojo.io.iframe.send( {
    contentType : "multipart/form-data",
    url : url,
    form : formId,
    handleAs : "json",
    handle : function(response, ioArgs) {
        redrata.util.handleJaxRSResponse(response.jaxrs_response, { feedbackmessage : new redrata.feedbackmessage( {
            messageDivSelector : '#rrid-ajax-form-feedback-message-image'
        })});
        if (response.jaxrs_response.response_type == "OK") {
            redrata.util.deleteSubviewFromHash("attrib-image", null);
            window.location.reload();
        }
    }
    });
},

/**
 *  clears a form's input fields as well as its associated error messages.
 */
clearFormFields : function(formId, idsToExclude) {
    if (!(typeof formId === 'string' && formId.length != 0)) {
        console.warn('parameter has to be a non-empty string!')
        return;
    }
    if (formId.indexOf('#') == 0 && formId.length > 1) {
        formId = formId.substring(1);
    }
    var form = dojo.byId(formId);
    if (!form) {
        console.warn('Form with id ' + formId + ' not found.');
        return;
    }
    dojo.query('input, textarea', formId).forEach(function(node) {
        var isExcluded = false;
        dojo.forEach(idsToExclude, function(idToExclude) {
            if (node.id == idToExclude) {
                isExcluded = true;
            }
        });
        if (!isExcluded && node.type != 'hidden' && node.type != 'button') {
            node.value = "";
        }
    });
    dojo.query('.rr-error-placeholder, .rr-error-message', formId).forEach(dojo.empty);
    dojo.query('.rr-feedback-message.rr-error-message', formId).forEach(function(node) {
        //node.className = "rr-error-message rr-is-hidden";
        node.removeClass('rr-error-message');
        node.innerHTML = "";
    });
},

/**
 *  adjusts text area by redrata constants
 */
adjustTextAreaByRedrataConstants: function(textarea) {
    redrata.util.adjustTextArea(textarea, redrata.constants.get('MAIL_TEXT_AREA_MIN_ROWS'), 
                redrata.constants.get('MAIL_TEXT_AREA_MIN_COLS'), 
                redrata.constants.get('MAIL_TEXT_AREA_MAX_ROWS'),
                redrata.constants.get('MAIL_TEXT_AREA_MAX_COLS'),
                redrata.constants.get('MAIL_TEXT_AREA_STEP'));
},

/**
 *  adjusts text area by function parameters
 */
adjustTextArea: function(textarea, minRows, minCols, maxRows, maxCols, step) {
    var lines = textarea.value.split("\n");
    var linesCount = lines.length;
    var maxChars = 0;
    dojo.forEach(lines, function(line) {
        maxChars = line.length> maxChars? line.length: maxChars;
    });

    if (linesCount > minRows - step) {
        textarea.rows = (linesCount > maxRows - step)? maxRows : linesCount + step;
    } else {
        textarea.rows = minRows;
    }

    if (maxChars > minCols - step) {
        textarea.cols = (maxChars > maxCols - step)? maxCols : maxChars + step;
    } else {
        textarea.cols = minCols;
    }
},

/**
 *  inserts quicktext (string) to textarea at cursor position
 */
insertQuickText: function(textAreaId, quickText) {
    quickText = quickText.replace(/double-quote/g, "\"");
    var textArea = dojo.byId(textAreaId);
    var scrollTop = textArea.scrollTop;
    if (document.selection) {
        textArea.focus();
        sel = document.selection.createRange();
        sel.text = quickText;
        textArea.focus();
    }
    else if (textArea.selectionStart || textArea.selectionStart == '0') {
        var startPos = textArea.selectionStart;
        var endPos = textArea.selectionEnd;
        textArea.value = textArea.value.substring(0, startPos) + quickText + textArea.value.substring(endPos, textArea.value.length);
        textArea.focus();
        textArea.scrollTop = scrollTop;
        textArea.selectionStart = startPos + quickText.length;
        textArea.selectionEnd = startPos + quickText.length;
    } else {
        textArea.value += quickText;
        textArea.focus();
    }
},

/**
 *  enables form
 */
enableForm : function(ajaxform) {
    if (ajaxform != null) {
        ajaxform.isSaving = false;
        ajaxform.setFormEnabled(true);
        dojo.query(ajaxform.formSelector).removeClass('rr-request-being-processed');
    }
},

/**
 *  searches up the dom tree from an element node and finds the correct parent element
 */
getParentNode : function(itemNode, parentclass) {
    if (itemNode == null) {
         return null;
    } else if (dojo.hasClass(itemNode,parentclass)) {
        return itemNode;
    } else {
        return redrata.util.getParentNode(itemNode.parentNode, parentclass);
    }
},

/**
 *  inserts payload to element, preserves values, focus and caret if possible, outputs feedback message
 */
insertPayload : function(elementInWhichToInsertResultSelector, payload, onajaxsuccessmessage, ajaxform) {
    var myValues = {};
    if(!elementInWhichToInsertResultSelector) {
        return;
    }
    var items = dojo.query(elementInWhichToInsertResultSelector);
    var element = items && items[0] ? items[0] : null;
    if(items && items.length>1) {
        console.error("got multiple elements for " + elementInWhichToInsertResultSelector);
        return;
    }
    if (!element) {
        console.error("no such element as " + elementInWhichToInsertResultSelector);
        return;
    }

    for (var index in redrata.defaultValues) {
        if (dojo.query(elementInWhichToInsertResultSelector + ' #' + index).length == 0) continue;
        var v = redrata.defaultValues[index].attrib == "value"? dojo.byId(index).value : dojo.byId(index).checked;
        myValues[index] = new redrata.defaultValue({attrib: redrata.defaultValues[index].attrib, value : v});
    }
    var caretPos = 0;
    var focusedEl = dojo.byId(redrata.focus);
    if (focusedEl != null) {
        caretPos = redrata.util.getCaretPosition(focusedEl);
    }
    
    var preservedElements = {};
    dojo.query(elementInWhichToInsertResultSelector  + ' .rr-preserve-content-on-ajax-reload').forEach(function(item) {
        preservedElements[item.id] = item.innerHTML;
    });
    
    dojo.attr(element, "innerHTML", payload);
    
    for (var index in preservedElements) {
        dojo.byId(index).innerHTML = preservedElements[index];
        /*for (var id in redrata.defaultValues) {
            if (dojo.query('#' + index + ' #' + id).length == 0) continue;
            redrata.defaultValues[id].attrib == "value"? (dojo.byId(id).value = redrata.defaultValues[id].value) : (dojo.byId(id).checked = redrata.defaultValues[id].value);
        }*/
    }

    for (var index in myValues) {
        var el = dojo.byId(index);
        if (el == null) {
            continue;
        }
        var newValue = myValues[index].attrib == "value"? el.value : el.checked;
        if (!onajaxsuccessmessage.isLocal && newValue != redrata.defaultValues[index].value && redrata.util.getParentNode(el, 'rr-preserve-content-on-ajax-reload') == null) { 
            //new value came (by someone else) for field which we were modifiing and its different from previous value and its not encapsulated in element havin rr-preserve-content-on-ajax-reload class
            dojo.byId(index.replace('if', 'errif')).innerHTML = "Value of this field changed to '" + newValue + "'";
            dojo.addClass(dojo.byId(index.replace('if', 'errif')), "rr-error-message");
            redrata.defaultValues[index] = new redrata.defaultValue({attrib: myValues[index].attrib, value : newValue});
        }
        if (onajaxsuccessmessage.isLocal && (newValue == myValues[index].value || newValue == "")) { // added check for newValue == ""
            delete redrata.defaultValues[index]; //we delete default value of element in case of locally initiated reload and submitting the value
        }
        if (redrata.defaultValues[index] != null) { //only in case it still is in default values (touched fields)
            (myValues[index].attrib == "value") ? (el.value = myValues[index].value) : (el.checked = myValues[index].value);  //setting the value of field to the value before reload
        }
        if (el.type.match('textarea') != null) { //adjusting size of text area (if any)
            redrata.util.adjustTextAreaByRedrataConstants(el);
        }
    }

    redrata.util.onPageContentHasChanged(elementInWhichToInsertResultSelector);
    redrata.util.initViewToggle();
    var toFocus = dojo.byId(redrata.focus);
    if (toFocus != null && redrata.util.getParentNode(toFocus, 'rr-is-hidden') == null) {
        toFocus.focus();
        redrata.util.setCaretPosition(toFocus, caretPos);
    }
    var feedbackmessage = new redrata.feedbackmessage( {
        messageDivSelector : onajaxsuccessmessage.messageDivSelector
    });
    if (onajaxsuccessmessage.jaxRSResponse) {
        redrata.util.handleJaxRSResponse(onajaxsuccessmessage.jaxRSResponse, {feedbackmessage : feedbackmessage});
    }
    //if(ajaxform) {
      //  redrata.util.enableForm(ajaxform);
    //}
},

/**
 *  inserts payload to element, preserves values, focus and caret if possible
 */
insertPayloadForSubview : function(elementInWhichToInsertResultSelector, payload) {
    if(!elementInWhichToInsertResultSelector) {
        return;
    }
    var items = dojo.query(elementInWhichToInsertResultSelector);
    var element = items && items[0] ? items[0] : null;
    if(items && items.length>1) {
        console.error("got multiple elements for " + elementInWhichToInsertResultSelector);
        return;
    }
    if (!element) {
        console.error("no such element as " + elementInWhichToInsertResultSelector);
        return;
    }
    
    dojo.attr(element, "innerHTML", payload);
    
    redrata.util.onPageContentHasChanged(elementInWhichToInsertResultSelector);
    //redrata.util.initViewToggle();
},

//utility method, gets id, creates inline edit, return id
initInplaceEdit : function(evt) {
    var node = evt.target;
    while (true) {
        node = node.parentNode; 
        if (node.id && (node.id.match('rrid-inline-edit-widget') != null)) {
            break; 
        }
    }
    var id = node.id;
    if (!redrata.inplaceceditSingleton[id]) {
        redrata.inplaceceditSingleton[id] = new redrata.inplaceedit( {
            widgetSelector : "#" + id
        });
    }
    return id;
},

//utility method, gets id, creates ajaxForm, return id
initAjaxForm : function(evt) {
    var node = evt.target;
    while (true) {
        node = node.parentNode;
        if(node == null) {
            if(evt)
                dojo.stopEvent(evt);
            console.warn('source of the event ' + evt.target.id + " does not appear to be an ajax form.  Ignoring.");            
            return;
        }
        if (node.id && (node.id.match('rrid-ajax-form') != null || node.id.match('rrid-inline-edit-widget') != null)) {
            break; 
        }
    }
    var formId = node.id;
    // bry->fed TODO is this comment yours?  dont we need to leave it in to prevent mem leaks
    //if (!redrata.ajaxformSingleton[formId]) {
        redrata.ajaxformSingleton[formId] = new redrata.ajaxform( {
            formSelector : "#" + formId
        });
    //}
    if (evt)
        dojo.stopEvent(evt);
    return formId;
},

// basic feedback layer message redrata.util.feedBackMsg("hello :-)");
feedBackMsg : function(arg){
	new redrata.feedBackLayer( {  
		message : arg
	});
}
};

/** ************ADD ON LOAD **************************** */

dojo.addOnLoad(function() {
    if (typeof dwr != "undefined") {
        //dwr's reverse ajax is used to receive events from other pages via the server
        dwr.engine.setActiveReverseAjax(true);
    }
    //redrata.util.onPageContentHasChanged();
    redrata.util.initViewToggle();
    var elementsToBeFocused = dojo.query(".rrca-focus-on-load");
    if (elementsToBeFocused && elementsToBeFocused.length > 0) {
        elementsToBeFocused[0].focus();
    }
});

/** *****************INPLACEEDIT*********************** */

dojo.declare("redrata.inplaceedit", redrata.inplaceedit, {
constructor : function(arguments) {
    dojo.mixin(this, arguments);
    var inlineedit = this;

    var mappedValues = {};
    var s = inlineedit.widgetSelector + ' .rr-inline-edit-initiate-edit-op';
    var elems = dojo.query(s);
    
    if (!elems || elems.length == 0) {
        console.info("could not find the initiate edit link " + s + ". the inline editor may have been set to read only on purpose.");
    }
    
    /* not used anymore, now inplace edits are created dynamically
    mappedValues[s] = {
        onclick : function(evt) {
            inlineedit.showEditView(evt);
        }
    };
    
    mappedValues[inlineedit.widgetSelector + ' .rr-cancel-op'] = {
        onclick : function(evt) {
            inlineedit.showDisplayView(evt);
        }
    };

    redrata.util.addBehavior(inlineedit.widgetSelector + " inline edit widget", mappedValues);
    */
    inlineedit.showDisplayView();
},
showEditView : function(evt) {
    var inlineedit = this;
    if (evt)
        dojo.stopEvent(evt);
    redrata.util.addSubviewToHash(inlineedit.widgetSelector.replace("#rrid-inline-edit-widget-", ""), "attrib-");
    dojo.query(".rr-inline-edit-widget .rr-inline-edit-edit-view").addClass('rr-is-hidden');
    dojo.query(".rr-inline-edit-widget .rr-inline-edit-readonly-view").removeClass('rr-is-hidden');
    dojo.query(inlineedit.widgetSelector + ' .rr-inline-edit-readonly-view').addClass('rr-is-hidden');
    dojo.query(inlineedit.widgetSelector + ' .rr-inline-edit-edit-view').removeClass('rr-is-hidden');
    var inputs = dojo.query("#" + inlineedit.widgetSelector + " .rr-input-edit-controls");
    if (inputs != null && inputs.length != 0) {
        inputs[0].focus();
    }
    // stop # being changed
    //dojo.focus(inlineedit.widgetForm);
},
showDisplayView : function(evt) {
    // stop # being changed
    if (evt)
        dojo.stopEvent(evt);
    var inlineedit = this;
    /*dojo.query(inlineedit.widgetSelector + ' .rr-error-placeholder').forEach(function(item) {
        item.innerHTML = "";
        dojo.removeClass(item, "rr-error-message");
    });
    var inputField = dojo.query("#" + redrata.util.getParentNode(evt.target, 'rr-ajax-form').id + " .rr-input-edit-controls")[0];
    if (redrata.defaultValues[inputField.id] != null) {
        inputField.value = redrata.defaultValues[inputField.id];
        redrata.defaultValues[inputField.id] = null;
    } */
    redrata.util.deleteSubviewFromHash(inlineedit.widgetSelector.replace("#rrid-inline-edit-widget-", ""), null);
    dojo.query(inlineedit.widgetSelector + ' .rr-inline-edit-edit-view').addClass('rr-is-hidden');
    dojo.query(inlineedit.widgetSelector + ' .rr-inline-edit-readonly-view').removeClass('rr-is-hidden');
},
doCancel : function(evt) {
    var inlineedit = this;
    inlineedit.showDisplayView();
}
}); // InPlaceEdit class definition

/* auto-create inplaceedit objects for each .rr-inline-edit-widget */
/* not used anymore, now inplace edits are created dynamically
dojo.behavior.add( {
    '.rr-inline-edit-widget.rr-auto-instantiate' : {
        found : function(evt) {
            var id = evt.id; //FED:singleton added
            if (!redrata.inplaceceditSingleton) {
                redrata.inplaceceditSingleton = {};
            }
            if (redrata.inplaceceditSingleton[id]) {
                return;
            }
            redrata.inplaceceditSingleton[id] = id;
            new redrata.inplaceedit( {
                widgetSelector : "#" + id
            });
        }
    }
}); */

if (!redrata.inplaceceditSingleton) {
    redrata.inplaceceditSingleton = {};
}

redrata.util.addBehavior('inplace edit - initiate edit op', {
    '.rr-inline-edit-initiate-edit-op' : {
        onclick : function(evt) {
            redrata.inplaceceditSingleton[redrata.util.initInplaceEdit(evt)].showEditView(evt);
            }
        }
});

redrata.util.addBehavior('inplace edit - cancel edit op', {
    '.rr-inline-edit-initiate-cancel-op' : {
        onclick : function(evt) {
            redrata.inplaceceditSingleton[redrata.util.initInplaceEdit(evt)].showDisplayView(evt);
            }
        }
});

/** *************FEEDBACK MESSAGE************************** */
//message can be an info, error, or normal message
//new redrata.feedBackLayer( {  
//message : "There was an error while performing this operation.",
//don't add either of these for a normal
//isError : true         ------   for error message  
//isInfo : true          ------   for info message
//isPerm : true          ------   makes the message stay and a close button
//}); 


//as each message gets displayed it will overlap a new section of the html and make some things invisible this is bad when the message is a permanent message
//so im adding padding to the bottom of each body element and any other element that is fixed/fullscreen.
//is used for large elements and  there should only be one of that class/id on a page at a time
dojo.declare("redrata.messageHeight",redrata.messageHeight,{
	element: null,
	unit : "px",
	padding: 0,
	getValue : function(){
		if(dojo.query(this.element)[0]){
			var match = /padding\-bottom\:(.*)(px|em|%|pc);/i.exec(dojo.attr(this.element, "style")); 
			if(dojo.attr(this.element, "style") != null && dojo.attr(this.element, "style").search("padding\-bottom") != -1){
				this.padding = parseInt(match[1].replace(/^\s\s*/, '').replace(/\s\s*$/, ''));
				this.unit = match[2];
			}
		}
	},
	add : function(){
		if(dojo.query(this.element)[0]){
			this.getValue();
			this.padding = this.padding + 23;
			dojo.attr(this.element, "style","padding-bottom:"+this.padding+this.unit+";");
			return this;
		}
	},
	remove : function(){
		if(dojo.query(this.element)[0]){
			this.getValue();
			this.padding = this.padding - 23;
			dojo.attr(this.element, "style","padding-bottom:"+this.padding+this.unit+";");
		}
	},
	constructor : function(obj) {
		this.element = obj;
	}
	
});
                     
dojo.declare("redrata.feedBackLayer", redrata.feedBackLayer, {
	id : 0,
	message : 0,
	fadeOut : null,
	isError : false,
	isInfo : false,
	isPerm : false,
	expandHTML : null,
	Type : false,
	heights : new Array(),
	inputId : null,
	constructor : function(args) {
	//as each message gets displayed it will overlap a new section of the html and make some things invisible this is bad when the message is a permanent message
	//so im adding padding to the bottom of each body element and any other element that is fixed/fullscreen. which will allow more scrool room
	/*********************add new height changer here*****************/
	var bodyH = new redrata.messageHeight(dojo.query("body")[0]);
	var fullscreenReply = new redrata.messageHeight(dojo.query(".rr-is-fullscreen")[0]);
	function addPadding(){
		bodyH.add();
		fullscreenReply.add();
	}
	function removePadding(){
		bodyH.remove();
		fullscreenReply.remove();
	}
	///////////////////////////////////////////////////////////////////////////
	dojo.declare("redrata.colorPicker", redrata.colorPicker, {
		id:null,
		change : null,
		style : "background-color",
		w:"20px",
		h:"20px",
		colors : null,
		onClick : null,
		//func : null;
		constructor : function(args) {
			
			dojo.mixin(this, args);
			var colorObj = this;
			if(typeof this.colors != "object"){console.error("need at least one color set, set with parameter 'colors:[#color1,#color2,#color3]'");}
			
			for(var a in this.colors){
					var color = this.colors[a];
					if(typeof color != "function"){
					var b = dojo.create("span", { 
						style : "display:inline-block;width:"+colorObj.w+";height:"+colorObj.h+";background-color:"+color+";"
					},dojo.query(colorObj.id)[0], "last");
					dojo.query(b).addClass("rr-color-box")
					b.color = color;
					dojo.query(b).onclick(function(e){
						if(typeof colorObj.onClick == 'function'){
							colorObj.onClick(e.target.color);
						}
					});
				}		
			}
					
		} 
	});
	/*
	new redrata.colorPicker({
		id:".to-place-colors",
		style:"backgroundColor",
		change:".to-place-colors", 
		colors:["#ff00ff","#00ff00","#ff0000","#f0f0f0","#000fff","#22ef2a"]
	});
	new redrata.colorPicker({
		id:".to-place-colors",
		w:"60px",
		h:"60px",
		change:".to-place-colors",
		style:"color",
		colors:["#ff00ff","#00ff00","#ff0000","#f0f0f0","#000fff","#22ef2a"]
	});
	*/
	/*****************************************************************/
	var shortTime = 6000;
	var mediumTime = 9000;
	var longTime = 11000;
		dojo.mixin(this, args);
		var object = this;
		// main container
		
		var re3 = new RegExp(this.message,"gim");
		dojo.query(".rr-feedback-item").forEach(function(elem){
			if(re3.test(elem.innerHTML)){
				dojo.query(elem).addClass("rr-is-hidden");
			}
			
		});
		var messageDiv = dojo.create("div");
		// message icon type container
		
		var messageType = dojo.create("div",{
			style : "width:16px;" +
					"display:inline-block;" +
					"float:left;"
		});
		var classBuffer = "";
		if (this.isError){
			delay = mediumTime;
			dojo.query(messageDiv).addClass("rr-feed-back-error rr-msg-border");
			classBuffer = "rr-feed-back-error rr-layer-item";
		}else if(this.isInfo){
			delay = longTime;
			dojo.query(messageDiv).addClass("rr-feed-back-info-message rr-msg-border");
			classBuffer = "rr-feed-back-info-message rr-layer-item";
		}else{
			delay = shortTime;
			dojo.query(messageDiv).addClass("rr-feed-back-message rr-msg-border");
			classBuffer = "";
		}
		dojo.query(messageType).addClass("rr-item-type");
		var textDiv = dojo.create("div", { 
			innerHTML : this.message,
			style : "margin-right:120px;display:block;margin-left:20px;"
		}, messageDiv, "last");
		if(this.isPerm){
			dojo.query(dojo.create("a", {
				innerHTML : "close",
				style : "float:right;margin-right:30px;"
			}, messageDiv, "first")).addClass("").onclick(function(){
				this.fadeOut = dojo.fadeOut( {
					node : messageDiv,
					onEnd : function() {
						dojo.destroy(messageDiv);
						removePadding();
					}
				});
				this.fadeOut.play();
			});
		}
		if(this.expandHTML){
			var view = dojo.create("div", {
				innerHTML : this.expandHTML
			});
			dojo.query(view).addClass("rr-is-hidden");
			dojo.query(dojo.create("a", { 
				innerHTML : "Expand"
			}, messageDiv, "last")).onclick(function(e){
				dojo.toggleClass(dojo.query(view)[0], "rr-is-hidden");
			});
			dojo.place(view, textDiv, "after");
		}
		dojo.query(textDiv).addClass(classBuffer);
		dojo.query(messageDiv).addClass("rr-feedback-item");
		dojo.place(messageDiv, dojo.query(".rrca-message-layers")[0], "first");
		dojo.place(messageType, messageDiv, "first");
		addPadding();
		if(!this.isPerm){
			this.fadeOut = dojo.fadeOut( {
				node : messageDiv,
				delay : delay,
				onEnd : function() {
					dojo.destroy(messageDiv);
					removePadding();
				}
			});
			this.fadeOut.play();
		}
		return this;
	}
});

dojo.declare("redrata.formValidationMessage", redrata.formValidationMessage, {
	message : "",
	delay : 4000,
	fadeOut : null,
	inputId : null,
	event : null,
	constructor : function(args) {
		dojo.mixin(this, args);
		var obj = this;
		if (dojo.query(dojo.byId(obj.inputId + "-error-span")).length) {
			dojo.destroy(dojo.byId(obj.inputId + "-error-span"));
		}
		var position = "after";
		var positioningNode = dojo.byId(obj.inputId);
		
		var errorSpan = dojo.create("span", {
			id : obj.inputId + "-error-span",
			innerHTML : obj.message
		},positioningNode, position);
		dojo.query(errorSpan).addClass("rr-error-message");
			var event = dojo.connect(dojo.byId(obj.inputId), 'onkeyup',function(e) {
				thisEvent = event;
					dojo.query("#" + e.target.id + "-error-span").removeClass("rr-error-message").addClass("rr-error-better");
					var n = dojo.query("#" + e.target.id+ "-error-span");
					if(n && n[0])
					dojo.fadeOut({
						node : n[0],
						delay : obj.delay,
						onEnd : function() {
					        var o = dojo.query("#" + e.target.id+ "-error-span")[0];
					        if(o)
					            dojo.destroy(o);
						}
					}).play();
					dojo.disconnect(thisEvent);
			});
		
	}
});



dojo.declare("redrata.feedbackmessage", redrata.feedbackmessage, {
messageDivSelector : '.rr-feedback-message',
constructor : function(arguments) {
    var feedbackmessage = this;
    dojo.mixin(this, arguments);
    if (!feedbackmessage.messageDivSelector) {
        feedbackmessage.messageDivSelector = '.rr-feedback-message';
    }
},
setReloadMessage : function(msg, reloadIconDivId) {
    if (typeof(msg) !== 'string' || msg == null) {
        msg = 'The content of this page has changed. Please refresh the page to see the updated content.';
    }
    if (typeof(reloadIconDivId) === 'string' && reloadIconDivId.length > 0) {
        dojo.query('#' + reloadIconDivId).removeClass('rr-is-hidden');
    }
    this.setMessage(msg, false);
},
setInfoMessage : function(msg) {
    this.setMessage(msg, false);
},
setErrorMessage : function(msg) {
    this.setMessage(msg, true);
},
setMessage : function(msg, isError, response_display_duration_type, responseHandlingOptions) {
    var fm = this;
    if (!response_display_duration_type) {
        response_display_duration_type = 'PERMANENT';
    }
    var elements = dojo.query(fm.messageDivSelector);
    if (!elements || !elements[0])
        elements = dojo.query('.rr-feedback-message');
    if (!elements || !elements[0]) {
        console.error("could not find a feedback element" + fm.messageDivSelector);
        return;
    }
    var item = elements[0];
    {
        if (item.fadeOut) {
            item.fadeOut.stop();
        }
        if (item.fadeIn) {
            item.fadeIn.stop();
        }
        if (isError) {
            dojo.addClass(item, 'rr-error-message');
            dojo.removeClass(item, 'rr-info-message');
        } else {
            dojo.addClass(item, 'rr-info-message');
            dojo.removeClass(item, 'rr-error-message');
        }
        dojo.addClass(item, 'rr-feedback-message');
        //item.className = isError ? 'rr-error-feedback-message' : 'rr-info-feedback-message';
        item.style.opacity = '0.1';
        item.innerHTML = msg;
        //item.style.display = 'block';
        dojo.removeClass(item, 'rr-is-hidden');
        /* response_display_duration_type one of PERMANENT, REGULAR, SHORT */
        if ("PERMANENT" == response_display_duration_type) {
            item.fadeIn = dojo.fadeIn( {
            node : item,
            duration : 300
            });
            item.fadeIn.play();
            if(!responseHandlingOptions || responseHandlingOptions.scrollFeedbackMessageIntoView ==null || responseHandlingOptions.scrollFeedbackMessageIntoView) { 
                redrata.util.scrollIntoView(item);
            }
            return;
        }
        var fadeOutDelay = "REGULAR" == response_display_duration_type ? 20000 : 6000;
        item.fadeIn = dojo.fadeIn( {
        node : item,
        duration : 300,
        onStop : function() {
            this.isStopped = true;
        },
        onEnd : function() {
            if (this.isStopped) {
                return;
            }
            item.fadeOut = dojo.fadeOut( {
            node : item,
            delay : fadeOutDelay,
            onStop : function() {
                this.isStopped = true;
            },
            onEnd : function() {
                if (this.isStopped)
                    return;
                //item.style.display = 'none';
                dojo.addClass(item, 'rr-is-hidden');
                dojo.removeClass(item, 'rr-error-message');
                dojo.removeClass(item, 'rr-info-message');
                item.innerHTML = '';
            }
            });
            item.fadeOut.play();
        }
        });
        item.fadeIn.play();
        if(!responseHandlingOptions || responseHandlingOptions.scrollFeedbackMessageIntoView ==null || responseHandlingOptions.scrollFeedbackMessageIntoView) { 
            redrata.util.scrollIntoView(item);
        }
    }
}
});

/** *******************AJAX FORM********************************** */
dojo.declare("redrata.ajaxform", redrata.ajaxform, {
/* one of PUT, DELETE, POST, etc */
httpMethod : null,
headers : {
"Accept" : "application/json",
"Content-Type" : "application/x-www-form-urlencoded",
"RR-Id" : redrata.sid
},
constructor : function(arguments) {
    dojo.mixin(this, arguments);
    var ajaxform = this;

    ajaxform.formSelector = ajaxform.formSelector || '#rrid-ajax-form-' + ajaxform.prefix;
    {
        var elems = dojo.query(ajaxform.formSelector + " .rr-form-selector");
        if (elems && elems[0] && elems[0].value) {
            ajaxform.formSelector = elems[0].value;
        }
    }

    if (!ajaxform.httpMethod) {
        var elems = dojo.query(ajaxform.formSelector + " .rr-http-method");
        if (elems && elems[0] && elems[0].value) {
            ajaxform.httpMethod = elems[0].value;
        }
    }
    ajaxform.httpMethod = ajaxform.httpMethod || 'PUT';
    if (!ajaxform.url) {
        var elems = dojo.query(ajaxform.formSelector + " .rr-rest-url");
        if (elems && elems[0] && elems[0].value) {
            ajaxform.url = elems[0].value;
        }
    }
    if (!ajaxform.prefix) {
        var elems = dojo.query(ajaxform.formSelector + " .rr-form-fieldid-prefix");
        if (elems && elems[0] && elems[0].value) {
            ajaxform.prefix = elems[0].value;
        }
    }
    if (!ajaxform.messageDivSelector) {
        var elems = dojo.query(ajaxform.formSelector + " .rr-feedback-message-selector");
        if (elems && elems[0] && elems[0].value) {
            ajaxform.messageDivSelector = elems[0].value;
        }
    }
    ajaxform.messageDivSelector = ajaxform.messageDivSelector || '#rrid-ajax-form-feedback-message-' + ajaxform.prefix;
    /*do { //FED: commented out as no longer needed (likely)
        var mappedValues = {};
        mappedValues[ajaxform.formSelector + " .rr-ajax-submit-op"] = {
            onclick : function(evt) {
                if (evt)
                    dojo.stopEvent(evt);
                ajaxform.doSave(evt);
            }
        };
        mappedValues[ajaxform.formSelector] = {
        onsubmit : function(evt) {
            if (evt)
                dojo.stopEvent(evt);
            ajaxform.doSave(evt);
        },
        onkeypress : function(evt) {
            ajaxform.onFormKeyPress(evt);
        }
        };
        mappedValues[ajaxform.formSelector + " .rr-delete-op"] = {
            onclick : function(evt) {
                if (evt)
                    dojo.stopEvent(evt);
                ajaxform.doDelete(evt);
            }
        };
        redrata.util.addBehavior(ajaxform.formSelector + " ajax form", mappedValues);
    } while (false); */
    ajaxform.feedbackmessage = new redrata.feedbackmessage( {
        messageDivSelector : ajaxform.messageDivSelector
    });
},
setFormEnabled : function(isEnabled) {
    var ajaxform = this;
    var vals = dojo.query(ajaxform.formSelector + " .rr-ajax-submit-op");
    vals.forEach(function(item) {
        item.disabled = !isEnabled;
    });
},
getForm : function() {
    // using this getForm rather than storing the actual dom element, since the actual dom element 
    // that a given selector will return may change between document reloads.  (since we are re-inserting html).
    // and the symptom you'd see/saw was no form variables passed to the server side.  form contents ignored.
    var ajaxform = this;
    // #foobar form
    var elems = dojo.query(ajaxform.formSelector + ' form');
    if (elems && elems.length == 1) {
        return elems[0];
    }
    // form#foobar
    var elems = dojo.query('form' + ajaxform.formSelector);
    if (elems && elems.length == 1) {
        return elems[0];
    }
    console.error("could not figure out the form element for " + ajaxform.formSelector);
    return null;
},
/*onFormKeyPress : function(evt) {
    switch (evt.keyCode) {
    case dojo.keys.ENTER:
        // prevent an enter key doing an actual form post resulting in page changing.
        // rather we want the js handlers to handle things (with the only exception of text areas to be hable to have multiple lines)
        if (evt.target.type == 'textarea') {
            return;
        }
        dojo.stopEvent(evt);
        return false;
    }
},*/
doSave : function(evt, subviewName) {
	var waitOnActions = new redrata.onWait({
		target: evt.target,
		placementClass : "rr-for-onload",
		parentClass : "rr-onload-parent",
		addClass: "rr-load-action-css"
	});
	waitOnActions.start();
    if (evt)
        dojo.stopEvent(evt);
    var ajaxform = this;
    if (ajaxform.isSaving || ajaxform.isDeleting)
        return;
    ajaxform.setFormEnabled(false);
    ajaxform.isSaving = true;
    dojo.query(ajaxform.formSelector).addClass('rr-request-being-processed');
    //ajaxform.feedbackmessage.setInfoMessage("Saving...");
    
    var messagebus = redrata.messagebus;

    for (var i in messagebus.connections) {
        var isMatch = messagebus.connections[i].isMatch;

        if (isMatch(null, ajaxform.url, ajaxform.httpMethod)) {
            var init = messagebus.connections[i].init;
            init(ajaxform.url, ajaxform.httpMethod);
        }
    }
    
    var deferred = dojo.xhr(ajaxform.httpMethod, {
    url : ajaxform.url,
    form : ajaxform.getForm(),
    headers : ajaxform.headers,
    //contentType : ajaxform.headers["Content-Type"],
    load : function(payload, data, evt) {  
    	ajaxform.isSaving = false;
        ajaxform.setFormEnabled(true);
        dojo.query(ajaxform.formSelector).removeClass('rr-request-being-processed');
        dojo.query(ajaxform.formSelector + ' .rr-error-placeholder').forEach(dojo.empty);
        dojo.query(ajaxform.formSelector + ' .rr-error-placeholder').removeClass('rr-error-message');
        var loadData = eval('(' + payload + ')');
		new redrata.feedBackLayer( {  
			message : loadData.jaxrs_response.human_readable_message,
			isError : false  
		});
        if (redrata.util.parseXHRAndHandleJaxRSResponse(data.xhr, { formidprefix : ajaxform.prefix, feedbackmessage : ajaxform.feedbackmessage})) {
        } else {
            ajaxform.feedbackmessage.setInfoMessage("Saved");
        }
        redrata.messagebus.fireAjaxSuccessEvent(new redrata.onajaxsuccessmessage( {
        formSelector : ajaxform.formSelector,
        method : ajaxform.httpMethod,
        messageDivSelector : ajaxform.feedbackmessage.messageDivSelector,
        resourceURL : ajaxform.url,
        xhr : data.xhr
        }), ajaxform);
        if (subviewName != null) {
            redrata.util.deleteSubviewFromHash(subviewName); 
        }
    },
    error : function(type, error) {
        ajaxform.setFormEnabled(true);
        ajaxform.isSaving = false;
        dojo.query(ajaxform.formSelector).removeClass('rr-request-being-processed');
        dojo.query(ajaxform.formSelector + ' .rr-error-placeholder').forEach(dojo.empty);
        dojo.query(ajaxform.formSelector + ' .rr-error-placeholder').removeClass('rr-error-message');
        
        for (var i in messagebus.connections) {
            var isMatch = messagebus.connections[i].isMatch;

            if (isMatch(null, ajaxform.url, ajaxform.httpMethod)) {
                var err = messagebus.connections[i].error;
                err(ajaxform.url, ajaxform.httpMethod);
            }
        }
        
        if (redrata.util.parseXHRAndHandleJaxRSResponse(error.xhr, {formidprefix: ajaxform.prefix, feedbackmessage : ajaxform.feedbackmessage})) {
            return;
        }
    	new redrata.feedBackLayer( {  
			message : "There was an error while performing this update.",
			isError : true 
		});
    }
    }, true);
},
doDelete : function(evt) {
	var waitOnActionsDelete = new redrata.onWait({
		target: evt.target,
		placementClass : "rr-for-onload",
		parentClass : "rr-onload-parent",
		addClass: "rr-load-action-css"
	});
    var ajaxform = this;
    if (ajaxform.isDeleting || ajaxform.isSaving) {
        return;
    }
    ajaxform.isDeleting = true;
    ajaxform.setFormEnabled(false);
    ajaxform.feedbackmessage.setInfoMessage("Deleting...");
    dojo.query(ajaxform.formSelector).addClass('rr-request-being-processed');
    waitOnActionsDelete.start(); 
    var ajaxform = this;
    
    var messagebus = redrata.messagebus;
    for (var i in messagebus.connections) {
        var isMatch = messagebus.connections[i].isMatch;

        if (isMatch(null, ajaxform.url, ajaxform.httpMethod)) {
            var init = messagebus.connections[i].init;
            init(ajaxform.url, ajaxform.httpMethod);
        }
    }
    
    var deferred = dojo.xhrDelete( {
    url : ajaxform.url,
    load : function(payload, data) {
        ajaxform.setFormEnabled(true);
        ajaxform.isDeleting = false;
        dojo.query(ajaxform.formSelector).removeClass('rr-request-being-processed');
        redrata.messagebus.fireAjaxSuccessEvent(new redrata.onajaxsuccessmessage( {
        formSelector : ajaxform.formSelector,
        method : "DELETE",
        messageDivSelector : ajaxform.messageDivSelector,
        resourceURL : ajaxform.url,
        xhr : data.xhr
        }));
    },
    error : function(type, error) {
        ajaxform.isDeleting = false;
        ajaxform.setFormEnabled(true);
        dojo.query(ajaxform.formSelector).removeClass('rr-request-being-processed');
        
        for (var i in messagebus.connections) {
            var isMatch = messagebus.connections[i].isMatch;

            if (isMatch(null, ajaxform.url, ajaxform.httpMethod)) {
                var err = messagebus.connections[i].error;
                err(ajaxform.url, ajaxform.httpMethod);
            }
        }
        
        if (redrata.util.parseXHRAndHandleJaxRSResponse(error.xhr, {formidprefix : ajaxform.prefix, feedbackmessage : ajaxform.feedbackmessage})) {
            return;
        }
    	new redrata.feedBackLayer( {  
			message : "There was an error while performing this delete.",
			isError : true 
		});
    },
    headers : {
    "Accept" : "application/json",
    "RR-Id" : redrata.sid
    }
    });
}
}); // ajaxform class

/* auto-create inplaceedit objects for each .rr-inline-edit-widget  //FED: commented out as no longer needed (likely)
dojo.behavior.add( {
    '.rr-ajax-form.rr-auto-instantiate' : {
        found : function(evt) {
            var id = evt.id;
            if (!redrata.ajaxformSingleton) {
                redrata.ajaxformSingleton = {};
            }
            if (redrata.ajaxformSingleton[id]) {
                return;
            }
            redrata.ajaxformSingleton[id] = id;
            new redrata.ajaxform( {
                formSelector : "#" + id
            });
        }
    }
}); */

//FED: singleton
if (!redrata.ajaxformSingleton) {
    redrata.ajaxformSingleton = {};
}

//FED: behavior function for submit (for ajax forms submits)
redrata.util.addBehavior('initiate ajax form save', {
    '.rr-ajax-submit-op:not(.rr-inline-edit-submit-operation)': {
        onclick: function(evt) {
            redrata.ajaxformSingleton[redrata.util.initAjaxForm(evt)].doSave(evt);
        }
    }
});

//FED: behavior function for submit (for inline edit submits)
redrata.util.addBehavior('initiate inline edit form save', {
    '.rr-ajax-submit-op.rr-inline-edit-submit-operation': {
        onclick: function(evt) {
            var parent = redrata.util.getParentNode(evt.target, "rr-inline-edit-widget");
            if(!parent) {
                console.warn('no parent for ' + evt.target.id);
                if (evt) dojo.stopEvent(evt);                
                return;
            }
            var subviewName = parent.id.replace("rrid-inline-edit-widget-", "");
            redrata.ajaxformSingleton[redrata.util.initAjaxForm(evt)].doSave(evt, subviewName);
        }
    }
});

redrata.util.addBehavior('form_enterkey', {
    'form.rr-ajax-form': {
        onkeypress : function(evt) {
            if (evt.keyCode == dojo.keys.ENTER && evt.target.type != 'textarea') {
                var subviewName = null;
                if (dojo.hasClass(evt.target, "rr-input-edit-controls")) {
                    var parent = redrata.util.getParentNode(evt.target, "rr-inline-edit-widget");
                    if (parent != null) {
                        subviewName = parent.id.replace("rrid-inline-edit-widget-", "");
                    }
                }
                redrata.ajaxformSingleton[redrata.util.initAjaxForm(evt)].doSave(evt, subviewName);
            }
        } 
    }
});

//FED: behavior function for delete (general)
redrata.util.addBehavior('handle form delete', {
    '.rr-delete-op': {
        onclick: function(evt) {
            redrata.ajaxformSingleton[redrata.util.initAjaxForm(evt)].doDelete(evt);
        }
    }
});

/** *******************SUBVIEW MANAGER********************************** */

/*
ok, so we have subviewManager object ...

whats the purpose of this?

imagine beein on ci page, havin one ci expanded ... now we click reply link for that ci, reply form appears (it was 
there before, we just show it by removing rr-is-hidden of it) ... now when the page or frag gets reloaded, the reply 
form disappears again ... might be confusing, when workin and things are goin away without knowing why (dwr updates)
... so we need to store the states we are in somewhere ... things, which are different from when page gets loaded, 
i called them subviews ... like reply subview, edit-attribs subview etc ... so basically we need a mechanism dealin 
with showing, toggling, hiding things and storing the state ... and, dealin with dependencies ... think of when we 
have one ci open, we open reply form 4 it ... what should happen when we collapse that ci? of course also reply form 
goes away, but when we uncollapse ci, it is there, and it shouldnt ... so we need to hide reply subview as well ... and 
get rid of reply subview from hash as well ... so to define that reply subview is dependant on ci subview ... thats why we 
have subviewManager object, it deals with everything ... we shouldnt ever access (modify) the hash, if really needed, 
then use methods addSubviewToHash or deleteSubviewFromHash in redrata.util ... but try to use subviewManager everytime 
something is beein shown/hidden ...

the idea is to programatically define subviews, their names, what should be shown and what hidden (switchers) and 
dependencies ...
subviewManager object has these parameters ...

id -an id which binds particular subviewManager with particular link ... its also used as a key to field of 
subviewManager objects ...
switchers - field of switcher objects which have 3 attributes - criteria, action, class ... criteria should be 
valid js selecting criteria (#id or .class), action is either "add" or "remove" and class is classname which is 
added or removed from object(s) selected by criteria, if u dont state classname it would be rr-is-hidden
subviewName - name of subview which is beein shown and added to hash in case of shower or in case of hider beein hidden 
and deleted from hash
subviewsToGetRidOn - field of strings, all subviews containing those strings are beein removed from hash !!! 
remember that this deals only with removing subviews from hash, not hiding the subviews themselfs, u need to hide 
them in switchers section !!!
revertedShowing - false by default ... set to true only when subview means that ure hidin something, so even though we 
are in subview - add it to hash, we are actually hidin something, not showing 
(rare thing, we have only one, show/hide filter view on conversation page)
subviewFunction - default set to false, if u set it to true, after subview was created (all logic from switchers applied and
hash modified), we also try to call function of this name subviewName.split('-')[0]SubviewFunction(id), 
eg replySubviewFunction('5') in case of subview name reply-5. so when creatin a subview also requires some js to call,
just set attribute subviewFunction to true and create appropriate function. when u dont need id from subview name, just ignore it
in your function implementation 

every subviewManager object is created only once and stored in singleton by id ... this allows us to have one 
object but dealin with group of same behaviors, but we somehow need to distiguish which one we are usin ... and 
usin it in switchers ... so expression (id) is beein replaced on fly by the actual id which comes from the event 
... special thing is expression (ids) , which u can use in subviewName and that creates subviews for all cis on 
page (used only once when expanding all cis)

lets deal with simple example ...

1. we define 2 objects, shower and hider

    new redrata.subviewManager({
        id : 'rrcaid-reply-shower',
        switchers : [['.rrca-conversation-item-reply', 'add'],
                     ['#rrcaid-reply-(id)', 'remove', 'blahblah'],
                     ['.rrca-reply-button', 'remove'],
                     ['#rrcaid-reply-shower-(id)', 'add']],
        subviewName : "reply-(id)",
        subviewsToGetRidOf : ['reply-']
    });

    new redrata.subviewManager({
        id : 'rrcaid-reply-hider',
        switchers : [['#rrcaid-reply-(id)', 'add'],
                     ['#rrcaid-reply-shower-(id)', 'remove']],
        subviewName : "reply-(id)",
        subviewsToGetRidOf : null
    });


2. we define links

    <div id='rrcaid-reply-shower-45' class='rr-subview-manager rrca-reply-button' title='Reply to the item via email.' >Reply</div>
    
    <div id='rrcaid-reply-shower2-45' class='rr-subview-manager rrca-reply-button' title='Reply to the item via email.' >Reply</div>

    <div id='rrcaid-reply-hider-45' class='rr-cancel-op rr-subview-manager'>Hide</div>

    things here :

    - the switchers have to have class rr-subview-manager on them, that binds them to behavior
    - the id of switcher have to have this format *-function(number)-id where
        * is whatever
        function is either shower or hider, or if u need two showers, u can have shower1 and shower2
        id is id we are usin for subview (in this case it is 45) ... if we dont need id (its general for page), dont put it there, so just *(number)-function

    and we define contents of subview, in this case

    <div id="rrcaid-reply-45" class='rrca-conversation-item-reply rr-is-hidden rr-reply-45-subview-div'>
        blahblah
    </div>

    - another thing, we need to have class on subview elements in this format rr-*-subview-div or rr-*subview-hide-div ... 
    * is subview name ...  this is used when the page (or fragment) gets reloaded ...
        if we have hash like #reply-45
        everything with class rr-reply-45-subview-div is beein shown (rr-is-hidden removed) after reload
        and
        everything with class rr-reply-45-subview-hide-div is beein hidden (rr-is-hidden added)
        if we use different class in showers than rr-is-hidden, it needs to be implemented as special case in initViewToggle method
        

3. so when we click on something with class rr-subview-manager and id rrcaid-reply-shower-45, we get the id of 
subview from id of link (45 in this case), we get the function from id (in this case shower)
    we get the appropriate subviewManager object,
    replace all occurences of string (id) by value of id in switchers and perfom logic which is beein defined in switchers ...
        so apply rr-is-hidden (default class) to .rrca-conversation-item-reply,
        remove blahblah class from #rrcaid-reply-45
        etc ...
        
    same logic would get executed if we click on something with class rr-subview-manager and id rrcaid-reply-shower2-45 ...

    subview name reply-45 is beein added to hash, comma separated
    and all subviews which match reply- are beein removed from hash
*/
 

if (!redrata.subviewManagerSingleton) {
    redrata.subviewManagerSingleton = {};
}

dojo.declare("redrata.subviewManager", redrata.subviewManager, {
    id : null,
    switchers : null,
    subviewName : null,
    subviewsToGetRidOf : null,
    revertedShowing : false,
    idToHighlight : null,
    subviewFunction : false,

    constructor : function(args) {
        var manager = this;
        dojo.mixin(manager, args);
        if (manager.id == null) {
            console.error('Id of subview manager is null');
            return;
        }
        //if (manager.switchers == null) manager.switchers = null;
        if (manager.subviewName == null) manager.subviewName = "";
        //manager.subviewsToGetRidOf = redrata.util.createArrayFromObject(manager.subviewsToGetRidOf);
        if (!redrata.subviewManagerSingleton[manager.id]) {
            redrata.subviewManagerSingleton[manager.id] = manager;
        }
    }
});

function processSubviewManagerFromEvent(evt, subviewManagerClass) {
    if (evt) dojo.stopEvent(evt);
    var idOfNode = redrata.util.getParentNode(evt.target, subviewManagerClass).id;
    var splittie =  idOfNode.split("-");
    var func, id, singletonId;
    if (splittie[splittie.length -1].match('shower') || splittie[splittie.length -1].match('hider') || splittie[splittie.length -1].match('toggler')) { //we whave no id, format *-func
        func = splittie[splittie.length -1].match('shower') ? 'shower' : splittie[splittie.length -1].match('hider') ? 'hider' : 'toggler';
        id = 'id';
        singletonId = idOfNode.split(func)[0] + func;
    } else if (splittie[splittie.length -2].match('shower') || splittie[splittie.length -2].match('hider') || splittie[splittie.length -2].match('toggler')) { //we whave id, format *-func-id
        func = splittie[splittie.length -2].match('shower') ? 'shower' : splittie[splittie.length -2].match('hider') ? 'hider' : 'toggler';
        id = splittie[splittie.length -1];
        singletonId = idOfNode.split(func)[0] + func;
    } else {
        console.error('subview manager - wrong format of nodeId - ' + idOfNode);
        return;
    }
    subviewManagerEventProcessor(singletonId, func, id);
}

function subviewManagerEventProcessor(singletonId, func, id) {
    var manager;
    var idAttribute = '\\(id\\)';
    var idsAttribute = '\\(ids\\)';
    if (!redrata.subviewManagerSingleton || !redrata.subviewManagerSingleton[singletonId]) {
        console.error('subview manager - we dont have subview manager object with such id - ' + singletonId);
        return;
    } else {
        manager = redrata.subviewManagerSingleton[singletonId];
    }
    dojo.forEach(manager.switchers, function(switcher) {//processing switchers from subview Manager
        switch(switcher[1]) {
            case 'add' : {
                dojo.query(redrata.util.replaceAttribute(switcher[0], idAttribute, id)).addClass(switcher.length == 3? switcher[2] : 'rr-is-hidden');
                break;
            }
            case 'remove' : {
                dojo.query(redrata.util.replaceAttribute(switcher[0], idAttribute, id)).removeClass(switcher.length == 3? switcher[2] : 'rr-is-hidden');
                break;
            }
            case 'toggle' : {
                dojo.query(redrata.util.replaceAttribute(switcher[0], idAttribute, id)).toggleClass(switcher.length == 3? switcher[2] : 'rr-is-hidden');
                break;
            }
            default : {
                console.error('subview manager - wrong function in switcher, has to be add or remove or toggle');
                return;
            }
        }
    });
    if (func != 'toggler') {
        if (manager.revertedShowing == true ? func == "hider" : func == "shower") { // if function shower or function hider and reversed showing, we add subview to hash
            if (manager.subviewName.match("(ids)")) {
                var ids = redrata.util.getIdsOfCisOnPage();
                dojo.forEach(ids, function(id, index, ids) {
                    redrata.util.addSubviewToHash(redrata.util.replaceAttribute(manager.subviewName, idsAttribute, id), redrata.util.replaceAttribute(manager.subviewsToGetRidOf, idAttribute, id));
                });
            } else {
                redrata.util.addSubviewToHash(redrata.util.replaceAttribute(manager.subviewName, idAttribute, id), redrata.util.replaceAttribute(manager.subviewsToGetRidOf, idAttribute, id));
            }
        } else if (manager.revertedShowing == true ? func == "shower" : func == "hider") { // if function hider or function shower and reversed showing, we delete subview from hash
            redrata.util.deleteSubviewFromHash(redrata.util.replaceAttribute(manager.subviewName, idAttribute, id), redrata.util.replaceAttribute(manager.subviewsToGetRidOf, idAttribute, id));
        }
    } else {
        var subviewName = redrata.util.replaceAttribute(manager.subviewName, idAttribute, id);
        if (!window.location.hash.match(subviewName)) {
            if (manager.switchers == null) {
                dojo.query('.rr-' + subviewName + '-subview-div').removeClass('rr-is-hidden');
                dojo.query('.rr-' + subviewName + '-subview-hide-div').addClass('rr-is-hidden');
            }
            redrata.util.addSubviewToHash(redrata.util.replaceAttribute(manager.subviewName, idAttribute, id), redrata.util.replaceAttribute(manager.subviewsToGetRidOf, idAttribute, id));
        } else {
            if (manager.switchers == null) {
                dojo.query('.rr-' + subviewName + '-subview-div').addClass('rr-is-hidden');
                dojo.query('.rr-' + subviewName + '-subview-hide-div').removeClass('rr-is-hidden');
            }
            redrata.util.deleteSubviewFromHash(redrata.util.replaceAttribute(manager.subviewName, idAttribute, id), redrata.util.replaceAttribute(manager.subviewsToGetRidOf, idAttribute, id));
        }
    }
    if (manager.subviewFunction) {
        var functionName = manager.subviewName.split('-')[0] + "SubviewFunction";
        var functionParam = manager.subviewName.split('-').length > 1 ? redrata.util.replaceAttribute(manager.subviewName.split('-')[1], idAttribute, id) : "no param";
        if (typeof window[functionName] == "function") {
            window[functionName](functionParam);
        } else {
        	console.error('subview manager - error while tryin to find execute ' + functionName + "('" + functionParam + "');");
        }
    }
    if (manager.idToHighlight) {
        var processedIdToHighlight = redrata.util.replaceAttribute(manager.idToHighlight, idAttribute, id);
        if (dojo.byId(processedIdToHighlight) != null) {
            redrata.util.highlightId(processedIdToHighlight);
            //dojo.query('#' + processedIdToHighlight).addClass('rr-subview-manager-highlight');
            //setTimeout(function() {dojo.query('#' + processedIdToHighlight).removeClass('rr-subview-manager-highlight')}, 1000);
        }
    }
}

redrata.util.addBehavior('handle subview change on click', {
    '.rr-subview-manager': {
        onclick: function(evt) {
            processSubviewManagerFromEvent(evt, 'rr-subview-manager');
        }
    }
});

redrata.util.addBehavior('handle subview change on double click', {
    '.rr-subview-manager-double-click': {
        ondblclick: function(evt) {
            processSubviewManagerFromEvent(evt, 'rr-subview-manager-double-click');
        }
    }
});

/** ******************TOGGLER*USED*ONLY*IN*RH*NOW*************** */
/*
 * give it an array of click selectors e.g. #id-val to 
 */
dojo.declare("redrata.toggler", redrata.toggler, {
classNameToToggle : null,
idNamesToShow : null,
classNameToHide : null,
classNameToShow : null,
duration : 300,
/* e.g. */
constructor : function(arguments) {
    var toggler = this;
    dojo.mixin(toggler, arguments);
    var hashPresent = false;
    dojo.forEach(toggler.idToIdMappings, function(idToId) {
        var a = idToId;
        if (window.location.hash.match(idToId.hash) != null) {
            hashPresent = true;
            toggler.idNamesToShow = a.showIDs;
            toggler.classNameToShow = a.classNameToShow;
            toggler.classNameToHide = a.classNameToHide;
            toggler.showElements();
        }
    });
    if (!hashPresent) {
        //toggler.showElements(); //disabled for the moment
    }
    dojo.forEach(toggler.idToIdMappings, function(idToId) {
        var a = idToId;
        var b = idToId.clickSelector;
        var x = {};
        x[b] = {
            onclick: function(evt) {
            toggler.idNamesToShow = a.showIDs;
            toggler.classNameToShow = a.classNameToShow;
            toggler.classNameToHide = a.classNameToHide;
            toggler.showElements();
            //dojo.stopEvent(evt);
            //if(evt) dojo.stopEvent(evt);
            return false;
        }};
        redrata.util.addBehavior(idToId.clickSelector+"_toggler", x);
    });
},
showElements : function() {
    var toggler = this;
    if (toggler.fadeIn) {
        toggler.fadeIn.stop();
    }
    if (toggler.classNameToShow != null) {
        dojo.query('.' + toggler.classNameToShow).forEach(function(item) {
            if (!dojo.hasClass(item, toggler.classNameToToggle)) {
                dojo.removeClass(item, 'rr-is-hidden');
            }
        });
    }
    if (toggler.classNameToHide != null) {
        dojo.query('.' + toggler.classNameToHide).forEach(function(item) {
            if (!dojo.hasClass(item, toggler.classNameToToggle)) {
                dojo.addClass(item, 'rr-is-hidden');
            }
        });
    }
    dojo.query('.' + toggler.classNameToToggle).forEach(function(item) {
        //dojo.removeClass(item, 'rr-is-hidden');
        var show = false;
        dojo.forEach(toggler.idNamesToShow, function(idNameToShow) {
            if (item.id && item.id == idNameToShow) {
                show = true;
            }
        });
        if (show) {
            //dojo.show(item);
            if (toggler.item == item) {
                dojo.removeClass(item, 'rr-is-hidden');
                item.style.opacity = '1';
                return;
            }
            toggler.item = item;
            item.style.opacity = '0.2';
            //item.style.display = 'block';
            dojo.removeClass(item, 'rr-is-hidden');
            var o = dojo.byId(item);
            //redrata.util.scrollIntoView(o);
            toggler.fadeIn = dojo.fadeIn( {
            node : item,
            duration : toggler.duration,
            onStop : function() {
            },
            onEnd : function() {
            }
            });
            toggler.fadeIn.play();
        } else {
            dojo.addClass(item, 'rr-is-hidden');
            // for the moment, this additional line is necessary to reset the set style attribute above
            // this is only a temporary work around
            //item.style.display = 'none';
        }
    });
}
});

/** ******************ONAJAXSUCCESSMESSAGE*********************************** */
dojo.declare("redrata.onajaxsuccessmessage", redrata.onajaxsuccessmessage, {
/** css selector (e.g. #form-id or '#id form') of form that contained the data we were get/put/post/deleting */
formSelector : null,
/** the method we were calling. e.g. GET, PUT, POST, DELETE, etc */
method : null,
/** true if this message is fired after the user did something locally (vs. some application notice delivered via dwr.) */
isLocal : true,
/** where we'd like the message to be displayed */
messageDivSelector : null,
/** a common response object */
jaxRSResponse : null,
/** the resource that was affected */
resourceURL : null,
xhr : null,
/* e.g. */
constructor : function(arguments) {
    var successMessage = this;
    dojo.mixin(successMessage, arguments);
}
});

/** ******************ONAJAXSUCCESSHANDLER***********************************
* create an onajaxsuccesshandler. call subscribe on it (give some resource paths to monitor exclude) when there is a successful ajax call to a resource path matching those subscribed values, then onAjaxSuccess is triggered. This will typically populate a specified div with some new html
*/

dojo.declare("redrata.onajaxsuccesshandler", redrata.onajaxsuccesshandler, {
/* if there is a Location header on the result, redurect to that location */
redirectToLocationIfProvided : false,
/* Load this url when onAjaxSuccess is called */
resourceToLoadURL : null,
resourceToLoadAccept : "text/vnd.redrata.detail+html",
/* insert the result into the element matching this css selector */
elementInWhichToInsertResultSelector : '#rrid-main-content',
/** this selector will be used to hide/remove an element on delete */
elementToHideOnDeleteSelector : null,
/* e.g. */
timer : null, /** timerDelayingSuccessAction */
lastUpdateMS : new Date().getTime(), /** timeTheLastActionWasTriggered */
interval : {local : 0, remote : 0}, /** minimalRefreshIntervalMS */
constructor : function(arguments) {
    var successHandler = this;
    dojo.mixin(successHandler, arguments);
},
/**
 * override this if you want to handle the success message before the regular onAjaxSuccess is called.  Return true
 * if you want to continue processing, otherwise it stops further processing
 */
customHandlingOfOnAjaxSuccess : function(onajaxsuccessmessage) {
    return true;
},
/**
 * override this if you want to perform some logic before we do ajax call.
 */
customHandlingOfOnAjaxCall : function(url, method) {
},
/**
 * override this if you want to perfrom some logic after ajax call failed.
 */
customHandlingOfOnAjaxError : function(url, method) {
},
onAjaxSuccess : function(onajaxsuccessmessage, ajaxform) {
    try {
        var onajaxsuccesshandler = this;
        
        function onAjaxSuccess2(onajaxsuccessmessage, ajaxform) {
            
            onajaxsuccesshandler.timer = null;
            onajaxsuccesshandler.lastUpdateMS = new Date().getTime();
        
            if (onajaxsuccesshandler.customHandlingOfOnAjaxSuccess) {
                if(!onajaxsuccesshandler.customHandlingOfOnAjaxSuccess(onajaxsuccessmessage)) {
                    return;
                }
            }
            var location = onajaxsuccessmessage.xhr.getResponseHeader("Location");
            if (onajaxsuccesshandler.redirectToLocationIfProvided) {
                if (location) {
                    window.location = location;
                    return;
                }
            }
            if ("DELETE" == onajaxsuccessmessage.method && onajaxsuccesshandler.elementToHideOnDeleteSelector) {
                // on a delete go and hide all the specified elements
                if (!dojo.isArray(onajaxsuccesshandler.elementToHideOnDeleteSelector)) {
                    onajaxsuccesshandler.elementToHideOnDeleteSelector = [ onajaxsuccesshandler.elementToHideOnDeleteSelector];
                }
                dojo.forEach(onajaxsuccesshandler.elementToHideOnDeleteSelector, function (selector) {
                    dojo.query(selector).forEach(function(item) {
                        dojo.fadeOut( {
                        node : item,
                        onStop : function() {
                        },
                        onEnd : function() {
                            //item.style.display = 'none';
                            dojo.addClass(item, 'rr-is-hidden');
                            item.innerHTML = '';
                        }
                        }).play();
                    });
                });
                return;
            }
        
            var ct = onajaxsuccessmessage.xhr.getResponseHeader("Content-Type")
            if (ct != null) {
                ct = ct.split(";", 1)[0];
            }
        
            if (ct == onajaxsuccesshandler.resourceToLoadAccept && !onajaxsuccesshandler.resourceToLoadURL) {
                redrata.util.insertPayload(onajaxsuccesshandler.elementInWhichToInsertResultSelector, onajaxsuccessmessage.xhr.responseText, onajaxsuccessmessage, ajaxform);
                return;
            }
        
            if (!onajaxsuccesshandler.resourceToLoadURL) {
                console.warn("no resourceToLoadURL specified.  In context of " + onajaxsuccesshandler.elementInWhichToInsertResultSelector);
                return;
            }
        
            dojo.xhrGet( {
            url : onajaxsuccesshandler.resourceToLoadURL ? onajaxsuccesshandler.resourceToLoadURL : location,
            load : function(payload, data) {
                redrata.util.insertPayload(onajaxsuccesshandler.elementInWhichToInsertResultSelector, payload, onajaxsuccessmessage, ajaxform);
            },
            error : function(type, error) {
                if (redrata.util.parseXHRAndHandleJaxRSResponse(error.xhr)) {
                    return;
                }
            	new redrata.feedBackLayer( {  
					message : "There was an error while automatically refreshing.  Please reload this page manually.",
					isError : true 
				});
            },
            headers : {
            "Accept" : onajaxsuccesshandler.resourceToLoadAccept,
            "RR-Id" : redrata.sid
            }
            });
        }
        if ((onajaxsuccesshandler.interval.local != 0 && onajaxsuccessmessage.isLocal) || (onajaxsuccesshandler.interval.remote != 0 && !onajaxsuccessmessage.isLocal)) {
            if (new Date().getTime() - onajaxsuccesshandler.lastUpdateMS > onajaxsuccesshandler.interval) { // were outside interval, callin action
                onAjaxSuccess2(onajaxsuccessmessage, ajaxform);
                return;
            } else {
                var i = onajaxsuccessmessage.isLocal ? onajaxsuccesshandler.interval.local : onajaxsuccesshandler.interval.remote;
                var delay = Math.max(0, i - (new Date().getTime() - onajaxsuccesshandler.lastUpdateMS));
                clearTimeout(onajaxsuccesshandler.timer);
                onajaxsuccesshandler.timer = setTimeout(function() {
                    onAjaxSuccess2(onajaxsuccessmessage, ajaxform);
                }, delay);
                return;
            } 
        }
        onAjaxSuccess2(onajaxsuccessmessage, ajaxform);
    } finally {
    }
},

/**
 * provide a string or string[] for each of the match/exclude regexs. When a resource is updated, and we find matching onajaxsuccesshandler and call them.
 */
subscribe : function(key, resourceToMatchRegex, resourceToExclueRegex, httpMethodsToInclude, httpMethodsToExclude) {
    var onajaxsuccesshandler = this;

    if (typeof(key) !== 'string') {
        console.error("Couldn't subscribe to message bus: parameter key is either missing or not a string!");
        return;
    }
    
    function isMatch(xhr, resourceURL, method) {
        var onajaxsuccesshandler = this;

        // rob->bry Here is where we check the returned RR-Id header to see if this session generated the event, and if so ignore it.
        if (xhr && xhr.getResponseHeader("RR-Id") && xhr.getResponseHeader("RR-Id") == redrata.sid) {
            return false;
        }

        if (!resourceURL) {
            return false;
        }
        if (!resourceToMatchRegex) {
            resourceToMatchRegex = [];
        }
        if (!dojo.isArray(resourceToMatchRegex)) {
            resourceToMatchRegex = [ resourceToMatchRegex ];
        }
        {
            var hasFoundIncluded = resourceToMatchRegex.length > 0 ? false : true;
            if (!resourceToMatchRegex) {
                hasFoundIncluded = true;
            }
            dojo.forEach(resourceToMatchRegex, function(item) {
                if (resourceURL.match(item)) {
                    hasFoundIncluded = true;
                } else {
                    false;
                }
            });
            if (!hasFoundIncluded) {
                return false;
            }
        }

        if (!httpMethodsToInclude) {
            httpMethodsToInclude = [];
        }
        if (!dojo.isArray(httpMethodsToInclude)) {
            httpMethodsToInclude = [ httpMethodsToInclude ];
        }
        {
            var hasFoundIncluded = httpMethodsToInclude.length > 0 ? false : true;
            if (!httpMethodsToInclude) {
                hasFoundIncluded = true;
            }
            dojo.forEach(httpMethodsToInclude, function(item) {
                if (method.match(item)) {
                    hasFoundIncluded = true;
                } else {
                    false;
                }
            });
            if (!hasFoundIncluded) {
                return false;
            }
        }

        if (!resourceToExclueRegex) {
            resourceToExclueRegex = [];
        }
        if (!dojo.isArray(resourceToExclueRegex)) {
            resourceToExclueRegex = [ resourceToExclueRegex ];
        }
        {
            var hasFoundExcluded = false;
            dojo.forEach(resourceToExclueRegex, function(item) {
                if (resourceURL.match(item)) {
                    hasFoundExcluded = true;
                }
            });
            if (hasFoundExcluded) {
                return false;
            }
        }
        if (!httpMethodsToExclude) {
            httpMethodsToExclude = [];
        }
        if (!dojo.isArray(httpMethodsToExclude)) {
            httpMethodsToExclude = [ httpMethodsToExclude ];
        }
        {
            var hasFoundExcluded = false;
            dojo.forEach(httpMethodsToExclude, function(item) {
                if (method.match(item)) {
                    hasFoundExcluded = true;
                }
            });
            if (hasFoundExcluded) {
                return false;
            }
        }
        return true;
    }
    ;
    function action(onajaxsuccessmessage, ajaxform) {
        if (onajaxsuccessmessage.xhr && !onajaxsuccessmessage.jaxRSResponse) {
            onajaxsuccessmessage.jaxRSResponse = redrata.util.getJaxRSResponseFromXHR(onajaxsuccessmessage.xhr);
        }
        onajaxsuccesshandler.onAjaxSuccess(onajaxsuccessmessage, ajaxform);
    }
    function init(url, method) {
        onajaxsuccesshandler.customHandlingOfOnAjaxCall(url, method);
    }
    function error(url, method) {
        onajaxsuccesshandler.customHandlingOfOnAjaxError(url, method);
    }
    redrata.messagebus.addListener(key, isMatch, action, init, error);
}
});

/** ******************DEFAULT*VALUE*********************************** **/
dojo.declare("redrata.defaultValue", redrata.defaultValue, {
    attrib : null,
    value : null,
    constructor : function(arguments) {
        dojo.mixin(this, arguments);
    }
});

if (!redrata.defaultValues) {
    redrata.defaultValues = {};
}

redrata.util.addBehavior("remember input/textarea default vals", {
    "input[type=text].rr-input-edit-controls:not(.rrca-dont-preserve-values), textarea.rr-input-edit-controls:not(.rrca-dont-preserve-values)": {
        onkeydown: function(evt) {
            if(redrata.defaultValues[evt.target.id] == null){
                redrata.defaultValues[evt.target.id] = new redrata.defaultValue({attrib: "value", value: dojo.byId(evt.target.id).value});
            }
        }
    }
});

redrata.util.addBehavior("remember select default vals", {
    "select.rr-input-edit-controls:not(.rrca-dont-preserve-values)": {
        onchange: function(evt) {
            if(evt.target.id && redrata.defaultValues[evt.target.id] == null){
                redrata.defaultValues[evt.target.id] = new redrata.defaultValue({attrib: "value", value: dojo.byId(evt.target.id).value});
            }
        }
    }
});

redrata.util.addBehavior("remember checkbox default vals", {
    ".rr-input-edit-controls:not(.rrca-dont-preserve-values) input[type=checkbox]": {
        onclick: function(evt) {
            if(evt.target.id && redrata.defaultValues[evt.target.id] == null){
                redrata.defaultValues[evt.target.id] = new redrata.defaultValue({attrib: "checked", value: dojo.byId(evt.target.id).checked});
            }
        }
    }
});

/** ******************create spinner or add class to parent until on ajax success***********************/ 
dojo.declare("redrata.onWait", redrata.onWait, {
	target: null,
	placementClass : "",
	parentClass : "",
	addClassToParent : "",
	addClass: "",
	parent : null,
	preserveNode : null,
	constructor : function(args) {
		if(args) {
			dojo.mixin(this, args);
		}
		
		var object = this;
		this.parent = redrata.util.getParentNode(this.target, this.parentClass);
		if(this.parent != null){
			this.preserveNode = dojo.query(" ." + this.placementClass, this.parent);
		}	
	},
	start :function() {
		var object = this;
		if(object.preserveNode != null){
			object.preserveNode.addClass("rr-is-hidden");
			dojo.place("<span class='rrca-confirm-in-action "+object.addClass+"'></span>", dojo.query(object.preserveNode)[0], "after");
			dojo.query(object.parent).addClass(object.addClassToParent);
		}  
	}/*,
	end : function() {
		if(object.preserveNode != null){
			var object = this;
			dojo.query(object.preserveNode).removeClass("rr-is-hidden");
			//dojo.destroy(dojo.query("#"+object.parent.id + " .rrca-confirm-in-action" ));
			dojo.query(object.parent).removeClass(object.addClassToParent);
		}
	}*/
});

/** ******************DELETION*DIALOG************************ **/

/*
 *     
 * create confirm delete with custom text i.e. confirm button, cancel button, body text
 * new redrata.confirmationDialog(evt.target,"rr-delete-op",{
 * 		fixedBox :true,												(if true fixes dialog modal in the center of screen, if false creates inline buttons)(if left out defaults to false);
 * 		addMainClass : "class to add to main container", 			(appends to default class "rrca-confirm-delete-dialog")
 *      confirm : "change confirm message here if you want",  		(if left out defaults to "confirm")
 *      cancel  : "change cancel message here if you want",			(if left out defaults to "cancel")
 *      bodyMsg : "add some  body text here if needed",				(if left out defaults to nothing)
 *      onConfirm : function() {}, function to run on confirmation, (if left out defaults to nothing)
		 onCancel : function() {}	function to run on cancel , 	(if left out defaults to nothing)
 * });
 * 
 * or just with "Confirm Delete" and "Cancel" as button text with no body text as default
 * new redrata.confirmationDialog(evt.target,"class which delete behaviour is attached");
**/
dojo.declare("redrata.confirmationDialog", redrata.confirmationDialog, {
	fixedBox :false,
    confirm : "Confirm Delete",
    cancel  : "Cancel",
    bodyMsg    : "",
    addBodyClass : "",
    addMainClass : "rrca-confirm-delete-dialog",
    constructor : function(node,deleteClass,values) {
        if(values)
            dojo.mixin(this, values);

        /*
        //destroy the confirm delete dialog if it is shown
        */
        dojo.destroy(dojo.byId('rrcaid-confirm-delete-dialog'));
        if(this.fixedBox)
        	dojo.destroy(dojo.byId('rrcaid-splash-screen'));
        /*
        //when clicked, if any confirm delete dialog initiator button is hidden then 
        //	remove the "rrca-hide-confirm-initiator" class and the "rr-is-hidden"
        */
        if(dojo.query(".rrca-hide-confirm-initiator").length){
        	var confirmInitiator =  dojo.query(".rrca-hide-confirm-initiator")[0];
            dojo.query(confirmInitiator).removeClass("rrca-hide-confirm-initiator");
            dojo.query(confirmInitiator).removeClass("rr-is-hidden");
        }
        /*
        //add the two classes onto the new item that was clicked
        */
        if(!this.fixedBox){
        	dojo.query(node).addClass("rrca-hide-confirm-initiator");
        	dojo.query(node).addClass("rr-is-hidden");
        }else{
        	var splash = dojo.create('div', {
            	id : "rrcaid-splash-screen", 
                style : "position:fixed;width:100%;height:100%;z-index:20;left:0px;top:0px;opacity:0.7;background-color:#9E9E9E;"
            },dojo.query(node)[0],"first");
        }  
        /*
         * once the confirm delete dialog initiator has been hidden
         * create the confirm delete dialog
         * create body text node
         * create submit button node
         * create cancel button node
         */
        var dialogbox = dojo.create('div', {
            id:"rrcaid-confirm-delete-dialog"
        });
        if(this.bodyMsg != ""){
            dojo.place("<br/>",dialogbox,"first");
            var bodyBox = dojo.create('span', {
                innerHTML : this.bodyMsg,
                id : "rrcaid-dialog-body-text"
            },dialogbox,"first");
        }
        var submit = dojo.create('input', {
        	type:"button",
        	id : "rrid-confirm-dialog-button",
            value : this.confirm,
            align : "center"
        },dialogbox,"last");
        dojo.query(submit).addClass(deleteClass);
        dojo.query(submit).addClass("rr-element-to-button link");
        var cancel = dojo.create('input', {
        	type:"button",
        	id    : "rrid-cancel-dialog-button",
            value : this.cancel,
            align :   "center"
        },dialogbox,  "last");
        dojo.query(cancel).addClass("rr-element-to-button link");
        dojo.query(dialogbox).place(node,"after").addClass(this.addMainClass);
        dojo.behavior.apply();
        /*
         * add a onclick event to the cancel button to destroy the  dialog and re-show the "rrca-hide-confirm-initiator"
         */
        var object = this;
        dojo.query(submit).onclick(function(e) {
        	dojo.byId("rrid-confirm-dialog-button").innerHTML += "<span class='rrca-confirm-in-action'></span>";
        	if(object.fixedBox){
	        	dojo.destroy(dojo.byId('rrcaid-confirm-delete-dialog'));
	            dojo.destroy(dojo.byId('rrcaid-splash-screen')); 
        	}
            if(typeof values != "undefined" && typeof values.onConfirm == "function") {
            	values.onConfirm();
        	}
        });
        dojo.query(cancel).onclick(function(e) {
        	dojo.destroy(dojo.byId('rrcaid-confirm-delete-dialog'));
            dojo.destroy(dojo.byId('rrcaid-splash-screen')); 
            var showInitiator =  dojo.query(".rrca-hide-confirm-initiator")[0];
	        dojo.query(showInitiator).removeClass("rrca-hide-confirm-initiator");  
	        dojo.query(showInitiator).removeClass("rr-is-hidden");
	        if(typeof values != "undefined" && typeof values.onCancel == "function") { 
            	values.onCancel(); 
        	}
            dojo.stopEvent(e);
        });
    }  
});
    
redrata.util.addBehavior(".rr-confirm-expand", {
    ".rr-confirm-expand" : {
		onclick : function(evt) {
	        new redrata.confirmationDialog(redrata.util.getParentNode(evt.target, "rr-confirm-expand"),"rr-delete-op");
		    if (evt) {
		        dojo.stopEvent(evt);
		    }
		}
}});
/*****************expanding to adresses******************/




function emailFields(changeheight,size,unit){
	nWidth = null;
	var target = null;
	var is_shift = false;
	var split_step = false;
	function changesize(event){
			
		if(changeheight){ 
			var ta= event.target;
	  		var t=ta.value.replace(/\r\n\f/gm, '\n').split('\n'), sum=0;
	  		for (var i=0;i<t.length;i++) if (t[i].length > ta.cols) sum++;
	  		var s = (t.length * size);
	  		//console.info(s+unit,t.length);
	  		dojo.attr(event.target,{
	  		   style:{
	  		       height:s+unit
	  		     }
	  		});
	  	}
	}
	dojo.behavior.add({
		".rr-in-list-format textarea" : {
		  	"onkeyup" : function(evt) {
		  		changesize(evt);
		  	}
		}
	});
}

new emailFields(true, 1.4, "em");
/**********************************************/
dojo.behavior.add({
	"body" : {  
	  	"onkeydown" : function(evt) {
	  		console.log(evt);
	  	}
	}
});


/********************************************/
/** ***********MESSAGE*BUS**************** **/
// the messagebus is a static class. i.e. no 'new' required. One instance serves all for the page.

redrata.messagebus = {};
redrata.messagebus.connections = {};

/**
 * isMatch(onajaxsuccessmessage) returns true is the action should be triggered action(onajaxsuccessmessage) handles the onajaxsuccessmessage
 */
redrata.messagebus.addListener = function(key, isMatch, action, init, error) {
    var messagebus = redrata.messagebus;
    
    if (typeof(key) !== 'string') {
        console.error("Couldn't subscribe to message bus: parameter key is either missing or not a string!");
        return;
    }
    
    //wax:multisuccesshandlerbug
    messagebus.connections[key] = new Object({isMatch : isMatch, action : action, init : init, error : error});
};
redrata.messagebus.fireAjaxSuccessEvent = function(onajaxsuccessmessage, ajaxform) {
    var messagebus = redrata.messagebus;

    for (var i in messagebus.connections) {
        var isMatch = messagebus.connections[i].isMatch;

        if (isMatch(onajaxsuccessmessage.xhr, onajaxsuccessmessage.resourceURL, onajaxsuccessmessage.method)) {
            var action = messagebus.connections[i].action;
            action(onajaxsuccessmessage, ajaxform);
        }
    }
};

/** ******************GENERAL*BEHAVIORS******** **/

redrata.util.addBehavior("remember on focus changes", {
    "*": {
        onfocus: function(evt) {
            redrata.focus = evt.target.id;
    }
}});

redrata.util.addBehavior('adjust text area size', {
    '.rrca-expandable-text-area': {
        oninput: function(evt) {
            redrata.util.adjustTextAreaByRedrataConstants(evt.target);
        },
        onpropertychange: function(evt) {
            redrata.util.adjustTextAreaByRedrataConstants(evt.target);
        }
    }
});

redrata.util.addBehavior('invite url selector', {
    '.rrca-invite-url-selector' : {
        onclick : function(evt) {
            var id = "rrcaid-invite-url-" + evt.target.id.split('-')[4];
            redrata.util.selectAllContentsOfTextfield(id);
            }
        }
});

redrata.util.addBehavior('id highlighter', {
    '.highlightId' : {
        onclick : function(evt) {
            dojo.stopEvent(evt);
            var id = evt.target.id.split('-highlighter')[0];
            redrata.util.highlightId(id, true);
            }
        }
});

/** ******************GENERAL*SUBVIEW*MANAGERS******* **/

new redrata.subviewManager({ //general switch to go to edit mode
    id : 'rrcaid-edit-mode-shower',
    switchers : [['.rr-read-only-view', 'add'], //for general switching
                 ['.rr-edit-view', 'remove'],
                 ['.rr-inline-edit-widget .rr-inline-edit-edit-view', 'add'], //for inline edits switching
                 ['.rr-inline-edit-widget .rr-inline-edit-readonly-view', 'remove']],
    subviewName : "edit-view",
    subviewsToGetRidOf : ['attrib-']
   
});

new redrata.subviewManager({ //general switch to go to view mode
    id : 'rrcaid-edit-mode-hider',
    switchers : [['.rr-read-only-view', 'remove'], //for general switching
                 ['.rr-edit-view', 'add'],
                 ['.rr-inline-edit-widget .rr-inline-edit-edit-view', 'add'], //for inline edits switching
                 ['.rr-inline-edit-widget .rr-inline-edit-readonly-view', 'remove']],
    subviewName : "edit-view",
    subviewsToGetRidOf : ['attrib-']
});


//redrata.logging.log("redrataJsEnd", "Logs from initial processing of redrata.js - END", false, true);