if (typeof USS411 == 'undefined') {
    var USS411 = {};
}

uss411 = {};
uss411.util = {};

USS411.namespace = function () {
    var a = arguments, o = null, i, j, d;
    for (i = 0; i < a.length; ++i) {
        d = a[i].split('.');
        o = USS411;
        for (j = (d[0] == 'USS411') ? 1 : 0; j < d.length; ++j) {
            o[d[j]] = o[d[j]] || {};
            o = o[d[j]];
        }
    }
    return o;
};

(function () {	   
	USS411.namespace('util','global','local','dynamic', 'msg', 'debug', 'vars' );
	USS411.global = {
		DB : (decodeURI(window.location.search).indexOf('<<DEBUG>>')!=-1),
		VERSION : '@VERSION@-@COMPILER@',
		PROTOCAL_PREFIX : window.location.protocol ,
		DATE : new Date(),
		BROWSER_TYPE : (function () {
			var y = Prototype.Browser, x;
			for (x in y) {
				if (y[x]) { 
					return x;
				}
			}			
		})()
    }
	if (USS411.global.PROTOCAL_PREFIX == 'undefined') {
		USS411.global.PROTOCAL_PREFIX = 'http://';
	};
	if (typeof console != 'undefined' && USS411.global.DB === true){
		USS411.debug.log = console.log;
		USS411.debug.debug = console.debug;
		USS411.debug.info = console.info;
		USS411.debug.warn = console.warn;
		USS411.debug.error = console.error;
		USS411.debug.assert = console.assert;
		USS411.debug.dir = console.dir;
		USS411.debug.trace = console.trace;
		USS411.debug.group = console.group;
		USS411.debug.groupEnd = console.groupEnd;
		USS411.debug.time = console.time;
		USS411.debug.timeEnd = console.timeEnd;
		USS411.debug.profile = console.profile;
		USS411.debug.profileEnd = console.profileEnd;
		USS411.debug.count = console.count;
		USS411.debug.clear = console.clear;
	} else {
		USS411.debug.log = function () {};
		USS411.debug.debug = function () {};
		USS411.debug.info = function () {};
		USS411.debug.warn = function () {};
		USS411.debug.error = function () {};
		USS411.debug.assert = function () {};
		USS411.debug.dir = function () {};
		USS411.debug.trace = function () {};
		USS411.debug.group = function () {};
		USS411.debug.groupEnd = function () {};
		USS411.debug.time = function () {};
		USS411.debug.timeEnd = function () {};
		USS411.debug.profile = function () {};
		USS411.debug.profileEnd = function () {};
		USS411.debug.count = function () {};
		USS411.debug.clear = function () {};
		}
})();

USS411.util.readCookie = function (_cName){
	var _cookieString = document.cookie/*.replace(/\s/g, '')*/;
	USS411.debug.log(_cookieString)
	var _cookiesArray = _cookieString.split('; ');
	for (var _i = 0, _l = _cookiesArray.length; _i < _l; _i++) {
		var _cookieNameValueArray = _cookiesArray[_i].split('=');
		if ( _cookieNameValueArray[0] == _cName) {
			return _cookieNameValueArray[1];
		}
	}
	return null;
}

USS411.util.setCookie = function(_cname, _value, _expiredays){
	document.cookie = _cname + '=' + _value;
}


USS411.util.deleteCookie = function(_cname){
	document.cookie = _cname + '=' + ';expires=Thu, 01-Jan-70 00:00:01 GMT;';
}

USS411.util.loadScript = function (_url, _callback) {
	var n = document.getElementsByTagName('head')[0];
	var s = document.createElement('script');
	s.type = 'text/javascript';
	s.src = _url;
	if (_callback) {
	    s.onerror = s.onload = _callback; //firefox
	    s.onreadystatechange = function () { //for IE
	        if (this.readyState == 'complete' || this.readyState == 'loaded') {
	            _callback();
	        }
	    }
	}
	n.appendChild(s);
};

