// JavaScript Document view
var url_news = 'http://news.trocatroca.com/news.php';

var agt = navigator.userAgent.toLowerCase();
var isIE = (agt.indexOf('msie') != -1);
var isIE5 = (agt.indexOf('msie 5') != -1);
var isIE6 = (agt.indexOf('msie 6') != -1);
frameWidth = 0;
frameHeight = 0;
if (self.innerWidth){
	frameWidth = self.innerWidth;
	frameHeight = self.innerHeight;
} else if (document.documentElement && document.documentElement.clientWidth){
	frameWidth = document.documentElement.clientWidth;
	frameHeight = document.documentElement.clientHeight;
} else if (document.body) {
	frameWidth = document.body.clientWidth;
	frameHeight = document.body.clientHeight;
}

var url_flag = 'http://www.trocatroca.com/vlite/images/flags/';
var objFlags = {'en':'us.gif', 'es':'es.gif', 'pt':'br.gif'};
var flagsloaded = false;

function setLanguage(lang){
	var page = new String(window.location);
	var return_url = page;
	page = page.substr( page.lastIndexOf('/')+1,  page.length);
	// the login page, should reload with the new language
	if(page=='index.php' || page=='index-main.php'){ 
		createCookie('language', lang, 1825); // 5 years
		var url = 'http://www.trocatroca.com/vlite/action/set_language.php?lang='+lang+'&url='+return_url;
		window.location = url;
	} else {
		alert('Você só pode mudar o Idioma na Página de Login\n(You can change the Language just in the Login Page)');
	}	
}

function Dimension() {
	this.Width = 0;
	this.Height = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		this.Width = window.innerWidth;
		this.Height = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		this.Width = document.documentElement.clientWidth;
		this.Height = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		this.Width = document.body.clientWidth;
		this.Height = document.body.clientHeight;
	}
}

function Browser(){
	var agent = navigator.userAgent.toLowerCase();
	this.isWin = agent.indexOf( "win" ) > 0;
	this.isUNIX = agent.indexOf( "x11" ) > 0;
	this.isMac = agent.indexOf( "mac" ) > 0;
	this.isOpera = agent.indexOf("opera") > -1;
	this.isAOL = agent.indexOf( "aol" ) > 0;
	this.isIE = agent.indexOf( "msie" ) > 0;
	this.isIE6 = agent.indexOf('msie 6') > 0;
	this.isNS6 = agent.indexOf( "netscape6" ) > 0;
	this.isGecko = agent.indexOf( "gecko" ) > 0;
	this.isNS4 = ( document.layers ) ? true : false;
	this.iWidth = window.screen.width;
	this.iHeight = window.screen.height;
	this.Width = 0;
	this.Height = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		this.Width = window.innerWidth;
		this.Height = window.innerHeight;
	} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
		//IE 6+ in 'standards compliant mode'
		this.Width = document.documentElement.clientWidth;
		this.Height = document.documentElement.clientHeight;
	} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
		//IE 4 compatible
		this.Width = document.body.clientWidth;
		this.Height = document.body.clientHeight;
	}
}

var browser = new Browser();

function loadInnerPage(page){
	setHideVideo();
	var args = 'http://'+location.hostname+'/vlite/'+page;
	setTimeout( "location.href = '"+args+"'", 0 );
	jQuery('#frame-banner').attr({src:'index-banner.php'});
}

function setLoadingWindow(show){	
	if(show){		
		if(arguments.length > 1){
			var mens = arguments[1];
			jQuery('#loading-msg').html(mens);
		}
		jQuery('#loading').css({ display: 'block'});
	} else {
		jQuery('#loading').css({ display: 'none' });
	}	
}

function setActionPage(url){
	setHideVideo();
	setLoadingWindow(true, 'Carregando...');
	setHideProfile();
	setHideMessageInbox(); // functions-email.js
	showInbox = false;
	if(!profileVerified) url = 'pages/profile_win.php';
	document.getElementById('content').src = url;
	jQuery('#frame-banner').attr({src:'index-banner.php'});
}

