$("#year").one("focus", function(){ $("#year :first-child").remove();});
$("#month").one("focus", function(){ $("#month :first-child").remove();});
$("#day").one("focus", function(){ $("#day :first-child").remove();});
$("#gender").one("focus", function(){ $("#gender :first-child").remove();});
$("#countrycode").one("focus", function(){ $("#countrycode :first-child").remove();});


var sectionMap = {
    'WT': { "wt-fields": 1, "wtbd-fields": 1, "ip-fields": 0},
    'BD': { "wt-fields": 0, "wtbd-fields": 1, "ip-fields": 0},
    'NETeller': { "wt-fields": 0, "wtbd-fields": 0, "ip-fields": 1},
    'MB': { "wt-fields": 0, "wtbd-fields": 0, "ip-fields": 1}
}

function showPmtSection(section)
{
    var cfg = sectionMap[section];
    jQuery.each(cfg, function(s, v)
                {
                    if (v == 1)
                        $('#' + s).show();
                    else
                        $('#' + s).hide();
                }
        );

        if(section == "MB"){
                  $("#txtcomments").text(js_t.get("Please input money bookers account name"));
              }else{
                   $("#txtcomments").text("");
              }


    /* attempts to fill in data previously gived
     $("#bname").val( ($("#bname").val()) ? ($("#firstname").val() + " " + $("#lastname").val())  : ($("#bname").val()));*/
}

$('input[type="radio"]').click(function () {
                                   showPmtSection($(':radio:checked').val());
                               });

showPmtSection('WT');

var imCount=1;
var websiteCount=1;

function addIm()
{
    imCount++;
    $('<div class="row"><div>' + js_t.get("Instant messenger") + '<select name="imaccounts[' + imCount + '][imtype]" id="imaccounts[' + imCount + '][type]" style="margin-left:99px"><option value="">' + js_t.get("Instant messenger") + '</option><option value="MSN">MSN</option><option value="AIM">AIM</option><option value="ICQ">ICQ</option><option value="Skype">Skype</option><option value="Yahoo">Yahoo</option></select></div><div>IM Account <input type="text" id="imaccounts[' + imCount + '][account]" name="imaccounts[' + imCount + '][account]" /></div></div>').insertBefore("#addIm");
}

function addWebsite(){
    websiteCount++;
    $('<div class="row"><div> ' + js_t.get("URL of the website") + ' <input type="text" id="websites[' + websiteCount + '][website]" name="websites[' + websiteCount + '][website]" /></div><div>' + js_t.get("Website type") + '<select name="websites[' + websiteCount + '][websitetype]" id="websites[' + websiteCount + '][websitetype]" style="margin-left:99px"><option value="Other">' + js_t.get("Other") + '</option><option value="Adult Entertainment">' + js_t.get("Adult Entertainment") + '</option><option value="Casino Portal">' + js_t.get("Casino Portal") + '</option><option value="Female Interest">' + js_t.get("Female Interest") +'</option><option value="Financial Services">' + js_t.get("Financial Services")+ '</option><option value="Message Boards/Chat Rooms">' + js_t.get("Message Boards/Chat Rooms") + '</option><option value="Non-Casino Betting">' + js_t.get("Non-Casino Betting") + '</option><option value="Online Games">' + js_t.get("Online Games") + '</option><option value="Personal">' + js_t.get("Personal") + '</option><option value="Referral Site">' + js_t.get("Referral Site") +'</option><option value="Shopping/Auction/Coupons">' + js_t.get("Shopping/Auction/Coupons") + '</option><option value="Small Business">' + js_t.get("Small Business") + '</option><option value="Sports">' + js_t.get("Sports") + '</option><option value="Sports Betting">' + js_t.get("Sports Betting") + '</option><option value="Website Services">' + js_t.get("Website Services") + '</option></select></div></div>').insertBefore("#addWebsite");
}


