var applicationKey;

function title(title)
{
    document.title = title;
}

var containerId = 1;

function showBlocker(element) {                  
    
    var blockerDivObj;
    
    if(element)
    {
        if(! element.viewNode.id)
        {
            while(document.getElementById('container_' + containerId))
                containerId++;
            element.viewNode.id = 'container_' + containerId;
        }
        
        
        blockerDivObj = document.getElementById( element.viewNode.id + '_blockerDiv' );
        if(!blockerDivObj)
        {
            var blockerDivObjMaster = bb.document.getElementById('blockerDiv');
            blockerDivObjMaster.setAttribute('id', '');
            blockerDivObj = bb.command.copy(blockerDivObjMaster,blockerDivObjMaster.getProperty('parentNode'));
            blockerDivObj.setAttribute('id', element.viewNode.id + '_blockerDiv');
            blockerDivObjMaster.setAttribute('id', 'blockerDiv');
            
            blockerDivObj = blockerDivObj.viewNode;
        }
    
        blockerDivObj.style.display = "block";

        var elementCoordsArray = getElementCoords(element);
        
        blockerDivObj.style.left = elementCoordsArray[0] + "px"; 
        blockerDivObj.style.top = elementCoordsArray[1] + "px";    
        blockerDivObj.style.width = elementCoordsArray[2] + "px"; 
        blockerDivObj.style.height = elementCoordsArray[3] + "px";

        // attach onunload event so it removes the blocker if the element is discarded
        element.addEventListener('DOMNodeRemovedFromDocument', function() { hideBlocker(element); }, false);
    }
    else
    {
        blockerDivObj = document.getElementById( 'blockerDiv' );
        blockerDivObj.style.display = "block";
        var pageSizesArray = getPageSize();
        blockerDivObj.style.left = "0px"; 
        blockerDivObj.style.top = "0px";    
        blockerDivObj.style.width = pageSizesArray[0] + "px"; 
        blockerDivObj.style.height = pageSizesArray[1] + "px";    
    }
}   

function hideBlocker(element) {

    if(element && element.viewNode && element.viewNode.id && document.getElementById( element.viewNode.id + '_blockerDiv' ))
    {
        var blockerDivObj = document.getElementById( element.viewNode.id + '_blockerDiv' );
    }
    else
    {
        var blockerDivObj = document.getElementById( 'blockerDiv' );
    }        
    blockerDivObj.style.display = "none";    
}

var globalLoadingMessages = new Array();
globalLoadingMessages['global'] = 0;
var hidingLoadingMessages = new Array();
hidingLoadingMessages['hiding'] = false;

function hideLoadingMessage(destination, loadingDelayTime, force) {
    
    var prefix = '';

    if(destination && destination.viewNode.id)
        prefix = destination.viewNode.id + '_';


    if(hidingLoadingMessages[prefix + 'hiding'])
    {
        setTimeout(function(){ hideLoadingMessage(destination, loadingDelayTime, force ); }, 100);
        return;
    }
    
   hidingLoadingMessages[prefix + 'hiding'] = true;
    
	setTimeout(
		function(){
            if(globalLoadingMessages[prefix + 'global'])
                globalLoadingMessages[prefix + 'global'] = globalLoadingMessages[prefix + 'global'] - 1;
            if(!globalLoadingMessages[prefix + 'global'] || force)
            {
				hideBlocker(destination);
            }
		}, 
	    ( loadingDelayTime > 0 ? loadingDelayTime * 1000 : 100 ) 
    );
		
   hidingLoadingMessages[prefix + 'hiding'] = false;
}

var allowedURLs = new Array('/index', '/auth', '/projects');
var projectURLs = new Array('/projects/newobjective', '/projects/newplanning', '/projects/surfaceplan', '/projects/airvolume', '/projects/gridselection', '/projects/airdistribution', '/projects/deviceselection', '/projects/accessories', '/projects/closure', '/projects/pdfgenerate');
var projectLoaded = false;

