﻿jQuery.validator.methods["date"] = function (value, element) { return true; }
$(function () {
    $(document).ready(function () {
        $(".countryName").autocomplete({ source: SAARCTag })
            .focusout(function () {
                if (this.value == "India") {
                    $(".stateName").autocomplete({ source: IndianStatesTag }).val("West Bengal");
                }
                else {
                    $(".stateName").autocomplete("destroy").val("");
                }

            });
        $(".stateName").autocomplete({ source: IndianStatesTag });

        $("#UG_Profiles_appNm").focus();
        $("#PG_Profiles_appNm").focus();
        $("#appNm").focus();

        var profileImage = $("[name='ProfileImages.profileImageString']").val();
        if (profileImage == "") {
            $("#profileImage").attr("src", "../Images/noPhoto.jpg");
        }
        else {
            $("#profileImage").attr("src", profileImage);
        }

        var signatureImage = $("[name='ProfileImages.signatureImageString']").val();
        if (signatureImage == "") {
            $("#signatureImage").attr("src", "../Images/noSignature.jpg");
        }
        else {
            $("#signatureImage").attr("src", signatureImage);
        }
    });

    $("#profileImageBtn,#profileImage").click(function (e) {
        $("#profileImageBase").click();
    })
    $("#signatureImageBtn,#signatureImage").click(function (e) {
        $("#signatureImageBase").click();
    })

    $("#profileImageBase").on('change', function (e) {
        LoadImage($("#profileImage"), e.target);
    });

    $("#signatureImageBase").on('change', function (e) {
        LoadImage($("#signatureImage"), e.target);
    });

    $("input[name=board]").click(ResetBoardSubjects);

    $("input[name=ReviewForm], #AdminUpdateSubmit").click(function (event) {
        if ($("#wb").prop("checked")) {
            for (var i = 3; i <= 5; i++)
                if ($("#UG_Profiles_hsSubID" + i).val() == "0") {
                    $("#ValMsgUG_Profiles_hsSubID" + i).attr('class', "field-validation-error");
                }
        }
        else {
            for (var i = 1; i <= 4; i++)
                if ($("#UG_Profiles_hsSubID" + i).val() == "0") {
                    $("#ValMsgUG_Profiles_hsSubID" + i).attr('class', "field-validation-error");
                }
        }

        if ($("#createProfileForm").valid()) {
            if (!checkImages())
            {
                event.preventDefault();
                return false;
            }
            updateAgg();
            if ($("#UG_Profiles_hsAggregate").val() == "0") {
                event.preventDefault();
                return false;
            }
        }
        else
        {
            return checkImages()
        }
    });

    $("#ReviewFormPG, #AdminUpdatePGSubmit").click(function (event) {
        if ($("#CreatePGProfileForm").valid()) {
            if (!checkImages()) {
                event.preventDefault();
                return false;
            }
        }
        else {
            return checkImages()
        }
    });


    $("#UG_Profiles_hsSubID1, #UG_Profiles_hsSubID2, #UG_Profiles_hsSubID3, #UG_Profiles_hsSubID4, #UG_Profiles_hsSubID5, #UG_Profiles_hsSubID6").change(function () {

        var subNo = this.id.slice(-1);
        if ($("#UG_Profiles_hsSubID" + subNo).val() == "0") {
            $("#UG_Profiles_hsMarks" + subNo).val(0);
            if(subNo!=6 && ($("#wb").prop("checked") || subNo!=5))
            {
                $("#ValMsgUG_Profiles_hsSubID" + subNo).attr('class', "field-validation-error");
            }
        }
        else {
            $("#ValMsgUG_Profiles_hsSubID" + subNo).attr('class', "field-validation-valid");
        }
        $("#SubjectValmsg")
            .html("")
            .attr('class', 'field-validation-valid');

        var noOfSub = 6;
        for (var i = 1; i <= noOfSub - 1; i++) {
            if ($("#UG_Profiles_hsSubID" + i).val() == "0") {
                continue;
            }
            for (var j = i + 1; j <= noOfSub; j++) {
                if ($("#UG_Profiles_hsSubID" + i).val() == $("#UG_Profiles_hsSubID" + j).val()) {
                    $("#SubjectValmsg")
                        .html("Select distinct subjects for Subject#" + i + " & Subject#" + j + ".")
                        .attr('class', 'field-validation-error');
                    return;
                }
            }
        }
    });

    
    $("input[name=ResetProfileData], #AdminReset").click(function (event) {
        setTimeout(function () {
            ResetBoardSubjects();
            $("#UG_Profiles_appNm").focus();
        }, 1000);
    });
    

    $("#submitBtn").click(function (event) {
        var htmlMsg = "<p style='text-align:justify'><img src='../Images/Alert.png' align='left' style='padding-right:10px;'/> "
            + "These data will be permanently saved and <u>cannot be altered</u>. If you are sure and want to save it for your admission profile, then click <i>\"Yes, Save Data & Create Profile\"</i>. If you want to check the data once again, then click <i>\"Cancel\"</i>.</p>";

        $("<div></div>")
            .html(htmlMsg)
            .dialog({
                autoOpen: true,
                modal: true,
                title: "Confirm Data Submission for Admission Profile",
                resizable: false,
                height: 250,
                width: 650,
                buttons: {
                    "Yes, Save Data & Create Profile": function () {
                        var theForm = "form[name='ProfileForm']";
                        $('<input />').attr('type', 'hidden')
                          .attr('name', "SaveData")
                          .attr('value', true)
                          .appendTo(theForm);
                        $(theForm).submit();
                        $(this).dialog("close");
                    },
                    Cancel: function () {
                        $(this).dialog("close");
                    }
                }
            });
    });

    $("#freshProfileUG").click(function (event) {
        freshProfileClick("UG");
    });
    $("#freshProfilePG").click(function (event) {
        freshProfileClick("PG");
    });
});