function LoadNews(id, menu){
	var args = '?section='+menu+'&id_news='+id+'&page=1';
	var url = url_news+args;
	window.open(url,'window_news')
	jQuery('#frame-banner').attr({src:'index-banner.php'});
}

function setCSSOpacity(){
	var str = '';
	if ((navigator.appName.indexOf('Microsoft')+1)) {
		str += '<style type="text/css">';
		str += ' .opacity1 {filter:alpha(opacity=70);  }';
		str += ' .opacity2 {filter:alpha(opacity=100);  }';
		str += '</style>';
	} else if ((navigator.appName.indexOf('Netscape')+1)) {
		str = '';
		str += '<style type="text/css">';
		str += ' .opacity1 {-moz-opacity:0.7;  } ';
		str += ' .opacity2 {-moz-opacity:1;  } ';
		str += '</style>';
	}
	document.write(str); 
}

function setCursorToBegin(control) {
  if (control.createTextRange) {
    var range = control.createTextRange();
    range.collapse(true);
    range.select();
  }
  else if (control.setSelectionRange) {
    control.focus();
    control.setSelectionRange(0, 0);
  }
}

function replaceWhiteSpaceTitle(field){
	field.value = field.value.replace("  ", " ");
}

//------------ functions to use in the Localization procedures
function getStates(element){
	var countryID = element.value;
	if(countryID==0){
	 	return;
	}
	parent.parent.setLoadingWindow(true, 'Aguarde... Listando Estados');
	var form = element.form; //document.forms['form-search'];
	var countryID = form.countryID.value;
	var selector = document.getElementById('stateID');
	//var stateID = form.stateID.value;

	// CLEAR
	var neigh = document.getElementById('neighborhoodID');
	neigh.options.length = 0;
	neigh.options[neigh.options.length] = new Option('[Todos os Bairros]','0');	

	var city = document.getElementById('cityID');
	city.options.length = 0;
	city.options[city.options.length] = new Option('[Todas as Cidades]','0');	
	
	var args = {'action':'get-states', 'countryID':countryID};			
	var url = 'http://www.trocatroca.com/vlite/action/getLocation.php';
	jQuery.ajax({
		type: "POST",
		url: url,
		data: args,
		dataType: 'json',
		success: function(data){
			var success = eval(data.success);
			//alert(data.total);
			
			if(success){
				setSelectorItems(selector, data.data, 'Todos os Estados');
			} else {
				alert('Problema: '+data.message);
			}
			parent.setLoadingWindow(false);	
		},
		error: function (XMLHttpRequest, textStatus, errorThrown){
			parent.setLoadingWindow(false);	
			alert('Error: '+textStatus+' => '+errorThrown);
		}
	});
	/*
	var myRequest = new Ajax.Request(url, {
		method: 'post',
		requestHeaders: {Accept: 'application/json'},
		encoding: {Accept: 'ISO-8859-1'},
		parameters: args,
		onSuccess: function(transport, json) {
			var jsonObject = transport.responseText.evalJSON(true);
			if(jsonObject.success){
				setSelectorItems(selector, jsonObject.data, 'Todos os Estados');
			} else {
				alert('Problema: '+jsonObject.message);
			}
		}
	});	// myRequest	
	*/
}

function getCities(element){
	var stateID = element.value;
	if(stateID==0){
		var neigh = document.getElementById('neighborhoodID');
		neigh.options.length = 0;
		neigh.options[neigh.options.length] = new Option('[Todos os Bairros]','0');	
		var city = document.getElementById('cityID');
		city.options.length = 0;
		city.options[city.options.length] = new Option('[Todas as Cidades]','0');	
		return;
	}
	parent.parent.setLoadingWindow(true, 'Aguarde... Listando Cidades');
	var form = element.form; //document.forms['form-search'];
	var countryID = form.countryID.value;
	var selector = document.getElementById('cityID');
	//var stateID = form.stateID.value;

	// CLEAR
	var neigh = document.getElementById('neighborhoodID');
	neigh.options.length = 0;
	neigh.options[neigh.options.length] = new Option('[Todos os Bairros]','0');	
	
	var args = {action:'get-cities', stateID: stateID, countryID: countryID};			
	var url = 'http://www.trocatroca.com/vlite/action/getLocation.php';
	
	jQuery.ajax({
		type: "POST",
		url: url,
		data: args,
		dataType: 'json',
		success: function(data){
			var success = eval(data.success);
			parent.parent.setLoadingWindow(false);
			if(success){
				setSelectorItems(selector, data.data, 'Todas as Cidades');
			} else { 
				alert(data.message);
			}
		},
		error: function (XMLHttpRequest, textStatus, errorThrown){
			parent.parent.setLoadingWindow(false);
			alert('Erro: '+textStatus+' => '+errorThrown+'\nPor favor, comunique ao Suporte do site');
		}
	});
}