USS411.util.dateObject = {

 	currentDate : USS411.global.DATE,
	currentMonth : USS411.global.DATE.getMonth() + 1,
	currentDay : USS411.global.DATE.getDate(),
	currentYear : USS411.global.DATE.getFullYear(),
	monthNames : ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'],

	getFormatedDate : function (_format) {
		switch (_format) {
		/*
		 * TODO: Add other formats 
		 */
		case 'MM/DD/YY':
			if (this.currentMonth.length > 1){
				this.currentMonth = '0' + this.currentMonth;
			}
			return (this.currentMonth + '/' + this.currentDay + '/' + this.currentYear);
			
		default:
			throw 'Must Pass a Format';
		}
	},
	getMonthName : function () {
		return USS411.util.dateObject.monthNames[USS411.util.dateObject.currentMonth-1];
	}
	 
}

USS411.util.CreateGoogleMap = Class.create({
    initialize: function(container, loc, options, indicator){
        this.container = (typeof(container) == "string") ? $(container) : container;
        this.key = 'ABQIAAAAPrfVF-v0KL4IONTFcG2jkBS5jiRAwAjUKfJNpJA8MQE0-CmvDRSKdnYyuwPlLucnUUsedGa7r7QdYg';
        this.loc = loc;
		this.options = Object.extend({
            zoom: 14,
            size: "500x450",
            format: "GIF",
            maptype: "roadmap",
            sensor: false,
            markers: null
        }, options || {});
		this.pre = 'http://';
		this.url = 'http://maps.google.com/staticmap?key=' + this.key +'&';
        this.lat = this.loc[0];
        this.lng = this.loc[1];
		this.getMap();
	},
    getMap: function(){
        USS411.debug.info(this.lat, this.lng);
        if (this.options.markers == null) 
            this.options.markers = this.lat + "," + this.lng;
        USS411.debug.info(this.options.markers);
        var t = this.url + "center=" + this.lat + "," + this.lng + "&" + Object.toQueryString(this.options);
        USS411.debug.log("t = " + t);
        this.container.update(new Element('img', {
            'src': t,
            'width': this.options.size.substring(0, this.options.size.indexOf('x')),
            'height': this.options.size.substring(this.options.size.indexOf('x') + 1, this.options.size.length)
        }));
    }
});

USS411.util.CreateGoogleMapString = Class.create({
    initialize: function(container, loc, options, indicator){
        this.container = (typeof(container) == "string") ? $(container) : container;
        this.key = 'ABQIAAAAPrfVF-v0KL4IONTFcG2jkBS5jiRAwAjUKfJNpJA8MQE0-CmvDRSKdnYyuwPlLucnUUsedGa7r7QdYg';
        this.loc = loc;
		this.options = Object.extend({
            zoom: 14,
            size: "500x450",
            format: "GIF",
            maptype: "roadmap",
            sensor: false,
            markers: null
        }, options || {});
		this.pre = 'http://';
		this.url = 'http://maps.google.com/maps/api/staticmap?';
        this.getMap(loc);
	},
    getMap: function(loc){
        if (this.options.markers == null) 
            this.options.markers = loc;
        USS411.debug.info(this.options.markers);
		USS411.debug.dir(this.options);
        var t = this.url + "center=" + loc + "&" + Object.toQueryString(this.options);
        USS411.debug.log("t = " + t);
        this.container.update(new Element('img', {
            'src': t,
            'width': this.options.size.substring(0, this.options.size.indexOf('x')),
            'height': this.options.size.substring(this.options.size.indexOf('x') + 1, this.options.size.length)
        }));
    }
})