function freshProfileClick(UGorPG)
{
    var htmlMsg = "<p style='text-align:justify'><img src='../Images/Alert.png' align='left' style='padding-right:10px;'/> "
        + "These will clear all the data you have entered & start a fresh form fillup. If you really want to discard them, then click <i>\"Yes, Clear All Data\"</i>. If you are not sure, then click <i>\"Cancel\"</i>.</p>";

    $("<div></div>")
        .html(htmlMsg)
        .dialog({
            autoOpen: true,
            modal: true,
            title: "Confirm Discard Data",
            resizable: false,
            height: 230,
            width: 650,
            buttons: {
                "Yes, Clear All Data": function () {
                    $(this).dialog("close");
                    location.href = "../AdmissionProfile/CreateProfile" + UGorPG;
                },
                Cancel: function () {
                    $(this).dialog("close");
                }
            }
        });
}

function LoadImage(imgElement, imageBase) {
    var imgId = imgElement.attr('id');
    if (imgId == "profileImage") {
        $(imgElement).attr("src", "../Images/loadingProfile.gif");
    }
    else {
        $(imgElement).attr("src", "../Images/loadingSignature.gif");
    }

    var ValMsgId = "#" + imgId + "Valmsg";
    $(ValMsgId).html("");
    $(ValMsgId).attr('class', 'field-validation-valid');

    var data = new FormData();
    var file = imageBase.files[0];
    data.append("file", file);
    data.append("imgId", imgId);
    $.ajax({
        type: "POST",
        url: 'GetImage',
        contentType: false,
        processData: false,
        data: data,
        success: function (result) {
            if (result.indexOf("data:") == 0) {
                $(imgElement).attr("src", result);
            }
            else {
                if (imgId == "profileImage") {
                    $(imgElement).attr("src", "../Images/noPhoto.jpg");
                }
                else {
                    $(imgElement).attr("src", "../Images/noSignature.jpg");
                }
                $(ValMsgId).html(result);
                $(ValMsgId).attr('class', 'field-validation-error');
            }
        },
        error: function (xhr, status, p3, p4) {
            if (imgId == "profileImage") {
                $(imgElement).attr("src", "../Images/noPhoto.jpg");
            }
            else {
                $(imgElement).attr("src", "../Images/noSignature.jpg");
            }
            $(ValMsgId).html(status);
            $(ValMsgId).attr('class', 'field-validation-error');
        }
    });
}