function getBairrosBrasil(element){
	var cityID = element.value;
	//alert(cityID);
	if(cityID==0){
		var neigh = document.getElementById('neighborhoodID');
		neigh.options.length = 0;
		neigh.options[neigh.options.length] = new Option('[Todos os Bairros]','0');	
		return;
	}
	parent.parent.setLoadingWindow(true, 'Aguarde... Listando Bairros');
	var form = element.form;//document.forms['form-search'];
	var countryID = form.countryID.value;
	var stateID = form.stateID.value;
	var selector = document.getElementById('neighborhoodID');
	var args = {action:'get-bairros', 'cityID':cityID, 'stateID':stateID, 'countryID':countryID};
	
	var url = 'http://www.trocatroca.com/vlite/action/getLocation.php';
	
	jQuery.ajax({
		type: "POST",
		url: url,
		data: args,
		dataType: 'json',
		success: function(data){
			var success = eval(data.success);
			parent.parent.setLoadingWindow(false);
			if(success){
				setSelectorItems(selector, data.data, 'Todos os Bairros');
			} else { 
				alert('Problema: '+data.message);
			}
		},
		error: function (XMLHttpRequest, textStatus, errorThrown){
			parent.parent.setLoadingWindow(false);
			alert('Erro: '+textStatus+' => '+errorThrown+'\nPor favor, comunique ao Suporte do site');
		}
	});	
}

function setSelectorItems(selector, optionObject, first_option){
	selector.options.length = 0;
	selector.options[selector.options.length] = new Option('['+first_option+']','0');
	for(var i=0; i<optionObject.length; i++){
		selector.options[selector.options.length] = new Option(optionObject[i].name, optionObject[i].id);
	}
	selector.focus();
	parent.parent.setLoadingWindow(false);
	
}

function toggleOption(element, title){
	if( document.getElementById(element).style.display=='block'){
		document.getElementById(element).style.display='none';
		document.getElementById('btn_'+element).src = '../images/down.png';
		document.getElementById('title_'+element).innerHTML = title;
	} else {
		document.getElementById('title_'+element).innerHTML = '';
		document.getElementById(element).style.display='block';
		document.getElementById('btn_'+element).src = '../images/up.png';
	}
}

//------------ functions to use in the Localization procedures

function checkdate(input){
	//var validformat=/^\d{2}\/\d{2}\/\d{4}$/ //Basic check for format validity
	var validformat=/^\d{2}\/\d{2}\/\d{4}$/; //Basic check for format validity
	var returnval=false;
	if (!validformat.test(input.value))
		alert("Formato de data inválido. Por favor corriga sua digitação (formato: dd/mm/aaaa).");
	else{ 
		//Detailed check for valid date ranges
		//Enter a valid date (mm/dd/yyyy): - dd/mm/yyyy
		//var monthfield=input.value.split("/")[0]
		//var dayfield=input.value.split("/")[1]
		//var yearfield=input.value.split("/")[2]

		var dayfield=input.value.split("/")[0];
		var monthfield=input.value.split("/")[1];
		var yearfield=input.value.split("/")[2];
		var dayobj = new Date(yearfield, monthfield-1, dayfield);
		if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))
			alert("Dia, Mês ou Ano inválido, corriga a digitação por favor.");
		else
			returnval=true;
	}
	if (returnval==false) 
		input.select();
	return returnval;
}

