﻿jQuery(function($) {


    if ($("textarea").attr('title') != undefined) {
        $('textarea[title!=""]').hint();
    }

    if ($.jqURL.get('mentor') != undefined) {
        checkUserExists($.jqURL.get('mentor'));
    }


    //submit hm mentor name for checking
    $("#submithmmentor").click(function() {

        if ($('#nominatorusername').val() == "") {

            $("#overlay").css({ display: "block", zIndex: "1" });
            $("#popoutcontainerhm").css({ zIndex: "10", display: "block" });
            $("#entryform").css({ zIndex: "10", display: "block" });
	     return false;
        }
        else {
            if ($("#hmmentorname").val() != "") {
                checkUserExists($("#hmmentorname").val());
                return false;
            }
            else {
                alert("Please enter a mentor name");
                return false;
            }
        };
    });

//    $("#Hmmentor").submit(function() {
//        if ($("#hmmentorname").val() != "") {
//            checkUserExists($("#hmmentorname").val());
//            return false;
//        }
//        else {
//            alert("Please enter a mentor name");
//            return false;
//        }
//    });

    //self nomination check

    $("#nominateself").click(function() {
        var nominator = $("#nominatorusername").val();
        $("#hmmentorname").val(nominator);
        $("#selfnomination").val('1');
        $("#lblnominationdesc").text('Why should this mentor win the Yell Small Business Mentor of the Year Award?');
	$("textarea").attr('title','Briefly describe the support this mentor has given on horsesmouth and why you think it\'s made a difference. It could be for providing an ongoing sounding board; offering timely support and encouragement or simply signposting useful resources. In a few words (up to 300) tell us why you think this mentor should be recognised in the Yell Awards.');
	$('textarea[title!=""]').hint();

    });

    //clear nominate input
    $("#nominateother").click(function() {
        $("#hmmentorname").val('').focus();
        $("#selfnomination").val('0');
        $("#lblnominationdesc").text('Why should this mentor win the Yell Small Business Mentor of the Year Award?');

    });


    //submit non-hm mentor
    $("#submitnonmentor").click(function() {
        if ($("#nonhmmentorname1").val() == "") {
            alert("Please enter a mentor name");
            return false;
        }
        else {
            displayNonHmEntryform();
            return false;
        }
    });

    $("#nonHMmentor").submit(function() {
        if ($("#nonhmmentorname1").val() == "") {
            alert("Please enter a mentor name");
            return false;
        }
        else {
            displayNonHmEntryform();
            return false;
        }
    });


    // close form action
    $("#closehmfrm").click(function() {

        if ($.jqURL.get('mentor') != "" && $("#confirmedmessage").css("display") == "block") {
            //location.href = "default.publisha";
            location.reload();
            return false;
        }


        if ($("#confirmedmessage").css("display") != "block" && $("#loginmessage").text() == "") {
            if (confirm("Wait! You haven’t finished your entry yet.\nClick Cancel to complete the form or \nclick OK to discard your entries and start again later. ")) {
                return true;
            }
            else {
                return false;
            }
        }
        return true;
    });

    $("#closenonhmfrm").click(function() {
        if ($("#confirmedmessage").css("display") != "block") {
            if (confirm("Wait! You haven’t finished your entry yet.\nClick Cancel to complete the form or \nclick OK to discard your entries and start again later. ")) {
                return true;
            }
            else {
                return false;
            }
        }
        return true;
    });


    //non hm mentor goto stage 2 of form
    $("#nextstage").click(function() {

        showhidefrmstage(this.id);
        return false;

    });

    //non hm mentor back to stage 1 of form
    $("#previousstage").click(function() {

        showhidefrmstage(this.id);
        return false;

    });

    // submit non hm mentor nomination    
    $("#submitNonHMmentor").click(function() {

        submitNonHMmentor();
        return false;

    });

    // submit hm mentor nomination    
    $("#sendHMnomination").click(function() {

        submitHMMentornomination();
        return false;

    });


    $('#NominationDescription').keyup(function() {
        limitChars('NominationDescription', 2000, 'NominationDescriptionLimit');
    });


    $('#NominationMessage').keyup(function() {
        limitChars('NominationMessage', 500, 'NominationMessageLimit');
    });

    $('#nominationDesc').keyup(function() {
        limitChars('nominationDesc', 2000, 'nominationDescLimit');
    });

    $('#Helpfulness').keyup(function() {
        limitChars('Helpfulness', 2000, 'HelpfulnessLimit');
    });

    $('#Friendliness').keyup(function() {
        limitChars('Friendliness', 2000, 'FriendlinessLimit');
    });

    $('#Timeliness').keyup(function() {
        limitChars('Timeliness', 2000, 'TimelinessLimit');
    });

    $('#message').keyup(function() {
        limitChars('message', 500, 'messageLimit');
    });

});


