/***************************************************
Javascript for HRR site
Jan 2009, Fraser Howard
****************************************************/

$(document).ready(function(){
		
		// hide otherdist div
		$("#otherdist").css("display","none");
		// hide copy/paste input for HRR results extraction
		//$("#cp_block").css("display","none");
		$("#cp_block").hide();

		stripetables();

		// autocomplete for input forms
		$("#yname").autocomplete("../inc/namehint.php");
		$("#yemail").autocomplete("../inc/emailhint.php");
		$("#etitle").autocomplete("../inc/racehint.php");
		
// end doc ready loop
});

function check4other() {

	var d = document.result_mod.distance.value
	
 	if (d == "Other") {
 		// show div tag
      $("#otherdist").css("display","block");
 	}
	else {
		// hide div tag
      $("#otherdist").css("display","none");
 	}
return;
}

function validateFormOnSubmit(theForm) {
  
  var reason = "";

  // check text fields are completed
  reason += validateEmpty(theForm.yourname);
  reason += validateEmpty(theForm.postingpassword);
  reason += validateEmpty(theForm.title);
  reason += validateEmpty(theForm.date);

  if (theForm.distance.value == "Other") {
   theForm.distance.style.background = 'White';
   reason += validateEmpty(theForm.otherdistance);
   reason += validateText(theForm.otherdistance);
  }
  else {
   reason += validateEmpty(theForm.distance);
  }
  reason += validateEmpty(theForm.type);
  reason += validateEmpty(theForm.results);

  // valid text?
  // removing validateTest on results to allow HTML
  // reason += validateText(theForm.results);
  reason += validateText(theForm.title);
  reason += validateText(theForm.youremail);
  reason += validateText(theForm.yourname);
  
  if (reason != "") {
    alert("Some fields need correction:\n" + reason);
    return false;
  }
    
  return true;
}
function validateEmpty(fld) {
    var error = "";
    
    if (fld.value.length == 0) {
        fld.style.background = 'Yellow'; 
        error = "The required field has not been filled in.\n"
    } else {
        fld.style.background = 'White';
    }
    return error;  
}

function validateURL(fld) {
    var error = "";
    var url = fld.value;
	
    if (fld.value.length == 0) {
		fld.style.background = 'Yellow'; 
		error = "Please submit the URL for the race results!\n";
	}
	else {
		if(url.match(/^https?:\/\/[a-z0-9-\.]+\.[a-z]{2,4}\/?([^\s<>\#"\,\{\}\\|\\\^\[\]`]+)?$/i)) {
			fld.style.background = 'White';
		}
		else {
			fld.style.background = 'Yellow'; 
			error = "Please submit a valid, complete URL (http://...)\n";
		}
	}
	
	return error;  
}

function validateNumb(fld,min,max) {
    var error = "";
    if (isNaN(fld.value)) {
	     fld.style.background = 'Yellow';
    	  error = "The required field is incomplete.\n";
    }
    else {
    		if ( (fld.value >= min ) && (fld.value <= max) ){
        		fld.style.background = 'White';
        	}
        	else {
        		fld.style.background = 'Yellow';
    	  		error = "The required field is out of range (" + min + " - " + max + ").\n";	
        	}    
    }

    return error;  
}

function validateText(fld) {
	var error = "";
	if (fld.value.length > 0 ) {
		if (fld.value.indexOf("<") != -1) {
			fld.style.background = 'Yellow';
    		error = "The required field is invalid.\n";
		}
		else {
			fld.style.background = 'White';
		}
	}
	
	return error;
}

function getresults(u_fld, r_fld) {

	// is results URL field populated?
	str = validateURL(u_fld);
	if(str != "") {
		alert("Error: " + str);
		return(false);
	}
	url = encodeURIComponent(u_fld.value);
	jsonurl = "http://www.hrr.org.uk/results/rbug.php?url=" + url + "&callback=?";
	success_status = new String("HRR results successfully extracted - please update as usual with PBs, records etc.");
	fail_status = new String("Failed to extract any HRR results. Try copying/pasting complete results listing into the box below, and then clicking 'Extract HRR results'.");

	// disable fetch button?
	// id="btn_resultsbug"
	
	//clear existing status and results content
	$("#getres_status").text(status);
	$("#paste_res").val("");
	//r_fld.value = "";
	$("#hrr_results").val("");
	
    $.jsonp({
        "url": jsonurl,
        "data": {
                "alt": "jsonp-res-dump"
        },
        "success": function(data) {
				res = data.results;
				$("#hrr_results").val(res);
				$("#getres_status").text("" + success_status + "");
				$("#cp_block").hide();
            },
            "error": function() {
				$("#getres_status").text("" + fail_status + "");
				$("#cp_block").show();
        }
    });
	
return;
}

function parseHRR(fld) {
	// called via parseHRR( document.getElementById(\'paste_res\') )

	jsonurl = "http://www.hrr.org.uk/results/rbug.php";
	success_status = new String("Done - extracted HRR results.");
	
	// replace line feeds with pipe
	paste = fld.value.replace(/(\r\n|[\r\n])/g, "|");
	
	recvd_flag=0;
	// blank current status messaeg
	$("#getres_status").text("");
	
	$.post( jsonurl, { res: paste},
		function(data) {
			res = data.results2;
			if(res.length > 0) {
				recvd_flag=1;
				$("#hrr_results").val(res);
				$("#getres_status").text("" + success_status + "");
				$("#cp_block").hide();
			}
		},
		'json'
	);

// after 5 sec delay - assume error
var delay = function() { doparseErr(recvd_flag); };
setTimeout(delay, 4000);

return;
}

function doparseErr(flg) {

if(flg==0) {
	fail_status ="Failed to extract any HRR results - over to you.";
	
	$("#getres_status").text("" + fail_status + "");
	$("#cp_block").hide();
}

return;
}

function old_getresults(u_fld, r_fld) {

	// is results URL field populated?
	str = validateURL(u_fld);
	if(str != "") {
		alert("Error: " + str);
		return(false);
	}
	url = encodeURIComponent(u_fld.value);
	jsonurl = "http://www.hrr.org.uk/results/rbug.php?url=" + url + "&callback=?";

	// disable fetch button?
	// id="btn_resultsbug"
	
	//clear existing status and results content
	$("#getres_status").text("");
	$("#paste_res").val("");
	r_fld.value = "";
	
    $.jsonp({
        "url": jsonurl,
        "data": {
                "alt": "jsonp-res-dump"
        },
        "success": function(data) {
				res = data.results;
				r_fld.value = res;
				status = "HRR results successfully extracted - please update as usual with PBs, records etc.";
				$("#getres_status").text(status);
            },
            "error": function() {
				status = "Failed to extract any HRR results. Try copying/pasting complete results listing into the box below, and then clicking 'Extract HRR results'.";
				$("#getres_status").text(status);
				$("#cp_block").css("display","block");
        }
    });

return;
}
