var Application = Class.create();
Application.AssemblyInfo = { Title:'CFEMCNaturalGas.com', Author: 'Brian R. Miedlar', Contact: 'bmiedlar@gmail.com', Company: 'McRae' };
Application.SubApplication = null;

Application.ActiveInteractions = [];
Application.OpenInteraction = function(element, onBeginShow, onEndShow, options) {
    var dlgInt = new DialogHandler(element, {onBeginShow:onBeginShow, onEndShow:onEndShow});
	dlgInt.show(options);
	Application.ActiveInteractions.push(dlgInt);
}
Application.CloseDialogs = function() {
	Application.ActiveInteractions.invoke('hide');
}
Application.SwitchPanel = function(pvContentElement, activePanel, onActive, navItemElement, isSafe) {
    $$('#' + $(pvContentElement).identify() + '>.panel').each(function(element) { if (isSafe) Element.SafeHide(element); else Element.hide(element); });
    if (isSafe) Element.SafeShow($(activePanel)); else Element.show(activePanel);
    if (onActive) onActive($(activePanel), navItemElement);
};
Application.OnRollover = function(element, classNames) {
    var arrClassName = ['active']; if (classNames) arrClassName = arrClassName.concat(classNames);
    arrClassName.each(function(className) {
        if (Element.hasClassName(element, className)) return;
        Element.addClassName(element, className);
    });
};
Application.OnRollout = function(element, classNames) {
    var arrClassName = ['active']; if (classNames) arrClassName = arrClassName.concat(classNames);
    arrClassName.each(function(className) {
        Element.removeClassName(element, className)
    });
};
Application.SetRollover = function(element, classNames, options) {
    if (!options) options = {};
    var onEvent = 'mouseover';
    if (options.onEvent) onEvent = options.onEvent;
    var sId = Element.identify(element);
    Event.observe(element, onEvent, function(e) {
        var bExclude = false;
        if (options.exclude && options.exclude(e)) bExclude = true;
        if (!bExclude) {
            Application.OnRollover(sId, classNames);
            if (options.onActive) options.onActive(sId);
            return;
        }
        Application.OnRollout(sId, classNames);
    });
    Event.observe(element, 'mouseout', function(e) {
        if (Position.within($(sId), e.pointerX(), e.pointerY())) {
            var bExclude = false;
            if (options.exclude && options.exclude(e)) bExclude = true;
            if (!bExclude) return;
        }
        Application.OnRollout(sId, classNames);
    });
}
Application.UnsetRollover = function(element) {
    Event.stopObserving(element, 'mouseover', function() { Application.OnRollover(element); });
    Event.stopObserving(element, 'mouseout', function() { Application.OnRollout(element); });
}
Application.SelectableEvents = new Hash();
Application.SelectableChangeEvents = new Hash();
Application.SetSelectable = function(dataElement, inputElement, onChange) {
    var sId = Element.identify(dataElement);
    var fSelect = Application.SelectableEvents.get(sId);
    if (fSelect) Event.stopObserving(dataElement, 'mousedown', fSelect);

    Application.SelectableChangeEvents.set(sId, onChange);
    fSelect = function() {
        var fChange = Application.SelectableChangeEvents.get(sId);
        if (Element.hasClassName(sId, 'selected')) {
            Element.removeClassName(sId, 'selected');
            if (fChange) fChange(false);
            return;
        }
        Element.addClassName(sId, 'selected');
        if (fChange) fChange(true);
        return;
    }
    Application.SelectableEvents.set(sId, fSelect);
    Event.observe(dataElement, 'mousedown', fSelect);
}
Application.SetSelectableGroup = function(groupElement, isIncremental) {
    groupElement = $(groupElement);
    Event.observe(groupElement, 'mousedown', function() {
        setTimeout(function() {
            var bFound = false;
            groupElement.select('.radio').each(function(dataElement) {
                var eRadio = dataElement.down('input'); if (!eRadio) return;
                if (eRadio.checked) {
                    dataElement.addClassName('selected');
                    bFound = true;
                    return;
                }
                if (bFound || !isIncremental) { dataElement.removeClassName('selected'); return; }
                dataElement.addClassName('selected');
            });
        }, 300);
    });
}
Application.SelectNav = function(element) {
    element = $(element);
    var eNav = element.up('.navigation');
    var arrItem = eNav.select('.navItem');
    eNav.LastSelected = eNav.down('.selected');
    arrItem.invoke('removeClassName', 'selected');
    element.addClassName('selected');
}
Application.SelectCommand = function(element) {
    element = $(element);
    element.up('.commands').select('.command').invoke('removeClassName', 'selected');
    element.addClassName('selected');
}
Application.SetPanelViewBehavior = function(pvElement, onActive, eventName, isSafe) {
    var eContent = pvElement.down('.content');
    pvElement.down('.navigation').select('.navItem').each(function(item) {        
        Application.ApplyPanelBehavior(eContent, item, onActive, eventName, isSafe);
    });
}
Application.PanelSwitches = new Hash();
Application.ApplyPanelBehavior = function(pvContentElement, navItemElement, onActive, eventName, isSafe) {
    if (!eventName) eventName = 'click';
    navItemElement.classNames().each(function(className) {
        if (className.indexOf('ni') == 0) {
            var sKey = className.substr(2);
            var ePanel = pvContentElement.down('.pnl' + sKey);
            if (!ePanel) return;
            var fSwitch = function() { Application.SwitchPanel(pvContentElement, ePanel, onActive, navItemElement, isSafe); Application.SelectNav(navItemElement); };
            Application.PanelSwitches.set(navItemElement.identify(), fSwitch);
            Event.observe(navItemElement, eventName, function() {
                var fTrySwitch = Application.PanelSwitches.get(navItemElement.identify());
                if (fTrySwitch) fTrySwitch();
            });
        }
    });
}
Application.ToggleEvents = new Hash();
Application.RunToggleBehavior = function(pvTogglableElementId, expandRecursive, onChange) {
    var eTogglable = $(pvTogglableElementId);
    var oToggle = eTogglable.down('.toggle');
    if (!oToggle) return;
    var bWillOpen = oToggle.hasClassName('tglClosed');
    var arrDeepToggleContent = [];
    if (!expandRecursive) arrDeepToggleContent = $$('#' + pvTogglableElementId + ' .toggleContent .toggleContent');
    eTogglable.select('.toggleContent').each(function(content) {
        if (arrDeepToggleContent.indexOf(content) >= 0) return;
        if (bWillOpen) {
            Element.show(content); setTimeout(function() { content.forceRerendering(); }, 50);
        } else {
            Element.hide(content);
        }
        var eToggle = content.up('.togglable').down('.toggle');
        if (bWillOpen) {
            Element.removeClassName(eToggle, 'tglClosed');
            Element.addClassName(eToggle, 'tglOpen');
            if(!Element.hasClassName(eToggle, 'caption')) eToggle.innerHTML = '-';
        } else {
            Element.removeClassName(eToggle, 'tglOpen');
            Element.addClassName(eToggle, 'tglClosed');
            if (!Element.hasClassName(eToggle, 'caption')) eToggle.innerHTML = '+';
        }
    });
    if (onChange) onChange();
}
Application.SetTogglableBehavior = function(pvTogglableElement, expandRecursive, onChange) {
    var sId = Element.identify(pvTogglableElement);
    var fnToggle = function() {
        Application.RunToggleBehavior(sId, expandRecursive, onChange);
    }
    var fSetToggle = function(toggle) {
        if (toggle.up('.togglable') != pvTogglableElement) return;
        Application.ToggleEvents.set(Element.identify(toggle), fnToggle);
        Event.observe(toggle, 'click', fnToggle);
    };
    Element.select(pvTogglableElement, '.toggle').each(fSetToggle);
}
Application.ThrowFire = function(element, message) {
	element = $(element);
	var sId = element.identify();
	var ef = new Effect.Highlight(element, {queue: {position:'end', scope: sId }});
	ef = null;
	element.update(message);
}

