﻿$(document).ready(function() {
    
    jQuery.validator.messages.required = "*";
    jQuery.validator.messages.email = "*";
    jQuery.validator.messages.equalTo = "*";
    jQuery.validator.messages.zipUSCA = "*";
    
    $('#form1').bind("invalid-form.validate", function(e, validator) {
		var errors = validator.numberOfInvalids();
		if (errors) {
		    var message = 'Please verify the fields below.';
		    
		    if(errors == 1) {
		        if($("#terms:checked").val() != 'on') {
		            message = 'You have not accepted the YouRepresent terms and conditions.';
		        }
		    }
			
			$("div.error span").html(message);
			$("div.error").show();
		} else {
			$("div.error").hide();
		}
	}).validate({
        rules: {
		    confirm_email: {
			    required:true,
				equalTo: "#email"
			}
		},
		submitHandler: function() {
		   
		   $("div.error").hide();
		   
		   var d = '{"method":"form1"';
           var inputs = [];

           $(':input', $("#form1")).each(function() {
                inputs.push(this.name + '=' + escape(this.value));
                $('#' + this.name + '-label').text(this.value);
                d += ',"' + this.name + '":"' + escape(this.value) + '"';                
           });
           
           d += "}";
           
           jQuery.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                data: d,
                url: '../ScriptServices/Members.asmx/register',
                timeout: 15000,
                dataType: "json",
                error: function(xml) {
                    alert(xml);
                },
                success: function(r) { 
                      val = r.d;
                      if(val.Successful == true) {
                        $("#form2,#memberID").val(val.Data);
                        show_step(2,4);     
                      }
                      else {
                        $("div.error span").html(val.Data.Message);
			            $("div.error").show();
                      }
                }
            })
		}		
    });
    
    $('#form2').validate({
        submitHandler: function() {
        
        
		   $("div.error").hide();
		   
            var d = '{"method":"form2"';
            var inputs = [];
            var genderSet = false;
            var unionSet = false;
            
            var memberID = $('#memberID').val();
            var gender = $("input[@name='gender']:checked").val();
            var union = $("input[@name='union']:checked").val();
            var height_ft = $('#height_ft').val();
            var height_in = $('#height_in').val();
            var weight = $('#weight').val();
            var describe1 = $('#describe1').val();
            var describe2 = $('#describe2').val();
            var describe3 = $('#describe3').val();
            var describe4 = $('#describe4').val();
            var eye_color = $('#eye_color').val();
            var hair_color = $('#hair_color').val();
            var hair_length = $('#hair_length').val();
            var ethnicity = $('#ethnicity').val();
            var union_name = $('#union_name').val();
            var result = "";
            $(".intrestGroup").each( function () {
                if($(this).attr('checked')) {
                    result = result + $(this).val() + ", ";
                }
            });
            var interests = escape(result);
            
            var arguments = {memberID:memberID,gender:gender,interests:interests,height_ft:height_ft,height_in:height_in,weight:weight,describe1:describe1,describe2:describe2,describe3:describe3,describe4:describe4,eye_color:eye_color,hair_color:hair_color,hair_length:hair_length,ethnicity:ethnicity,union:union,union_name:union_name};
            var d = JSON.stringify(arguments);
            
            if(validateStep2(arguments)) {
                jQuery.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    data: d,
                    url: '/ScriptServices/Members.asmx/createProfile',
                    timeout: 15000,
                    dataType: "json",
                    error: function(xml) {
                        alert(xml);
                    },
                    success: function(r) { 
                        val = r.d;
                        if(val.Successful == true) {
                            show_step(3,4);     
                        }
                        else {
                            $("#form2error span").html(val.Data.Message);
			                $("#form2error").show();
                        }
                    }
                });
           }
           else {
                $("#form2error span").html('Please fill in all the questions below.');
                $("#form2error").show(); 
           }
        }
    });
    
    $('#form3').validate({
        submitHandler: function() {
                    
            var profileID = $('#memberID').val();
            var known = $('#known').val();
            var live_1 = $('#live_1').val();
            var live_2 = $('#live_2').val();
            var live_3 = $('#live_3').val();
            
            var created = create_profile_object(profileID, known, live_1, live_2, live_3);
        
        }
    });
    
    try {
        $('#birthdateMonth').autotab({ target: 'birthdateDay', format: 'numeric' });
        $('#birthdateDay').autotab({ target: 'birthdateYear', format: 'numeric', previous: 'birthdateMonth' });
        $('#birthdateYear').autotab({ previous: 'birthdateDay', format: 'numeric' });
    } catch(e) {
    }
    
    $("#describe1").jSuggest({
       url: "/ScriptServices/Handlers/TagList.ashx",
       type: "GET",
       loadingImg: "/images/ajax-loader.gif",
       data: "searchQuery" ,
       delay: 200,
       autoChange: true
     });

     $("#describe2").jSuggest({
       url: "/ScriptServices/Handlers/TagList.ashx",
       type: "GET",
       loadingImg: "/images/ajax-loader.gif",
       data: "searchQuery" ,
       delay: 200,
       autoChange: true
     });
     
     $("#describe3").jSuggest({
       url: "/ScriptServices/Handlers/TagList.ashx",
       type: "GET",
       loadingImg: "/images/ajax-loader.gif",
       data: "searchQuery" ,
       delay: 200,
       autoChange: true
     });
     
     $("#describe4").jSuggest({
       url: "/ScriptServices/Handlers/TagList.ashx",
       type: "GET",
       loadingImg: "/images/ajax-loader.gif",
       data: "searchQuery" ,
       delay: 200,
       autoChange: true
     });
     
        // JScript File
    jQuery.validator.messages.required = "*";

    jQuery.validator.addMethod("zip", function(value, element) { 
        return this.optional(element) || value.match(/^((\d{5}-\d{4})|(\d{5})|([a-z]\d[a-z]\s?\d[a-z]\d))$/i); 
    }, "*"); 

    jQuery.validator.addMethod("phone", function(value, element) { 
        return this.optional(element) || value.match(/^\d{3}-\d{3}-\d{4}$/); 
    }, "*");


    $('#step3Cancel').click(function()
    {
        window.location.href = '/profile.aspx';
    });
    
});

