var oSelectList = new SelectList( );
var sThoroTrackBaseUrl = location.href.substring(0, location.href.lastIndexOf('.php')+4)

var nav = window.Event ? true : false;
if (nav) {
   window.captureEvents(Event.KEYDOWN);
   window.onkeydown = NetscapeEventHandler_KeyDown;
} else {
   document.onkeydown = MicrosoftEventHandler_KeyDown;
}

function NetscapeEventHandler_KeyDown(e) {
  if (e.which == 13 && e.target.type != 'textarea' && e.target.type != 'submit') { return false; }
  return true;
}

function MicrosoftEventHandler_KeyDown() {
  if (event.keyCode == 13 && event.srcElement.type != 'textarea' && event.srcElement.type != 'submit')
    return false;
  return true;
}

function searchHorse(sBaseUrl) {
	var str = document.getElementById('txtSearch').value;
	var test_str = str.replace(/%/gi,''); test_str = test_str.replace(/\*/gi,'');
	if ( test_str.length < 3 ) {
		alert('Search string must contain at least 3 characters');
		return(false);
	}
	str = escape(str);
	var sUrl = sBaseUrl+'?step=search&horse='+str;
	
	if ( document.getElementById( 'wrpAjaxLoading' ) )
		document.getElementById( 'wrpAjaxLoading' ).innerHTML = '<img id="ajax" name="ajax" src="/images/ajax.gif" width="10" height="10"  hspace="10" border="0">';
	
	makeRequestThreaded(sUrl,'populate_available_horses');
}

function login_LEGACY(sBaseUrl) {
	sThoroTrackBaseUrl = sBaseUrl;
	var login	= document.frmMain.vcLogin.value;
	var pwd	= document.frmMain.vcPassword.value;
//	var login	= escape(document.getElementById('vcLogin').value);
//	var pwd		= escape(document.getElementById('vcPassword').value);
	
	if ( login != "" && pwd != "" ) { 
		var sUrl	= sBaseUrl+'?step=execute_login&vcLogin='+login+'&vcPassword='+pwd;
		if ( document.getElementById( 'wrpAjaxLoginLoading' ) )
			document.getElementById( 'wrpAjaxLoginLoading' ).innerHTML = '<img id="ajax" name="ajax" src="/images/ajax.gif" width="10" height="10"  hspace="10" border="0">';
		makeRequestThreaded(sUrl,'login_results');
	} else {
		alert('Please provide a username and password');
		return(false);
	}
}

function populate_user_horses(rawdata) {
	//var rawdata = handleRequest();
	if ( rawdata != undefined ) {
		if ( rawdata == "" ) return;
		//oSelectList.setEmpty( 'selectAvailableHorses' );
		oSelectList.setOptions( 'selectChosenHorses', oSelectList.rawdataToArray( rawdata ), 'selectChosenHorses', true );
		
		populate_email_info();
	}
}

function execAfterLogin() {
	//alert('execAfterLogin()');
	enable_submit();
}
function execAfterLogout() {
	//alert('execAfterLogout()');
	disable_submit();
}

function populate_email_info() {
	var sUrl	= sThoroTrackBaseUrl+'?step=get_email_info';
	makeRequestThreaded(sUrl,'populate_email_info_results');
}

function populate_email_info_results(rawdata) {
	//var rawdata = handleRequest();
	if ( rawdata != undefined ) {
		if ( document.getElementById( 'wrpAjaxEmailInfo' ) )
			document.getElementById( 'wrpAjaxEmailInfo' ).innerHTML = rawdata;
	}
}

function enable_submit() {
	var path = '/secure/thorotrack.php';
	if ( document.getElementById( 'wrpAjaxAction' ) ) {
		var strHTML = '';
		strHTML +=	'<table border="0" cellspacing="0" cellpadding="0">';
		strHTML +=	'<tr>';
		strHTML +=	'	<td><input type="button" name="submit" value="Update Thoro-Mail Settings" onClick="javascript:storeHorses(\''+iGlobalCustomerID+'\',\''+path+'\');"></td>';
		strHTML +=	'	<td><div id="wrpAjaxActionLoading" style="visibility:show;"><img id="ajax" name="ajax" src="/images/space.gif" width="10" height="10" hspace="10" border="0"></div></td>';
		strHTML +=	'</tr></table>';
		document.getElementById( 'wrpAjaxAction' ).innerHTML = strHTML;
		
		var sUrl	= sThoroTrackBaseUrl+'?step=execute_get_horse_list&cid='+iGlobalCustomerID;
		makeRequestThreaded(sUrl,'populate_user_horses');
		//document.getElementById( 'wrpAjaxAction' ).innerHTML = '<input type="button" name="submit" value="Update Thoro-Mail Settings" onClick="javascript:storeHorses(\''+result+'\',\''+path+'\');">';
	}
}

function disable_submit() {
	document.getElementById( 'wrpAjaxAction' ).innerHTML = '<fieldset><legend>Please login</legend>Please login above to save your horses list.</fieldset>';
	if ( document.getElementById( 'wrpAjaxEmailInfo' ) )
		document.getElementById( 'wrpAjaxEmailInfo' ).innerHTML = '';

}