//Util
Application.ValidateEmail = function(email) {
    return (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email));
}
Application.ToCurrency = function(num, hideCents) {
    num = num.toString().replace(/\$|\,/g,''); 
    if(isNaN(num)) num = "0"; 
    sign = (num == (num = Math.abs(num))); 
    num = Math.floor(num*100+0.50000000001); 
    cents = num%100; 
    num = Math.floor(num/100).toString(); 
    if(cents<10) cents = "0" + cents; 
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++) num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3)); 
    var sCurrency = (((sign)?'':'-') + '$' + num);
    if(!hideCents) sCurrency += '.' + cents; 
    return sCurrency;
}
Application.ToFixed = function(num, places) {
    num = num.toString();
    var idxDecimal = num.search(/\./);
    var sOut = num;
    if (idxDecimal >= -1) {
       sOut = num.substring(0, idxDecimal + 1 + places);
    }
    return sOut;
}
Application.ToPhone = function(number) {
    var sPhone;
    var sOriginal = number;    
    var re1 = /\D/;
    var re2 = /^\({1}\d{3}\)\d{3}-\d{4}/; // test for this format: (xxx)xxx-xxxx
    if (!number || re2.test(number)) return number;

    while (re1.test(number)) number = number.replace(re1, "");

    if (number.length == 11) {
        // for format 1-(xxx)xxx-xxxx
        return number.substring(0, 1) + ' (' + number.substring(1, 4) + ') ' + number.substring(4, 7) + '-' + number.substring(7, 11);
    } else if (number.length == 10) {
        // for format (xxx)xxx-xxxx
        return '(' + number.substring(0, 3) + ') ' + number.substring(3, 6) + '-' + number.substring(6, 10);
    } else if (number.length == 7) {
        // for format xxx-xxxx
        return number.substring(0, 3) + '-' + number.substring(3, 7);
    } else {
        return sOriginal; //invalid return original
    }
}
//Validation scripts
Application.ActiveRadioList = new Hash();
Application.ActiveThrows = new Hash();
Application.ValidateStatuses = new Hash();
Application.IsValidThrowStatus = function(container) {
    container = $(container);
    return (Application.ValidateStatuses.get(container.identify()) == true);
}
Application.ThrowMessages = new Hash();
Application.ResetThrowStatus = function(container, formContainer) {
    container = $(container);
    container.innerHTML = '';
    var iThrow = Application.IncrementThrow(container);
    Element.hide(container);
    Application.ActiveRadioList = new Hash();
    Application.ValidateStatuses.set(container.identify(), true);
    if (formContainer) {
        var arrInput = Element.select(formContainer, '.highlight');
        arrInput.each(function(input) {
            Element.removeClassName(input, 'highlight');
        });
    }
}
Application.IncrementThrow = function(container) {
    container = $(container);
    var iThrow = (Application.ActiveThrows.get(container.identify()) || 0) + 1;
    if(iThrow > 1000) iThrow = 0;
    Application.ActiveThrows.set(container.identify(), iThrow);
    return iThrow;
}
Application.RemoveThrowStatus = function(container, delayWriteKey) {
    var sId = Element.identify(container);
    var hMessage = Application.ThrowMessages.get(sId);
    if (!hMessage) return;
    hMessage.unset(delayWriteKey);
}
Application.ThrowStatus = function(container, message, inputContainer, triggerInput, delayWriteKey) {
    container = $(container);
    var sId = Element.identify(container);
    var hMessage = Application.ThrowMessages.get(sId);
    if (!hMessage) hMessage = new Hash();

    if (triggerInput && triggerInput != inputContainer) return;
    Application.ValidateStatuses.set(container.identify(), false);
    inputContainer = $(inputContainer);
    if (inputContainer) Element.addClassName(inputContainer, 'highlight');
    if (triggerInput) return;
    var iThrow = Application.IncrementThrow(container);
    if (!delayWriteKey) {
        Element.show(container);
        container.innerHTML += '<p>* ' + message + '</p>';
    } else {
        hMessage.set(delayWriteKey, message);
    }
    Application.ThrowMessages.set(sId, hMessage);
    return false;
};
Application.ThrowStatusSummary = function(container) {
    container = $(container);
    var sId = Element.identify(container);
    container.innerHTML = '';
    var hMessage = Application.ThrowMessages.get(sId);
    if (!hMessage) return;
    hMessage.each(function(pair) {
        container.innerHTML += '<p>* ' + pair.value + '</p>';
    });
    Element.show(container);
}