function customeLoad( loadingMessage, loadingDelayTime, autoHideLoadingMessage, url, method, data, headers, destination, mode, success ) {

    var prefix = '';

    if(destination)
        if(! destination.viewNode.id)
        {
            while(document.getElementById('container_' + containerId))
                containerId++;

            destination.viewNode.id = 'container_' + containerId;

            prefix = destination.viewNode.id + '_';
            
            globalLoadingMessages[prefix + 'global'] = 1;
            hidingLoadingMessages[prefix + 'hiding'] = false;
        }
        else
        {
            prefix = destination.viewNode.id + '_';
            globalLoadingMessages[prefix + 'global'] = globalLoadingMessages[prefix + '_' + 'global'] + 1;;
        }
    
	showBlocker(destination);
    
	if ( url ) {

        if(url.indexOf('/projects/newobjective') == 0)
            projectLoaded = true;
            
        if(projectLoaded && contentChanged && destination.viewNode.id == 'content' && mode == 'replaceChildren')
        {
            var i;
            var found = false;
            for(i in projectURLs) {
            	if(typeof projectURLs[i] == 'function') continue;
                if(url.indexOf(projectURLs[i]) == 0)
                {
                    found = true;
                    break;
                }
            }
            if(!found)
                if(!confirm(leaveProjectMessage))
                {
                    hideLoadingMessage( destination, loadingDelayTime );
                    return;
                }
                else
                    projectLoaded = false;
        }
        
        var found = false;
        var search;
        var i;
        for(i in allowedURLs)
        {
        	if(typeof allowedURLs[i] == 'function') continue;
            search = allowedURLs[i];
            if(url.substring(0, search.length)==search)
                found = true;
        }
        if(!found)
        {
            found = checkUser();
        }

        if(found) {
        	
        	if(mode == 'replace' || mode == 'replaceChildren') {
        		var accessKeyedObjects = bb.evaluateSmart("[descendant"+(mode == 'replace' ? '-or-self' : '')+"::*[@accesskey!='']]", destination);
        		
        		for(i in accessKeyedObjects) {
        			if(typeof accessKeyedObjects[i] == 'function') continue;
        			accessKeyedObjects[i].removeAttribute('accesskey');
        			
        		}
        	}
        	
            if(url.indexOf('?') == -1)
                url = url + '?&applicationkey=' + applicationKey;
            else
                url = url + '&applicationkey=' + applicationKey;
            
		    bb.command.load( url, method, data, headers, destination, mode, 
                function() 
                { 
                    if(autoHideLoadingMessage) hideLoadingMessage( destination, loadingDelayTime ); 
                    if(success) success();
                },
                function() 
                {
                    var modalLocked = bb.document.getElementById('modalLocked');
                    if(modalLocked)
                        modalLocked.open();
                }
            );
        }
        else
        {
            var modalLocked = bb.document.getElementById('modalLocked');
            if(modalLocked)
                modalLocked.open();
                
            hideLoadingMessage( destination, loadingDelayTime );
        }
	}
}