USS411.util.AdvanceMe = Class.create({
	initialize : function () {
		this.inputs = $$('.USS411-js-advance-field'); //gets all inputs with USS411-js-advance-field class
		this.inputs.each(function (_input) {
			USS411.debug.log('this is %o', this);
			_input.observe('keyup', this.handleKeyUp.bind(this));
			_input.observe('keydown', this.handleKeyDown.bind(this));
		}.bind(this));
	},

	handleKeyUp : function (_ev) {
		USS411.debug.info('arguments %o', arguments);
		var _input = Event.element(_ev);
		var _maxLength = _input.getAttribute('maxlength');
		var _valueLength = $F(_input).length + this._increm;
		var _keyCode = _ev.keyCode;
		switch (_keyCode) {
		case 16:
			break;
		case 9: 
			break;
		case 39: 
			break;
		case 37:
			break;
		case 8:
			if (_valueLength == 0) {
	  		_input.previous('input').focus();
	  	}
			break;
			default:
				USS411.debug.info(_input.next('input') != null);
				if (_maxLength == _valueLength) {
					if (_input.next('input') != null) {
						_input.next('input').focus();
					}
				} 
		}
	},
	handleKeyDown : function (_ev) {
		USS411.debug.log('arguments %o', arguments);
		var _input = Event.element(_ev);
		USS411.debug.log('keycode on key down is %s, value %s, length %s', _ev.keyCode, _input.value, _input.value.length );	
		this._increm = 0;
		if(_input.value.length == 1 && _ev.keyCode == 8){
			this._increm = -1;
		}
	}
});


USS411.util.formatPhone = function (_phone, _format){
	if (typeof _format === 'undefined') {
		USS411.debug.warn('Must define a format EX: ###-###-####');
		throw 'Must define a format EX: ###-###-####';
	}
	var _phoneArray = _phone.replace(/\D/g, "");
	USS411.debug.info('PHONE WITH NOTHING BUT DIGITS %s', _phoneArray);
	_phoneArray = _phoneArray.split('');
	USS411.debug.info('PHONE ARRAY AFTER SPILT %o', _phoneArray);
	for (var _i = 0, _l = _phoneArray.length; _i < _l; _i++) {
		_format = _format.replace('#', _phoneArray[_i]);
		USS411.debug.info('FORMAT IS %o', _format);	
	} 
	return _format;
	
}




USS411.util.formValidation = function (_form){
	//The forms elements are collected
	var _valElements = _form.getElements();
	USS411.debug.info('_valElements IS : %o', _valElements);
	
	//Remove all CSS error classes
	_valElements.invoke('removeClassName', 'input-error-dyn');
	for (var i = 0, l = _valElements.length; i < l; i++) {
		USS411.debug.group();
		USS411.debug.info('FORM FIELD NAME IS %s', _valElements[i].name);
		/*SEO LINK CONTRUCTION NO LONGER ALLOWS THIS TO WORK
		 * 
		 if (_valElements[i].type === 'text') { //If element is text input
			_valElements[i].value = USS411.util.formatCapitalize(_valElements[i].value); //Captialize it
		}*/
		
		/*
		 * This section will take the values of the phone number pieces and concantanate them
		 * together and store the value inside of input name=searchPhone. In order for this to work,
		 * the phone fields must be named accordingly: phoneArea, phoneExchange, phoneNumber     
		 */
		if (_valElements[i].name == 'searchPhone') {
			USS411.util.validationSearchPhone = _valElements[i];
		}
		
		//trim whitespace on sides
		_valElements[i].value = _valElements[i].value.replace(/(^\s+)/g,'').replace(/(\s+)$/g,'');
		
		//if the element HAS an error message assigned ...
		if (typeof USS411.util.validationErrorMess[_valElements[i].name] != 'undefined') {
			var _isRequired  = _valElements[i].className.match(/val-req-js/ig);
			USS411.debug.info('HAS CLASS NAME FOR REQ: ' ,_isRequired);
			USS411.debug.info('IS NOT EMPTY : ', _valElements[i].value.length > 0);
			
			//if the length is <= 0 and it's required 
			if (_valElements[i].value.length <= 0 && _isRequired) {
				
				//alert with the empty message and add the CSS class
				alert(USS411.util.validationErrorMess[_valElements[i].name]['empty']);
				_valElements[i].addClassName('input-error-dyn');
				USS411.debug.groupEnd();
				return false;
			}
			
			/*
			 * If it's not required and empty check to see if it has any validations,
			 * if it does run it otherwise return true
			 */
			var _valThis = (typeof USS411.util.validationFuncs[_valElements[i].name] === 'function') ? 
				USS411.util.validationFuncs[_valElements[i].name](_valElements[i]) : true;
			USS411.debug.info('FAILED VALIDATION: ', _valThis !== true);
			USS411.debug.info('DOES THIS FAIL? : ', (_valThis !== true && (_isRequired || _valElements[i].value.length > 0)));
			
			//if it fails validation and is either required or not empty ...
			if (_valThis !== true && (_isRequired || _valElements[i].value.length > 0)) {
				USS411.debug.info('VALIDATION ERROR IS: ', _valThis);
				
				//alert message based on the failed validation and ad CSS class
				alert(USS411.util.validationErrorMess[_valElements[i].name][_valThis]);
				_valElements[i].addClassName('input-error-dyn');
				USS411.debug.groupEnd();
				return false;
			}
		}
		USS411.debug.groupEnd();
	}
	return true;
}


