var title_entries = {'gmail': "Please enter your entire email, including @gmail.com.",
					 'hotmail': "Please enter your entire email, including @hotmail.com.",
					 'lycos': "Please enter the username you use to log in.",
					 'orkut': "Please enter your entire email, including @gmail.com.",
					 'yahoo': "Please enter your entire email, including @yahoo.com."
};

var button_swaps = {'submit.jpg': 'submit.gif',
					'submit.gif': 'submit.jpg',
					'cancel.jpg': 'cancel2.gif',
					'cancel2.gif': 'cancel.jpg',
					'edit.jpg': 'edit.gif',
					'edit.gif': 'edit.jpg',
					'find.jpg': 'find.gif',
					'find.gif': 'find.jpg',
					'ok.jpg': 'ok.gif',
					'ok.gif': 'ok.jpg',
					'refresh1.png': 'refresh2.png',
					'refresh2.png': 'refresh1.png',
					'reset.jpg': 'reset.gif',
					'reset.gif': 'reset.jpg',
					'save.jpg': 'save.gif',
					'save.gif': 'save.jpg',
					'signup.jpg': 'signup.gif',
					'signup.gif': 'signup.jpg',
					'search.jpg': 'search.gif',
					'search.gif': 'search.jpg',
					'send.jpg': 'send.gif',
					'send.gif': 'send.jpg',
					'upload.jpg': 'upload.gif',
					'upload.gif': 'upload.jpg',
					'refine-search.jpg': 'refine-search.gif',
					'refine-search.gif': 'refine-search.jpg',
					'add-favorite.jpg': 'add-favorite.gif',
					'add-favorite.gif': 'add-favorite.jpg',
					'enlarge-image.png': 'enlarge-image2.png',
					'enlarge-image2.png': 'enlarge-image.png',
					'send-message.jpg': 'send-message.gif',
					'send-message.gif': 'send-message.jpg'
};

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 nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function getViewportSize(dimwanted) {
	var viewportwidth;
	var viewportheight;
 
	// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
 
	if (typeof window.innerWidth != 'undefined') {
		viewportwidth = window.innerWidth,
		viewportheight = window.innerHeight
	 }
 
	// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)

	else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0)
	{
		viewportwidth = document.documentElement.clientWidth,
		viewportheight = document.documentElement.clientHeight
	}
 	// older versions of IE
 
 	else
	{
		viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
		viewportheight = document.getElementsByTagName('body')[0].clientHeight
	}

	if(dimwanted == "width") {
		return viewportwidth;
	}else{
		return viewportheight;
	}
}

function doEmailCheck(field, tdiv){
	//checks if contents of a field is a valid email - if it is will make text green, if not red
	tdiv = document.getElementById(tdiv);
	if(isValidEmail(field.value)){
		try{
		tdiv.innerHTML = "";		
		field.style.color = "Green";
		field.style.borderColor = "";
		}catch(err){
			//do nothing
		}
		return true;
	}else{
		try{
		tdiv.innerHTML = "Please enter a valid email";
		field.style.borderColor = "#FF0000";
		field.style.color = "Red";
		}catch(err){
			//do nothing
		}
		return false;
	}
}

function isValidEmail(anEmail){
	//will check for valid email based on a passed value
	regEmail = /^[A-Za-z0-9\-_]+(\.[A-Za-z0-9\-_]+)*@([A-Za-z0-9\-_\.]+\.)+[A-Za-z]{2,3}$/i;
	return regEmail.test(anEmail);
}

function isValidPass(pass, cpass){
	if(pass.length<6){
		return false;
	}
	if(pass!=cpass){
		return false;
	}
	return true;
}
var lastBlurred = undefined;
function lastBlur(event) {
	lastBlurred = event.element();
}
var field = undefined;
var cfield = undefined;
var targ = undefined;
function disableCheck(event) {
	if(field == undefined || cfield == undefined) {
		return;
	}
	if(event.element == field || event.element == cfield) {
		$(targ).update('').hide();
		field.removeClassName("err");
		cfield.removeClassName("err");
	}
}