function customeSubmit(loadingMessage, loadingDelayTime, autoHideLoadingMessage, form, action, method, destination, mode ) {

    var prefix = '';

    if(!destination && form && form.getProperty('destination'))
        destination = form.getProperty('destination');

    if(destination)
        if(! destination.viewNode.id)
        {
            while(document.getElementById('container_' + containerId))
                containerId++;

            destination.viewNode.id = 'container_' + containerId;

            prefix = destination.viewNode.id + '_';
            
            globalLoadingMessages[prefix + 'global'] = 1;
        }
        else
        {
            prefix = destination.viewNode.id + '_';
            globalLoadingMessages[prefix + 'global'] = globalLoadingMessages[prefix + '_' + 'global'] + 1;;
        }
        
    showBlocker(destination);
    
    if(form)
    {
        if(action)
            form.setAttribute('action', action);
        action = form.getAttribute('action');

        if(action.indexOf('?') == -1)
            action = action + '?&applicationkey=' + applicationKey;
        else
            action = action + '&applicationkey=' + applicationKey;

        form.setAttribute('action', action);
        
        
        if(method)    
            form.setAttribute('method', method);
        else
            if(!form.getAttribute('method'))
                form.setAttribute('method', 'POST');
        
        if(destination)
            form.setProperty('destination', destination);
        else
            destination = form.getProperty('destination');
            
    	if(mode == 'replace' || mode == 'replaceChildren') {
    		var accessKeyedObjects = bb.evaluateSmart("[descendant"+(mode == 'replace' ? '-or-self' : '')+"::*[@accesskey!='']]", destination);
    		
    		for(i in accessKeyedObjects) {
    			if(typeof accessKeyedObjects[i] == 'function') continue;
    			accessKeyedObjects[i].removeAttribute('accesskey');
    			
    		}
    	}
        
        if(mode)
            form.setProperty('mode', mode);

        if(action)
        {
            var search;
            var i;
            var found = false;
            
            for(i in allowedURLs)
            {
            	if(typeof allowedURLs[i] == 'function') continue;
                search = allowedURLs[i];
                if(action.substring(0, search.length)==search)
                    found = true;
            }
            if(!found)
            {
                found = checkUser();
            }

            if(action.indexOf('/projects/newobjective') == 0)
                projectLoaded = true;
                
            if(projectLoaded && contentChanged && destination.viewNode.id == 'content' && mode == 'replaceChildren')
            {
                var i;
                var found = false;
                for(i in projectURLs) {
                	if(typeof projectURLs[i] == 'function') continue;
                    if(action.indexOf(projectURLs[i]) == 0)
                    {
                        found = true;
                        break;
                    }
                }
                if(!found)
                    if(!confirm(leaveProjectMessage))
                    {
                        hideLoadingMessage( destination, loadingDelayTime );
                        return;
                    }
                    else
                        projectLoaded = false;
            }

            if(found){
            	convertFormDecimals(form.viewNode);
                form.submit();
            }    
            else
            {
                var modalLocked = bb.document.getElementById('modalLocked');
                if(modalLocked)
                    modalLocked.open();
                    
                if(!autoHideLoadingMessage)
                        hideLoadingMessage( destination, loadingDelayTime );
            }
        }
        
        if(autoHideLoadingMessage)
            hideLoadingMessage( destination, loadingDelayTime );
    }
}

var _decimalClass = 'calc_value';

function convertFormDecimals(_form, _revert) {
	// converts all form input elements with class calc_value to correct decimal
	// if __decimalSeparator is NOT a dot
	// if you set _revert param, it will alter value back to fit the __decimalSeparator
	_form = document.getElementById(_form.id);
	if(__decimalSeparator == '.' || !_form)return;
	if(typeof _form == 'string') _form = document.getElementById(_form);
	if(!_form || !_form.elements) return;
	for(i=0; i<_form.elements.length; i++){
		if(_form.elements[i].tagName.toLowerCase() == 'input' 
			&& _form.elements[i].getAttribute('type')
			&& (
					   _form.elements[i].getAttribute('type').toLowerCase() == 'text'
					|| _form.elements[i].getAttribute('type').toLowerCase() == 'number' // html5
					|| _form.elements[i].getAttribute('type').toLowerCase() == 'range'	// html5
				)	
			&& _form.elements[i].className.replace(_decimalClass, '') != _form.elements[i].className){
				_find 	 = (_revert ? '.' : __decimalSeparator);
				_replace = (!_revert ? '.' : __decimalSeparator); 
				_form.elements[i].value = _form.elements[i].value.replace(_find, _replace);
		}
	}
}

function destroyChildren(object)
{
    if(object)
    {                                       
        bb.controller.destructChildren(object);
    }
}