function checkUserExists(username)
{
    $.ajax
        ({
            type: "GET",
            url: "/_extension/hmapi/api.aspx?section=yell&operation=checkmentorname&value=" + username,
            async: false,
            success: function(msg) {
                switch (msg) {
                    case '4':
                        alert("We can't find that Horsesmouth mentor name anywhere.\nCheck for typos and try again.");
                        return false;
                        break;
                    case '3':
                        alert("We can't find that Horsesmouth mentor name anywhere.\nCheck for typos and try again..");
                        return false;
                        break;
                    case '2':
                        alert("We can't find that Horsesmouth mentor name anywhere.\nCheck for typos and try again.");
                        return false;
                        break;
                    case '1':

                        $("#overlay").css({ display: "block", zIndex: "1" });
                        $("#popoutcontainerhm").css({ zIndex: "10", display: "block" });
                        $("#entryform").css({ zIndex: "10", display: "block" });

                        if ($("#selfnomination").val() == '1') {

                            $("#personalmsg").hide();

                        } else {
                        $("#personalmsg").show();
                        }

                        $("#mentorname").val($("#hmmentorname").val());
                        return false;
                        break;
                    default:
                        return false;
                        break;
                }
            },
            error: function(msg) {
                //alert(msg)
            }
        });
        
        return false;
}

function displayNonHmEntryform()
{
     $("#overlay").css({display:"block",zIndex:"1"});
     $("#popoutcontainernonhm").css({zIndex : "10", display:"block" }); 
     $("#nonhmentryform").css({zIndex : "10", display:"block" }); 
     $("#nonhmmentorname").val($("#nonhmmentorname1").val());
     $("#stage2").css({display:"none"});
     return false;
}

function showhidefrmstage(id)
{
    if(id=="nextstage")
    {        
      
     if(validateStage1NonHMnomination())
        {
            $("#stage1").css({display:"none"});
            $("#stage2").css({display:"block"});
            $("#stepcounter").empty();
            $("#stepcounter").append("step 2 of 2"); 
        }
        return false;
    }
    else if(id=="previousstage")
    {
        $("#stage2").css({display:"none"});
        $("#stage1").css({display:"block"});
        $("#stepcounter").empty();
        $("#stepcounter").append("step 1 of 2");
        window.scrollTo(0, 0);
        return false;
    }
    
    return false;
}


function validatedHMNomination()
{
    var valid= false;
    
    var nominatorid =$("#nominatorID");
    var nominatorname = $("#nominatorname");
    var selfnomination = $("#selfnomination");
    var mentorname = $("#mentorname");
    var nominationDesc = $("textarea[name = NominationDescription]"); 
    var nominationMessage = $("textarea[name = NominationMessage]");


    if (nominationDesc.val() == $("#NominationDescription").attr('title') || nominationDesc.val().length<3) {
        alert("This form isn’t quite complete!\nFill in the missing bits and things should run more smoothly")
        nominationDesc.focus();


    }
    else {

        valid = true;
    }

    
    return valid;
}


function submitHMMentornomination()
{

    var nominatorname = $("#nominatorname");
    var mentorname = $("#mentorname");

    if (nominatorname.val().toLowerCase() == mentorname.val().toLowerCase()) {  
        $("#selfnomination").val('1');
    }
   
   var data = $("#hmnomination").serialize();

    
    if(validatedHMNomination())
    {
        $.ajax({

            type: "POST",
            data: data,
            url: "confirmation.publisha?ajax=t",
            async: true,
            error: function(msg) {
                return false;
            },
            success: function(msg) {


                $(".frmelement").remove();
                $("#hmnomination").append($("#confirmedmessage"))
                $("#confirmedmessage").css({ display: "block" });
                window.scrollTo(0, 0);
                return false;
            }
        });    
        return false;
    }
    
   
}