function checkFieldTextLength(textField, maxLimit, element) {
	if (textField.value.length > maxLimit){ 
		textField.value = textField.value.substring(0, maxLimit);
	} else {
		var str = '('+(maxLimit - textField.value.length)+')';
		document.getElementById(element).innerHTML = str;
	}
}

function showInfo(action, width, height){
	var url = "http://www.trocatroca.com/vlite/pages/info.php?action="+action;
	var config = 'status=no,resizable=yes,scrollbars=yes,height='+height+',width='+width+',location=no';
	var win = window.open(url, 'WIN_INFO', config, false);
	win.focus();
}

function CheckMail(emailStr) {	
	/* The following variable tells the rest of the function whether or not
	to verify that the address ends in a two-letter country or well-known
	TLD.  1 means check it, 0 means don't. */	
	var checkTLD=1;
	
	/* The following is the list of known TLDs that an e-mail address must end with. */	
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	
	/* The following pattern is used to check if the entered e-mail address
	fits the user@domain format.  It also is used to separate the username
	from the domain. */	
	var emailPat=/^(.+)@(.+)$/;
	
	/* The following string represents the pattern for matching all special
	characters.  We don't want to allow special characters in the address. 
	These characters include ( ) < > @ , ; : \ " . [ ] */	
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	
	/* The following string represents the range of characters allowed in a 
	username or domainname.  It really states which chars aren't allowed.*/
	var validChars="\[^\\s" + specialChars + "\]";
	
	/* The following pattern applies if the "user" is a quoted string (in
	which case, there are no rules about which characters are allowed
	and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
	is a legal e-mail address. */
	var quotedUser="(\"[^\"]*\")";
	
	/* The following pattern applies for domains that are IP addresses,
	rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
	e-mail address. NOTE: The square brackets are required. */
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	
	/* The following string represents an atom (basically a series of non-special characters.) */
	var atom=validChars + '+';
	
	/* The following string represents one word in the typical username.
	For example, in john.doe@somewhere.com, john and doe are words.
	Basically, a word is either an atom or quoted string. */
	var word="(" + atom + "|" + quotedUser + ")";
	
	// The following pattern describes the structure of the user
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	
	/* The following pattern describes the structure of a normal symbolic
	domain, as opposed to ipDomainPat, shown above. */
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
	
	/* Finally, let's start trying to figure out if the supplied address is valid. */
	
	/* Begin with the coarse pattern to simply break up user@domain into
	different pieces that are easy to analyze. */
	var matchArray=emailStr.match(emailPat);
	if (matchArray==null) {
		/* Too many/few @'s or something; basically, this address doesn't
		even fit the general mould of a valid e-mail address. */
		//alert("Email address seems incorrect (check @ and .'s)");
		return false;
	}
	var user=matchArray[1];
	var domain=matchArray[2];
	
	// Start by checking that only basic ASCII characters are in the strings (0-127).
	for (i=0; i<user.length; i++) {
		if (user.charCodeAt(i)>127) {
			alert("Ths username contains invalid characters.");
			return false;
	   }
	}
	for (i=0; i<domain.length; i++) {
		if (domain.charCodeAt(i)>127) {
			alert("Ths domain name contains invalid characters.");
			return false;
	   }
	}
	
	// See if "user" is valid 
	if (user.match(userPat)==null) {
		// user is not valid
		//alert("The username doesn't seem to be valid.");
		return false;
	}
	
	/* if the e-mail address is at an IP address (as opposed to a symbolic
	host name) make sure the IP address is valid. */
	var IPArray=domain.match(ipDomainPat);
	if (IPArray!=null) {
		// this is an IP address
		for (var i=1;i<=4;i++) {
			if (IPArray[i]>255) {
				alert("Destination IP address is invalid!");
				return false;
			}
		}
		return true;
	}
	
	// Domain is symbolic name.  Check if it's valid.
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++) {
		if (domArr[i].search(atomPat)==-1) {
			//alert("The domain name does not seem to be valid.");
			return false;
	   }
	}
	
	/* domain name seems valid, but now make sure that it ends in a
	known top-level domain (like com, edu, gov) or a two-letter word,
	representing country (uk, nl), and that there's a hostname preceding 
	the domain or country. */
	if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1) {
		//alert("The address must end in a well-known domain or two letter " + "country.");
		return false;
	}
	
	// Make sure there's a host name preceding the domain.
	if (len<2) {
		//alert("This address is missing a hostname!");
		return false;
	}
	
	// If we've gotten this far, everything's valid!
	return true;
}