//Require fields
//container: the HUD to display the message
//element: the input element
//msg: validation message
//triggerInput: optional - the object triggering the event will be highlighted if provided
Application.RequireAutocomplete = function(container, element, requiredMsg, invalidValueMsg, triggerInput, valueCollection) {
    element = $(element);
    var sKey = 'AC_' + Element.identify(element);
    if (!Application.RequireTextbox(container, element, requiredMsg, triggerInput)) return false;
    if (valueCollection.indexOf(element.value) < 0) {
        Application.ThrowStatus(container, invalidValueMsg, element, triggerInput, sKey); return false;
    }
    Application.RemoveThrowStatus(container, sKey);
    return true;
};
Application.RequireTextbox = function(container, element, msg, triggerInput) {
    element = $(element);
    var sKey = 'TB_' + Element.identify(element);
    if (element.value.length == 0) { Application.ThrowStatus(container, msg, element, triggerInput, sKey); return false; }
    Application.RemoveThrowStatus(container, sKey);
    return true;
};
Application.RequireDigitsLength = function(container, element, length, msg, triggerInput) {
    element = $(element);
    var sVal = element.value.replace(/[^0-9]+/g, '');
    var sKey = 'TBDig_' + Element.identify(element);
    element.value = sVal;
    if (element.value.length != length) { Application.ThrowStatus(container, msg, element, triggerInput, sKey); return false; }
    Application.RemoveThrowStatus(container, sKey);
    return true;
};
Application.RequireCheckbox = function(container, element, msg, triggerInput) {
    element = $(element);
    var sKey = 'CB_' + Element.identify(element);
    var eCheckbox = Element.up(element, '.checkbox');
    var eLastTrigger = triggerInput;
    if (triggerInput) {
        var eGroup = Element.up(triggerInput, '.group');
        if (eGroup) triggerInput = Element.down(eGroup, '.checkbox');
    }
    if (!triggerInput) triggerInput = eLastTrigger;
    if (!element.checked) { Application.ThrowStatus(container, msg, eCheckbox, triggerInput, sKey); return false; }
    Application.RemoveThrowStatus(container, sKey);
    return true;
};
Application.RequireRadioGroup = function(form, container, radioGroup, radioContainer, msg, triggerInput) {
    var sKey = 'RG_' + radioGroup;
    var oActive = Application.ActiveRadioList.get(radioGroup);
    var eLastTrigger = triggerInput;
    if (triggerInput) {
        var eGroup = Element.up(triggerInput, '.group')
        if (eGroup) triggerInput = Element.down(eGroup, '.radioList');
    }
    if (!triggerInput) triggerInput = eLastTrigger;
    if (!oActive && !Application.GetRadioValue(form, radioGroup)) {
        Application.ThrowStatus(container, msg, $(radioContainer), triggerInput, sKey);
        Application.ActiveRadioList.set(radioGroup, true);
        return false;
    }
    Application.RemoveThrowStatus(container, sKey);
    return true;
};
Application.RequireReadonly = function(container, element, msg, triggerInput) {
    element = $(element);
    var skey = 'RO_' + Element.identify(element);
    if (element.innerHTML.length == 0 || element.innerHTML == '0') { Application.ThrowStatus(container, msg, element, triggerInput, sKey); return false; }
    Application.RemoveThrowStatus(container, sKey);
    return true;
};
Application.RequireInteger = function(container, element, msg, triggerInput) {
    element = $(element);
    var sKey = 'INT_' + Element.identify(element);
    var iValue = parseInt(element.value) || 0;
    if (iValue != element.value || iValue <= 0) {
        Application.ThrowStatus(container, msg, element, triggerInput, sKey);
        return false;
    }
    Application.RemoveThrowStatus(container, sKey);
    return true;
};
Application.RequireGreaterThan = function(container, greaterElement, lesserElement, msg, triggerInput) {
    greaterElement = $(greaterElement);
    lesserElement = $(lesserElement);
    var sKey = 'GT_' + Element.identify(greaterElement);
    var iValue = parseInt(greaterElement.value) || 0;
    var iValue2 = parseInt(lesserElement.value) || 0;
    if (iValue <= iValue2) { Application.ThrowStatus(container, msg, lesserElement, triggerInput, sKey); return false; }
    Application.RemoveThrowStatus(container, sKey);
    return true;
};
Application.RequireEqual = function(container, firstElement, secondElement, msg, triggerInput) {
    firstElement = $(firstElement);
    secondElement = $(secondElement);
    var sKey = 'EQ_' + Element.identify(firstElement);
    var iValue = firstElement.value;
    var iValue2 = secondElement.value;
    if (iValue != iValue2) { Application.ThrowStatus(container, msg, secondElement, triggerInput, sKey); return false; }
    Application.RemoveThrowStatus(container, sKey);
    return true;
};
Application.RequireWatermark = function(container, element, msg, triggerInput) {
    element = $(element);
    var sKey = 'WM_' + Element.identify(element);
    if (element.watermark.emptyValue()) { Application.ThrowStatus(container, msg, element, triggerInput, sKey); return false; }
    Application.RemoveThrowStatus(container, sKey);
    return true;
};
Application.ApplyMultipleClassName = function(selector, ignoreList) {
    $$(selector).each(function(element) {
        var sCombinedPrevious = "";
        var arrCombined = [];
    	element.classNames().each(function(className) {
	    	if(className.indexOf('mc-') == 0) { sCombinedPrevious = className; return; }
	    	var bIgnore = false;
	    	if(ignoreList) ignoreList.each(function(ignore) { if(className == ignore) bIgnore = true; });
	    	if(bIgnore) return;
	    	arrCombined.push(className);
        });
        if(sCombinedPrevious.length > 0) element.removeClassName(sCombinedPrevious);
        if(arrCombined.length > 0) {
            var sCombined = "mc-";
            arrCombined.OrderBy(function(item) { return item; }).each(function(className) {
	    	    if(sCombined.length > 3) sCombined += '-';
                sCombined += className;
            });            
            element.addClassName(sCombined);
        }
    });
};