var globalKey = false;
function checkUser()
{
    var url = '/auth/check/key/'+globalKey+'/cache/'+Date();
    
    globalKey = false;
    
    bb.command.load(url, 'get', null, null,null,null,

    function(oRequest, oResponseElm) {        
        var response = oRequest.responseText.substr( 42, oRequest.responseText.length-48);
        if(response && response.length)
            globalKey = response;
    },
    function() {        
        var modalLocked = bb.document.getElementById('modalLocked');
        if(modalLocked)
            modalLocked.open();
    },
    null,
    false);

    if(globalKey)
        return true;
    
    return false;
}

function getPageSize(){
    
    var xScroll, yScroll;
    
    if (window.innerHeight && window.scrollMaxY) {    
        xScroll = document.body.scrollWidth;
        yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
        xScroll = document.body.scrollWidth;
        yScroll = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
        xScroll = document.body.offsetWidth;
        yScroll = document.body.offsetHeight;
    }
    
    var windowWidth, windowHeight;
    if (self.innerHeight) {    // all except Explorer
        windowWidth = self.innerWidth;
        windowHeight = self.innerHeight;
    } else if (document && document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
    } else if (document && document.body) { // other Explorers
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
    }    
    
    // for small pages with total height less then height of the viewport
    if(yScroll < windowHeight){
        pageHeight = windowHeight;
    } else { 
        pageHeight = yScroll;
    }

    // for small pages with total width less then width of the viewport
    if(xScroll < windowWidth){    
        pageWidth = windowWidth;
    } else {
        pageWidth = xScroll;
    }


    arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
    return arrayPageSize;
}
 
function getElementCoords(element)
{
    if(!element)
        return;
    element = element.viewNode;
    if(!element)
        return;
    var offsetArray = getElementOffset(element);
    return new Array(offsetArray[0], offsetArray[1], element.clientWidth, element.clientHeight)
}

function getElementOffset(element)
{
    var xp, yp, op;
    xp = element.offsetLeft;    // Element's offset x in pixels
    yp = element.offsetTop;    // Element's offset y in pixels
    // Now loop through all parent containers, adding offsets as we do so
    while (element.offsetParent) 
    {
        op = element.offsetParent;    // Get container parent
        xp = xp + op.offsetLeft;    // Add this element's offset x in pixels
        yp = yp + op.offsetTop;        // Add this element's offset y in pixels
        element = element.offsetParent;    // Update current container
    }
    return new Array(xp, yp)
}
 
var modalResponse = 0;
function launchModalWarning( message, type, width, height ) {	
	var modal = bb.document.getElementById('generalModalWarning');
	modal.setProperty("label", type);
	var modalMessage = bb.document.getElementById('generalModalWarningMessage');	
	modalMessage.viewNode.innerHTML = message; 
	if ( width == null || width == "" ) {
		width = 300;
	}
	if ( height == null || height == "" ) {
		height = 100;
	}
	var modalLabel = "";
	var modalImage = "";
	switch ( type ) {
		case "warning":
			modalLabel = "Warning";
			modalImage = "warning.gif";
			break;
		case "error": 
			modalLabel = "Error";
			modalImage = "error.gif";
			break;
		case "help": 
			modalLabel = "Help";
			modalImage = "help.gif";
			break;
		default:
			modalLabel = "Alert";
			modalImage = "custom.gif";
			break;
	}
	modal.viewNode.style.width = width + 'px';
	modal.viewNode.style.height = height + 'px';
    modal.open();
}

function getElementsByParticle(inParticle, inRoot)
{                        
    var elem_array = new Array();
    if(typeof(inRoot.firstChild) != 'undefined')
    {
        var elem = inRoot.firstChild;
        while(elem != null)
        {
            if(typeof(elem.firstChild) != 'undefined')
                elem_array = elem_array.concat(getElementsByParticle(inParticle, elem));
            if(elem.id!=null && elem.id!='' && elem.id.search(inParticle)!=-1)
                elem_array.push(elem.id);
            elem = elem.nextSibling;
        }                            
    }
    return elem_array;
}    


