var email="";
var password="";
var firstname="";
var lastname="";
var isMale=true;
var dob=new Date();
var dobYear=null;
var dobMonth=null;
var dobDate=null;
var handicap=isMale?28:36;
var handicapType="UK";
var autoHandicap=true;
var autoStrict=false;
var town="";
var registercounty="";
var registercountyName="";
var registercountry="";
var registercountryName="";
var postalCode="";

var lastCountrySearch="";
var lastCountySearch="";
var theCountrySearchField=null;
var theCountySearchField=null;



function loadDefault() {
    registercountry=document.getElementById("defaultCountry").value;
    registercountryName=document.getElementById("defaultCountryName").value;
    if (registercountryName!="") {
        document.getElementById("registercountrySearchField").value=registercountryName;
        document.getElementById("registercountrySearchField").style.backgroundImage="url(/skin/inputValid.gif)";
        document.getElementById("registercountyType").innerHTML=document.getElementById("defaultStateType").value;
        if (registercountry=="US") {
            document.getElementById("postcodeLabel").innerHTML="Zip code";
            handicapType="US";
        }else{
            if (registercountry=="GB") {
                document.getElementById("postcodeLabel").innerHTML="Postcode";
            }else{
                document.getElementById("postcodeLabel").innerHTML="Postal code";
                handicapType="US";
            }
        }
    }
    //var theInputs=["emailInput","passwordInput","firstnameInput","lastnameInput","dobdate","dobmonth","dobyear","townInput","postcodeInput","registercountySearchField"];
    //for (i=0;i<theInputs.length;i++) {
        //document.getElementById(theInputs[i]).value="";
    //}
    drawHandicapButtons();
    showHandicapInfo();
}
function showHandicapInfo() {
    var toInsert="";
    if (handicapType=="UK") {
        if (autoHandicap) {
            if (autoStrict) {
                toInsert="<b>Auto-strict UK</b><br />";
                toInsert+="Your handicap will be automatically calculated, when a round is played on an 18 hole course with a defined <span title=\"Standard Scratch Score\"><oblique>SSS</oblique></span>";
                toInsert+=" and when the round is played with a friend who has accepted the round.";
            }else{
                toInsert="<b>Automatic UK</b><br />";
                toInsert+="Your handicap will be automatically calculated, when a round is played on an 18 hole course.";
            }
        }else{
            toInsert="<b>Manual UK</b><br />";
            toInsert+="Your handicap must be defined manually when entering a new round.<br />";
            toInsert+="Insert your current handicap: <input type=\"text\" id=\"initialHandicap\" style=\"width:30px;font-size:12px;text-align:center\" value=\""+handicap+"\" />";
        }
    }else{
        if (autoHandicap) {
            if (autoStrict) {
                toInsert="<b>Auto-strict US</b><br />";
                toInsert+="Your handicap will be automatically calculated, when a round is played on an 18 hole course with a defined rating and slope";
                toInsert+=" and when the round is played with a friend who has accepted the round.";
            }else{
                toInsert="<b>Automatic US</b><br />";
                toInsert+="Your handicap will be automatically calculated, when a round is played on an 18 hole course with a defined rating and slope.";
            }
        }else{
            toInsert="<b>Manual US</b><br />";
            toInsert+="Your handicap must be defined manually when entering a new round.<br />";
            toInsert+="Insert your current handicap: <input type=\"text\" id=\"initialHandicap\" style=\"width:30px;font-size:12px;text-align:center\" value=\""+handicap+"\" />";
        }
    }
    document.getElementById("handicapDescription").innerHTML=toInsert;
}
function drawHandicapButtons() {
    if (!autoHandicap && !autoStrict) {
        document.getElementById("manualSelection").style.color="#ff5555";
        document.getElementById("manualSelection").style.cursor="default";
     }else{
        document.getElementById("manualSelection").style.color="#aaaaaa";
        document.getElementById("manualSelection").style.cursor="pointer";
     }
    if (autoHandicap && !autoStrict) {
        document.getElementById("automaticSelection").style.color="#ff5555";
        document.getElementById("automaticSelection").style.cursor="default";
     }else{
        document.getElementById("automaticSelection").style.color="#aaaaaa";
        document.getElementById("automaticSelection").style.cursor="pointer";
     }
    if (autoHandicap && autoStrict) {
        document.getElementById("strictSelection").style.color="#ff5555";
        document.getElementById("strictSelection").style.cursor="default";
     }else{
        document.getElementById("strictSelection").style.color="#aaaaaa";
        document.getElementById("strictSelection").style.cursor="pointer";
     }
    if (handicapType=="UK") {
        document.getElementById("conguSelection").style.color="#ff5555";
        document.getElementById("conguSelection").style.cursor="default";
     }else{
        document.getElementById("conguSelection").style.color="#aaaaaa";
        document.getElementById("conguSelection").style.cursor="pointer";
     }
    if (handicapType=="US") {
        document.getElementById("usgaSelection").style.color="#ff5555";
        document.getElementById("usgaSelection").style.cursor="default";
     }else{
        document.getElementById("usgaSelection").style.color="#aaaaaa";
        document.getElementById("usgaSelection").style.cursor="pointer";
     }
}
function selectHandicap(type) {
    var changed=false;
    if (type=="uk" && handicapType!="UK") {
        handicapType="UK";
        changed=true;
    }else{
        if (type=="us" && handicapType!="US") {
            handicapType="US";
            changed=true;
        }else{
            if (type=="manual") {
                if (autoHandicap) changed=true;
                autoHandicap=false;
                autoStrict=false;
            }else{
                if (type=="auto") {
                    if (!autoHandicap || autoStrict) changed=true;
                    autoHandicap=true;
                    autoStrict=false;
                }else{
                    if (!autoStrict) changed=true;
                    autoHandicap=true;
                    autoStrict=true;
                }
            }
        }
    }
    if (changed) {
        drawHandicapButtons();
        showHandicapInfo();
    }
}
function selectGender(toMale) {
    if (toMale!=isMale) {
        if (toMale) {
            document.getElementById("male").src="/skin/maleOn.gif";
            document.getElementById("male").style.cursor="default";
            document.getElementById("female").src="/skin/femaleOff.gif";
            document.getElementById("female").style.cursor="pointer";
            if (handicap>28) {
                handicap=28;
                showHandicapInfo();
            }
         }else{
            document.getElementById("female").src="/skin/femaleOn.gif";
            document.getElementById("female").style.cursor="default";
            document.getElementById("male").src="/skin/maleOff.gif";
            document.getElementById("male").style.cursor="pointer";
            if (!autoHandicap && handicap==28) {
                handicap=36;
                showHandicapInfo();
            }
        }
        isMale=toMale;
    }
}
function checkRegEmail() {
    email=document.getElementById("emailInput").value;
    var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (filter.test(email)) {
	    checkRegEmailWithDatabase(email);
	}else{
	    document.getElementById("emailInput").style.backgroundImage="url(/skin/inputRequired.gif)";
        document.getElementById("emailInput").title="Required";
	}
}