/*----------- General use functions -----------*/
function createCookie(name, value, days){
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	} else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name){
	var ca = document.cookie.split(';');
	var nameEQ = name + "=";
	for(var i=0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') 
			c = c.substring(1, c.length); //delete spaces
		if (c.indexOf(nameEQ) == 0) 
			return c.substring(nameEQ.length, c.length);
	}
	return '';
}

function eraseCookie(name){
  createCookie(name, "", -1);
}


if (!Array.prototype.indexOf){
	Array.prototype.indexOf = function(elt){
		var len = this.length;
		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;
		};
}

var VideoPlayer = function(){
	var arg = arguments[0]; // JSON parameters 
	var typePlayer = {qt:['dv','mov','moov','movie','mp4'], wmp:['asf','wm','wmv'], qtwmp:['avi','mpg','mpeg']};
	var ua = navigator.userAgent.toLowerCase();
	var plugins;
				
	var setWinMediaPlayer = function(filme, width, height, player){
		if(window.ActiveXObject){
			// showcontrols must be a string in IE
			height += 70; // height of WMP controller in IE
			var html = ''+
			'<object id="movie_player" name="movie_player" height="'+height+'" width="'+width+'" '+
				'classid="clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6" type="application/x-oleobject" >'+
			'	<param name="url" value="' + url + '" /> '+
			'	<param name="autoStart" value="true" /> '+
			'	<param name="uimode" value="full" /> '+
			'</object>';
			jQuery('#'+player).html(html);	
		}else{
			// showcontrols and autostart must be an integer in browsers other than IE
			height += 45; // height of WMP controller in non-IE
			var html = '';
			html = ''+
			'<object classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6" id="movie_player"  width="'+width+'" height="'+height+'">'+
			'	<param name="url" value="'+filme+'" />'+
			'	<param name="src" value="'+filme+'" />'+
			'	<param name="showcontrols" value="false" />'+
			'	<param name="autostart" value="true" />'+
			'	<!--[if !IE]>--> '+
			'		<object type="video/x-ms-wmv" data="'+filme+'"	width="'+width+'" height="'+height+'" >'+
			'			<param name="src" value="'+filme+'" />'+
			'			<param name="autostart" value="true" />'+
			'			<param name="controller" value="true" />'+
			'		</object>'+
			'	<!--<![endif]-->'+
			'</object>';
			
			jQuery('#'+player).html(html);
		}
	}; //setWinMediaPlayer
	
	var setQuickTimePlayer = function(url, width, height, player){
		height += 45; 
		var html = ''+		
		'<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" id="movie_player" '+
		'		codebase="http://www.apple.com/qtactivex/qtplugin.cab" width="'+width+'" height="'+height+'">'+
		'	<param name="src" value="'+url+'" />'+
		'   <param name="controller" value="true" />'+
		'   <param name="autoplay" value="true" />'+
		'	<object type="video/quicktime" data="'+url+'" width="'+width+'" height="'+height+'">'+
		'   	<param name="autoplay" value="true" />'+
		'       <param name="controller" value="true" />'+
		'   </object>'+
		'</object>';
		jQuery('#'+player).html(html);
	};
			
	this.Play = function(){
		url = arg.url;
		width = arg.width;
		height = arg.height;
		player = arg.player;
		
		var array = url.split('.');		
		var ext = (array[array.length-1]).toLowerCase();
		
		var checkPluginObj = function(){
			if(navigator.plugins && navigator.plugins.length){	
				var detectPlugin = function(plugin_name){
					var detected = false;
					for (var i = 0, len = navigator.plugins.length; i < len; ++i){
						if(navigator.plugins[i].name.indexOf(plugin_name) > -1){
							detected = true;
							break;
						}
					}
					return detected;
				};			
				var f4m = detectPlugin('Flip4Mac');
				plugins = {
					fla:    detectPlugin('Shockwave Flash'),
					qt:     detectPlugin('QuickTime'),
					wmp:    !f4m && detectPlugin('Windows Media'), // if it's Flip4Mac, it's not really WMP
					f4m:    f4m
				};
			}else{
				var detectPlugin = function(plugin_name){
					var detected = false;
					try{
						var axo = new ActiveXObject(plugin_name);
						if(axo) detected = true;
					}catch(e){}
					return detected;
				};
				plugins = {
					fla:    detectPlugin('ShockwaveFlash.ShockwaveFlash'),
					qt:     detectPlugin('QuickTime.QuickTime'),
					wmp:    detectPlugin('wmplayer.ocx'),
					f4m:    false
				};
			}		
			if(typePlayer.qtwmp.indexOf(ext) > -1){
				return {valid:plugins.wmp || plugins.qt, type:'wmp', player: 'QuickTime/Windows Media Player'};
			} else if(typePlayer.qt.indexOf(ext) > -1){
				return {valid:plugins.qt, type:'qt', player:'QuickTime'};
			} else if(typePlayer.wmp.indexOf(ext) > -1){
				return {valid:plugins.wmp, type:'wmp', player:'Windows Media Player'};
			}
		}; // checkPluginObj
		
		var checkPlugin = checkPluginObj();
		if(checkPlugin.valid){			
			if(checkPlugin.type=='wmp'){
				setWinMediaPlayer(url, width, height, player);
			} else if(checkPlugin.type=='qt'){
				setQuickTimePlayer(url, width, height, player);
			}
		} else {
			alert('Precisa instalar o plugin para tocar: '+checkPlugin.player);
		}
							
	}; // Play
	
	this.Clear = function(){
		player = arg.player;
		var obj = document.getElementById(player);
		if(obj != null){
			// Remove just the video object
			var videoObj = obj.childNodes[0];
			if(videoObj)
				obj.removeChild(videoObj);	
		}
	}; // Clear
}