function disableSelection(target)
{
    if (typeof target.onselectstart!="undefined") //IE route
    {
        target.onselectstart=function(){return false;};
    }
    else if (typeof target.style.MozUserSelect!="undefined") //Firefox route
    {
        target.style.MozUserSelect="none";
    }
    else //All other route (ie: Opera)
    {
        target.onmousedown=function(){return false}
    }
}

var calculatorDigits = new Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '-', '/', '*', '.');
var calculatorSigns = new Array('+', '-', '/', '*', '.', ',');

function resetCalculator(input)
{
    input.setProperty('value', '');
}

function evalCalculator(input)
{
    input.setProperty('value', eval(input.getProperty('value').toString().replace(new RegExp(__decimalSeparator, 'g'),'.')).toString().replace(new RegExp('[.]', 'g'),__decimalSeparator));
}

function typeCalculator(input, type)
{
    var i;
    
    var found = false;
    var sign =  false;

    for(i in calculatorDigits) {
    	if(typeof calculatorDigits[i] == 'function') continue;
        if(type == calculatorDigits[i])
            found = true;
    }
    for(i in calculatorSigns) {
    	if(typeof calculatorSigns[i] == 'function') continue;
        if(type == calculatorSigns[i])
        {
            found = true;
            sign = true;
        }
    }

    if(!found)
        return;
            
    var value = input.getProperty('value');
    if(!value.length)
    {
        input.setProperty('value', type);
        return;
    }
    
    var lastType = value.substr(value.length - 1, 1);
    found = false;
    for(i in calculatorSigns) {
    	if(typeof calculatorSigns[i] == 'function') continue;
        if(lastType == calculatorSigns[i])
        {
            found = true;
        }
    }
    
    if(found && sign)
    {
        input.setProperty('value', value.substr(0, value.length - 1) + type);
        return;
    }

        input.setProperty('value', value + type);
        return;
}

var accessKeys =  new Array();
var lastFocused = new Array();

function addAccessKey(id, key)
{
    if(!accessKeys[key])
        accessKeys[key] = new Array();
    
    accessKeys[key].push(id);
}

function clickPressed()
{
    lastFocused = new Array();
}

function keyPressed(e)
{
    var keynum;
    var keychar;
    var isAlt;
    var isCtrl;
    var isShift;

    if(window.event) // IE
    {
        keynum = e.keyCode;
        if(window.event.altKey)
            isAlt = true;
        else
            isAlt = false;
        if(window.event.ctrlKey)
            isCtrl = true;
        else
            isCtrl = false;
        if(window.event.shiftKey)
            isShift = true;
        else
            isShift = false;
    }
    else if(e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which;
        if(e.altKey)
            isAlt = true;
        else
            isAlt = false;
        if(e.ctrlKey)
            isCtrl = true;
        else
            isCtrl = false;
        if(e.shiftKey)
            isShift = true;
        else
            isShift = false;
    }

    if(isAlt)
    {
        keychar = String.fromCharCode(keynum);

        if(accessKeys[keychar])
        {
            var i;
            var j;
            if(typeof(lastFocused[keychar]) == 'undefined')
                lastFocused[keychar] = -1;
            for(i in accessKeys[keychar])
            {
            	if(typeof accessKeys[keychar][i] == 'function') continue;
                j = parseInt(i) + parseInt(lastFocused[keychar]) + 1;

                if(j == accessKeys[keychar].length)
                    j = j - accessKeys[keychar].length;
                    
                node = bb.document.getElementById(accessKeys[keychar][j]);
                if(node && node.getAttribute('id') != lastFocused[keychar])
                {
                    node.focus();
                    lastFocused[keychar] = j;
                    e.preventDefault();

                    bb.command.fireEvent(node, "click", false, false);

                    /*
                    if(node.getProperty('nodeName') == 'b:listGrid')
                    {
                        if(!node.getProperty('selectedIndex'))
                        {
                            node.setAttribute('selectedIndexes', 0);
                            node.setProperty('focusedRow', 0);
                        }
                        bb.command.fireEvent(node, "focus", false, false);
                        bb.command.fireEvent(node, "selectionChanged", false, false);
                    }
                    
                    if(node.getProperty('nodeName') == 'input' && node.getAttribute('type') == 'radio' && node.getAttribute('disabled') == '')
                    {
                        node.setAttribute('selected', 'selected');
                    }
                    
                    if(node.getProperty('nodeName') == 'input' && node.getAttribute('type') == 'checkbox' && node.getAttribute('disabled') == '')
                    {
                        node.setAttribute('checked', 'checked');
                    }
                    */
                    
                    return true;
                }
            }
        }
    }

    return true;
}