function validateStage1NonHMnomination()
{
     var valid= false;
     var yourname = $("#yourname").val();
     var youremail = $("#youremail").val();
     var contactnumber = $("#contactnumber").val();
     var yourage = $("#selage").val();
     var gender = $("input[@name=gender]:checked").val();
     var county = $("#CountyId").val();
     var mentorname = $("#nonhmmentorname").val();
     var mentoremail = $("#mentoremail").val();
     var validalert="";
     
     if(yourname!= undefined || youremail != undefined || contactnumber != undefined || yourage=="0" || gender != undefined || county =="")
     {   
         if(yourname == "" )
         {
            validalert = "Please tell us your name\n";
         }
         if(!checkMail($("#youremail").val()) & $("#youremail").val()!=undefined)
         {
            validalert = "Your email address doesn’t look right… \nCheck for typos and try again, or use another email address. \n";
         }
         if($("#contactnumber").val()=="")
         {
            validalert ="Please enter your contact number\n";
         }   
         if($("#selage").val()=="0")
         {
            validalert ="Please select your age\n";
         }         
         if($("input[@name=gender]:checked").val()== undefined)
         {
            validalert ="Please select your gender\n";
         } 
         if( $("#CountyId").val()== "")
         {
            validalert ="Please select where you live\n";
         }                 
     }
     if(mentorname=="")
     {
        validalert ="Please tell us your mentors name\n";
     }    
     if(!checkMail(mentoremail))
     {
        validalert ="Your mentor's email address doesn’t look right… \nCheck for typos and try again, or use another email address. \n"
     }
     
     if (youremail!= undefined)
     {
        if(youremail == mentoremail && youremail !="" )
        {
            validalert ="Oops, as fabulous as you may be you cannot nominate yourself! \nThe Yell Mentoring Works Awards are a chance for you to nominate someone else - a mentor who has give you support or advice in your work or business.\n"
        }
     
     }

    if(validalert.length >0) 
    {
     alert(validalert);
    }
    else
    {
        valid=true;
    }
   
    return valid; 
}

function validateStage2NonHMnomination()
{
    var valid= false;
    var alertvalid="";
    var nominationDesc = $("#nominationDesc").val();
    var friendlyness = $("#Friendliness").val();
    var timelyness = $("#Timeliness").val();
    var helpfulness =  $("#Helpfulness").val();
    var message = $("#message").val();
    
    if(nominationDesc =="" || nominationDesc == $("#nominationDesc").attr('title'))
    {
        alertvalid = "This form isn’t quite complete!\nFill in the missing bits and things should run more smoothly";
    }
     if(friendlyness =="" || friendlyness==$("#Friendliness").attr('title'))
    {
        alertvalid = "This form isn’t quite complete!\nFill in the missing bits and things should run more smoothly";
    }
     if(timelyness =="" || timelyness==$("#Timeliness").attr('title') )
    {
        alertvalid = "This form isn’t quite complete!\nFill in the missing bits and things should run more smoothly";
    }
     if(helpfulness =="" || helpfulness==$("#Helpfulness").attr('title'))
    {
        alertvalid = "This form isn’t quite complete!\nFill in the missing bits and things should run more smoothly";
    }
    
    if(alertvalid.length >0) 
    {
     alert(alertvalid);
    }
    else
    {
        valid=true;
    }
    
    
    return valid;
}


function submitNonHMmentor()
{
    if(validateStage2NonHMnomination())
    {  
       var data = $("#nonhmnomination").serialize(); 
            
        $.ajax({

                type: "POST",
                data: data,
                url: "confirmation.publisha?ajax=t",
                async: true,
                error: function(msg)
                {
                   return false;
                },
                success: function(msg){
                   
                    $(".frmelement").remove();
                    $("#nonhmentryform").append($("#confirmedmessage"))
                    $("#confirmedmessage").css({display:"block"});
                    $("#stepcounter").empty();
                    $("#stepcounter").append("Completed");
                    window.scrollTo(0, 0);
                    return false;           
                }   
        });
    }
    return false;
}


function checkMail(email)
{
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (filter.test(email)) return true;
	else return false;
}


function limitChars(textid, limit, infodiv)
{
 var text = $('#'+textid).val();
 var textlength = text.length;
 if(textlength > limit)
 {
 $('#' + infodiv).html('all '+limit+' characters used');
 $('#'+textid).val(text.substr(0,limit));
 return false;
 }
 else
 {
 $('#' + infodiv).html((limit - textlength) +' characters left.');
 return true;
 }
}

 