Application.SetFilter = function(filterableElement, filterKey) {
	$(filterableElement).select('.filtered').each(function(filtered) {
		if(Element.hasClassName(filtered, 'flt' + filterKey)) {
			Element.show(filtered); return; 
		}
		Element.hide(filtered);
	});
}

Application.Loading = new Hash();
Application.UpdateLoaderStatus = function() {
    var sKeys = '';
    var bHourglass = false;
    Application.Loading.each(function(pair) {
        if (pair.value.caption) {
            if (sKeys.length > 0) sKeys += ', ';
            sKeys += pair.value.caption;
        }
        if (pair.value.showHourglass) bHourglass = true;
    });
    if (bHourglass) { } //show loader here
    if (sKeys.length == 0) { Element.hide('Hud_Status'); return; }
    Element.show('Hud_Status');
    $('Hud_Status').innerHTML = 'Please Wait - ' + sKeys;
}
Application.ShowLoader = function(key, caption, showHourglass, singleThread) {
    var oLoad = Application.Loading.get(key);
    if (oLoad && !singleThread) {
        oLoad.iterations++;
        Application.Loading.set(key, oLoad);
    } else {
        Application.Loading.set(key, { caption: caption, iterations: 1, showHourglass: showHourglass });
    }
    Application.UpdateLoaderStatus();
}
Application.HideLoader = function(key) {
    setTimeout(function() {
        var oLoad = Application.Loading.get(key);
        if (oLoad) {
            var iValue = oLoad.iterations - 1;
            if (iValue <= 0) {
                Application.Loading.unset(key);
            } else {
                oLoad.iterations = iValue;
                Application.Loading.set(key, oLoad);
            }
        }
        if (Application.Loading.size() == 0) { Element.hide('Hud_Status');  }
        Application.UpdateLoaderStatus();
    }, 1500);
}
Application.ShowProgress = function(value) {
    if (!$('Progress_Module')) return;
    $('Progress_Module').innerHTML = value + '%';
    Element.show('Progress_Module');
}
Application.HideProgress = function() {
    if (!$('Progress_Module')) return;
    new Effect.Fade('Progress_Module'); 
}