function checkPass(event, form, f, cf, tdiv){
	f = $(f);
	cf = $(cf);
	if(field == undefined || cfield == undefined) {
		field = f;
		cfield = cf;
		targ = tdiv;
		return;
	}
	
	if(f.getValue().length<5){
		try{
		$(tdiv).update("Password must be at least 6 characters").show();
		f.addClassName("err");
		/* field.style.borderColor = "#FF0000";
		field.style.color = "Red"; */
		}catch(err){
			//do nothing
		}
	}else if(field.getValue() != cfield.getValue()){
		try{
		$(tdiv).update("Passwords do not match").show();
		f.addClassName("err");
		cf.addClassName("err");
		/* field.style.borderColor = "#FF0000";
		field.style.color = "Red";
		cfield.style.borderColor = "#FF0000";
		cfield.style.color = "Red";*/
		}catch(err){
			//do nothing
		}
	
	}else{
		try{
		$(tdiv).update('').hide();
		f.removeClassName("err");
		cf.removeClassName("err");
		/* field.style.borderColor = "";
		field.style.color = "Black";
		cfield.style.borderColor = "";
		cfield.style.color = "Black";*/
		}catch(err){
			//do nothing
		}
	}
}

function addClassToObject(obj, className) {
	var classes = obj.className;
	if(classes == '') {
		classes = new Array();
	}else{
		classes = classes.split(' ');
	}
	classes[classes.length] = className;
	obj.className = classes.join(' ');
	return true;
}

function removeClassFromObject(obj, className) {
	var classes = obj.className.split(' ');
	var result;
	result = new Array();
	result[0] = '';
	var length = classes.length;
	for(var i = 0; i < length; i++) {
		if(classes[i] != className) {
			result[result.length] = classes[i];
		}
	}
	obj.className = resut.join(' ');
	return true;
}

function removeAllClasses(id) {	var tag = document.getElementById(id);	var entries = tag.getElementsByTagName('li');	for(var i = 0; i < entries.length; i++) {		entries[i].className = '';	}
	return;
}

function hasClass(obj, className) {
	var classes = explode(' ', obj.className);
	for(var i = 0; i < classes.length; i++) {
		if(classes[i] == className) {
			return true;
		}
	}
	return false;
}

function popUp(URL,width,height) {
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open('" + URL+"', '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width="+width+",height="+height+",left = 695,top = 425');");
}
/*
function addToFavorites(url,page_name)
{
	if (window.external)
	{
		window.external.AddFavorite(urlAddress,pageName);
	}
	else if (window.sidebar)  // Mozilla Firefox Bookmark
	{
		window.sidebar.addPanel(bookmarktitle, bookmarkurl,"")
	}
	else
	{
		alert("Sorry! Your browser doesn't support this function.");
	}
}
*/

function addToFavorites(bookmarkurl, bookmarktitle)
{
	if (document.all)
		window.external.addFavorite(bookmarkurl , bookmarktitle)
	else if (window.sidebar)  // Mozilla Firefox Bookmark
		window.sidebar.addPanel(bookmarktitle, bookmarkurl,"")
}


function checkAll(field)
{
for (i = 0; i < field.length; i++)
	field[i].checked = true ;
}

function uncheckAll(field)
{
for (i = 0; i < field.length; i++)
	field[i].checked = false ;
}

function useNative(id) {
	if(document.implementation && document.implementation.hasFeature && document.implementation.hasFeature("WebForms", "2.0")) {
		var obj = document.getElementById(id);
		var img = obj.nextSibling;
		img.style.display = 'none';
		return true;
	}
	return false;
}