function toggleProgressDetails(id)
{
    if(!id)
        return;
    var container = bb.document.getElementById(id);
    if(!container)
        return;

    if(container.viewNode.style.display == 'none')
        container.viewNode.style.display = '';
    else
        container.viewNode.style.display = 'none';
    // plus and minus icons
    id_a = id.replace('_details','_overall_valid');
    container = bb.document.getElementById(id_a);
    if(!container)
        return;
    if(container.viewNode.className.split(' ')[1] == 'bullet_toggle_minus_icon')
        container.viewNode.className = 'btl-icon-left bullet_toggle_plus_icon';
    else
        container.viewNode.className = 'btl-icon-left bullet_toggle_minus_icon';
    
    id_b = id.replace('_details','_overall_unvalid');
    container = bb.document.getElementById(id_b);
    if(!container)
        return;
    if(container.viewNode.className.split(' ')[1] == 'bullet_toggle_minus_icon')
        container.viewNode.className = 'btl-icon-left bullet_toggle_plus_icon';
    else
        container.viewNode.className = 'btl-icon-left bullet_toggle_minus_icon';
}

function setProgressItem(id)
{
    if(!bb.document.getElementById(id))
        return;
        
    bb.document.getElementById(id).setProperty('value', '1');
    bb.document.getElementById(id + '_valid').viewNode.style.display = '';
    bb.document.getElementById(id + '_unvalid').viewNode.style.display = 'none';
}
function resetProgressItem(id)
{
    if(!bb.document.getElementById(id))
        return;
        
    bb.document.getElementById(id).setProperty('value', '');
    bb.document.getElementById(id + '_valid').viewNode.style.display = 'none';
    bb.document.getElementById(id + '_unvalid').viewNode.style.display = '';
}

function gridRightClick(event, grid)
{
    if(!event || !grid || event.button != 2)
        return;
        
    // Focus the grid
    if(event.target == grid)
    {
        event.preventDefault();
        var refocused = grid != bb.activeElement;

        var iScrollX = btl.getScrollLeft(grid.viewNode);
        var iScrollY = btl.getScrollTop(grid.viewNode);
        var aCoordinates = bb.html.getBoxObject(grid.viewNode);
        var iNewX = event.clientX + iScrollX - aCoordinates[0] + 1;
        var iNewY= event.clientY + iScrollY - aCoordinates[1] + 1;
        var oFocusElement = grid.getProperty('focusElement');
        oFocusElement.style.left = iNewX + 'px';
        oFocusElement.style.top = iNewY + 'px';

        grid.focus();
    }
    
    if((event.target == grid) || btl.containsElement(grid.viewDataTableContainer, event.viewTarget))
    {
        // Get reference to new row
        var oNewRow = null;
        var oElm = event.viewTarget;
        var oCell = null;
        var oLimit = grid.viewNode;
        while(oElm && oElm != oLimit)
        {
            if(oElm.tagName && oElm.tagName.toLowerCase() == 'td')
                oCell = oElm;//top cell is found

            else if(oElm.tagName && oElm.tagName.toLowerCase() == 'tr')
            {
                oNewRow = oElm;
                //bug 6854 do not break; here since editors may contain tr's and only an actual row of the grid should be set.
            }
            oElm = oElm.parentNode;
        }

        if(oNewRow && btl.containsElement(grid.viewDataTableContainer, oNewRow))
//            if(bb.array.indexOf(grid.getProperty('selectedIndexes'), oNewRow.attributes[0].nodeValue) == -1)
            {
                if(oNewRow != btl.listGrid.edit.row)
                {
                    if(!oNewRow.className.match('selected') || refocused)
                        grid.setProperty('suppressedEditRow', oNewRow);
                    else
                        grid.setProperty('suppressedEditRow', null);

                    grid.commandOnRow(oNewRow, null, null);
                }
            }
    }

}