Application.NumberFormat = function (number, decimals, thousands_sep) {
  var n = number;
  var c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
  var d = ".";
  var t = thousands_sep ? "," : "";
  var s = n < 0 ? "-" : "";
  var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
  return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}

Application.ToShortDate = function(date) {
    date = new Date(date);
    return date.getMonth() + '/' + date.getDay() + '/' + date.getFullYear();
}

Application.GetSystemFeed = function(feed) {
    switch (feed) {
        case 1:
            return 'gamls';
        case 2:
            return 'fmls';
        default:
            return 'unknown';
    }
}
Application.SetSystemFeed = function(element, name) {
    for (var i = 1; i <= 2; i++) {
        var sFeed = Application.GetSystemFeed(i);
        if (sFeed != name) { Element.removeClassName(element, sFeed); continue; }
        Element.addClassName(element, name);
    }
}
Application.GetFlashObject = function(key) {
    if (Prototype.Browser.IE) return window[key]; 
    return $(key);
}
Application.GetRadioValue = function(form, radioGroup) {
    var checked = $(form).getInputs('radio', radioGroup).find(
        function(re) { return re.checked; }
    );
    return (checked) ? { text:checked.next('label').innerHTML, value: $F(checked)} : null;
}  
Application.OpenToggle = function(targetElement) {
    targetElement = $(targetElement);
    if (!targetElement) return;
    var eTogglable = targetElement.up('.togglable');
    for (var i = 0; i < 30; i++) {
        if (!eTogglable) return;
        eToggle = eTogglable.down('.toggle');
        eContent = eTogglable.down('.toggleContent');
        if (eToggle) {
            Element.removeClassName(eToggle, 'tglClosed');
            Element.addClassName(eToggle, 'tglOpen');
        }
        if (eContent) Element.show(eContent);

        eTogglable = eTogglable.up('.togglable');
    }
}