function format_phone(field_id){
	// Attempt to auto-format basic US phone numbers.  This method supports
	// 7 and 10 digit numbers.  Example: (410) 555-1212
	// Get the field that fired the event
	var oField = document.getElementById(field_id);
	// If we have the field and all is well
	if (typeof(oField) != "undefined" && oField != null){
		// Remove any non-numeric characters
		var sTmp = oField.value.replace(/[^0-9]/g, "");
		// If the number is a length we expect and support, format the number
		if(sTmp.length<10){
			document.getElementById(field_id + "err").innerHTML = "Invalid Phone";
			return;
		}
		//strip any preceeding 1's
		if(sTmp.indexOf('1')==0){
			sTmp = sTmp.substr(1);
		}
		switch (sTmp.length){
			/*case "14105551212".length:
				oField.value = sTmp.substr(0,1) + "(" + sTmp.substr(1, 3) + ") " + sTmp.substr(4, 3) + "-" + sTmp.substr(7, 4);
				document.getElementById(field_id + "err").innerHTML = "";
				break;*/
			case "4105551212".length:
				oField.value = "(" + sTmp.substr(0, 3) + ") " + sTmp.substr(3, 3) + "-" + sTmp.substr(6, 4);
				document.getElementById(field_id + "err").innerHTML = "";				
				break;
			default:
				oField.value = "(" + sTmp.substr(0, 3) + ") " + sTmp.substr(3, 3) + "-" + sTmp.substr(6, 4) + " ext " + sTmp.substr(10, sTmp.length-10);
				document.getElementById(field_id + "err").innerHTML = "";				
				break;
		}
	}
}

function showLoading() {
	var mydiv = new Element('div', {'id': 'loader'})
	.update('<img src="/images/loading.gif" alt="Loading..." /><br />Uploading image...')
	.setStyle({
		'backgroundColor': 'rgb(255,255,255)',
		'color': 'rgb(0,0,0)',
		'border': 'rgb(46, 99, 141) 1px solid',
		'zIndex': 200,
		'width': '160px',
		'height': '80px',
		'padding': '20px',
		'textAlign': 'center',
		'position': 'fixed'
	});
	var width = getViewportSize('width');
	var height = getViewportSize('height');
	var w = ((width/2) - 100);
	if(w < 0) {
		w = 0;
	}
	var h = ((height/2) - 50);
	if(h < 0) {
		h = 0;
	}
	mydiv.setStyle({'top': h + 'px', 'left': w + 'px'});
	var backdrop = $('fade-out');
	backdrop.setStyle({'opacity': 0.0});
	backdrop.appear({'from': 0.0, 'to': 0.5});
	Element.extend(backdrop.parentNode).insert(mydiv);
	return true;
}

function hideLoading() {
	var backdrop = document.getElementById('fade-out');
	backdrop.parentNode.removeChild(backdrop.parentNode.lastChild);
	backdrop.style.display = 'none';
	return true;
}

function confirmRun(commands, type, objstring) {
	var prompt = false;
	switch(type) {
		case 'delete':
			prompt = confirm("Are you sure you want to delete this " + objstring + "?");
			break;
		default:
			prompt = confirm(objstring);
			break;
	}
	if(prompt) {
		eval(commands);
		return true;
	}
	return false;
}

function init_wysiwyg(parenttag){
	if(parenttag != undefined) {
		var wyg = $A($(parenttag).getElementsBySelector('.mceEditor'));
		if(wyg.length == 0) {
			return;
		}
		var entry = new Array();
		wyg.each(function(item) {
			new Insertion.After(item, "<input type='hidden' name='wysiwyg" + item.getAttribute('name') + "' value='true' />")
			entry.push(item.identify());
		});
		var e = entry.join(',');
		var t = tinyMCE.init({
			theme : "advanced",
			mode : "exact",
			elements: e,
			plugins : "",
			//cleanup : false,
			remove_linebreaks : false,
			theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,undo,redo,|,link,unlink,|,image,|,bullist,numlist,|,removeformat,cleanup",
			theme_advanced_buttons2 : "",
			theme_advanced_buttons3 : "",
			content_css : "/css/bb.css",
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "center",
			theme_advanced_styles : "Code=codeStyle;Quote=bb-quote"
		});
	}else{
		var wyg = $A($$('.mceEditor'));
		if(wyg.length == 0) {
			return;
		}
		var entry = new Array();
		wyg.each(function(item) {
			new Insertion.After(item, "<input type='hidden' name='wysiwyg" + item.getAttribute('name') + "' value='true' />")
			entry.push(item.identify());
		});
		var e = entry.join(',');
		var t = tinyMCE.init({
			theme : "advanced",
			mode : "exact",
			elements: e,
			plugins : "",
			//cleanup : false,
			remove_linebreaks : false,
			theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,undo,redo,|,link,unlink,|,image,|,bullist,numlist,|,removeformat,cleanup",
			theme_advanced_buttons2 : "",
			theme_advanced_buttons3 : "",
			content_css : "",
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "center",
			theme_advanced_styles : ""
		});
	}
}