function drawProgressBar(color, width, percent) { 
	var p = parseInt(percent);
	var pixels = width * (p / 100); 
	document.write('<div class="progress-wrapper" style="width: ' + width + 'px">'); 
	document.write('	<div class="progress-bar" style="width: ' + pixels + 'px; background-color: ' + color + ';"></div>'); 
	document.write('	<div class="progress-text" style="width: ' + width + 'px">' + percent + '%</div>'); 
	document.write('</div>'); 
}

/*
// Verificar email digitado
"^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$"

A primeira parte:
^[\\w-_\.]

^ significa "verifique o primeiro caracter". 
Neste caso tem que garantir que seja uma letra (a-z0-9) então usa o \\w para isso,
mas também um underline, um hífem ou um ponto.

Próxima:
*[\\w-_\.]

O * significa "confronte a expressão anterior zero ou mais vezes" e, claro, 
a próxima parte [\\w-_\.] assegura que sejam caracteres, underline, etc.

Próximo:
\@[\\w]\.+

O \@ checa pelo símbolo @, o \.+ significa "encontre pelo menos um ponto depois do símbolo". 
Isso significa que ele deve está no formato @w. e não assim @. ou assim @#.

Último:
[\\w]+[\\w]$

O [\\w] garante que existe uma letra depois do ponto.
O [\\w]$ verifica a última letra para ver se é mesmo uma letra (domínio ou endereço de IP) 
e não um outro caracter.
O $ significa "verifique o último caracter". 
*/

String.prototype.trim = function() {
  //^=start of string
  //\s=whitespace
  //+=1 or more occurence
  //| alternate
  //\s whitespace
  //+ one or more occrence
  //$ at end of string
  //g = global -- replace more than one occurence
  
   return this.replace(/^\s+|\s+$/g,'');
}
String.prototype.rtrim = function() {
  // \s = white space
  // + = one or more occurence
  // $ = at end of string
  // g = global -- replace more than one occrence

   return this.replace(/\s+$/g,'');
}
String.prototype.ltrim = function() {
  // ^ = at beginning of string
  // /s = white space
  // + = one or more occurence
  // g = global -- replace more than one occurence

   return this.replace(/^\s+/g,'');     
}