var progressLoader = '';

function loadProgressItem(item)
{
    var content = bb.document.getElementById('content');
    if(!content)
        return;
    
    var buttons = content.getElementsByTagName('b:button');

    if(!buttons || !buttons.length)
        return;
        
    var back;
    var next;
    
    for(var i in buttons)
    {
    	if(typeof buttons[i] == 'function') continue;
        if(buttons[i].getAttribute('id').indexOf('_back') != -1 && !buttons[i].getAttribute('disabled'))
            back = buttons[i];
        if(buttons[i].getAttribute('id').indexOf('_next') != -1 && !buttons[i].getAttribute('disabled'))
            next = buttons[i];
    }
    
    if(next)
    {
        progressLoader = item;
        bb.command.fireEvent(next, 'click', false, false);
        return;
    }
    
    if(back)
    {
        progressLoader = item;
        bb.command.fireEvent(back, 'click', false, false);
        return;
    }
    
}

function focusFieldset(fieldset) {
	
	var inputElementTags = ['input','select','b:comboBox','textarea','b:spinner','b:calendar','b:richTextEditor','b:spinner','b:checkBoxGroup','b:suggestBox'];
	
	var inputElements = bb.evaluateSmart("[descendant::*[(name()='"+inputElementTags.join("' or name()='")+"') and (not(@readonly) or @readonly != 'readonly') and (not(@type) or @type != 'hidden')]]", fieldset);

	var inputElementCandidate = null;
	var inputElementCandidatePreceding = -1;
	
	for(i in inputElements) {
		
		if(typeof inputElements[i] == 'function') continue;
		var preceding = bb.evaluateSmart("[preceding::*]", inputElements[i]);
		
		if(inputElementCandidatePreceding == -1 || preceding.length < inputElementCandidatePreceding) {
			inputElementCandidate = inputElements[i];
			
			if(inputElementCandidate.viewNode.style.display != 'none') {
				inputElementCandidatePreceding = preceding.length;
			
				if(inputElementCandidatePreceding == 0) {
					break;
				}
			}
		}
	}
	
	if(inputElementCandidate != null) {
		inputElementCandidate.focus();
	}
}

function focusElement(ele) {
	bb.command.focus(ele);
	window.setTimeout(function(){
	    bb.command.focus(ele);
	}, 100);
	window.setTimeout(function(){
	    bb.command.focus(ele);
	}, 300);
}

function focusAddressNew() {
	bb.command.fireEvent(
			bb.evaluateSmart('id(\'objectaddress\')//b:tab[property::selected]//span[contains(@id, \'searchaddress_new\')]'), 
		'click', false, false);
}

function focusAddressEnable() {
	bb.command.fireEvent(
			bb.evaluateSmart('id(\'objectaddress\')//b:tab[property::selected]//span[contains(@id, \'searchaddress_enable\')]')
		, 'click', false, false);
}

function clickElement(ele) {
	bb.command.fireEvent(
			ele
		, 'click', false, false);
}