/************************************
*Application Specific Functions		*
*************************************/



/**
*  Instant messenger
*/

function jspopup(location,name,width,height){
	return window.open (location,name,'status=0,toolbar=0,menubar=0,directories=0,scrollbars=1,resizable=1,width='+width+',height='+height);
}

function check_for_messages(){
	makeGETRequest('/blank.php?module=instant_message&action=check');
	http_request.onreadystatechange = function() {		
		if(http_request.readyState == 4 && http_request.status == 200) {
			if(http_request.responseText!='false'){
				var ids = http_request.responseText.split(';');
				var i = 0;
				for ( var i in ids ){
					if(isInteger(ids[i])){
						if(ids[i]!=''){
							if (window['Messenger'+ids[i]]==undefined||window['Messenger'+ids[i]].closed) {							
								window['Messenger'+ids[i]]=jspopup('/blank.php?module=instant_message&action=launch_chat&id='+ids[i], 'Messenger'+ids[i], 450, 470);
							}
						}
					}
				}
			}
		}
	}
}

function popup_chat(user_id){
	loadobjs('/css/message_system/inbox.css');
	jspopup('blank.php?module=instant_message&action=launch_chat&id='+user_id, 'Messenger', 450, 470);
}

var tmr;
var txt;

function init_tmr(id){	
	tmr = setTimeout("window.location.reload();init_tmr("+id+");",10000);	
}

function stop_tmr(){
	clearTimeout (tmr);
}

function isInteger(s) {
	return (s.toString().search(/^-?[0-9]+$/) == 0);
}

function showPitching(event) {
	if($('pri_position').getValue() == 1 || $('sec_position').getValue() == 1 || $('pri_position').getValue() == 2 || $('sec_position').getValue() == 2) {
		$('pitcher_stats').show();
	}else{
		$('pitcher_stats').hide();
	}
}

function swapButtons(event) {
	var obj = event.element();
	if(obj.tagName.toLowerCase() == 'a') {
		var key = obj.getStyle('background-image').substring(obj.getStyle('background-image').lastIndexOf('/') + 1, obj.getStyle('background-image').length - 1);
		if(key.lastIndexOf('"') != -1) {
			key = key.substring(0, key.length - 1);
		}
		//alert("Replacing " + key + " with " + button_swaps[key]);
		obj.setStyle({backgroundImage: obj.getStyle('background-image').gsub(key, button_swaps[key])});
	}else{
		var key = obj.src.substring(obj.src.lastIndexOf('/') + 1);
		//alert("Replacing " + key + " with " + button_swaps[key]);
		if(key.lastIndexOf('"') != -1) {
			key = key.substring(0, key.length - 1);
		}
		obj.src = obj.src.gsub(key, button_swaps[key]);
	}
}

function popSelect(event) {
	var tar = $('timezone-continent');
	if(this == tar) {
		repopulateSelect('/blank.php?do=personalDetails_getTimezone&con=' + escape(this.getValue()), 'timezone');
	}
}

var count = 1;
var player_stats;