Application.QueueList = new Hash();
Application.QueueTask = function(key, waitTime, task, beforeStart) {
    var oWork = Application.QueueList.get(key);
    if (!oWork) oWork = { isRequested: false, task: task, running: false, wait: waitTime * 1000, beforeStart: beforeStart };
    if (oWork.running) {
        oWork.isRequested = true;
        oWork.task = task;
        Application.QueueList.set(key, oWork);
        //console.log('Work already running, added to queue:' + key);
        return;
    }

    Application.QueueList.set(key, oWork);
    setTimeout(function() { Application.RunQueuedTask(key); }, 5);
};
Application.RunQueuedTask = function(key) {
    var oWork = Application.QueueList.get(key);
    if (!oWork || oWork.running) return;
    oWork.running = true;
    Application.QueueList.set(key, oWork);

    if (oWork.beforeStart) oWork.beforeStart();
    setTimeout(function() {
        //console.log('Running queue task(d' + oWork.wait + '):' + key);
        setTimeout(function() {
            //console.log('Starting task:' + key);
            oWork.isRequested = false;
            Application.QueueList.set(key, oWork);
            oWork.task(function() {
                //console.log('Completed task:' + key);
                oWork = Application.QueueList.get(key);
                oWork.running = false;
                if (oWork.isRequested) {
                    //console.log('New request found:' + key);
                    Application.QueueList.set(key, oWork);
                    setTimeout(function() { Application.RunQueuedTask(key); }, 5);
                    return;
                }
                //console.log('Remove from queue:' + key);
                Application.QueueList.unset(key);
            });
        }, oWork.wait);
    });
}
//data in format [{key:.., caption:.., content:..},{..}]
Application.BuildDetailPanelView = function(viewElement, navElement, contentElement, data) {
    viewElement = $(viewElement);
    navElement = $(navElement);
    contentElement = $(contentElement);

    Event.stopObserving(navElement, 'click');
    navElement.innerHTML = '';
    contentElement.innerHTML = '';
    var i = 0;
    data.each(function(item) {
        var eNav = OS.AppendChild(navElement, 'li', 'navItem ni' + item.key);
        eNav.innerHTML = item.caption;
        var ePanel = OS.AppendDiv(contentElement, 'panel pnl' + item.key);
        ePanel.innerHTML = item.content;
        if (i > 0) Element.hide(ePanel);
        if (i == 0) Element.addClassName(eNav, 'selected');
        i++;
    });

    Application.SetPanelViewBehavior(viewElement, null, 'click', false);
}
Application.ShowAutocompleter = function(autocompleter) {

    autocompleter.changed = true;
    autocompleter.hasFocus = true;
    if (autocompleter.observer) clearTimeout(autocompleter.observer);
    autocompleter.observer =
		setTimeout(autocompleter.onObserverEvent.bind(autocompleter), autocompleter.options.frequency * 1000);
}
Application.CreateFilter = function(key, text, parent, checked, onChange) {
    var eItem = document.createElement('span');
    eItem.className = 'data checkbox';
    var eCheck;
    if (!Prototype.Browser.IE) { eCheck = OS.AppendChild(eItem, 'input'); }
    else { eCheck = document.createElement('<input type="checkbox">'); eItem.appendChild(eCheck); }
    eCheck.id = key;
    if (!Prototype.Browser.IE) eCheck.setAttribute('type', 'checkbox');
    var eLabel = OS.AppendChild(eItem, 'label');
    eLabel.setAttribute('for', key);
    eLabel.innerHTML = text;
    parent.appendChild(eItem);
    if (checked) { Element.addClassName(eItem, 'selected'); }
    Application.SetSelectable(eItem, eCheck, onChange);
    return eItem;
};