function checkRegEmailWithDatabase(emailToCheck){
    url="/checkEmail.ashx?email="+emailToCheck;
    sendRequest(url,emailRegCheckReceived);
}
function emailRegCheckReceived(reply) {
            if (reply=="ok") {
                document.getElementById("emailInput").style.backgroundImage="url(/skin/inputValid.gif)";
                document.getElementById("emailInput").title="This email address is valid";
            }else{
                document.getElementById("emailInput").style.backgroundImage="url(/skin/inputError.gif)";
                document.getElementById("emailInput").title="This email address is already registered";
            }
}
function checkPassword() {
    password=document.getElementById("passwordInput").value;
    var filter  = /^([a-zA-Z0-9])+$/;
	if (password.length>=6) {
	    if (filter.test(password)) {
            document.getElementById("passwordInput").style.backgroundImage="url(/skin/inputValid.gif)";
            document.getElementById("passwordInput").title="This password is valid";
        }else{
            document.getElementById("passwordInput").style.backgroundImage="url(/skin/inputError.gif)";
            document.getElementById("passwordInput").title="The password must be alhpanumeric";
        }
	}else{
	    document.getElementById("passwordInput").style.backgroundImage="url(/skin/inputRequired.gif)";
        document.getElementById("passwordInput").title="6 to 10 alphanumeric characters";
	}
}
function filterDOBKeys(src,e) {
    var allowAlpha=false;
    var allowKey=false;
    if (src.id=="dobmonth")  allowAlpha=true;
    if (window.event) keycode=window.event.keyCode;
    else if (e) keycode=e.which;
    if (keycode==38 || keycode==40 || keycode==13 || keycode==27 || keycode==9 || keycode==11 || keycode==16 || keycode==8 || keycode==37 || keycode==39 || keycode==46) {
        if (shortlistSrc!=null) {
            if (keycode==27) cancelShortlist();
            if (keycode==9 || keycode==11) selectShortlistOption(shortlistHighlight);
            if (keycode==38) shortlistSelect(-1);
            if (keycode==40) shortlistSelect(+1);
            if (keycode==13) selectShortlistOption(shortlistHighlight);
        }else{
            if (keycode==8 || keycode==46) {
                shortlistConstruct(src,setDOBValue,false);
                styleInputSelected(src,false);
            }
        }
        allowKey=true;
    }else{
        if (keycode>47 && keycode<58) allowKey=true;
        if (keycode>95 && keycode<106) allowKey=true;
        if (allowAlpha) {
            if (keycode>64 && keycode<91) allowKey=true;
        }
        if (!isNaN(src.value)) {
            if (src.value.substring(0,1)=="0") src.value="";
            //if (src.value.substring(0,1)=="0") src.value=src.value.substring(1,src.value.length-1);
        }
        if (allowKey) shortlistConstruct(src,setDOBValue,false);
    }
    return allowKey;
}
function dobShortlist(src,e) {
    var allowAlpha=false;
    var allowKey=false;
    if (src.id=="dobmonth")  allowAlpha=true;
    if (window.event) keycode=window.event.keyCode;
    else if (e) keycode=e.which;
    //shortlistConstruct(src,setDOBValue,false);
    if (keycode==8 || keycode==46) {
//        if (keycode==27) cancelShortlist();
//        if (keycode==9 || keycode==11) selectShortlistOption(shortlistHighlight);
//        if (keycode==38) shortlistSelect(-1);
//        if (keycode==40) shortlistSelect(+1);
//        if (keycode==13) selectShortlistOption(shortlistHighlight);
        allowKey=true;
    }else{
        if (keycode>47 && keycode<58) allowKey=true;
        if (keycode>95 && keycode<106) allowKey=true;
        if (allowAlpha) {
            if (keycode>64 && keycode<91) allowKey=true;
        }
    }
        if (allowKey) {
            dobShortlistContent(src);
            styleInputSelected(src,false);
        }
    return allowKey;
}
function dobShortlistContent(src) {
    reply="";
    toCheck=new Array();
    if (src.id=="dobmonth") {
        toCheckAlias=["January","February","March","April","May","June","July","August","September","October","November","December"];
        for (i=1;i<13;i++) {
            toCheck.push([i.toString(),toCheckAlias[i-1]]);
        }
    }
    if (src.id=="dobdate") {
        for (i=1;i<32;i++) {
            toCheck.push([i.toString(),i.toString()]);
        }
    }
    if (src.id=="dobyear") {
        for (i=1900;i<=new Date().getFullYear();i++) {
            toCheck.push([i.toString(),i.toString()]);
        }
    }
    toShort="";
    found=0;
    reg= new RegExp("^"+src.value,"i");
    if (isNaN(src.value)) {
        for (i=0;i<toCheck.length;i++) {
            if (toCheck[i][1].search(reg)>=0) {
                found++;
                if (found<10) {
                    if (toShort!="") toShort+="-optionsplit-";
                    toShort+=toCheck[i][0]+"-datasplit-"+toCheck[i][1];
                }
            }
        }
    }else{
        for (i=0;i<toCheck.length;i++) {
            if (toCheck[i][0].search(reg)>=0) {
                found++;
                if (found<10) {
                    if (toShort!="") toShort+="-optionsplit-";
                    toShort+=toCheck[i][0]+"-datasplit-"+toCheck[i][1];
                }
            }
        }
     }
     updateShortlist(toShort);
}
function setDOBValue(val) {
    if (val==null) val="";
    saveDOBValue(shortlistSrc,val);
}
function saveDOBValue(srcObj,val) {
    if (val!="") {
        styleInputSelected(srcObj,true);
    }else{
        styleInputSelected(srcObj,false);
    }
    if (srcObj.id=="dobmonth") {
        theMonths=["January","February","March","April","May","June","July","August","September","October","November","December"];
        srcObj.value=theMonths[val-1];
        dobMonth=val-1;
    }
    if (srcObj.id=="dobyear") {
        srcObj.value=val;
        dobYear=val;
    }
    if (srcObj.id=="dobdate") {
        srcObj.value=val;
        dobDate=val;
    }
    if (dobDate!=null && dobMonth!=null && dobYear!=null) {
        days=[31,28,31,30,31,30,31,31,30,31,30,31];
        if (checkleapyear(dobYear)) days[1]++;
        if (dobDate>days[dobMonth-1]) {
            dobDate=days[dobMonth-1];
            document.getElementById("dobdate").value=dobDate;
        }
        dob=new Date(dobYear,dobMonth,dobDate,0,0,0,0);
        today=new Date();
        age=0;
        while(today>dob) {
            age++;
            today.setFullYear(new Date().getFullYear()-age-1);
        }
        document.getElementById("ageComment").innerHTML="This makes you "+age;
    }else{
        document.getElementById("ageComment").innerHTML="D.o.B not set";
    }
}
function checkleapyear(dateyear)
{

	if(dateyear%4 == 0)
	{
		if(dateyear%100 != 0)
		{
			return true;
		}
		else
		{
			if(dateyear%400 == 0)
				return true;
			else
				return false;
		}
	}
return false;
}

