/*
 * Utility functions
 * requires YAHOO.util.Event, Dom
 *
 */
(function(){
    var util  = YAHOO.namespace('OH.util'),
        Event = YAHOO.util.Event,
        DOM   = YAHOO.util.Dom;
        
		if (YAHOO.widget.Panel){
			util.wait = new YAHOO.widget.Panel("wait",
				{ width:"240px",
				  fixedcenter:true,
				  close:false,
				  draggable:false,
				  zindex:4000,
				  modal:false,
				  visible:false
				}
			);
	
			util.wait.setHeader("Loading, please wait...");
			util.wait.setBody('<img src="http://x.ourhistree.com/i/content/rel_interstitial_loading.gif" />');
			util.wait.render(document.body);
		}
     // http://dean.edwards.name/weblog/2006/07/enum/
     // generic enumeration
     Function.prototype.forEach = function(object, block, context) {
         for (var key in object) {
             if (typeof this.prototype[key] == "undefined") {
                 block.call(context, object[key], key, object);
             }
         }
     };

     // globally resolve forEach enumeration
     util.forEach = function(object, block, context) 
     {
         if (object) {
             var resolve = Object; // default
             if (object instanceof Function) {
                 // functions have a "length" property
                 resolve = Function;
             } else if (object.forEach instanceof Function) {
                 // the object implements a custom forEach method so use that
                 object.forEach(block, context);
                 return;
             } else if (typeof object.length == "number") {
                 // the object is array-like
                 resolve = Array;
             }
             resolve.forEach(object, block, context);
         }
     };

     // ASK: Should spaces be allowed?
    util.validation_types = {
        alpha: /^[a-zA-Z]+$/,
        alphanum: /^\w+$/,
        number: /^\d+$/,
        digits: /^[\d ]+$/
        // email: /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,}$/,
        // url: /^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]+)(\.[A-Z0-9][A-Z0-9_-]+)+)(:(\d+))?/i
        // currency_dollar: /^\$?\-?([1-9]{1}\d{0,2}(\,\d{3})*(\.\d{0,2})?|[1-9]{1}\d*(\.\d{0,2})?|0(\.\d{0,2})?|(\.\d{1,2})?)$/
        // date functions? date, date-YYYY-MM-DD, date-MM-DD-YYYY
        // how do you deal with different separators ('-' vs '/')
    };

    // create accessor functions
    for (var type in util.validation_types){
        util[type] = (function(type){
            return function(val){
                return util.validation_types[type].test(val);
            };
        })(type);
    }

    util.get_html_translation_table = function (table, quote_style) 
    {
        // Returns the internal translation table used by htmlspecialchars and htmlentities  
        // 
        // version: 908.406
        // discuss at: http://phpjs.org/functions/get_html_translation_table
        // +   original by: Philip Peterson
        // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
        // +   bugfixed by: noname
        // +   bugfixed by: Alex
        // +   bugfixed by: Marco
        // +   bugfixed by: madipta
        // +   improved by: KELAN
        // +   improved by: Brett Zamir (http://brett-zamir.me)
        // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
        // +      input by: Frank Forte
        // +   bugfixed by: T.Wild
        // +      input by: Ratheous
        // %          note: It has been decided that we're not going to add global
        // %          note: dependencies to php.js, meaning the constants are not
        // %          note: real constants, but strings instead. Integers are also supported if someone
        // %          note: chooses to create the constants themselves.
        // *     example 1: get_html_translation_table('HTML_SPECIALCHARS');
        // *     returns 1: {'"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}
        
        var entities = {}, hash_map = {}, decimal = 0, symbol = '';
        var constMappingTable = {}, constMappingQuoteStyle = {};
        var useTable = {}, useQuoteStyle = {};
        
        // Translate arguments
        constMappingTable[0]      = 'HTML_SPECIALCHARS';
        constMappingTable[1]      = 'HTML_ENTITIES';
        constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
        constMappingQuoteStyle[2] = 'ENT_COMPAT';
        constMappingQuoteStyle[3] = 'ENT_QUOTES';
    
        useTable       = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';
        useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT';
    
        if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
            throw new Error("Table: "+useTable+' not supported');
            // return false;
        }
    
        entities['38'] = '&amp;';
        if (useTable === 'HTML_ENTITIES') {
            entities['160'] = '&nbsp;';
            entities['161'] = '&iexcl;';
            entities['162'] = '&cent;';
            entities['163'] = '&pound;';
            entities['164'] = '&curren;';
            entities['165'] = '&yen;';
            entities['166'] = '&brvbar;';
            entities['167'] = '&sect;';
            entities['168'] = '&uml;';
            entities['169'] = '&copy;';
            entities['170'] = '&ordf;';
            entities['171'] = '&laquo;';
            entities['172'] = '&not;';
            entities['173'] = '&shy;';
            entities['174'] = '&reg;';
            entities['175'] = '&macr;';
            entities['176'] = '&deg;';
            entities['177'] = '&plusmn;';
            entities['178'] = '&sup2;';
            entities['179'] = '&sup3;';
            entities['180'] = '&acute;';
            entities['181'] = '&micro;';
            entities['182'] = '&para;';
            entities['183'] = '&middot;';
            entities['184'] = '&cedil;';
            entities['185'] = '&sup1;';
            entities['186'] = '&ordm;';
            entities['187'] = '&raquo;';
            entities['188'] = '&frac14;';
            entities['189'] = '&frac12;';
            entities['190'] = '&frac34;';
            entities['191'] = '&iquest;';
            entities['192'] = '&Agrave;';
            entities['193'] = '&Aacute;';
            entities['194'] = '&Acirc;';
            entities['195'] = '&Atilde;';
            entities['196'] = '&Auml;';
            entities['197'] = '&Aring;';
            entities['198'] = '&AElig;';
            entities['199'] = '&Ccedil;';
            entities['200'] = '&Egrave;';
            entities['201'] = '&Eacute;';
            entities['202'] = '&Ecirc;';
            entities['203'] = '&Euml;';
            entities['204'] = '&Igrave;';
            entities['205'] = '&Iacute;';
            entities['206'] = '&Icirc;';
            entities['207'] = '&Iuml;';
            entities['208'] = '&ETH;';
            entities['209'] = '&Ntilde;';
            entities['210'] = '&Ograve;';
            entities['211'] = '&Oacute;';
            entities['212'] = '&Ocirc;';
            entities['213'] = '&Otilde;';
            entities['214'] = '&Ouml;';
            entities['215'] = '&times;';
            entities['216'] = '&Oslash;';
            entities['217'] = '&Ugrave;';
            entities['218'] = '&Uacute;';
            entities['219'] = '&Ucirc;';
            entities['220'] = '&Uuml;';
            entities['221'] = '&Yacute;';
            entities['222'] = '&THORN;';
            entities['223'] = '&szlig;';
            entities['224'] = '&agrave;';
            entities['225'] = '&aacute;';
            entities['226'] = '&acirc;';
            entities['227'] = '&atilde;';
            entities['228'] = '&auml;';
            entities['229'] = '&aring;';
            entities['230'] = '&aelig;';
            entities['231'] = '&ccedil;';
            entities['232'] = '&egrave;';
            entities['233'] = '&eacute;';
            entities['234'] = '&ecirc;';
            entities['235'] = '&euml;';
            entities['236'] = '&igrave;';
            entities['237'] = '&iacute;';
            entities['238'] = '&icirc;';
            entities['239'] = '&iuml;';
            entities['240'] = '&eth;';
            entities['241'] = '&ntilde;';
            entities['242'] = '&ograve;';
            entities['243'] = '&oacute;';
            entities['244'] = '&ocirc;';
            entities['245'] = '&otilde;';
            entities['246'] = '&ouml;';
            entities['247'] = '&divide;';
            entities['248'] = '&oslash;';
            entities['249'] = '&ugrave;';
            entities['250'] = '&uacute;';
            entities['251'] = '&ucirc;';
            entities['252'] = '&uuml;';
            entities['253'] = '&yacute;';
            entities['254'] = '&thorn;';
            entities['255'] = '&yuml;';
            entities['8220'] = '&ldquo;';
            entities['8221'] = '&rdquo;';
        }
    
        if (useQuoteStyle !== 'ENT_NOQUOTES') {
            entities['34'] = '&quot;';
        }
        if (useQuoteStyle === 'ENT_QUOTES') {
            entities['39'] = '&#39;';
        }
        entities['60'] = '&lt;';
        entities['62'] = '&gt;';
    
    
        // ascii decimals to real symbols
        for (decimal in entities) {
            symbol = String.fromCharCode(decimal);
            hash_map[symbol] = entities[decimal];
        }
        
        return hash_map;
    }; /* OH.util.get_html_translation_table */
   
   util.html_entity_decode = function(string, quote_style) 
   {
        // Convert all HTML entities to their applicable characters  
        // 
        // version: 908.406
        // discuss at: http://phpjs.org/functions/html_entity_decode
        // +   original by: john (http://www.jd-tech.net)
        // +      input by: ger
        // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
        // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
        // +   bugfixed by: Onno Marsman
        // +   improved by: marc andreu
        // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
        // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
        // +      input by: Ratheous
        // -    depends on: get_html_translation_table
        // *     example 1: html_entity_decode('Kevin &amp; van Zonneveld');
        // *     returns 1: 'Kevin & van Zonneveld'
        // *     example 2: html_entity_decode('&amp;lt;');
        // *     returns 2: '&lt;'
        var hash_map = {}, symbol = '', tmp_str = '', entity = '';
        tmp_str = string.toString();
        
        if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
            return false;
        }
    
        for (symbol in hash_map) {
            entity = hash_map[symbol];
            tmp_str = tmp_str.split(entity).join(symbol);
        }
        tmp_str = tmp_str.split('&#039;').join("'");
        
        return tmp_str;
    }; /* OH.util.html_entity_decode */

    util.htmlentities = function(string, quote_style)
    {
        // Convert all applicable characters to HTML entities  
        // 
        // version: 907.503
        // discuss at: http://phpjs.org/functions/htmlentities
        // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
        // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
        // +   improved by: nobbler
        // +    tweaked by: Jack
        // +   bugfixed by: Onno Marsman
        // +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
        // +    bugfixed by: Brett Zamir (http://brett-zamir.me)
        // +      input by: Ratheous
        // -    depends on: get_html_translation_table
        // *     example 1: htmlentities('Kevin & van Zonneveld');
        // *     returns 1: 'Kevin &amp; van Zonneveld'
        // *     example 2: htmlentities("foo'bar","ENT_QUOTES");
        // *     returns 2: 'foo&#039;bar'
        var hash_map = {}, symbol = '', tmp_str = '', entity = '';
        tmp_str = string.toString();
        
        if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
            return false;
        }
        hash_map["'"] = '&#039;';
        for (symbol in hash_map) {
            entity = hash_map[symbol];
            tmp_str = tmp_str.split(symbol).join(entity);
        }
        
        return tmp_str;
    }; /* OH.util.htmlentities */

    util.onlyInt = function(val, radix, ndx)
    {
        var num = null;
        if ("number" === typeof val){
            num = parseInt(val, radix || 0);
        } else if ("string" === typeof val){
            var matches = val.match(/\d+/g);
            if (matches){
                if (ndx == 'last'){ ndx = matches.length - 1; }
                num = parseInt(matches[ndx || 0], radix || 10);
            }
        }
        return num;
    }
	
	util.checkEmail = function(email){
		if(email.indexOf("@") === -1){
			return false;
		}
		return true;
	}

    /* based on http://my.opera.com/GreyWyvern/blog/show.dml/1725165 */
    util.clone = util.byValue = function(obj)
    {
        var clone = obj.constructor();
        for (var key in obj) {
            if (! obj.hasOwnProperty(key)) continue;
            clone[key] = (obj[key] && typeof obj[key] === "object") 
                ? arguments.callee(obj[key])
                : obj[key];
        }
        
        return clone;
    };

    util.obj2URL = function(obj)
    {
        var array_suffix = '[]', parts = [];

        util.forEach(obj, function(v, k)
        {
            if (YAHOO.lang.isArray(v)){
                if (/\[\]$/.test(k)){ k = k.replace(/\[\]$/, ''); }
                util.forEach(v, function(av){
                    parts.push(encodeURIComponent(k) +array_suffix+'='+ av );
                });
            } else {
                parts.push(k + '=' + v );
            }
        });

        return parts.join('&');
    }
    
    util.cursorToEnd = function(el)
    {
        util.cursorToPosition(el);
    }

    util.cursorToStart = function(el)
    {
        util.cursorToPosition(el, 0);
    }

    util.cursorToPosition = function(el, pos)
    {
        if (typeof el === 'string') { el = DOM.get(el); }
        pos = isNaN(pos) ? el.value.length : parseInt(pos);

        if (el.setSelectionRange) {
            el.focus();
            el.setSelectionRange(pos, pos);
        }
        else if (el.createTextRange) {
            var range = el.createTextRange();
            range.collapse(true);
            range.moveEnd('character', pos);
            range.moveStart('character', pos);
            range.select();
        }
    }
    
    util.getLinkFromTarget = function(target)
    {
        if(!target) {
            return;
        }   
        return (target.nodeName.toUpperCase() === 'A')
                ? target
                : DOM.getAncestorByTagName(target, 'a');
    }

    util.injectLink = function(idTrigger)
    {
        var trigger = DOM.get(idTrigger), 
            link = document.createElement('a');

        if (!trigger){
            return null;
        }
        link.href = '#';
        link.innerHTML = trigger.innerHTML; // copy link text from text
        trigger.innerHTML = '';             // clear trigger text
        trigger.appendChild(link);          // replace with link

        return trigger;
    }

    util.inputPlaceholder = function(id)
    {
        Event.onAvailable(id, function()
        {
            var trim = YAHOO.lang.trim, el = this,
                title = trim(this.title), elsForm = this.form;

            setValueToTitle();
            Event.addListener(el, 'blur', setValueToTitle);
            
            Event.addListener(el, 'focus', function()
            {
                if (trim(el.value) === title) { el.value = ""; }
            });
            
            Event.addListener(elsForm, 'submit', function()
            {
                if (trim(el.value) == title){ el.value = ""; }
            });
            
            function setValueToTitle()
            {
                if (trim(el.value) == "") { el.value = el.title; }
            }
        });
    };

    util.xhrCountryState = function (idCountrySelect, idSwapRow)
    {
        OH.loader.require('json', 'connection', 'OH.Selector');
        OH.loader.onSuccess = init;
        OH.loader.insert();

        function init()
        {
            var JSON = YAHOO.lang.JSON,
                row = DOM.get(idSwapRow),
                origLabel = OH.Selector('label', row)[0],
                origInput = OH.Selector('input, select', row)[0];

            Event.onAvailable(idCountrySelect, function() {
                getStateType(DOM.get(idCountrySelect).value);
            });

            Event.on(DOM.get(idCountrySelect), 'change', getStateType);

            function getStateType(mix)
            {
                var cc = (typeof mix === 'string') ? mix : Event.getTarget(mix).value,
                    url = "/xhr/member/getstatetype?country="+cc;

                OH.util.asyncRequest('GET', url,
                {
                    success: function(o)
                    {
                        var resp = JSON.parse(o.responseText);
                        if (resp){ getStates(cc, resp); }
                    }
                });

            } // getStateType

            function getStates(cc, type)
            {
                var url = "/xhr/member/getstates?country="+cc;
    
                OH.util.asyncRequest('GET', url, {
                    success: function(o)
                    {
                        buildStates(type, JSON.parse(o.responseText));
                    }
                });
            }
    
            function buildStates(type, states)
            {
                var currInput = OH.Selector('input, select', row)[0],
                    newInput;
    
                if (states){ newInput = OH.util.form.createSelect(type, states); }
                else { newInput = origInput; }
                origLabel.htmlFor = newInput.id = origLabel.form.name +'-'+ type;
                origLabel.innerHTML = OH.util.capitalize(type);
                row.replaceChild(newInput, currInput);
                if (origInput.value){ newInput.value = origInput.value; }

                var input_type = newInput.nodeName.toLowerCase();
                if (input_type == 'input'){
                    DOM.replaceClass(row, 'select', 'text');
                } else if (input_type == 'select'){
                    DOM.replaceClass(row, 'text', 'select');
                }
            }

        } // init
    } // xhrCountryState

    util.birthdateEnhancement = function(idBirthdate)
    {
        OH.loader.require('calendar', 'OH.FormValidator','OH.Selector');
        OH.loader.onSuccess = loaded;
        OH.loader.insert();

        function loaded()
        {
            var elBirthdate = document.getElementById(idBirthdate),
                idHelper = idBirthdate + '-calendar-helper-link',
                elHelper = DOM.get(idHelper),
                link = document.createElement('a'),
                elCalendar = document.createElement('div'),
                icon = document.createElement('img');
        
            link.href = '#';
            icon.src = "http://x.ourhistree.com/i/content/14-calendar-helper-link.gif";
            icon.alt = icon.title = "Choose date from calendar.";
        
            link.appendChild(icon);
            elHelper.appendChild(link);
        
            elCalendar.className = 'calendar-helper';
            elCalendar.style.display = 'none';
            DOM.getAncestorByClassName(idHelper, 'date').appendChild(elCalendar);
        
            // When container is ready, instantiate the calendar and its behaviors
            YAHOO.util.Event.onAvailable(idHelper, init);
        
            function init()
            {
                var clsYUICal = 'yui-calcontainer',
                    cal_open = false,
                    calendar = new YAHOO.widget.Calendar(elCalendar, { navigator: true}),
                    FV_instance = OH.FormValidator.get(DOM.getAncestorByTagName(idBirthdate, 'form').id);
    
                Event.on(link, 'click', toggleCalendar);
                calendar.selectEvent.subscribe(handleSelect, calendar, true);
                FV_instance.defaults.messages.birthday = {'false': ''};
                FV_instance.addValidator('birthday', OH.Selector('select.date'), 'change', validateBirthdate);
    
                Event.on(document.body, 'click', function(e)
                {
                    if (cal_open && e.target != icon && e.target != link &&
                        !DOM.getAncestorByClassName(e.target, clsYUICal)
                    ) {
                        hideCalendar();
                    }
                });
    
                function validateBirthdate()
                {
                    var min_age = 13,
                        birthdate = (new Date(getBirthdate())),
                        min_date = (new Date());
                    min_date.setFullYear(min_date.getFullYear() - min_age);
    
                    return birthdate < min_date;
                }
    
                function toggleCalendar(e)
                {
                    Event.preventDefault(e);
                    if (cal_open){
                        hideCalendar();
                    } else {
                        updateCalendar();
                        showCalendar();
                    }
                }
    
                function hideCalendar()
                {
                    calendar.hide();
                    forceValidation();
                    cal_open = false;
                }
    
                function showCalendar()
                {
                    calendar.show();
                    cal_open = true;
                }
    
                function handleSelect(type, args, obj)
                {
                    if (!cal_open){ return; }
                    var dates = args[0], date = dates[0],
                        year = date[0], month = date[1], day = date[2];
    
                    updateDateSelects(year, month, day);
                    hideCalendar();
                    forceValidation();
                }
                
                function forceValidation()
                {
                    // Manually kick off custom validation
                    var el = OH.util.form.getEl('birthdate_y', true),
                        fv = OH.FormValidator.validators[el.name][0];
                    fv.post(fv.validator(), el, fv.type);
                }
                
                function getBirthdate()
                {
                    var y = OH.Selector('.year', elBirthdate)[0].value,
                        m = OH.Selector('.month', elBirthdate)[0].value,
                        d = OH.Selector('.day', elBirthdate)[0].value;
    
                    return [m, d, y].join('/');
                }
    
                function updateCalendar()
                {
                    var strDate = getBirthdate();
                    calendar.select(strDate);
                    calendar.cfg.setProperty("pagedate", new Date(strDate));
                    calendar.render();
                }
    
                function updateDateSelects(y, m, d)
                {
                    OH.Selector('.year', elBirthdate)[0].value = y;
                    OH.Selector('.month', elBirthdate)[0].value = m;
                    OH.Selector('.day', elBirthdate)[0].value = d;
                    validateBirthdate(y,m,d);
                }
    
            }; // init
        }
    } // calendarEnhancement
    
    util.colorFadeInOut = function(els, color_new)
    {
        color_new = color_new || '#efefef';
        OH.loader.require('animation');
        OH.loader.onSuccess = function()
        {
            DOM.batch(els, function(el)
            {
                var color_orig = DOM.getStyle(el, 'background-color'),
                    orig2new = new YAHOO.util.ColorAnim(el, {
                        backgroundColor: { to: color_new }
                    }, 1),
                    new2orig = new YAHOO.util.ColorAnim(el, {
                        backgroundColor: { to: color_orig }
                    }, 1);

                orig2new.onComplete.subscribe(function(){ new2orig.animate(); });
                orig2new.animate();
            });
        }
        OH.loader.insert();
    }
    
    util.hide = function(els)
    {
		DOM.setStyle(els, 'display', 'none');
    }

    util.show = function(els, restore)
    {
        DOM.setStyle(els, 'display', restore || '');
    }

     util.toggle = function(mix, restore)
     {
         DOM.batch(mix, function(el)
         {
             DOM.getStyle(el, 'display') == 'none' 
                 ? util.show(el, restore)
                 : util.hide(el);
         });
     };

     util.toggleClass = function(mix, clas)
     {
         DOM.batch(mix, function(el)
         {
             DOM.hasClass(el, clas) 
                 ? DOM.removeClass(el, clas) 
                 : DOM.addClass(el, clas);
         });
     }

     util.swapClass = function(mix, classA, classB)
     {
         DOM.batch(mix, function(el)
         {
             if (DOM.hasClass(el, classA)){
                 DOM.replaceClass(el, classA, classB);
             } else if (DOM.hasClass(el, classB)){
                 DOM.replaceClass(el, classB, classA);
             } else {
                 DOM.addClass(el, classB);
             }
         });
     };
     
    util.subHandler = function(key, val, sArgs)
    {
		return OH.util.wbr(val, 10);
		// this crap is too complex to make any sense
        if (sArgs){
            var aArgs = sArgs.split(' '), /* convert string to array of args*/
                ndx = aArgs.indexOf('truncate');
            
            if (val && ndx !== -1){
                /* allow {key truncate 30}, {key otherFunc truncate 100}, etc */
                val = val.substr(0, aArgs[ndx+1]);
            }
        }
        if (!val){ return ''; } /* don't want {key} showing in HTML */
        else     { return util.htmlentities(val); } /* escape on output */
													  
    }
	
	util.formatHistree = function(field, value, extra){
		if (field === "thumbnail" && typeof(value) === "object"){
			return (value ? value['squarethumbnailurl'] : '');
		}
		else if(field == "thumbnail" && typeof(value) === "undefined"){
			return "http://x.ourhistree.com/i/content/55-histree-placeholder.gif";
		}
		else if (field === "name" && extra === "truncated"){
			if (value.length < 36){
				return value;
			}
			return value.substring(0,35) + "...";
		}
		
		return value;
	}
    
     util.capitalize = function(s)
     {
         return s.charAt(0).toUpperCase() + s.substr(1).toLowerCase();
     }

    util.map = function(list, func, scope)
    {
        var arr = [];
        OH.util.forEach(list, function(/* val, ndx, list */){
            arr.push(func.apply(this, arguments));
        }, scope || this);
        return arr;
    }
    
    util.getUrlParameter = function(name){
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexS = "[\\?&]" + name + "=([^&#]*)";
        var regex = new RegExp(regexS);
        var results = regex.exec(window.location.href);
        if (results == null) 
            return "";
        else 
            return results[1];
		
    }

     // Array method(s)
     if (!Array.prototype.contains) {
         Array.prototype.contains = function(comparison)
         {
            if (!comparison){
                return;
            }
             for (var i=0, len=this.length; i<len; ++i) {
                 if (comparison.constructor === RegExp && // is a Regular Expression
                     comparison.exec(this[i])) {          // and there are matches
                     return true;
                 }
                 else {
                     if (this[i] == comparison) {
                         return true;
                     }
                 }
             }
             return false;
         };
     }

    if (!Array.prototype.indexOf)
    {
      Array.prototype.indexOf = function(elt /*, from*/)
      {
        var len = this.length >>> 0;
    
        var from = Number(arguments[1]) || 0;
        from = (from < 0)
             ? Math.ceil(from)
             : Math.floor(from);
        if (from < 0)
          from += len;
    
        for (; from < len; from++)
        {
          if (from in this &&
              this[from] === elt)
            return from;
        }
        return -1;
      };
    }


     util.mergeHippie = function(/* objA, objB, ... objN */)
     {
         for (var merged={}, i=0, l=arguments.length; i<l; i=i+1) {
            merged = (function (first, second) // merge two objs recursively
            {
                for (var key in second){
                    if (second.hasOwnProperty(key)){
                        if (! first[key]){
                            first[key] = second[key];
                        } else {
                            if (YAHOO.lang.isObject(second[key])){
                                arguments.callee(first[key], second[key]);
                            }
                        }
                    }
                }
                return first;
            })(merged, arguments[i]);
         }
         return merged;
     };

    util.disable = function(el)
    {
        if (typeof el === 'string') { el = DOM.get(el); }
        el.setAttribute('disabled', 'disabled');
        DOM.addClass(el, 'disabled');
    }

    util.enable = function(el)
    {
        if (typeof el === 'string') { el = DOM.get(el); }
        el.removeAttribute('disabled');
        DOM.removeClass(el, 'disabled');
    }

     /*
      * Form manipulation functions
      *   el = (DOM) Element
      *   t = Text / Title
      *   val = Value
      *   i = Index
      */
     util.form = YAHOO.namespace('OH.util.form');

     util.form.getEl = function (mixed, only_first)
     {
         if (! mixed) return;

         var el = '';
         if (typeof mixed == "string"){
            el = document.getElementsByName(mixed);
            if (only_first && el.length){ el = el[0]; }
         } else {
             el = mixed;
         }
         return el;
     };

     util.form.addOption = function(el, t, val, i)
     {
         el = util.form.getEl(el);
         if(i && isNaN(i)){ return false; }
         i = (el.options.length < 0 ? 0 : el.options.length);
         el.options[i] = new Option(t, val);
     };

     util.form.createSelect = function(name, obj)
     {
         var elSelect = document.createElement('select');
         elSelect.name = name;

         for (var k in obj){
             elSelect.options[elSelect.options.length] = new Option(obj[k], k);
         }

         return elSelect;
     };

     util.form.reset = function(el)
     {
         el = util.form.getEl(el);
         var l = el.length;
         if (l > 1){

             for(var i=0; i < l; i++){
                 if(el.options){
                     if (el.options[i].selected){ el.options[i].selected = false; }
                 } else {
                     if (el[i].checked)         { el[i].checked = false; }
                 }
             }

         } else { el.value = ''; }

     };

     util.form.erase = function(el, i)
     {
         el = util.form.getEl(el);
         if(el.value) { el.value = ''; }

         if(i || i==0)
         {
             if      (el.options) { el.options[i] = null; }
             else if (el.length)  { el[i] = null; }
         }
         else
         {
             if      (el.options) { while(el.options.length){ el.options[0] = null; } }
             else if (el.length)  { while(el.length)        { el[0] = null; } }
         }
     };

    util.form.getValue = function(el)
    {
        if (! el) return;

        el = util.form.getEl(el);
        if (el.length === 1){ el = el[0]; }

        if (el.value && el.type) {
            if ('checkbox' === el.type.toLowerCase()){
                if (el.checked) { return el.value; }
                else            { return ''; }
            } else {
                return el.value;
            }
        }
        else if (el.length > 1)
        {
            for (var c=0, vals=[], len=el.length; c < len; c++){
                if (el.options){ if (el.options[c].selected){ vals.push(el.options[c].value); } }
                else           { if (el[c].checked)         { vals.push(el[c].value); } }
            }
     
           return (vals.length === 1 ? vals[0] : vals);
     
        }
        else { return ''; }
    }

    util.form.setValue = function(el, val)
    {
        el = util.form.getEl(el);
        if (el.length === 1){ el = el[0]; }

        var test_el = el.length > 1 ? el[0] : el;
        switch(test_el.type)
        {
            case 'select-multiple':
                break;
            case 'checkbox':
                if (val instanceof Array){
                    OH.util.forEach(el, function(box){
                        box.checked = !!val.contains(box.value);
                    });
                } else {
                    el.checked = !!(el.value == val);
                }
                break;
            default:
                el.value = val;
        }

    }
    
    util.form.value = function(el, val)
    {
       if (arguments.length === 2){ return util.form.setValue(el, val); }
       else                       { return util.form.getValue(el); }
    };

     util.form.selectOptionByIndex = function(el, i)
     {
         el = util.form.getEl(el, true);
         el.selectedIndex = i;
     };

     util.form.selectOptionByValue = function(el, val)
     {
         el = util.form.getEl(el, true);
         var l = (el.options.length ? el.options.length : el.length);
         for (var c=0; c < l; c++){
             if      (el.options[c].value == val){ el.options[c].selected = true; }
             else if (el[c].value == val)        { el[c].checked = true; }
         }
     };
     
     util.isFeatureEnabled = function(feature){
        return (!OH.FeaturesDisabled.contains(feature));
     }
	 
	 util.wbr = function(str, num) { 
		return str.toString().replace(RegExp("(\\w{" + num + "})(\\w)", "g"), function(all,text,charr){
		  return text + "<wbr>" + charr;
		});
	  }
	
	util.parseQueryString = function(url){
		var qs = url.split('?')[1];
		var args = qs.split('&'); // parse out name/value pairs separated via &
		var params = {};
		
		// split out each name=value pair
		for (var i = 0; i < args.length; i++) {
			var pair = args[i].split('=');
			var name = decodeURIComponent(pair[0]);
			
			var value = (pair.length==2)
				? decodeURIComponent(pair[1])
				: name;
			
			params[name] = value;
		}
		
		return params;

	}
	
	util.flashFail = function(e){
		if (!e.success){
			DOM.get('histree-swf').innerHTML = '<a href="http://www.adobe.com/go/getflashplayer"><img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a>';
		}
	}
	
	util.asyncRequest = function(method, uri, callback, postData){
		var objecttype = '';
		var objectid = 0;
		var data = util.parseQueryString("http://www.ourhistree.com?"+postData);
		
		if (data.histreeid){
			objecttype = "Histree";
			objectid = data.histreeid;
		}
		else if (data.branchid){
			objecttype = "Branch";
			objectid = data.branchid;
		}
		else if (data.communitreeid){
			objecttype = "Communitree";
			objectid = data.communitreeid;
		}
		else if (data.accountid){
			objecttype = "Account";
			objectid = data.accountid;
		}
		else if (data.assetid){
			objecttype = "Asset";
			objectid = data.assetid;
		}
		else if (data.personalwebid){
			objecttype = "PersonalWeb";
			objectid = data.personalwebid;
		}
		else if (data.inviteeid){
			objecttype = "Invite";
			objectid = data.inviteeid;
		}
		
		pageTracker._trackEvent('XHR'+method, uri, objecttype, parseInt(objectid, 10)); 

		YAHOO.util.Connect.asyncRequest(method, uri, callback, postData);
	}

	util.zeroPad = function(num,count){
		var numZeropad = num + '';
		while(numZeropad.length < count) {
		numZeropad = "0" + numZeropad;
		}
		return numZeropad;
	}

     YAHOO.register("OH.util", util, { version: "1.0.0", build: "1" });
 })();

OH.Language = null;
function DetectLanguage(){
	if (OH.Language != null){
		return;
	}
	var translationEl = OH.Selector('#translationRef font font');
	if (translationEl.length === 0){
		OH.Language = "en";
		return;
	}
	
	google.language.detect(translationEl[0].innerHTML, function(result) {
		if (!result.error) {
			OH.Language = result.language;
		}
	});
}

// Translate every element under this one element
transCount = 0;
function translateOHPage(els){
	if (typeof(google) === "undefined" || !google.language || els.length === 0 || OH.Language == "en"){
		return;
	}
		
	var element = els[transCount];
	//bad element needs to skip
	if (typeof(element) === "undefined" || element.innerHTML.length === 0) {
		transCount++;
		if (transCount < els.length){
			translateOHPage(els);
		}
		return;
	}
	google.language.translate(element.innerHTML, 'en', OH.Language, function(result) {
	
		if (result.translation) {
			element.innerHTML = result.translation;
			transCount++;
			if (transCount < els.length){
				translateOHPage(els);
			}
		}
	
	});
}