Application.ViewName = null;
Application.PageTracker = null;
Application.Track = function(view) {
    Application.ViewName = view;
    if (Application.PageTracker) { Application.PageTracker._trackPageview(view); }
}

Application.IsSelected = function(inputElement) {
    var eCb = $(inputElement).up('.checkbox');
    if (!eCb) return false;
    return eCb.hasClassName('selected');
}

Application.DisguiseElements = new Hash();
Element.Disguise = function(element) {
    element = $(element);
    Element.setStyle(element, { left: '-9999px' });
}
Element.UnDisguise = function(element) {
    element = $(element);
    if (element.identify() == 'Map_Locator') { Element.setStyle(element, { left: '3px' }); return; }
    Element.setStyle(element, { left: 'auto' });
    //    var oReset = Application.DisguiseElements.get(element.identify());
    //    if (!oReset) return;
    //    Element.setStyle(element, { left: oReset.left + 'px' });
}

var _grabCookies = function() {
    return {
        baseName: OS.GetCookie('BowenRegionBaseName'),
        state: OS.GetCookie('BowenRegionState')
    }
}

Application.FeaturesEnabled = true;
Application.HandleBrowser = function() {
    if ((Prototype.Browser.IE && Prototype.BrowserVersion() < 7)) {
        Application.FeaturesEnabled = false;
        if ($('SeoContent')) Element.show('SeoContent');
        if ($('App_Find')) Element.hide('App_Find');
        return;
    }
    if ($('SeoContent')) { Element.hide('SeoContent'); $('SeoContent').innerHTML = ''; }
    if ($('App_Find')) Element.show('App_Find');
}
Application.GetHash = function() {
    if (window.location.hash.length == 0) return '';
    return window.location.hash.substring(1);
};
Application.UrlEncode = function(val) {
    val = val.replace(/ /g, "%20");
    val = val.replace(/\'/g, "%27");
    return val;
};
Application.JsEncode = function(val) {
    val = val.replace(/\'/g, "\\\'");
    return val;
};
Application.GetUrl = function() {
    return window.location.href;
}
Application.GetTitle = function(noHash) {
    var sTitle = document.title;
    var iHash = sTitle.indexOf("#");
    if (!noHash || iHash < 0) return sTitle;
    var sTitle = sTitle.substring(0, iHash);
    return sTitle;
}
Application.Title = '';
Application.SetTitle = function(title) {
    document.title = title;
}
Application.SetHash = function(hash) {
    Application.CurrentHash = hash;
    if (!Prototype.Browser.IE) {
        window.location.hash = hash;
        return;
    } else if (Prototype.BrowserVersion() < 7) return;

    if (!$('Frame_History')) return;
    var doc = $('Frame_History').contentWindow.document;
    doc.open("javascript:'<html></html>'");
    doc.write("<html><head><scri" + "pt type=\"text/javascript\">parent._onHistoryFrameLoaded('" + (hash) + "');</scri" + "pt></head><body></body></html>");
    doc.close();
};
Application.CurrentHash = Application.GetHash();
Application.CurrentTitle = Application.GetTitle(true);
Application.HistoryMonitor = null;
Application.InitHistory = function() {
    if (window.opera && window.history) {
        history.navigationMode = 'compatible';
    }
    if (Prototype.Browser.IE) return;

    Application.HistoryMonitor = new PeriodicalExecuter(function() {
        if (Application.Loading.size() > 0) return;
        var sHash = Application.GetHash();
        AppBehavior.OnChangeHistory(sHash);
    }, .3);
};
var _onHistoryFrameLoaded = function(hash) {
    if (!Prototype.Browser.IE) return;
    //if (Prototype.BrowserVersion() < 7) return;

    if (!Application.Ready) return;
    window.location.hash = hash;    
    Application.SetTitle(Application.CurrentTitle);
    setTimeout(function() { Application.SetTitle(Application.CurrentTitle) }, 0);
    AppBehavior.OnChangeHistory(hash);
}
Application._googleLoadCount = 0;
Application._loadAnalytics = function(trackerId) {
    if (typeof (_gat) == 'undefined' || !_gat) { if (Application._googleLoadCount < 100) setTimeout(function() { Application._loadAnalytics(trackerId); }, 500); Application._googleLoadCount++; return; }
    Application.PageTracker = _gat._getTracker(trackerId);
    Application.Track();
};
Application.LoadAnalytics = function(trackerId) {
    var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
    document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
    Application._loadAnalytics(trackerId);
}
Application.Trim = function(val) { return val.replace(/^\s+|\s+$/g, ''); }
Application.Alert = function(val) { console.log(val); };
Application.Ready = false;