function signup(url){

    $("p.error").remove();
    $(".error").removeClass("error");
    var hasErrors = false;


    //trim fileds
    $("#signupForm > :input").each(function(){ $(this).val(($.trim($(this).val())))});

    if(!($("#agree").attr('checked'))){
	$('<p class="error">^' + js_t.get("Please approve you have read and agreed to the terms and conditions") + '</p>').insertAfter($("#agreeText"));
	hasErrors = true;
    };

    // marking empty fileds
    $("#firstname,#lastname,#username,#password1,#password2,#city,#zip,#phone,#email,#company,#occupation,#city,#zip,#countrycode,#address").each(function(){
			                                                                                                                              if(!($(this).val())){
				                                                                                                                          $(this).addClass("error");
				                                                                                                                          $('<p class="error">^ ' + js_t.get("Required Field") + ' </p>').insertAfter($(this));
				                                                                                                                          hasErrors = true;
			                                                                                                                              }
		                                                                                                                                  });

    //checking id passwords match
    if(($("#password1").val() && $("#password2").val()) && ($("#password1").val() != $("#password2").val())){
	$('<p class="error">^ ' + js_t.get(" Passwords do not match") + '</p>').insertAfter($("#password2,#password1"));
	hasErrors = true;
    }

    //validate e-mail address
    if($("#email").val() && !(isValidEmail($("#email").val()))){
	$('<p class="error">^' + js_t.get("Not a valid email address") + '</p>').insertAfter($("#email"));
	hasErrors = true;
    }

    //validate phone number
    if($("#phone").val() && !(isValidPhone($("#phone").val()))){
	$('<p class="error">^ ' + js_t.get("Phone number not valid") + '</p>').insertAfter($("#phone"));
	hasErrors = true;
    }

    //validate mobile number
    if($("#mobile").val() && (($("#mobile").val()).length > 20)){
	$('<p class="error">^ ' + js_t.get("Mobile phone number can not be more than 20 numbers") + '</p>').insertAfter($("#phone"));
	hasErrors = true;
    }

    if(!hasErrors){

	// loading overlay effect
	$("#loadingOverlay").expose({closeOnEsc : false, closeOnClick : false,  api: true, onLoad : function() { this.getExposed().css({'display' : 'block'}); }, onClose : function() { this.getExposed().css({'display' : 'none'}); }}).load();

	$.ajax({ "url" : url, type : "post",  "data" : $("#signupForm").serialize(), "error" : function(data,textStatus){

		     // closing overlay effect
		     $("#loadingOverlay").expose().close();

		     $('<p>' + js_t.get("There seems to have been an internal error, please try again. If the error persist please contact <a href=\"mailto:support@affeurope.com\">support@affeurope.com</a>") +'</p>').dialog({ "resizable" : false, buttons: { "Ok": function() { $(this).dialog("close"); }}});
		 },success : function(data){

		     // closing overlay effect
		     $("#loadingOverlay").expose().close();

		     if(data.errors){
			 displayErrors(data.errors);
		     }else{
			 $('<p>' + data.msg +'</p>').dialog({"title" : js_t.get("AffEurope Sign up"), "resizable" : false, buttons: { "Ok": function()
                                                                                                                                      {
                                                                                                                                          if (data.url !== undefined)
						                                                                                              location.href = '' + data.url + '';
                                                                                                                                          else
                                                                                                                                              $(this).dialog("close");
						                                                                                      }
					                                                                                            }});
		     }
		 }
		 ,"dataType" : "json"});
    }
}

//function for regex email validation (also accepts gmail's handy + signs)
//had to supress dwoo for the regex

function isValidEmail(email){
    var emailRegEx = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if(email.match(emailRegEx)){
	return true;
    }
    else{
	return false;
    }
}

//Check if phone number is valid
function isValidPhone(phone){
    phoneRegEx = /^[\w\d\.\+\(\)-]{4,20}$/
	if(phone.match(phoneRegEx)){
	    return true;
	}
    else{
	return false;
    }
}

function escapeField(str) {
    return str.replace(/([\[\]])/g, "\\$1");
}

/* Attach error messages to fields */

function displayErrors(errors){
    $.each(errors,function(field,msg){
               if (msg == null) return;
               escselector = "#signupForm *[name='" + escapeField(field) + "']"; // because some form elements are foo[bar]
	       $('<p class="error">^' + msg +'</p>').insertAfter($(escselector));
	   })
}