function styleInputSelected(srcObj,selected) {
    if (selected) {
        srcObj.style.backgroundImage="url(/skin/inputValid.gif)";
    }else{
        srcObj.style.backgroundImage="url(/skin/inputRequired.gif)";
    }
}

    function alignObjectUnderTarget(obj,target,offset) {
        src=target;
	    var curleft = curtop = 0;
	    if (target.offsetParent) {
		    curleft = target.offsetLeft;
		    curtop = target.offsetTop;
		    while (target == target.offsetParent) {
		    	curleft += target.offsetLeft;
		    	curtop += target.offsetTop;
		    }
	    }
	    
        obj.style.left=(curleft)+"px";
        obj.style.top=(curtop+src.clientHeight+offset)+"px";
    }
function removeTheNode(idname) {
    if (document.getElementById(idname)!=null) {
        thisNode=document.getElementById(idname);
        //alert(thisNode.id);
        thisNode.parentNode.removeChild(thisNode);
    }
}
function validatePostcode(srcObj) {
    var regExp = /^([a-zA-Z0-9])+$/i;
    if (country=="GB") {
        regExp= /^((([A-PR-UWYZ])([0-9][0-9A-HJKS-UW]?))|(([A-PR-UWYZ][A-HK-Y])([0-9][0-9ABEHMNPRV-Y]?))\s{0,2}(([0-9])([ABD-HJLNP-UW-Z])([ABD-HJLNP-UW-Z])))|(((GI)(R))\s{0,2}((0)(A)(A)))$/i;
    }
//    if (country=="ES") {
//        regExp= /^([1-9]{2}|[0-9][1-9]|[1-9][0-9])[0-9]{3}$/i;
//    }
//    if (country=="AU") {
//        regExp= /^(((2|8|9)\d{2})|((02|08|09)\d{2})|([1-9]\d{3}))$/i;
//    }
//    if (country=="NL") {
//        regExp= /^[1-9]{1}[0-9]{3}\s?[A-Z]{2}$/i;
//    }
    if (country=="US") {
        regExp= /^(?!0{5})(\d{5})(?!-?0{4})(-?\d{4})?$/i;
    }
    if (country=="CA") {
        regExp= /^[abceghjklmnprstvxyABCEGHJKLMNPRSTVXY][0-9][abceghjklmnprstvwxyzABCEGHJKLMNPRSTVWXYZ] {0,1}[0-9][abceghjklmnprstvwxyzABCEGHJKLMNPRSTVWXYZ][0-9]$/i;
    }
    if (regExp.test(srcObj.value) && srcObj.value.length>0) {
        srcObj.style.backgroundImage="url(/skin/inputValid.gif)";
    }else{
        if (srcObj.value.length==0) {
            srcObj.style.backgroundImage="url(/skin/inputRequired.gif)";
        }else{
            srcObj.style.backgroundImage="url(/skin/inputError.gif)";
        }
    }
}
function validateOverLength(srcObj,theLength) {
    if (srcObj.value.length>=theLength) {
        srcObj.style.backgroundImage="url(/skin/inputValid.gif)";
    }else{
        srcObj.style.backgroundImage="url(/skin/inputRequired.gif)";
    }
}
//function openTheCalendar(srcObj) {
//    var today=new Date();
//    showCalendar(srcObj,"setDOB",dob.getFullYear()+"-"+dob.getMonth()+"-"+dob.getDate()+"-0-0",null,today.getFullYear()+"-"+today.getMonth()+"-"+today.getDate()+"-0-0",'D.o.B');
//}
//function setDOB(y,m,d) {
//    dob=new Date(y,m,d,0,0,0,0);
//    document.getElementById("dobText").innerHTML=dob.toDateString();
//    document.getElementById("dobText").style.backgroundImage="url(/skin/inputValid.gif)";
//}
function registerUser() {
    showWaiting();
    sendRequest("/login.ashx?validateip=1",sendRegistration);
}
function sendRegistration(code) {
    var validBackground=/inputValid/;
    checkAll=true;
    if (isdefined("FacebookUserID")) {
        checkAll=false;
        if (validBackground.test(document.getElementById("emailInput").style.backgroundImage)) checkAll=true;
        if (validBackground.test(document.getElementById("passwordInput").style.backgroundImage)) checkAll=true;
    }
    if (checkAll) {  
        var theInputs=["emailInput","passwordInput","firstnameInput","lastnameInput","dobdate","dobmonth","dobyear","townInput","postcodeInput"];
        var theInputNames=["email","password","firstname","lastname","date of birth","month of birth","year of birth","town",document.getElementById("postcodeLabel").innerHTML];
    }else{     
        var theInputs=["firstnameInput","lastnameInput","dobdate","dobmonth","dobyear","townInput","postcodeInput"];
        var theInputNames=["firstname","lastname","date of birth","month of birth","year of birth","town",document.getElementById("postcodeLabel").innerHTML];
    }
    var invalids=new Array();
    var isOk="";
    for (i=0;i<theInputs.length;i++) {
        if (!validBackground.test(document.getElementById(theInputs[i]).style.backgroundImage)) {
            invalids.push(theInputNames[i]);
        }
    }
    if (registercounty=="") invalids.push("County");
    if (registercountry=="") invalids.push("Country");
    if (invalids.length>0) {
        startFadeDown();
        removeTheNode("waitingForProfile");
        alert("Some fields are not valid!\n["+invalids.join(",")+"]");
    }else{
        
        var docUrl="/saveUser.ashx";
        var params="";
        if (checkAll) {
            params+="email="+document.getElementById("emailInput").value;
            params+="&password="+document.getElementById("passwordInput").value;
            params+="&";
        }
        params+="fn="+document.getElementById("firstnameInput").value;
        params+="&ln="+document.getElementById("lastnameInput").value;
        monthint=dob.getMonth()+1;
        params+="&dob="+dob.getFullYear()+"-"+monthint+"-"+dob.getDate();
        params+="&town="+document.getElementById("townInput").value;
        params+="&postcode="+document.getElementById("postcodeInput").value;    
        params+="&gender="+(isMale?"male":"female");
        if (!autoHandicap) handicap=document.getElementById("initialHandicap").value
        params+="&handicap="+handicap;
        params+="&auto="+(autoHandicap?(autoStrict?"strict":"auto"):"manual");
        params+="&handicapType="+handicapType;
        params+="&county="+registercounty;
        params+="&country="+registercountry;
        params+="&code="+code;
        if (isdefined("FacebookUserID")) params+="&newfbuserid="+FacebookUserID;
        sendPostRequest(docUrl,params,userSaved);
    }
}
function showWaiting() {
    startFadeUp();    
    toInsert=returnRoundedBox("waitingForProfile","Creating your profile...","<img src=\"/skin/loading.gif\" />",true,30,null,false,true);
    pasteRawHTML(toInsert,document.body);
    centerObject(document.getElementById("waitingForProfile"));
}
function userSaved(reply) {
    if (reply=="reload page") {
        gotoUrl("/index.aspx");
    }else{
        startFadeDown();
        removeTheNode("waitingForProfile");
        closeDiv("registerForm");
        alert(reply);
    }
}
function registersearchCountries(srcObj,e)
{
    var searchField=srcObj.value;
    //lastClubSearch=searchField;
    var docUrl="/shortlistCountries.ashx?q="+searchField;
    checkShortlistKeys(srcObj,e,registercountrySelect,docUrl,true);
}
function registercountrySelect(reply) {
    if (reply==null) {
        registercountry="";
        registercounty="";
        document.getElementById("registercountrySearchField").style.backgroundImage="url(/skin/inputRequired.gif)";
        document.getElementById("registercountySearchField").style.backgroundImage="url(/skin/inputRequired.gif)";
    }else{
        var data=reply.split("^");
        if (registercountry!=data[0]) {
            document.getElementById("registercountrySearchField").style.backgroundImage="url(/skin/inputValid.gif)";
            document.getElementById("registercountySearchField").style.backgroundImage="url(/skin/inputRequired.gif)";
            registercounty="";
        }
        registercountry=data[0];
        document.getElementById("registercountrySearchField").value=data[1];
        document.getElementById("registercountyType").innerHTML=data[2];
    }
}
function registersearchCounties(srcObj,e)
{
    if (registercountry!=null && registercountry!="") {
        var searchField=srcObj.value;
        //lastClubSearch=searchField;
        var docUrl="/shortlistCounties.ashx?q="+searchField+"&country="+registercountry;
        checkShortlistKeys(srcObj,e,registercountySelect,docUrl,true);
    }
}
function registercountySelect(reply) {
    if (reply==null) {
        registercounty="";
        document.getElementById("registercountySearchField").style.backgroundImage="url(/skin/inputRequired.gif)";
    }else{
        document.getElementById("registercountySearchField").style.backgroundImage="url(/skin/inputValid.gif)";
        var data=reply.split("^");
        registercounty=data[0];
        document.getElementById("registercountySearchField").value=data[1];
    }
}