function storeResults(rawdata) {
	//var rawdata = handleRequest();
	if ( rawdata != undefined ) {
		if ( rawdata == "" ) { 
			return(false);
		} else {
			//alert(rawdata);
			var array1 = rawdata.split("\|\|\|");
			var result	= array1[0];
			var msg		= array1[1];
			alert(msg);
		}
		if ( document.getElementById( 'wrpAjaxActionLoading' ) )
			document.getElementById( 'wrpAjaxActionLoading' ).innerHTML = '<img id="ajax" name="ajax" src="/images/space.gif" width="10" height="10" hspace="10" border="0">';
	}
}

function populate_available_horses(rawdata) {
	//var rawdata = handleRequest();
	if ( rawdata != undefined ) {
		if ( rawdata == "" ) { rawdata = "||No matches found, retry\n"; }
		oSelectList.setEmpty( 'selectAvailableHorses' );
		oSelectList.setOptions( 'selectAvailableHorses', oSelectList.rawdataToArray( rawdata ), 'selectChosenHorses' );
		
		if ( document.getElementById( 'wrpAjaxLoading' ) )
			document.getElementById( 'wrpAjaxLoading' ).innerHTML = '<img id="ajax" name="ajax" src="/images/space.gif" width="10" height="10" hspace="10" border="0">';
	}
}

function opt(the_obj, the_var, the_val, the_color) {
	var bDoAdd = true;
    for (var i = 0;i < the_obj.length;i++) {
		if (the_obj.options[i].value == the_val) {
			bDoAdd = false;
			the_obj.options[i].style.background = the_color;
		}
	}
	if (bDoAdd) {
	    var optionName = new Option(the_val, the_var, false, false)
		var length = the_obj.length;
		the_obj.options[length] = optionName;
		if ( (the_color != null) && (the_color != '') ) {
			the_obj.options[length].style.background = the_color;
		}
	}
}
function transferOption(the_type) {
	var bDoTransferBack = 1;
	if (the_type == "ADD") {
		var dropdownlist_FROM	= document.getElementById('selectAvailableHorses');
		var dropdownlist_TO		= document.getElementById('selectChosenHorses');
		
		// ensure not already in the list
		if (dropdownlist_FROM.selectedIndex >= 0) {
			var the_selected_track_race	= dropdownlist_FROM[dropdownlist_FROM.selectedIndex].value;
			if ( is_select_list_item(dropdownlist_TO, the_selected_track_race) ) {
				bDoTransferBack = 0;
			}
		}
	} else {
		var dropdownlist_FROM	= document.getElementById('selectChosenHorses');
		var dropdownlist_TO		= document.getElementById('selectAvailableHorses');
		
		if ( dropdownlist_FROM.selectedIndex < 0 ) { return; }
		bDoTransferBack = 1;
	}
    var index = dropdownlist_FROM.selectedIndex;
    if (index > -1) {
		var the_color = dropdownlist_FROM.options[index].style.background;
        var newoption = new Option(dropdownlist_FROM.options[index].text, dropdownlist_FROM.options[index].value, true, true);
		newoption.style.background = the_color;
        if (bDoTransferBack > 0) {
			if ( dropdownlist_FROM.options[index].value != "" ) {
				dropdownlist_TO.options[dropdownlist_TO.length] = newoption;
				dropdownlist_FROM.options[index] = null;
			}
		}
        //if (!document.getElementById) history.go(0);
    }
//	sort_select_list(dropdownlist_TO);
//	document.frmMain.btn_submit.disabled = false;
//	document.frmMain.btn_submit.style.background = '#5a928b';
}

function sort_select_list(selObj) {
	var opts = document.getElementById('option');
	var listVals = new Array();
	
	for(var i = 0; i < opts.length; i++) 
		listVals.push(opts.item(i).value+"~"+opts.item(i).text+"~"+opts.item(i).selected+"~"+opts.item(i).style.background);
	listVals.sort();
	
	for(var i = 0; i < listVals.length; i++) {
		selObj.options[i].value = String(listVals[i]).split("~")[0];
		selObj.options[i].text = String(listVals[i]).split("~")[1];
		selObj.options[i].selected = (String(listVals[i]).split("~")[2]=="true"?1:0);
		selObj.options[i].style.background = String(listVals[i]).split("~")[3];
	}
}


function is_select_list_item(theObj, search_val) {
	var the_val;
    for (var i = theObj.length-1;i >= 0;i--) {
        the_val = theObj.options[i].value;
		//alert(search_val+' => '+the_val);
		if (search_val == the_val) return(1);
	}
	return(0);
}

function storeHorses(intCustID, sBaseUrl) {
	var theObj	= document.getElementById('selectChosenHorses');
	var theIDs = '';
    for (var i = theObj.length-1;i >= 0;i--) {
		if ( i < (theObj.length-1) ) theIDs += ',';
        theIDs += theObj.options[i].value;
	}
	var sUrl = sBaseUrl+'?step=execute_update&cid='+intCustID+'&ids='+theIDs;
	if ( document.getElementById( 'wrpAjaxActionLoading' ) )
		document.getElementById( 'wrpAjaxActionLoading' ).innerHTML = '<img id="ajax" name="ajax" src="/images/ajax.gif" width="10" height="10"  hspace="10" border="0">';
	
	makeRequestThreaded(sUrl,'storeResults');
}

var undefined;
function isUndefined(property) {
  return (typeof property == 'undefined');
}