USS411.util.validationErrorMess = {
	searchFName : {
		invalid : 'Please Enter a valid first name'
	},
	searchLName : {
		empty : 'Please enter a last name',
		len : 'Last name must contain more than one letter',
		invalid : 'Please Enter a valid last name'
	},
	searchEmail: {
		empty : 'Please enter an email',
		invalid : 'Please enter a valid email address'
	},
	searchCity: {
		empty : 'Please enter a city',
		invalid : 'You can not use special characters in city names'
	},
	searchCityState: {
		empty : 'Please enter a city/state',
		invalid : 'Please enter a valid city/state'
	},	
	filterAge : {
		invalid : 'Please enter a valid age' 
	},
	phoneArea : {
		empty : 'Please enter a valid 10 digit phone number',
		invalid : 'Please enter a valid 10 digit phone number',
		len : 'Please enter 3 digits for the area code'
	},
	phoneExchange : {
		empty : 'Please enter a valid 10 digit phone number',
		invalid : 'Please enter a valid 10 digit phone number',
		len : 'Please enter 3 digits for the prefix'
	},
	phoneNumber : {
		empty : 'Please enter a valid 10 digit phone number',
		invalid : 'Please enter a valid 10 digit phone number',
		len : 'Please enter 4 digits for the phone number'
	},
	streetNumber : {
		empty : 'Please enter a street number'
	},
	streetName : {
		empty : 'Please enter a street name'
	}
}
USS411.util.validationFuncs = {
	isEmpty : function (_el) {
		return (_el.value.length > 0);
	},
	isValidLength : function (_el, _len) {
		return (_el.value.length >= _len);
	},
	isValidAlpha : function (_el) {
		return !/[^a-z\-\s']/gi.test(_el.value);
	},
	isValidNumber : function (_el) {
		return /(^-?\d+$)/.test(_el.value);
	},
	noSpecialChars : function (_el) {
		return !/`|@|~|!|#|\$|%|\^|&|\*|\(|\)|\[|\]|<|>|\?|\/|\||;/.test(_el.value);
	},
	isValidEmail : function (_el) {
		return /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(_el.value);
	},	
	searchFName : function (_el) {
		if (!this.isValidAlpha(_el)) {
			return 'invalid';
		} else {
			return true;
		}
	},
	searchLName : function (_el) {
		if (!this.isEmpty(_el)) {
			return 'empty';
		} else if (!this.isValidLength(_el, 2)) {
			return 'len';
		} else if (!this.isValidAlpha(_el)) {
			return 'invalid';
		} else {
			return true;
		}
	},	
	searchCity : function (_el) {
		if (!this.noSpecialChars(_el)) {
			return 'invalid'
		} else {
			return true;
		}
	},	
	searchState : function (_el) {
		return true;
	},
	searchCityState : function (_el) {
		if (!this.noSpecialChars(_el)) {
			return 'invalid'
		} else if (!this.isEmpty(_el)) {
			return 'empty';
		} else {
			return true;
		}
	},	
	phoneArea : function (_el) {
		if (!this.isValidNumber(_el)) {
			return 'invalid'
		} else if (!this.isValidLength(_el, 2)) {
			return 'len'
		} else {
			return true;
		}
	},
	phoneExchange : function (_el) {
		if (!this.isValidNumber(_el)) {
			return 'invalid'
		} else if (!this.isValidLength(_el, 2)) {
			return 'len'
		} else {
			return true;
		}
	},
	phoneNumber : function (_el) {
		if (!this.isValidNumber(_el)) {
			return 'invalid'
		} else if (!this.isValidLength(_el, 4)) {
			return 'len'
		} else {
			return true;
		}
	},
	searchEmail : function (_el) {
		if (!this.isValidEmail(_el)) {
			return 'invalid'
		} else {
			return true;
		}
	},	
	filterAge : function (_el) {
		if (!this.isValidNumber(_el)) {
			return 'invalid'
		} else {
			return true;
		}
	}
}

/*
USS411.util.seoPeopleSearch = function (_form) {
	var _reg = /\s/g;
	var _formFName = _form.searchFName.value;
	var _urlLName = _form.searchLName.value.replace(_reg, '+').toLowerCase();
	var _formState = (_form.searchState) ? _form.searchState.value : null;
	var _formCity = (_form.searchCity) ? _form.searchCity.value : null;
	var _formCityState = (_form.searchCityState) ? _form.searchCityState.value : null;
	var _urlFName = 'last_name';
	var _urlCityState = 'nationwide';
	if (_formFName.length > 0) {
		_urlFName = _formFName.replace(_reg, '+').toLowerCase();
	};
	if (_form.searchState) {
		if (_formState.length > 0) {
			_urlCityState = (_formCity.length > 0) ? _formState.toLowerCase() + '+' + _formCity.replace(_reg, '+').toLowerCase() : _formState;
		//_urlCityState = (_formCity.length > 0) ? _formCity.replace(_reg, '+').toLowerCase() : 'nationwide';
		}
	} else {
		_urlCityState = (_formCityState.length > 0) ? _formCityState.replace(_reg, '+').toLowerCase() : 'nationwide';
	}
	window.location = 'http://www.people411.com/namesdirectory/' + _urlCityState + '/' + _urlFName + '/' + _urlLName + '.htmls';
	
	
}
*/

USS411.util.formatCapitalize = function(_string){
	if (typeof _string == "string") {
		var _splitString =_string.split(" ");
        for (var i = 0, l = _splitString.length; i < l; i++) {
            _splitString[i] = _splitString[i].capitalize();
        }
        _formatedString = _splitString.join(' ');
	}
	USS411.debug.info('CAPTIALIZE - BEFORE: %s, AFTER: %s', _string, _formatedString);
	return _formatedString;
}

if(unescape(window.location.search).indexOf('<<DEBUG>>')!=-1){
	USS411.util.loadScript(window.location.protocol+'//'+window.location.host+'/topix/includes/js/test/test-tool-topix.js');
}


document.observe('dom:loaded', function() {
	//ONLOAD GOES HERE
	USS411.debug.info('ADD VALIDATION TO FORMS: ',$$('form.simple-validation-js') );
	$$('form.simple-validation-js').invoke('observe', 'submit', function (_ev) { //All Forms with This Class Attached
		if(!USS411.util.formValidation(this)) {
			_ev.stop();
		}
	});
	
	/*$$('form.people-search-js').invoke('observe', 'submit', function (_ev) { //All Forms with This Class Attached
		_ev.stop();
		if(USS411.util.formValidation(this)) {
			USS411.util.seoPeopleSearch(this);
		}
	});*/
	new USS411.util.AdvanceMe(); 
	$$('.format-phone-number-js').each(function(_el){
		_el.update(USS411.util.formatPhone(_el.innerHTML, '(###) ###-####'));
	});
	
});


document.observe('dom:loaded', function() {
	/*USS411.local.phoneToolTip = new Control.Window($('phone-tool-tip-js'), {
		position: 'relative',
		offsetTop: -105,
		offsetLeft: -20,
		hover: true
	});*/
	USS411.local.phoneToolTip = new Control.ToolTip($('phone-tool-tip-js'), $('tool-tip'), {
		offsetTop : -105, 
		offsetLeft : -30
	}); 

})