function addNewFilter(e) {
	if(player_stats == undefined) {
		if (window.XMLHttpRequest) // if Mozilla, Safari etc
			page_request = new XMLHttpRequest()
		else if (window.ActiveXObject){ // if IE
			try {
				page_request = new ActiveXObject("Msxml2.XMLHTTP")
			} 
			catch (e){
				try{
					page_request = new ActiveXObject("Microsoft.XMLHTTP")
				}
				catch (e){}
			}
		}
		else{
			return false
		}
		page_request.open('GET', '/blank.php?do=player_getAttributeListing', false)
		page_request.send(null)
		var json = page_request.responseText;
					
		player_stats = eval(json);
		if(player_stats == undefined) {
			return false;
		}
	}
	
	var entry = '<p id="filter' + count + '" class="three-count nolabel">\
			<select id="filter' + count + '_attribute" name="filter[attribute][]">';
			for(var i = 0; i < player_stats.length; i++) {
				entry += '<option value="' + player_stats[i]['value'] + '">' + player_stats[i]['label'] + '</option>';
			}
			entry += '</select>\
			<select id="filter' + count + '_comparator" name="filter[comparator][]">\
				<option value="gte">Is Greater Than or Equal To</option>\
				<option value="lte">Is Less Than or Equal To</option>\
				<option value="gt">Is Greater Than (&gt;)</option>\
				<option value="lt">Is Less Than (&lt;)</option>\
			</select>\
			<input type="text" name="filter[value][]" id="filter' + count + '_value" />\
			<input type="button" name="plus" value="+" />\
			<input type="button" name="minus" value="-" />\
		</p>';
	$('adsearch-options').insert(entry);
	$$("p#filter" + count + ">input[type='button']").each(function(child) {
		if(child.name == 'plus') {
			child.observe('click', addNewFilter);
		}else{
			child.observe('click', removeFilter);
		}
	})
	count++;
}

function removeFilter(e) {
	this.parentNode.remove();
}

function showHideAdvanced(e) {
	Effect.toggle('user-advanced-search', 'slide');
}

function standardSwap(obj) {
	obj.observe('mouseover', swapButtons).observe('mouseout', swapButtons);
}

/******************************************************************************
VIDEO FORM VALIDATION CLIENT SIDE
ADDED BY: Peter B.
******************************************************************************/


var video_frm = '';

function video_validator(div)
{
	mesg = "";
	error = (false);
	if ($('AssetName').value.length < 2)
	{
		mesg = mesg + "Please enter a value for the title.\n"
		$('AssetName').focus();
		error = (true);	
	}
	
	if ($('AssetDescription').value.length < 1)
	{
		mesg = mesg + "Please enter a value for the Description.\n"
		$('AssetDescription').focus();
		error = (true);	
	}
	
	if ($('File1').value.length < 1)
	{
		mesg = mesg + "Please choose a file to upload.\n"
		$('File1').focus();
		error = (true);	
	}
	
	if(error)
	{
		alert(mesg);
		return (false);
	}else{
		$(div).innerHTML="<b>uploading...</b>";
		//video_frm = document.getElementById('av-form');
		return (true);
	}
}

function test(){
	//video_frm.action = "doAjaxSubmitClean('av-form', '/blank.php?do=video_video_process','profile-content')";
	//video_frm.submit();
}

function repopulateSelect(select, url, options) {
	options = Object.extend({
			method: 'get',
			postBody: '',
			allowAny: true,
			onRepopulate: function(event) { 
				return true;
			}
		},
		options || {}
	);
	new Ajax.Request(url, {
		evalJSON: true,
		method: options.method,
		parameters: options.postBody,
		asynchronous: false,
		onComplete : function(transport){
			if(transport.headerJSON != null) {
				obj = $A(transport.headerJSON);
			}else{
				obj = $A(eval(transport.responseText));
			}
			select = $(select);
			select.options.length = 0; /* clear old options*/
			/*var children = $A(select.options)
			children.each(function(item) {
				item.remove();
				
			});*/
			if(options.allowAny) {
				select.insert("<option label=\"Any\" value=\"\">Any</option>");
			}
			obj.each(function(i) {
				select.insert("<option label=\"" + i.value + "\" value=\"" + i.id + "\">" + i.value + "</option>");
		  	});
		  	select.selectedIndex = 0;
		  	options.onRepopulate.call(select);
		}
	});
}

Object.extend(Form.Element.Methods, {
	repopulate: function(element, url, options) {
		if($(element).tagName.toLowerCase() != 'select') {
			return true;
		}
		options = Object.extend({
				method: 'get',
				postBody: '',
				allow_any: false,
				onRepopulate: function(event) { 
					return true;
				}
			},
			options || {}
		);
		repopulateSelect(element, url, options);
		return true;
	}
});

Element.addMethods();