function records2xml(records, containerName, itemName) {

	var xmlStr = '<'+containerName+'>';
	
	for(i=0; i < records.length; i++) {
		xmlStr += '<'+itemName+'>';
		for(j in records[i].data) {
			if(typeof records[i].data[j] == 'function') continue;
			if(__decimalSeparator != '.' && parseInt(records[i].data[j].toString().replace(__decimalSeparator, '.'))) {
				records[i].data[j] = records[i].data[j].toString().replace(__decimalSeparator, '.');	
			}	
			xmlStr += '<'+j+'><![CDATA['+records[i].data[j]+']]></'+j+'>';
		}
		xmlStr += '</'+itemName+'>';
	}
	
	xmlStr += '</'+containerName+'>';
	
	return xmlStr;
}

function changeSpinner(spinner)
{
    if(!spinner)
        return;
    
    var mandatory = parseInt(spinner.getAttribute('mandatory'));
    var number = parseInt(spinner.getAttribute('number'));
    var old = parseInt(spinner.getAttribute('old'));
    var value = parseInt(spinner.getProperty('value'));
    if(value < number)
        if(mandatory)
            spinner.setProperty('value', number);
        else
            if(old < value)
                spinner.setProperty('value', number);
            else
                spinner.setProperty('value', 0);
    
    if(spinner.getProperty('value') != old)
    {
        spinner.setAttribute('old', spinner.getProperty('value'));
        return true;
    }
    return false;
}
/** overrides for backbase tooltip */
var toolTipEl = null;
hiderTimeOut = false;
function toolTipHide (eEvent) {
	if(hiderTimeOut) clearTimeout(hiderTimeOut);
	btl.toolTipBase.removeHideTriggering(toolTipEl);
	var oChild = btl.toolTipBase.getToolTip(toolTipEl);
    if(oChild.viewNode)
    {
	    document.body.removeChild(oChild.viewNode);
	    oChild.viewNode.style.left = '';
	    oChild.viewNode.style.top = '';
    }
	bb.command.fireEvent(oChild, 'hide', false, false);
	btl.toolTipBase.currentToolTip = null;
	toolTipEl = null;
}

function stringContainsUrl(value) {
	var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
	return regexp.test(value);
}

var selectedSection = '';

function selectProgressItem(selection)
{
    var progressForm = bb.document.getElementById('progressForm');
    
    if(!progressForm)
        return;
        
    var divs = progressForm.getElementsByTagName('div');
    var i;
    for(i in divs)
        if(typeof(divs[i]) != 'function')
            bb.command.removeClass(divs[i], 'selectedProgress');
    
    if(!selection)
        selection = selectedSection;
        
    if(!selection)
        return;
        
    var div;
    
    div = bb.document.getElementById(selection + '_valid');
    if(div)
        bb.command.addClass(div, 'selectedProgress');

    div = bb.document.getElementById(selection + '_unvalid');
    if(div)
        bb.command.addClass(div, 'selectedProgress');
}

var contentChanged = false;


                            
Ext.override(Ext.data.Store, 
    {
        sortByFields: function(fields) 
        {
            var st = [];
            for (var i = 0; i < fields.length; i++) 
            {
                if (typeof fields[i] == 'string') 
                {
                    fields[i] = 
                    {
                        field: fields[i],
                        direction: 'ASC'
                    };
                }
                st.push(this.fields.get(fields[i].field).sortType);
            }

            var fn = function(r1, r2) 
            {
                var result;
                for (var i = 0; !result && i < fields.length; i++) 
                {
                    var v1 = st[i](r1.data[fields[i].field]);
                    var v2 = st[i](r2.data[fields[i].field]);
                    result = (v1 > v2) ? 1 : ((v1 < v2) ? -1 : 0);
                    if (fields[i].direction == 'DESC') result = -result;
                }
                return result;
            };
            
            this.data.sort('ASC', fn);
            
            if(this.snapshot && this.snapshot != this.data)
            {
                this.snapshot.sort('ASC', fn);
            }
            
            this.fireEvent("datachanged", this);
        }
    }
);