function validateStep2(obj)
{
    var isValid = true;
    
    if(obj.height_ft == '' || obj.height_ft == 'undefined') {
        isValid = false;
    }
    
    if(obj.height_in == '' || obj.height_in == 'undefined') {
        isValid = false;
    }
    
    if(obj.weight == '' || obj.weight == 'undefined') {
        isValid = false;
    }
    
    if(obj.describe1 == '' || obj.describe1 == 'undefined') {
        isValid = false;
    }
    
    if(obj.describe2 == '' || obj.describe2 == 'undefined') {
        isValid = false;
    }
    
    if(obj.describe3 == '' || obj.describe3 == 'undefined') {
        isValid = false;
    }
    
    if(obj.describe4 == '' || obj.describe4 == 'undefined') {
        isValid = false;
    }
    
    if(obj.eye_color == '' || obj.eye_color == 'undefined') {
        isValid = false;
    }
    
    if(obj.hair_color == '' || obj.hair_color == 'undefined') {
        isValid = false;
    }
    
    if(obj.hair_length == '' || obj.hair_length == 'undefined') {
        isValid = false;
    }
    
    if(obj.ethnicity == '' || obj.ethnicity == 'undefined') {
        isValid = false;
    }
    
    return isValid;
}

function create_profile_object(profileID, known, live_1, live_2, live_3)
{
    var arguments = {profileID:profileID,known:known,live_1:live_1,live_2:live_2,live_3:live_3};
    var jason_str = JSON.stringify(arguments);
    $.ajax({
        type: "POST",
        url: '../ScriptServices/Members.asmx/createProfileQuestions',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: jason_str,
        success: function(r) {
            val = r.d;
            if(val.Successful == true) {
                window.location.href="/Profile.aspx";     
            }
            else {
                $("#step3.error span").html(val.Data.Message);
			    $("#step3.error").show();
            }
        },
        error: function(xhr) {
            alert(xhr.responseText);
        }
    });
}

//shows the current_step span and hides the rest of the steps
//current_step is the integer number for the step to be shown
//length is the integer number for the maximum number of steps
function show_step(current_step, length)
{
    var step_id;
    for(var i=1;i<=length;i++)
    {
        step_id = "#step" + i;
        $(step_id).css("display", "none");
    }
    step_id = "#step" + current_step;
    $(step_id).css("display", "block");
}