function checkImages()
{
    var chk = true;

    var profileImagesSrc = $("#profileImage").attr("src");
    if (profileImagesSrc.indexOf("data:") == 0) {
        $("[name='ProfileImages.profileImageString']").val(profileImagesSrc);
    }
    else {
        $("#profileImageValmsg").html("The Passport Photo of applicant is required.");
        $("#profileImageValmsg").attr('class', 'field-validation-error');
        chk = false;
    }

    var signatureImagesSrc = $("#signatureImage").attr("src");
    if (signatureImagesSrc.indexOf("data:") == 0) {
        $("[name='ProfileImages.signatureImageString']").val(signatureImagesSrc);
    }
    else {
        $("#signatureImageValmsg").html("The Scanned Signature of applicant is required.");
        $("#signatureImageValmsg").attr('class', 'field-validation-error');
        chk = false;
    }
    
    return chk;
}

function updateAgg() {
    if ($("#SubjectValmsg").attr('class') == "field-validation-error") {
        $("#UG_Profiles_hsAggregate").val("0");
        $("#aggregate").html("0 (0.0%)");
        return;
    }

    if ($("#wb").prop("checked") == false
        && $("#UG_Profiles_hsSubID5").val() == "0") {
        $("#UG_Profiles_hsMarks5").val("0");
    }

    if ($("#UG_Profiles_hsSubID6").val() == "0") {
        $("#UG_Profiles_hsMarks6").val("0");
    }

    var total_aggregate = 0;
    var per_aggregate = 0;
    $("#aggregate").html(total_aggregate + " (" + per_aggregate + "%)");
    $("#UG_Profiles_hsAggregate").val(total_aggregate);

    if ($("#wb").prop("checked")) {
        for (var i = 3; i <= 5; i++) {
            if ($("#UG_Profiles_hsSubID" + i).val() == "0") {
                $("#ValMsgUG_Profiles_hsSubID" + i).attr('class', "field-validation-error");
                return;
            }
        }
        total_aggregate = parseInt($("#UG_Profiles_hsMarks1").val()) + parseInt($("#UG_Profiles_hsMarks2").val());
        var arr = [4];
        for (var i = 0; i < 4; i++) {
            arr[i] = parseInt($("#UG_Profiles_hsMarks" + (i + 3)).val());
        }
        total_aggregate += totalBestOf(arr, 3);
        per_aggregate = (total_aggregate / 5).toFixed(1);
    }
    else {
        for (var i = 1; i <= 4; i++) {
            if ($("#UG_Profiles_hsSubID" + i).val() == "0") {
                $("#ValMsgUG_Profiles_hsSubID" + i).attr('class', "field-validation-error");
                return;
            }
        }
        var arr = [6];
        for (var i = 0; i < 6; i++) {
            arr[i] = parseInt($("#UG_Profiles_hsMarks" + (i + 1)).val());
        }
        total_aggregate = totalBestOf(arr, 4);
        per_aggregate = (total_aggregate / 4).toFixed(1);
    }


    $("#aggregate").html(total_aggregate + " (" + per_aggregate + "%)");
    $("#UG_Profiles_hsAggregate").val(total_aggregate);
    if(total_aggregate==0)
    {
        $("#AggregateValmsg").attr('class', "field-validation-error");
    }
    else
    {
        $("#AggregateValmsg").attr('class', "field-validation-valid");
    }
}

function totalBestOf(marks, number) {
    var t = 0;
    for (var i = 0; i < number; i++) {
        for (var j = 0; j < marks.length - i; j++) {
            if (marks[j] > marks[j + 1]) {
                var tmp = marks[j];
                marks[j] = marks[j + 1];
                marks[j + 1] = tmp;
            }
        }
        t += parseInt(marks[marks.length - 1 - i]);
    }
    return t;
}
/*
function haveDuplicate() {
    var noOfSub = 6;
    for (var i = 1; i <= noOfSub - 1; i++) {
        if ($("#UG_Profiles_hsSubID" + i).val() == "0") {
            continue;
        }
        for (var j = i + 1; j <= noOfSub; j++) {
            if ($("#UG_Profiles_hsSubID" + i).val() == $("#UG_Profiles_hsSubID" + j).val()) {
                $("#SubjectValmsg")
                    .html("Select distinct subjects for Subject#" + i + " & Subject#" + j+".")
                    .attr('class', 'field-validation-error');
                return true;
            }
        }
    }
    return false;
}
*/
function loadHS_SubjectOptions(dropDownList, InitValue, BoardName) {
    dropDownList.empty();
    if (BoardName == "W.B.C.H.S.E.") {
        if (dropDownList.is($("[name='UG_Profiles.hsSubID1']"))) {
            // Bengali(1), Hindi (3), Urdu(15) 
            $(document.createElement('option'))
                    .attr('value', 1)
                    .text("Bengali")
                    .appendTo(dropDownList);
            $(document.createElement('option'))
                    .attr('value', 3)
                    .text("Hindi")
                    .appendTo(dropDownList);
            $(document.createElement('option'))
                    .attr('value', 15)
                    .text("Urdu")
                    .appendTo(dropDownList);
            //////////////////////////////////
            dropDownList.val(InitValue);
            return;
        }
        else if (dropDownList.is($("[name='UG_Profiles.hsSubID2']"))) {
            ///////// English(2) //////////
            $(document.createElement('option'))
                    .attr('value', 2)
                    .text("English")
                    .appendTo(dropDownList);
            //////////////////////////////
            return;
        }
    }

    $(document.createElement('option'))
        .attr('value', "0")
        .text("No Subject Selected")
        .appendTo(dropDownList);

    $.ajax({
        type: "POST",
        url: "../Common/GetHS_SubjectList",
        accept: 'application/json',
        success: function (result) {
            $(result).each(function () {
                $(document.createElement('option'))
                    .attr('value', this.ID)
                    .text(this.subNm)
                    .appendTo(dropDownList);
            });
            dropDownList.val(InitValue);
        }
    });
}

function ResetBoardSubjects() {
    if ($("#wb").prop("checked")) {
        $("#UG_Profiles_hsBoardNm").val("W.B.C.H.S.E.").hide();
        $("#ValMsgHsBoardNm").attr('class', 'field-validation-valid');
        loadHS_SubjectOptions($("#UG_Profiles_hsSubID1"), 1, "W.B.C.H.S.E.");
        loadHS_SubjectOptions($("#UG_Profiles_hsSubID2"), 2, "W.B.C.H.S.E.");
        $("#ValMsgUG_Profiles_hsSubID1").attr('class', "field-validation-valid");
        $("#ValMsgUG_Profiles_hsSubID2").attr('class', "field-validation-valid");
    }
    else {
        $("#UG_Profiles_hsBoardNm").show().val("").focus();
        if ($("#UG_Profiles_hsBoardNm").attr('class') == 'input-validation-error') {
            $("#ValMsgHsBoardNm").attr('class', 'field-validation-error');
        }
        $("#ValMsgUG_Profiles_hsSubID5").attr('class', "field-validation-valid");
        loadHS_SubjectOptions($("#UG_Profiles_hsSubID1"), "0");
        loadHS_SubjectOptions($("#UG_Profiles_hsSubID2"), "0");
        $("#ValMsgUG_Profiles_hsSubID1").attr('class', "field-validation-error");
        $("#ValMsgUG_Profiles_hsSubID2").attr('class', "field-validation-error");
    }
}

$("#recoverReset").click(function (event) {
    setTimeout(function () {
        $("input[type=text]").val("");
    }, 200);
});