/*
 * @Function            : createXMLHTTP
 * @Used IN             : Within functions whrere AJAX Calling Required
 * @Description         : Creates the XMLHTTP object for ajax calling
 * @Developed By        : Unknown
 * @Start Date          : Unknown
 * @Parameter           : xmlhttp [Undefined variable]
 * @Return              : xmlhttp object
 * @Status              : Available       
 */
function createXMLHTTP(xmlhttp) {
    xmlhttp = false;
    try {
        return xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            return xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (E) {
            xmlhttp = false;
        }
    }
    if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
        return xmlhttp = new XMLHttpRequest();
    }
}

function documentID(el) {
    return document.getElementById(el);
}

function getCurrentDate() {
    var current_date;
    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth() + 1; //January is 0!
    var yyyy = today.getFullYear();
    if (dd < 10) {
        dd = '0' + dd;
    }
    if (mm < 10) {
        mm = '0' + mm;
    }
    return current_date = yyyy + '-' + mm + '-' + dd;
}

var imageInputFile;
function getPersonImage(imageFile) {
    documentID('upload_status').value = '';
    var allowedImageFileType = "jpeg gif png bmp jpg";
    var file = imageFile.files[0];
    var fileType = (file.type).split('/');
    var fileName = file.name;
    switch (fileType[0]) {
        case 'image':
            var fileExtention = fileName.split('.').pop().toLowerCase();
            var n = allowedImageFileType.search(fileExtention);
            if (n > -1) {
                if (file.size < 2097152) {
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        $('#src_image_file')
                                .attr('src', e.target.result);
                    };
                    reader.readAsDataURL(file);
                    documentID('picture_button').style.display = 'block';
                    documentID('image_error').innerHTML = '';
                    imageInputFile = file;
                } else {
                    documentID('picture_button').style.display = 'none';
                    documentID('image_error').innerHTML = 'Image size must less then 2 Mb';
                }
            } else {
                documentID('picture_button').style.display = 'none';
                documentID('image_error').innerHTML = 'Please select Image type: jpeg gif png bmp jpg';
            }
            break;
        default:
            documentID('picture_button').style.display = 'none';
            documentID('image_error').innerHTML = 'Invalid Image File';
            break;
    }
}

function savePersonImage(url) {
    var imageResponse;
    imageResponse = createXMLHTTP(imageResponse);
    var formdata = new FormData();
    formdata.append("person_image", imageInputFile);
    imageResponse.upload.addEventListener("progress", function (event) {
        var percent = (event.loaded / event.total) * 100;
        if (Math.round(percent) === 100) {
            documentID('upload_status').value = '1';
        } else {
            documentID('src_image_file');
        }
    }, false);
    imageResponse.addEventListener("load", function () {
        if (imageResponse.responseText === 'error') {
            documentID('picture_button').style.display = 'none';
            documentID('image_error').innerHTML = 'Some problem of Uploading Image';
        } else {
            documentID('picture_button').style.display = 'none';
            documentID('image_error').innerHTML = '';
        }

////        if (documentID('upload_status').value === '1') {
////            location.reload();
////        }
////
////        imageResponse.send(null);
//        alert(imageResponse.responseText);
    }
    , false);
    imageResponse.open("POST", url);
    imageResponse.send(formdata);
}
var i = 0;
function rotateImage() {
    ++i;
    if (i === 1) {
        documentID('imageSource').setAttribute("style", ' margin-top: -7px; width: 100%; height: 100%; transform: rotate(90deg);');
    }
    if (i === 2) {
        documentID('imageSource').setAttribute("style", ' margin-top: -7px; width: 100%; height: 100%; transform: rotate(180deg);');
    }
    if (i === 3) {
        documentID('imageSource').setAttribute("style", ' margin-top: -7px; width: 100%; height: 100%; transform: rotate(270deg);');
    }
    if (i === 4) {
        documentID('imageSource').setAttribute("style", ' margin-top: -7px; width: 100%; height: 100%; transform: rotate(360deg);');
    }
    if (i === 5) {
        i = 0;
    }
}

//======================== Edit name section start =============================

/*
 * @Function            : EditName
 * @Used IN             : profile
 * @Description         : Displays the form for editing name upon clicking edit icon
 * @Developed By        : Unknown [Comment added By Md Mashqur Ul Alam 30-11-16]
 * @Start DateTime      : Unknown
 * @Parameter           : Null *   
 * @Status              : Available       
 */

function EditName() {
    var full_name = documentID('full_name');
    full_name.setAttribute("style", 'display:none; ');
    var EditNameForm = documentID('EditNameForm');
    EditNameForm.setAttribute("style", 'display:block; ');
    var NameSubmit = documentID('NameSubmit');
    NameSubmit.setAttribute("style", 'display:block; ');
    var edit_pencil = documentID('edit_pencil');
    edit_pencil.setAttribute("style", 'display:none; ');
}
/*
 * @Function            : nameRequired
 * @Used IN             : edit_person_name.php
 * @Description         : Validate the first name when user edit name in profile.
 * @Developed By        : Unknown [Comment added By Md Mashqur Ul Alam 30-11-16]
 * @Start DateTime      : Unknown
 * @Parameter           : first_name, errorID, btn
 * @Status              : Available       
 */
function nameRequired(first_name, errorID, btn) {
    if (first_name == '') {
        documentID(errorID).innerHTML = "First Name is Required";
        documentID(btn).style.pointerEvents = "none";
    } else {
        checkFirstName(first_name, errorID, btn)
    }
}
/*
 * @Function            : checkFirstName
 * @Used IN             : @function 'nameRequired'
 * @Description         : checks the character of first name using regxp
 * @Developed By        : Unknown [Comment added By Md Mashqur Ul Alam 30-11-16]
 * @Start DateTime      : Unknown
 * @Parameter           : first_name, errorID, btn
 * @Status              : Available       
 */
function checkFirstNames(first_name, errorID, btn) {
    validName = /^[0-9a-zA-Z\. \ ' \-']+$/;
    if (first_name.match(validName)) {
        documentID(errorID).innerHTML = '';
        documentID(btn).style.pointerEvents = "auto";
    } else {
        documentID(errorID).innerHTML = "No Special Carecter Allow Except ' , . or - '";
        documentID(btn).style.pointerEvents = "none";
    }
}

/*
 * @Function            : checkLastName
 * @Used IN             : edit_person_name.php
 * @Description         : Validate the last name when user edit name in profile.
 * @Developed By        : Unknown [Comment added By Md Mashqur Ul Alam 30-11-16]
 * @Start DateTime      : Unknown
 * @Parameter           : last_name, errorID, btn
 * @Status              : Available       
 */
function checkLastNames(last_name, errorID, btn) {
    var first_name = documentID('personFirstName').value;
    if (last_name != '') {
        if (first_name == '') {
            documentID('first_name_error').innerHTML = "First Name is Required";
            documentID(btn).style.pointerEvents = "none";
        } else {
            validName = /^[0-9a-zA-Z\. \ ' \-']+$/;
            if (last_name.match(validName)) {
                documentID(errorID).innerHTML = '';
                documentID(btn).style.pointerEvents = "auto";
            } else {
                documentID(errorID).innerHTML = "No Special Carecter Allow Except ' , . or - '";
                documentID(btn).style.pointerEvents = "none";
            }
        }
    }
}


/*
 * @Function            : UpdateName
 * @Used IN             : profile
 * @Description         : Updates the name of user in profile edit
 * @Developed By        : Unknown [Comment added By Md Mashqur Ul Alam 30-11-16]
 * @Updated By          : Tania
 * @Update DateTime     : 08-08-16
 * @Parameter           : url  
 * @Status              : Available       
 */

function UpdateName(url) {
    var first_name = documentID('personFirstName').value;
    var last_name = documentID('personLastName').value;
    var person_id = documentID('personID').value;
    if (first_name === '' && last_name !== '') {
        documentID('first_name_error').innerHTML = "First Name is Required";
        documentID('btn_save_name').style.pointerEvents = "none";
    }
    if (last_name === '') {
        last_name = 'null';
    }
    var xmlhttp2;
    xmlhttp2 = checkXMLHTTP(xmlhttp2);
    var formdata = new FormData();
    formdata.append("first_name", first_name);
    formdata.append("last_name", last_name);
    formdata.append("person_id", person_id);
    xmlhttp2.addEventListener("load", function () {
        if (xmlhttp2.responseText === '1') {
            documentID('first_name_error').innerHTML = "There is some problem. Please change your name";
            documentID('btn_save_name').style.pointerEvents = "none";
        } else if (xmlhttp2.responseText === '2') {
            location.reload();
            documentID('EditNameForm').setAttribute("style", 'display:none; ');
            documentID('full_name').setAttribute("style", 'display:block;');
            documentID('NameSubmit').setAttribute("style", 'display:none;');
            documentID('edit_pencil').setAttribute("style", 'display:block; ');
        }
    }, false);
    xmlhttp2.addEventListener("error", function () {
        alert("There is some problem in your browser, not working");
    }, false);
    xmlhttp2.addEventListener("abort", function () {
        alert("There is some problem in your browser, aborted");
    }, false);
    xmlhttp2.open("POST", url);
    xmlhttp2.send(formdata);
}
//======================== Edit name section end =============================



// --------------------------Start Edit URL-------------------------------------

/*
 * @Function            : updateUrlFormAction
 * @Used IN             : @ function 'updateUrlForm'
 * @Description         : Makes the url field editatble
 * @Developed By        : Unknown [Comment added By Md Mashqur Ul Alam 01-12-16]
 * @Parameter           : url  
 * @Status              : Available       
 */
function updateUrlFormAction() {
    var URLfield = documentID('URLfield');
    URLfield.setAttribute('style', 'display:block');
    URLfield.setAttribute('style', 'margin-left:-14px');
    var old_url = documentID('viewURL').innerHTML;
    documentID('URLfield').value = old_url;
    var viewURL = documentID('viewURL');
    viewURL.setAttribute('style', 'display:none');
    var edit_url = documentID('edit_url');
    edit_url.setAttribute('style', 'display:none');
    var save_update_url = documentID('save_update_url');
    save_update_url.setAttribute('style', 'display:block');
}

/*
 * @Function            : updateUrlForm
 * @Used IN             : profile
 * @Description         : Restricts updating url within 1 day
 * @Developed By        : Unknown [Comment added By Md Mashqur Ul Alam 01-12-16]
 * @Parameter           : Null  
 * @Status              : Available       
 */
function updateUrlForm() {
    var urlChangeDifferent = documentID('url_change_different').value;
    if (urlChangeDifferent === '') {
        updateUrlFormAction();
    } else {
        if (urlChangeDifferent > 1) {
            updateUrlFormAction();
        } else {
            documentID('message').innerHTML = 'You can not change url within 1 day';
        }
    }
}

/*
 * @Function            : updateUrl
 * @Used IN             : profile
 * @Description         : Restricts updating url within 1 day
 * @Developed By        : Unknown 
 * @Updated By          : Md Mashqur Ul Alam
 * @Update Date         : 01-12-16 
 * @Parameter           : Null  
 * @Status              : Available       
 */
function updateUrl(ID, inputUrl, oldUrl) {
    var baseUrl = $("#baseUrl").val();
    var update_url = baseUrl + 'update-person-url';
    if (inputUrl !== oldUrl) {
        var urlValidate = documentID('url_validate').value;
        if (urlValidate == 1) {
            documentID('message').innerHTML = 'Please Type URL';
            return false;
        } else if (urlValidate == 2) {
            documentID('message').innerHTML = 'No hypen allow at the first';
            return false;
        } else if (urlValidate == 3) {
            documentID('message').innerHTML = 'No hypen allow at the last';
            return false;
        } else if (urlValidate == 4) {
            documentID('message').innerHTML = 'Multiple hypen does not allow';
            return false;
        } else if (urlValidate == 5) {
            documentID('message').innerHTML = 'No Capital Letter or Special Caracter Allow Accept -';
            return false;
        } else if (urlValidate == 6) {
            documentID('message').innerHTML = "Url Exists";
            return false;
        } else {
            var profileResponse1;
            profileResponse1 = createXMLHTTP(profileResponse1);
            serverPage = update_url + '/' + ID + '/' + inputUrl + '/' + oldUrl;
            profileResponse1.open("GET", serverPage);
            profileResponse1.onreadystatechange = function ()
            {
                if (profileResponse1.readyState === 4 && profileResponse1.status === 200)
                {
                    if (profileResponse1.responseText) {
                        window.location.href = baseUrl + profileResponse1.responseText + '/profile';
                    }
                }
            };
            profileResponse1.send(null);
        }
    } else {
        location.reload();
    }
}

/*
 * @Function            : checkUrlExists
 * @Used IN             : profile
 * @Description         : Validates url and checks url already exist or not
 * @Developed By        : Unknown
 * @Updated By          : Md Mahqur Ul Alam
 * @Update Date         : 01-12-16
 * @Parameter           : newUrl, oldUrl  
 * @Status              : Available       
 */
function checkUrlExists(newUrl, oldUrl) {
    var baseUrl = $("#baseUrl").val();
    var url_existence = baseUrl + 'profile-url-existance';
    var profileResponse;
    profileResponse = createXMLHTTP(profileResponse);
    var urlRegx = /^[0-9a-z\-]+$/;
    var hypenRegex = /--/g;
    if (newUrl === '') {
        documentID('message').innerHTML = 'Please Type URL';
        documentID('url_validate').value = 1;
    } else if (newUrl === oldUrl) {
        documentID('message').innerHTML = '';
        documentID('url_validate').value = '';
    } else {
        if (newUrl.charAt(0) === '-') {
            documentID('message').innerHTML = 'No hypen allow at the first';
            documentID('url_validate').value = 2;
        } else if (newUrl.charAt(newUrl.length - 1) === '-') {
            documentID('message').innerHTML = 'No hypen allow at the last';
            documentID('url_validate').value = 3;
        } else if (hypenRegex.test(newUrl)) {
            documentID('message').innerHTML = 'Multiple hypen does not allow';
            documentID('url_validate').value = 4;
        } else if (urlRegx.test(newUrl)) {
            serverPage = url_existence + '/' + newUrl;
            profileResponse.open("GET", serverPage);
            profileResponse.onreadystatechange = function ()
            {
                if (profileResponse.readyState === 4 && profileResponse.status === 200)
                {
                    if (profileResponse.responseText == 1) {
                        documentID('message').innerHTML = "Url Exists";
                        documentID('url_validate').value = 6;
                    } else {
                        documentID('message').innerHTML = '';
                        documentID('url_validate').value = '';
                    }
                }
            };
            profileResponse.send(null);
        } else {
            documentID('message').innerHTML = 'No Capital Letter or Special Caracter Allow Accept -';
            documentID('url_validate').value = 5;
        }
    }
}

// --------------------------End Edit URL------------------------------------------- 



//-------------------------- Start Edit Education----------------------------------------
/*
 * @Function            : selectInstituForm
 * @Used IN             : profile page education details Add Education plus icon
 * @Description         : displays the add education form
 * @Developed By        : Unknown
 * @Updated By          : Md Mahqur Ul Alam
 * @Update Date         : 02-12-16
 * @Parameter           : url  
 * @Status              : Available       
 */

function addEducationForm(url) {
    var educationResponse;
    educationResponse = createXMLHTTP(educationResponse);
    var serverPage = url;
    educationResponse.open("GET", serverPage);
    educationResponse.onreadystatechange = function ()
    {
        if (educationResponse.readyState === 4 && educationResponse.status === 200)
        {
            var addEducationForm = documentID('add_education_form');
            addEducationForm.setAttribute('style', 'display:block');
            addEducationForm.innerHTML = educationResponse.responseText;
            populateCountries("person_country", "person_city");
            $(function () {
                $('#datetimepicker1').datetimepicker({
                    viewMode: 'years',
                    format: 'YYYY-MM-DD'

                });
            });
            $(function () {
                $('#datetimepicker2').datetimepicker({
                    viewMode: 'years',
                    format: 'YYYY-MM-DD'

                });
            });
        }
    };
    educationResponse.send(null);
}

/*
 * @Function            : cancelAddEducation
 * @Used IN             : profile page education details
 * @Description         : cancel the add education
 * @Developed By        : Unknown
 * @Comment Added By    : Md Mahqur Ul Alam 02-12-16
 * @Parameter           : Null  
 * @Status              : Available       
 */
function cancelAddEducation() {
    var addEducationForm = documentID('add_education_form');
    addEducationForm.innerHTML = '';
    addEducationForm.setAttribute('style', 'display:none');
}

/*
 * @Function            : otherInstitution
 * @Used IN             : adding or editing education information in profile
 * @Description         : Displays the other option for institute name
 * @Developed By        : Unknown
 * @Comment Added By    : Md Mahqur Ul Alam 02-12-16
 * @Parameter           : givenText  
 * @Status              : Available       
 */
function otherInstitution(givenText) {

    if (givenText == 'other') {
        var O_Institution = documentID('O_Institution');
        O_Institution.setAttribute("style", 'display:block; ');
    } else {
        var O_Institution = documentID('O_Institution');
        O_Institution.setAttribute("style", 'display:none; ');
    }
}

/*
 * @Function            : EducationStatus
 * @Used IN             : @function 'viewEditEducation'
 * @Description         : Displays the education end date in form
 * @Developed By        : Unknown
 * @Comment Added By    : Md Mahqur Ul Alam 02-12-16
 * @Parameter           : GivenText
 * @Status              : Available       
 */
function EducationStatus(GivenText) {
    var eduEndDate = documentID('eduEndDate');
    if (GivenText == 2) {
        eduEndDate.setAttribute('style', 'display:block');
    } else {
        eduEndDate.setAttribute('style', 'display:none');
    }
}


/*
 * @Function            : checkAddEducationCurrentDate
 * @Used IN             : add_education_action.php [ajax view page]
 * @Description         : validates education start date.
 * @Developed By        : Unknown
 * @Comment Added By    : Md Mahqur Ul Alam 02-12-16
 * @Parameter           : date  
 * @Status              : Available       
 */
function checkAddEducationCurrentDate(date) {
    var current_date = getCurrentDate();
    if (current_date > date) {
        documentID('start_date').innerHTML = '';
        compareAddEducationDate();
    } else {
        documentID('start_date').innerHTML = "Can not Enter date after Today's Date";
    }
}

/*
 * @Function            : compareAddEducationDate
 * @Used IN             : @function 'checkAddEducationCurrentDate'
 * @Description         : compares the education start and end date for validation
 * @Developed By        : Unknown
 * @Comment Added By    : Md Mahqur Ul Alam 02-12-16
 * @Parameter           : Null 
 * @Status              : Available       
 */
function compareAddEducationDate() {
    var startDate = documentID('New_attended_date').value;
    var endDate = documentID('New_finished_date').value;
    var view_status = document.forms['add_new_education_form'].elements['person_current_education_instute'].value;
    if (startDate && endDate && view_status) {
        if (view_status == 2) {
            if (startDate < endDate) {
                documentID('end_date').innerHTML = '';
            } else {
                documentID('end_date').innerHTML = "Enter date before today and after start date";
            }
        } else {
            documentID('end_date').innerHTML = '';
        }
    }
}

/*
 * @Function            : checkEditCurrentDate
 * @Used IN             : edit_education_form.php [ajax view page]
 * @Description         : checks the date entered by user
 * @Developed By        : Unknown
 * @Comment Added By    : Md Mahqur Ul Alam 02-12-16
 * @Parameter           : date 
 * @Status              : Available       
 */
function checkEditCurrentDate(date) {
    var current_date = getCurrentDate();
    if (current_date > date) {
        documentID('start_date').innerHTML = '';
        compareEditEducationDate();
    } else {
        documentID('start_date').innerHTML = "Can not Enter date after Today's Date";
    }
}

/*
 * @Function            : compareEditEducationDate
 * @Used IN             : @function checkEditCurrentDate
 * @Description         : Checks the date while editing education
 * @Developed By        : Unknown
 * @Comment Added By    : Md Mahqur Ul Alam 02-12-16
 * @Parameter           : Null  
 * @Status              : Available       
 */
function compareEditEducationDate() {
    var startDate = documentID('New_attended_date').value;
    var endDate = documentID('New_finished_date').value;
    var view_status = document.forms['edit_education_form'].elements['person_current_education_instute'].value;
    if (startDate && endDate && view_status) {
        if (view_status == 2) {
            if (startDate < endDate) {
                documentID('end_date').innerHTML = '';
            } else {
                documentID('end_date').innerHTML = "Enter date before today and after start date";
            }
        } else {
            documentID('end_date').innerHTML = '';
        }
    }
}


/*
 * @Function            : addNewEducation
 * @Used IN             : add_education_action.php
 * @Description         : Add new education detail in users profile
 * @Developed By        : Unknown
 * @Comment Added By    : Md Mahqur Ul Alam 02-12-16
 * @Parameter           : url  
 * @Status              : Available       
 */
function addNewEducation(url) {
    var educationResponse;
    educationResponse = createXMLHTTP(educationResponse);
    // Collecting the values from Add education form
    var new_attended = document.forms['add_new_education_form'].elements['new_attended'].value;
    var person_country = document.forms['add_new_education_form'].elements['person_country'].value;
    var person_city = document.forms['add_new_education_form'].elements['person_city'].value;
    var education_institute_id = document.forms['add_new_education_form'].elements['education_institute_id'].value;
    var education_institute_name = document.forms['add_new_education_form'].elements['other_education_institute_name'].value;
    var new_education_description = document.forms['add_new_education_form'].elements['new_education_description'].value;
    var new_attended_date = document.forms['add_new_education_form'].elements['new_attended_date'].value;
    var person_current_education_instute = document.forms['add_new_education_form'].elements['person_current_education_instute'].value;
    var new_finished_date = document.forms['add_new_education_form'].elements['new_finished_date'].value;
    var new_education_view_type = document.forms['add_new_education_form'].elements['new_education_view_type'].value;
    var current_date = getCurrentDate();
// check form validation Start
    if (new_attended == '') {
        documentID('attended').innerHTML = "Education Attended is required";
        return false;
    } else {
        documentID('attended').innerHTML = "";
    }
    if (person_country == '') {
        documentID('country').innerHTML = "Education Institute Country is required";
        return false;
    } else {
        documentID('country').innerHTML = "";
    }
    if (person_city == '') {
        documentID('city_id').innerHTML = "Education Institute city is required";
        return false;
    } else {
        documentID('city_id').innerHTML = "";
    }
    if (education_institute_id == '') {
        documentID('institute_id').innerHTML = "Education Institute is required";
        return false;
    } else {
        documentID('institute_id').innerHTML = "";
    }

    if (education_institute_id == 'other') {
        if (education_institute_name == '') {
            documentID('other_institute_id').innerHTML = "Education Institute Name is required";
            return false;
        } else {
            documentID('other_institute_id').innerHTML = "";
        }
    }
    if (new_attended_date == '') {
        documentID('start_date').innerHTML = "Education Start Date is required";
        return false;
    } else {
        if (current_date > new_attended_date) {
            documentID('start_date').innerHTML = '';
        } else {
            documentID('start_date').innerHTML = "Can not Enter date after Today's Date";
            return false;
        }
    }

    if (person_current_education_instute == '') {
        documentID('current_status').innerHTML = "Education Current Status is required";
        return false;
    } else {
        documentID('current_status').innerHTML = "";
    }
    if (person_current_education_instute == 2) {
        if (new_finished_date == '') {
            documentID('end_date').innerHTML = "Education Finish Date is required";
            return false;
        } else {
            if (new_attended_date < new_finished_date) {
                documentID('end_date').innerHTML = '';
            } else {
                documentID('end_date').innerHTML = "Enter date before today and after start date";
                return false;
            }
        }
    }
    if (new_education_description == '') {
        documentID('endu_description').innerHTML = "Education Description is required";
        return false;
    } else {
        documentID('endu_description').innerHTML = "";
    }
    if (new_education_view_type == '') {
        documentID('edu_view_type').innerHTML = "Education View Type is required";
        return false;
    } else {
        documentID('edu_view_type').innerHTML = "";
    }

// check form validation End

    var formdata = new FormData();
    formdata.append("attended_for", new_attended);
    formdata.append("education_institute_country", person_country);
    formdata.append("education_institute_city", person_city);
    formdata.append("education_institute_id", education_institute_id);
    formdata.append("education_institute_name", education_institute_name);
    formdata.append("educational_description", new_education_description);
    formdata.append("start_time_period", new_attended_date);
    formdata.append("person_current_education_instute", person_current_education_instute);
    formdata.append("end_time_period", new_finished_date);
    formdata.append("person_education_view_status", new_education_view_type);
    educationResponse.addEventListener("load", function () {
        documentID('view_education_details').innerHTML = educationResponse.responseText;
        documentID('add_education_form').innerHTML = '';
        documentID('add_education_btn').setAttribute('style', 'display:block');
        educationResponse.send(null);
    }
    , false);
    educationResponse.addEventListener("error", function () {
        alert("Upload Failed");
    }, false);
    educationResponse.addEventListener("abort", function () {
        alert("Upload Aborted");
    }, false);
    //Sending form data via Ajax
    educationResponse.open("POST", url);
    educationResponse.send(formdata);
    return true;
}

/*
 * @Description         : on changing the country and city name
 *                        updates the list of education institute name
 * @Developed By        : Md Mashqur Ul Alam
 * @Start DateTime      : 26-12-2016 05:21 PM      
 */
$(document).on('change', "#person_country", function () {
    selectInstitute();
}).on('change', "#person_city", function () {
    selectInstitute();
});
/*
 * @Function            : selectInstitute
 * @Used IN             : profile education section
 * @Description         : Creates the list of education institute for dropdown
 * @Developed By        : Unknown
 * @Updated By          : Md Mahqur Ul Alam [Global variables made local]
 * @Update Date         : 02-12-16
 * @Parameter           : eduInsType [optional]  
 * @Status              : Available       
 */
function selectInstitute() {
    var attendedFor = document.forms['add_new_education_form'].elements['new_attended'].value.trim();
    var country = documentID('person_country').value.trim();
    var city = documentID('person_city').value.trim();
    var baseUrl = $("#baseUrl").val();
    $.post(baseUrl + 'admin/select-institute',
            {
                eduInsType: attendedFor,
                eduInsCountry: country,
                eduInsCity: city
            },
            function (data) {
                var eduIns = JSON.parse(data);
                var options = $('#education_institute_id');
                options.empty();
                options.append($("<option />").val('').text('Select  Institution Name'));
                $.each(eduIns, function () {
                    options.append($("<option />").val(this.education_institute_id).text(this.education_institute_name));
                });
                options.append($("<option />").val('other').text('Other'));
            });
}

/*
 * @Function            : viewEditEducation
 * @Used IN             : profile.php [view page]
 * @Description         : Displays the edit form for editing education details
 * @Developed By        : Unknown
 * @Updated By          : Md Mahqur Ul Alam
 * @Update Date         : 02-12-16
 * @Parameter           : url, ID  
 * @Status              : Available       
 */
function viewEditEducation(url, ID) {
    if (documentID('check_education_form_view')) {
        alert('An Edit Form is Already Open !');
    } else {
        var educationResponse;
        educationResponse = createXMLHTTP(educationResponse);
        var serverPage = url;
        educationResponse.open("GET", serverPage);
        educationResponse.onreadystatechange = function ()
        {
            if (educationResponse.readyState === 4 && educationResponse.status === 200)
            {
                documentID('add_education_btn').setAttribute('style', 'display:none');
                documentID('education_form_view' + ID).innerHTML = educationResponse.responseText;
                document.forms['edit_education_form'].elements['new_attended'].value = documentID('hidden_attended_for').value.trim();
                var country = documentID('hidden_edu_country').value.trim();
                populateCountries("person_country", "person_city");
                document.forms['edit_education_form'].elements['person_country'].value = country;
                var city = documentID('hidden_edu_city').value.trim();
                populateStates('person_country', 'person_city');
                document.forms['edit_education_form'].elements['person_city'].value = city;
                // Loads to dropdown of education institute name.
                selectEditInstitute();
                var current_edu_intiture = documentID('hidden_current_edu_institute_status').value;
                document.forms['edit_education_form'].elements['person_current_education_instute'].value = current_edu_intiture;
                EducationStatus(current_edu_intiture);
                document.forms['edit_education_form'].elements['new_education_view_type'].value = documentID('hidden_edu_view_status').value;
                $('#datetimepicker1').datetimepicker({
                    viewMode: 'years',
                    format: 'YYYY-MM-DD'

                });
                $('#datetimepicker3').datetimepicker({
                    viewMode: 'years',
                    format: 'YYYY-MM-DD'

                });
            }
        };
        educationResponse.send(null);
    }
}

/*
 * @Function            : selectEditInstitute
 * @Used IN             : @function 'viewEditEducation'
 * @Description         : Displays the education institute dropdown for edit 
 *                        education institute form
 * @Developed By        : Unknown
 * @Updated By          : Md Mahqur Ul Alam
 * @Update Date         : 27-12-16
 * @Parameter           : Null
 * @Status              : Available       
 */
function selectEditInstitute() {
    var eduInsId = $("#hidden_edu_institute_id").val().trim();
    var eduInsName = $("#hidden_edu_institute_name").val().trim();
    var eduInsStatus = $("#hidden_edu_institute_status").val().trim();
    var attendedFor = document.forms['edit_education_form'].elements['new_attended'].value.trim();
    var country = documentID('person_country').value.trim();
    var city = documentID('person_city').value.trim();
    var baseUrl = $("#baseUrl").val();
    $.post(baseUrl + 'admin/select-institute',
            {
                eduInsType: attendedFor,
                eduInsCountry: country,
                eduInsCity: city
            },
            function (data) {
                var eduIns = JSON.parse(data);
                var options = $('#education_institute_id');
                options.empty();
                if (eduInsStatus != 3) {
                    options.append($("<option />").val(eduInsId).text(eduInsName));
                }
                options.append($("<option />").val('').text('Select  Institution Name'));
                $.each(eduIns, function () {
                    options.append($("<option />").val(this.education_institute_id).text(this.education_institute_name));
                });
                options.append($("<option />").val('other').text('Other'));
                options.val(eduInsId);
            });
}

/*
 * @Description         : Delete the education detail from profile
 * @Developed By        : Md Mahqur Ul Alam 
 * @Start Date Time     : 28-12-16
 */

$(document).on('click', 'a[id^="deleteEducation"]', function () {
    var eduDetail = this.id.replace('deleteEducation', '');
    $("#deleteEducationModal" + eduDetail).modal('show');
}).on('click', 'button[id^="modalNoButton"]', function () {
    var eduDetail = this.id.replace('modalNoButton', '');
    $("#deleteEducationModal" + eduDetail).modal('hide');
}).on('click', 'button[id^="modalYesButton"]', function () {
    var eduDetail = this.id.replace('modalYesButton', '');
    deleteEducation(eduDetail);
    $("#deleteEducationModal" + eduDetail).modal('hide');
});
/*
 * @Function            : deleteEducation
 * @Used IN             : Profile 
 * @Description         : Delete education details
 * @Developed By        : Md Mahqur Ul Alam
 * @Updated Date        : 28-12-16
 * @Parameter           : eduDetail
 * @Status              : Available       
 */

function deleteEducation(eduDetail) {
    var url = $("#baseUrl").val() + 'admin/delete-education';
    var profileUrl = $('#profileUrl').val();
    //alert(eduDetail);
    $.post(url,
            {
                eduDetail: eduDetail,
                profileUrl: profileUrl
            },
            function () {
                $('#education_form_view' + eduDetail).remove();
            });
}

/*
 * @Function            : cancelUpdateEducation
 * @Used IN             : profile page education details
 * @Description         : cancel the edit or update education
 * @Developed By        : Unknown
 * @Updated By          : Md Mahqur Ul Alam
 * @Updated Date        : 02-12-16
 * @Parameter           : url, ID  
 * @Status              : Available       
 */
function cancelUpdateEducation(url, ID) {
    var upEducationResponse2;
    upEducationResponse2 = createXMLHTTP(upEducationResponse2);
    serverPage = url + '/' + ID;
    upEducationResponse2.open("GET", serverPage);
    upEducationResponse2.onreadystatechange = function ()
    {
        if (upEducationResponse2.readyState === 4 && upEducationResponse2.status === 200)
        {
            documentID('view_education_details').innerHTML = '';
            documentID('view_education_details').innerHTML = upEducationResponse2.responseText;
            $("#add_education_btn").show().css('padding-right', '20px');
        }
    };
    upEducationResponse2.send(null);
}

/*
 * @Function            : UpdateEducation
 * @Used IN             : edit_education_form.php [ajax view page]
 * @Description         : saves the updated education information
 * @Developed By        : Unknown
 * @Comment Added By    : Md Mahqur Ul Alam 02-12-16
 * @Parameter           : url, ID  
 * @Status              : Available       
 */
function updateEducation(url, ID) {
    var upEducationResponse;
    upEducationResponse = createXMLHTTP(upEducationResponse);
    var new_attended = document.forms['edit_education_form'].elements['new_attended'].value;
    var person_country = document.forms['edit_education_form'].elements['person_country'].value;
    var person_city = document.forms['edit_education_form'].elements['person_city'].value;
    var education_institute_id = document.forms['edit_education_form'].elements['education_institute_id'].value;
    var education_institute_name = document.forms['edit_education_form'].elements['other_education_institute_name'].value;
    var new_education_description = document.forms['edit_education_form'].elements['new_education_description'].value;
    var new_attended_date = document.forms['edit_education_form'].elements['new_attended_date'].value;
    var person_current_education_instute = document.forms['edit_education_form'].elements['person_current_education_instute'].value;
    var new_finished_date = document.forms['edit_education_form'].elements['new_finished_date'].value;
    var new_education_view_type = document.forms['edit_education_form'].elements['new_education_view_type'].value;
    var current_date = getCurrentDate();
    if (new_attended == '') {
        documentID('attended').innerHTML = "Education Attended is required";
        return false;
    } else {
        documentID('attended').innerHTML = "";
    }
    if (person_country == '') {
        documentID('country').innerHTML = "Education Institute Country is required";
        return false;
    } else {
        documentID('country').innerHTML = "";
    }
    if (person_city == '') {
        documentID('city_id').innerHTML = "Education Institute city is required";
        return false;
    } else {
        documentID('city_id').innerHTML = "";
    }
    if (education_institute_id == '') {
        documentID('institute_id').innerHTML = "Education Institute is required";
        return false;
    } else {
        documentID('institute_id').innerHTML = "";
    }

    if (education_institute_id == 'other') {
        if (education_institute_name == '') {
            documentID('other_institute_id').innerHTML = "Education Institute Name is required";
            return false;
        } else {
            documentID('other_institute_id').innerHTML = "";
        }
    }
    if (new_attended_date == '') {
        documentID('start_date').innerHTML = "Education Start Date is required";
        return false;
    } else {
        if (current_date > new_attended_date) {
            documentID('start_date').innerHTML = '';
        } else {
            documentID('start_date').innerHTML = "Can not Enter date after Today's Date";
            return false;
        }
    }
    if (person_current_education_instute == '') {
        documentID('current_status').innerHTML = "Education Current Status is required";
        return false;
    } else {
        documentID('current_status').innerHTML = "";
    }
    if (person_current_education_instute == 2) {
        if (new_finished_date == '') {
            documentID('end_date').innerHTML = "Education Finish Date is required";
            return false;
        } else {
            if (new_attended_date < new_finished_date) {
                documentID('end_date').innerHTML = '';
            } else {
                documentID('end_date').innerHTML = "Enter date before today and after start date";
                return false;
            }
        }
    }
    if (new_education_description == '') {
        documentID('endu_description').innerHTML = "Education Description Name is required";
        return false;
    } else {
        documentID('endu_description').innerHTML = "";
    }
    if (new_education_view_type == '') {
        documentID('edu_view_type').innerHTML = "Education View Type is required";
        return false;
    } else {
        documentID('edu_view_type').innerHTML = "";
    }

    var formdata = new FormData();
    formdata.append("attended_for", new_attended);
    formdata.append("education_institute_country", person_country);
    formdata.append("education_institute_city", person_city);
    formdata.append("education_institute_id", education_institute_id);
    formdata.append("education_institute_name", education_institute_name);
    formdata.append("educational_description", new_education_description);
    formdata.append("start_time_period", new_attended_date);
    formdata.append("person_current_education_instute", person_current_education_instute);
    formdata.append("end_time_period", new_finished_date);
    formdata.append("person_education_view_status", new_education_view_type);
    upEducationResponse.addEventListener("load", function () {
        documentID('view_education_details').innerHTML = upEducationResponse.responseText;
    }, false);
    upEducationResponse.addEventListener("error", function () {
        alert("Upload Failed");
    }, false);
    upEducationResponse.addEventListener("abort", function () {
        alert("Upload Aborted");
    }, false);
    upEducationResponse.open("POST", url);
    upEducationResponse.send(formdata);
    return true;
}
// End edit Education Form


//-------------------------- END Education----------------------------------------



//-------------------------- Start Work Experience----------------------------------------

//var getWorkEXperienceValue;

function addWorkExperiecneForm(url) {
    var addWorkResponse;
    addWorkResponse = createXMLHTTP(addWorkResponse);
    var serverPage = url;
    addWorkResponse.open("GET", serverPage);
    addWorkResponse.onreadystatechange = function ()
    {
        if (addWorkResponse.readyState === 4 && addWorkResponse.status === 200)
        {
            var addWorkExperience = documentID('add_new_work_experience');
            addWorkExperience.setAttribute('style', 'display:block');
            addWorkExperience.innerHTML = addWorkResponse.responseText;
            $(function () {
                $('#datetimepicker5').datetimepicker({
                    viewMode: 'years',
                    format: 'YYYY-MM-DD'

                });
            });
            $(function () {
                $('#datetimepicker6').datetimepicker({
                    viewMode: 'years',
                    format: 'YYYY-MM-DD'

                });
            });
        }
    };
    addWorkResponse.send(null);
}

function cancelAddWorkExperience() {
    var addWorkExperience = documentID('add_new_work_experience');
    addWorkExperience.innerHTML = '';
    addWorkExperience.setAttribute('style', 'display:none');
}

function checkCompanyName(inputName) {
    var regx = /^[0-9a-zA-Z\. \ ' \-',]+$/;
    if (inputName === '') {
        documentID('company_error').innerHTML = "Please type company name";
    } else {
        if (regx.test(inputName)) {
            documentID('company_error').innerHTML = "";
            documentID('profile_company_validate').value = '';
        } else {
            documentID('profile_company_validate').value = '1';
            documentID('company_error').innerHTML = "No Special Carecter Allow Except ' , . or - ";
        }
    }
}

function checkDesignation(inputName) {
    var regx = /^[0-9a-zA-Z\. \ ' \-',]+$/;
    if (inputName === '') {
        documentID('designation_error').innerHTML = "Please type Designation";
    } else {
        if (regx.test(inputName)) {
            documentID('designation_error').innerHTML = "";
            documentID('designation_validate').value = '';
        } else {
            documentID('designation_validate').value = '1';
            documentID('designation_error').innerHTML = "No Special Carecter Allow Except ' , . or - ";
        }
    }
}

function WorkStatus(GivenText) {
    var workEndDate = documentID('workEndDate');
    if (GivenText == 2) {
        workEndDate.setAttribute('style', 'display:block');
    } else {
        workEndDate.setAttribute('style', 'display:none');
    }
}

function addWorkExperience(url) {
    var workResponse;
    workResponse = createXMLHTTP(workResponse);
    //                    var person_id = documentID('person_id').value;
    var company_name = documentID('profile_company_name').value;
    var designation = documentID('profile_designation').value;
    var company_website_url = documentID('profile_company_website_url').value;
    var company_address = documentID('profile_company_address').value;
    var job_responsibility_details = documentID('profile_job_responsibility_details').value;
    var start_time_period = documentID('start_time_period').value;
    var work_currently_here = document.forms['add_work_experience'].elements['work_currently_here'].value;
    var end_time_period = documentID('end_time_period').value;
    var person_work_view_status = documentID('account_type').value;
//alert(start_time_period); alert(end_time_period);

    if (company_name == '') {
        documentID('company_error').innerHTML = "Company Name is Required";
        return false;
    } else {
        if (documentID('profile_company_validate').value == '1') {
            documentID('company_error').innerHTML = "No Special Carecter Allow Except ' , . or - ";
            return false;
        } else {
            documentID('company_error').innerHTML = "";
        }
    }
    if (designation == '') {
        documentID('designation_error').innerHTML = "Designation is Required";
        return false;
    } else {
        if (documentID('designation_validate').value == '1') {
            documentID('designation_error').innerHTML = "No Special Carecter Allow Except ' , . or - ";
            return false;
        } else {
            documentID('designation_error').innerHTML = "";
        }
    }

    if (company_website_url == '') {
        documentID('url_error').innerHTML = "Company Website Url is Required";
        return false;
    } else {
        if (documentID('url_validate').value == '1') {
            documentID('url_error').innerHTML = "Invalid URL";
            return false;
        } else {
            documentID('url_error').innerHTML = "";
        }
    }

    if (company_address == '') {
        documentID('address_error').innerHTML = "Company Address is Required";
        return false;
    } else {
        documentID('address_error').innerHTML = "";
    }
    if (job_responsibility_details == '') {
        documentID('responsibility_error').innerHTML = "Job Responsibility Details is Required";
        return false;
    } else {
        documentID('responsibility_error').innerHTML = "";
    }

    if (start_time_period == '') {
        documentID('start_date_error').innerHTML = "Start Date is Required";
        return false;
    } else {
        if (documentID('start_time_period_validate').value == '1') {
            documentID('start_date_error').innerHTML = "Enter date before today’s Date";
            return false;
        } else {
            documentID('start_date_error').innerHTML = "";
        }
    }

    if (work_currently_here == '') {
        documentID('current_work_error').innerHTML = "Current Work Status is Required";
        return false;
    } else {
        documentID('current_work_error').innerHTML = "";
    }

    if (work_currently_here == 2) {
        if (end_time_period == '') {
            documentID('end_date_error').innerHTML = "End Date is Required";
            return false;
        } else {
            if (documentID('job_end_date_validate').value == '1') {
                documentID('end_date_error').innerHTML = "Enter date before today and after start date";
                return false;
            } else {
                documentID('end_date_error').innerHTML = "";
            }
        }
    }

    if (person_work_view_status == '') {
        documentID('view_status_error').innerHTML = "Work View Status is Required";
        return false;
    } else {
        documentID('view_status_error').innerHTML = "";
    }

    var formdata = new FormData();
    formdata.append("company_name", company_name);
    formdata.append("designation", designation);
    formdata.append("company_website_url", company_website_url);
    formdata.append("company_address", company_address);
    formdata.append("job_responsibility_details", job_responsibility_details);
    formdata.append("job_start_date", start_time_period);
    formdata.append("work_currently_here", work_currently_here);
    formdata.append("job_end_date", end_time_period);
    formdata.append("person_work_view_status", person_work_view_status);
    workResponse.addEventListener("load", function () {
//        alert(xmlhttp.responseText);
        documentID('add_new_work_experience').style.display = 'none';
        documentID('add_work_experience_btn').style.display = 'block';
        documentID('work_experience_view').innerHTML = workResponse.responseText;
    }, false);
    workResponse.addEventListener("error", function () {
        alert("Upload Failed");
    }, false);
    workResponse.addEventListener("abort", function () {
        alert("Upload Aborted");
    }, false);
    workResponse.open("POST", url);
    workResponse.send(formdata);
    return true;
}

/*
 * @Function            : WorkStatusCheck
 * @Used IN             : viewEditWorkExperience
 * @Description         : Displays the input for work end date in admin section
 * @Developed By        : Unknown
 * @Start Date          : Unknown
 * @Comment Added By    : Md Mashqur Ul Alam [08-01-17]
 * @Parameter           : GivenText
 * @Return              : NULL
 * @Status              : Available       
 */
function WorkStatusCheck(GivenText) {
    var workEndDate = document.getElementById('workEndDate11');
    if (GivenText == 2) {
        workEndDate.setAttribute('style', 'display:block');
    } else {
        workEndDate.setAttribute('style', 'display:none');
    }
}


/*
 * @Function            : viewEditWorkExperience
 * @Used IN             : Profile work exp editing
 * @Description         : Loads the edit work experience form in admin section
 * @Developed By        : Unknown
 * @Start Date          : Unknown
 * @Comment Added By     : Md Mashqur Ul Alam [08-01-17]
 * @Parameter           : url, ID
 * @Return              : NULL
 * @Status              : Available       
 */

function viewEditWorkExperience(url, ID) {
    var xmlhttp = createXMLHTTP(xmlhttp);
    if (documentID('check_work_form_view')) {
        alert('already opn a form');
    } else {
        serverPage = url;
        xmlhttp.open("GET", serverPage);
        xmlhttp.onreadystatechange = function ()
        {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
            {
                documentID('work_info' + ID).innerHTML = xmlhttp.responseText;
                $('#datetimepicker2').datetimepicker({
                    viewMode: 'years',
                    format: 'YYYY-MM-DD'

                });
                var currently_work_status = documentID('hidden_work_currently_here').value;
                document.forms['edit_work_experience'].elements['work_currently_here'].value = currently_work_status;
                WorkStatusCheck(currently_work_status);
                $('#datetimepicker1').datetimepicker({
                    viewMode: 'years',
                    format: 'YYYY-MM-DD'

                });
                var work_view_status = documentID('hidden_person_work_view_status').value;
                document.forms['edit_work_experience'].elements['person_work_view_status'].value = work_view_status;
            }
        };
        xmlhttp.send(null);
    }
}


/*
 * @Function            : updateWorkExperiencs
 * @Used IN             : Profile work exp updating
 * @Description         : Updates work experience details
 * @Developed By        : Unknown
 * @Start Date          : Unknown
 * @Comment Added By    : Md Mashqur Ul Alam [08-01-17]
 * @Parameter           : url, ID
 * @Return              : NULL
 * @Status              : Available       
 */
function updateWorkExperiencs(url, ID) {
    var workResponse1;
    workResponse1 = createXMLHTTP(workResponse1);
    var person_id = documentID('person_id').value;
    var company_name = documentID('company_name').value;
    var designation = documentID('designation').value;
    var company_website_url = documentID('company_website_url').value;
    var company_address = documentID('company_address').value;
    var job_responsibility_details = documentID('job_responsibility_details').value;
    var start_time_period = document.forms['edit_work_experience'].elements['job_start_date'].value;
    var work_currently_here = document.forms['edit_work_experience'].elements['work_currently_here'].value;
    var end_time_period = document.forms['edit_work_experience'].elements['job_end_date'].value;
    var person_work_view_status = documentID('account_type').value;
//alert(company_name);
    var validName = /^[0-9a-zA-Z\. \ ' \-']+$/;
    var current_date = getCurrentDate();
    if (company_name == '') {
        documentID('company_error1').innerHTML = "Company Name is Required";
        return false;
    } else {
        if (company_name.match(validName)) {
            documentID('company_error1').innerHTML = "";
        } else {
            documentID('company_error1').innerHTML = "No Special Carecter Allow Except ' , . or - '";
            return false;
        }
    }

    if (designation == '') {
        documentID('designation_error1').innerHTML = "Designation is Required";
        return false;
    } else {
        if (company_name.match(validName)) {
            documentID('designation_error1').innerHTML = "";
        } else {
            documentID('designation_error1').innerHTML = "No Special Carecter Allow Except ' , . or - '";
            return false;
        }
    }

    if (company_website_url == '') {
        documentID('url_error1').innerHTML = "Company Website Url is Required";
        return false;
    } else {
        if (company_name.match(validName)) {
            documentID('url_error1').innerHTML = "";
        } else {
            documentID('url_error1').innerHTML = "Invalud url";
            return false;
        }
    }

    if (company_address == '') {
        documentID('address_error1').innerHTML = "Company Address is Required";
        return false;
    } else {
        documentID('address_error1').innerHTML = "";
    }

    if (job_responsibility_details == '') {
        documentID('responsibility_error1').innerHTML = "Job Responsibility Details is Required";
        return false;
    } else {
        documentID('responsibility_error1').innerHTML = "";
    }

    if (start_time_period == '') {
        documentID('start_date_error1').innerHTML = "Start Date is Required";
        return false;
    } else {
        if (current_date > start_time_period) {
            documentID('start_date_error1').innerHTML = '';
        } else {
            documentID('start_date_error1').innerHTML = "Enter date before today’s Date";
            return false;
        }
    }
    if (work_currently_here == '') {
        documentID('current_work_error1').innerHTML = "Current Work Status is Required";
        return false;
    } else {
        documentID('current_work_error1').innerHTML = "";
    }
    if (work_currently_here == 2) {
        if (end_time_period == '') {
            documentID('end_date_error1').innerHTML = "End Date is Required";
            return false;
        } else {
            if (start_time_period < end_time_period) {
                documentID('end_date_error1').innerHTML = '';
            } else {
                documentID('end_date_error1').innerHTML = "Enter date before today and start date";
                return false;
            }
        }
    }
    if (person_work_view_status == '') {
        documentID('view_status_error1').innerHTML = "Work View Status is Required";
        return false;
    } else {
        documentID('view_status_error1').innerHTML = "";
    }

    var formdata = new FormData();
    formdata.append("person_id", person_id);
    formdata.append("company_name", company_name);
    formdata.append("designation", designation);
    formdata.append("company_website_url", company_website_url);
    formdata.append("company_address", company_address);
    formdata.append("job_responsibility_details", job_responsibility_details);
    formdata.append("job_start_date", start_time_period);
    formdata.append("work_currently_here", work_currently_here);
    formdata.append("job_end_date", end_time_period);
    formdata.append("person_work_view_status", person_work_view_status);
    workResponse1.addEventListener("load", function () {
//                                        alert(xmlhttp.responseText);
        documentID('work_info' + ID).innerHTML = workResponse1.responseText;
    }, false);
    workResponse1.addEventListener("error", function () {
        alert("Upload Failed");
    }, false);
    workResponse1.addEventListener("abort", function () {
        alert("Upload Aborted");
    }, false);
    workResponse1.open("POST", url);
    workResponse1.send(formdata);
    return true;
}

function cancelUpdateWorkExperience(url, ID) {
    var workResponse2;
    workResponse2 = createXMLHTTP(workResponse2);
    serverPage = url + '/' + ID;
    workResponse2.open("GET", serverPage);
    workResponse2.onreadystatechange = function ()
    {
        if (workResponse2.readyState === 4 && workResponse2.status === 200)
        {
            documentID('work_info' + ID).innerHTML = workResponse2.responseText;
        }
    };
    workResponse2.send(null);
}

//-------------------------- End Work Experience----------------------------------------


//-------------------------- Start Person Language----------------------------------------

/*
 * @Used In             : Profile Language section in admin
 * @Description         : Displays add language form in admin section
 * @Developed By        : Unknown
 * @Updated By          : Md Mashqur Ul Alam [15-01-17]
 * @Parameter           : url
 * @Return              : Null 
 */
function addLanguageForm(url) {
    var xmlhttp = createXMLHTTP(xmlhttp);
    var serverPage = url;
    xmlhttp.open("GET", serverPage);
    xmlhttp.onreadystatechange = function ()
    {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
            documentID('add_language_form').setAttribute('style', 'display:block');
            documentID('add_language_form').innerHTML = xmlhttp.responseText;
            documentID('add_language_btn').setAttribute('style', 'display:none');
            $('a[id^="editLangBtn"]').attr('style', 'pointer-events: none');
        }
    }
    xmlhttp.send(null);
}

/*
 * @Description         : Cancel the add language form                        
 * @Developed By        : Md Mashqur Ul Alam
 * @Start DateTime      : 15-01-17      
 */
$(document).on('click', 'div[id=addLangCancel]', function () {
    $('#add_language_form').hide();
    $('a[id^="editLangBtn"]').removeAttr('style');
    $('#add_language_btn').show();
});
/*
 * @Function            : cancelEditLang
 * @Used IN             : Language section of Profile
 * @Description         : Cancel the edit language form
 * @Developed By        : Md Mashqur Ul Alam [16-01-17]
 * @Parameter           : profileUrl
 * @Return              : Null
 * @Status              : Available       
 */
function cancelEditLang(profileUrl) {
    var url = $('#baseUrl').val() + 'super_admin_profile/cancel_edit_language/' + profileUrl;
    $.get(url, function (data) {
        $('#edit_language_form').empty();
        $('#edit_language_form').hide();
        $('#view_language').show();
        $('#view_language').html(data);
        $('#add_language_btn').show();
    });
}

function addLanguage(url) {
    var xmlhttp = false;
    try {
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (E) {
            xmlhttp = false;
        }
    }
    if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
        xmlhttp = new XMLHttpRequest();
    }

    var person_language = documentID('person_language').value;
    var person_language_proficiency = documentID('person_language_proficiency').value;
    if (person_language == '') {
        documentID('language_error').innerHTML = "Language Name is Required";
        return false;
    } else {
        documentID('language_error').innerHTML = "";
    }
    if (person_language_proficiency == '') {
        documentID('proficiency_error').innerHTML = "Language Proficiency is Required";
        return false;
    } else {
        documentID('proficiency_error').innerHTML = "";
    }

    var formdata = new FormData();
    formdata.append("person_language", person_language);
    formdata.append("person_language_proficiency", person_language_proficiency);
    xmlhttp.addEventListener("load", function () {
//                        alert(xmlhttp.responseText);
        documentID('view_language').innerHTML = xmlhttp.responseText;
        documentID('add_language_btn').setAttribute('style', 'display:block');
        documentID('add_language_form').setAttribute('style', 'display:none');
    }, false);
    xmlhttp.addEventListener("error", function () {
        alert("Upload Failed");
    }, false);
    xmlhttp.addEventListener("abort", function () {
        alert("Upload Aborted");
    }, false);
    xmlhttp.open("POST", url);
    xmlhttp.send(formdata);
    return true;
}

function editLanguage(url) {
    var xmlhttp = createXMLHTTP(xmlhttp);
    var serverPage = url;
    xmlhttp.open("GET", serverPage);
    //                alert(serverPage);
    xmlhttp.onreadystatechange = function ()
    {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
            documentID('view_language').setAttribute('style', 'display:none');
            documentID('edit_language_form').setAttribute('style', 'display:block');
            documentID('edit_language_form').innerHTML = xmlhttp.responseText;
            var language_proficiency = documentID('language_proficiency').value;
//            alert(language_proficiency);
            documentID('person_language_proficiency').value = language_proficiency;
            documentID('add_language_btn').setAttribute('style', 'display:none');
//                          document.forms['edit_language_form'].elements['person_language_proficiency'].value = 1';

        }
    }
    xmlhttp.send(null);
}

function updateLanguage(url) {
    var xmlhttp = false;
    try {
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (E) {
            xmlhttp = false;
        }
    }
    if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
        xmlhttp = new XMLHttpRequest();
    }

    var person_language = document.forms['edit_language_form'].elements['person_language'].value;
    var person_language_proficiency = document.forms['edit_language_form'].elements['person_language_proficiency'].value;
    if (person_language == '') {
        documentID('language_error').innerHTML = "Language Name is Required";
        return false;
    } else {
        documentID('language_error').innerHTML = "";
    }
    if (person_language_proficiency == '') {
        documentID('proficiency_error').innerHTML = "Language Proficiency is Required";
        return false;
    } else {
        documentID('proficiency_error').innerHTML = "";
    }

    var formdata = new FormData();
    formdata.append("person_language", person_language);
    formdata.append("person_language_proficiency", person_language_proficiency);
    xmlhttp.addEventListener("load", function () {
//                        alert(xmlhttp.responseText);
        documentID('view_language').setAttribute('style', 'display:block');
        documentID('view_language').innerHTML = xmlhttp.responseText;
        documentID('add_language_btn').setAttribute('style', 'display:block');
        documentID('add_language_form').setAttribute('style', 'display:none');
        documentID('edit_language_form').setAttribute('style', 'display:none');
    }, false);
    xmlhttp.addEventListener("error", function () {
        alert("Upload Failed");
    }, false);
    xmlhttp.addEventListener("abort", function () {
        alert("Upload Aborted");
    }, false);
    xmlhttp.open("POST", url);
    xmlhttp.send(formdata);
    return true;
}

/*
 * @Description         : Delete the language detail from profile
 * @Developed By        : Md Mahqur Ul Alam 
 * @Start Date Time     : 15-01-17
 */

$(document).on('click', 'a[id^="deleteLang"]', function () {
    var langDetail = this.id.replace('deleteLang', '');
    $("#deleteLangModal" + langDetail).modal('show');
}).on('click', 'button[id^="modalNoButtonLang"]', function () {
    var langDetail = this.id.replace('modalNoButtonLang', '');
    $("#deleteLangModal" + langDetail).modal('hide');
}).on('click', 'button[id^="modalYesButtonLang"]', function () {
    var langDetail = this.id.replace('modalYesButtonLang', '');
    deleteLanguage(langDetail);
});
/*
 * @Function            : deleteLanguage
 * @Used IN             : Language section of Profile
 * @Description         : Deletes the selected language details
 * @Developed By        : Md Mashqur Ul Alam [16-01-17]
 * @Parameter           : langDetail
 * @Return              : Null
 * @Status              : Available       
 */
function deleteLanguage(langDetail) {
    var url = $('#baseUrl').val() + 'super_admin_profile/delete_language_by_language_id';
    var profileUrl = $('#profileUrl').val();
    $.post(url,
            {
                person_language_id: langDetail,
                profile_url: profileUrl
            },
            function (data) {
                $('#view_language').html(data);
            });
}

//-------------------------- End Person Language----------------------------------------



//-------------------------- Start Self Assesment----------------------------------------

/*
 * @Function            : UpdatePersonAssessmentForm
 * @Used IN             : Profile Personall assesment in skill section updating
 * @Description         : Loads form for updating personal assessment
 * @Developed By        : Unknown
 * @Start Date          : Unknown
 * @Comment Added By    : Md Mashqur Ul Alam [09-01-17]
 * @Parameter           : url
 * @Return              : NULL
 * @Status              : Available       
 */
function UpdatePersonAssessmentForm(url) {
    var assesmentSkillResponse;
    assesmentSkillResponse = createXMLHTTP(assesmentSkillResponse);
    var serverPage = url;
    assesmentSkillResponse.open("GET", serverPage);
    assesmentSkillResponse.onreadystatechange = function ()
    {
        if (assesmentSkillResponse.readyState === 4 && assesmentSkillResponse.status === 200)
        {
            documentID('self_asssesment').innerHTML = assesmentSkillResponse.responseText;
            $('select#tokenize_placeholder').tokenize({placeholder: ""});
        }
    };
    assesmentSkillResponse.send(null);
}

function updatePersonAssessment(url) {
//                        alert(url);
    var xmlhttp = false;
    try {
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (E) {
            xmlhttp = false;
        }
    }
    if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
        xmlhttp = new XMLHttpRequest();
    }

    var self_assesment = documentID('to_address').value;
    if (self_assesment == '') {
        documentID('assesment_error').innerHTML = 'Self Assessment is required';
        return false;
    } else {
        documentID('assesment_error').innerHTML = '';
    }

    var formdata = new FormData();
    formdata.append("self_assesment_name", self_assesment);
    xmlhttp.addEventListener("load", function () {
//                                        alert(xmlhttp.responseText);
        documentID('self_asssesment').innerHTML = xmlhttp.responseText;
    }, false);
    xmlhttp.addEventListener("error", function () {
        alert("Upload Failed");
    }, false);
    xmlhttp.addEventListener("abort", function () {
        alert("Upload Aborted");
    }, false);
    xmlhttp.open("POST", url);
    xmlhttp.send(formdata);
    return true;
}

/*
 * @Function            : cancelSelfAssessment
 * @Used IN             : admin profile edit self assesssment
 * @Description         : cancel the person self assesment edit form
 * @Developed By        : Md Mashqur Ul Alam
 * @Start Date          : 10-01-17
 * @Parameter           : url
 * @Return              : NULL
 * @Status              : Available    
 */

function cancelSelfAssessment(url) {
    $.get(url, function (data) {
        $('#self_asssesment').html(data);
    });
}



//-------------------------- END Self Assesment----------------------------------------


//------------------------Strat Interest Field---------------------------------

/*
 * @Description         : Reloads the view when Update Interest in Profile
 *                        cancel button clicked.
 * @Developed By        : Md Mashqur Ul Alam
 * @Start DateTime      : 07-01-17    
 */

$(document).on('click', '#cancelUpdateinterest', function () {
    var baseUrl = $('#baseUrl').val();
    var profileUrl = $('#profileUrl').val();
    var url = baseUrl + 'super_admin_profile/cancel_update_interest_field';
    $.post(url, {profile_url: profileUrl}, function (data) {
        documentID('view_interest').innerHTML = data;
    });
});
/*
 * @Function            : editPersonInterestForm 
 * @Used IN             : admin profile edit
 * @Description         : loads the form for editing interest field
 * @Developed By        : Unknown
 * @Updated By          : Md Mashqur Ul Alam
 * @Update DateTime     : 07-01-17     
 * @Parameter           : url
 * @Status              : Available       
 */
function editPersonInterestForm(url) {
    var xmlhttp;
    xmlhttp = createXMLHTTP(xmlhttp);
    var serverPage = url;
    xmlhttp.open("GET", serverPage);
    xmlhttp.onreadystatechange = function ()
    {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
//                                alert(xmlhttp.responseText);
            documentID('view_interest').innerHTML = xmlhttp.responseText;
            $('select#tokenize_placeholder').tokenize({placeholder: ""});
        }
    }
    xmlhttp.send(null);
}


/*
 * @Function            : updatePersonInterest 
 * @Used IN             : admin profile edit
 * @Description         : Updates the person interests
 * @Developed By        : Unknown
 * @Comment Added By    : Md Mashqur Ul Alam
 * @Parameter           : url
 * @Status              : Available       
 */
function updatePersonInterest(url) {
//    alert(url);
    var xmlhttp = false;
    try {
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (E) {
            xmlhttp = false;
        }
    }
    if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
        xmlhttp = new XMLHttpRequest();
    }

    var interest_field = documentID('to_address').value;
//    var interest_field_test = documentID('tokenize_placeholder_interest').value
//    alert(interest_field_test);
    if (interest_field == '') {
        documentID('interest_error').innerHTML = "Interest Field is required";
        return false;
    } else {
        documentID('interest_error').innerHTML = "";
    }


    var formdata = new FormData();
    formdata.append("field_of_interest_name", interest_field);
    xmlhttp.addEventListener("load", function () {
//                                        alert(xmlhttp.responseText);
        documentID('view_interest').innerHTML = xmlhttp.responseText;
    }, false);
    xmlhttp.addEventListener("error", function () {
        alert("Upload Failed");
    }, false);
    xmlhttp.addEventListener("abort", function () {
        alert("Upload Aborted");
    }, false);
    xmlhttp.open("POST", url);
    xmlhttp.send(formdata);
    return true;
}

//------------------------End Interest Field---------------------------------




//------------------------Start Personal Information------------------------------

/*
 * @Description         : Reloads the view when Update personal information
 *                        cancel button clicked.
 * @Developed By        : Md Mashqur Ul Alam
 * @Start DateTime      : 07-01-17      
 */

$(document).on('click', '#cancelUpdatePersonalInfo', function () {
    var baseUrl = $('#baseUrl').val();
    var profileUrl = $('#profileUrl').val();
    var url = baseUrl + 'super_admin_profile/cancel_update_person_info';
    $.post(url, {profile_url: profileUrl}, function (data) {
        documentID('personal_information').innerHTML = data;
    });
});
/*
 * @Function            : editPersonDetailForm 
 * @Used IN             : admin profile edit
 * @Description         : loads the form for editing person detail
 * @Developed By        : Unknown
 * @Updated By          : Md Mashqur Ul Alam
 * @Update DateTime     : 07-01-17     
 * @Parameter           : url
 * @Status              : Available       
 */

function editPersonDetailForm(url) {
    var xmlhttp = createXMLHTTP(xmlhttp);
    var serverPage = url;
    xmlhttp.open("GET", serverPage);
    xmlhttp.onreadystatechange = function ()
    {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
//                                alert(xmlhttp.responseText);
            documentID('personal_information').innerHTML = xmlhttp.responseText;
            var person_country = documentID('person_country_hidden').value;
            var person_city = documentID('person_city_hidden').value;
            var person_gender = documentID('person_gender_hidden').value;
            populateCountries("person_country", "person_city");
            document.forms['edit_person_detail_info'].elements['person_country'].value = person_country;
            populateStates('person_country', 'person_city');
            document.forms['edit_person_detail_info'].elements['person_city'].value = person_city;
            document.forms['edit_person_detail_info'].elements['person_gender'].value = person_gender;
            $('#datetimepicker2').datetimepicker({
                viewMode: 'years',
                format: 'YYYY-MM-DD'

            });
        }
    }
    xmlhttp.send(null);
}

function updatePersonInformation(url) {
    var xmlhttp = false;
    try {
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (E) {
            xmlhttp = false;
        }
    }
    if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
        xmlhttp = new XMLHttpRequest();
    }

    var person_email = document.forms['edit_person_detail_info'].elements['person_email'].value;
    var person_country_code = document.forms['edit_person_detail_info'].elements['country_code'].value;
    var person_contact_number = document.forms['edit_person_detail_info'].elements['person_contact_number'].value;
    var person_country = documentID('person_country').value;
    var person_city = document.forms['edit_person_detail_info'].elements['person_city'].value;
    var person_address = document.forms['edit_person_detail_info'].elements['person_address'].value;
    var person_gender = document.forms['edit_person_detail_info'].elements['person_gender'].value;
    var person_birthday = document.forms['edit_person_detail_info'].elements['person_birthday'].value;
//alert(person_country_code);
    if (person_email == '') {
        documentID('email_error').innerHTML = "Person Email is required";
        return false;
    } else {
        documentID('email_error').innerHTML = "";
    }

    if (person_contact_number == '') {
        documentID('contact_error').innerHTML = "Person Contact Number is required";
        return false;
    } else {
        documentID('contact_error').innerHTML = "";
    }

    if (person_country == '') {
        documentID('country_error').innerHTML = "Person Country is required";
        return false;
    } else {
        documentID('country_error').innerHTML = "";
    }

    if (person_city == '') {
        documentID('city_error').innerHTML = "Person City is required";
        return false;
    } else {
        documentID('city_error').innerHTML = "";
    }

    if (person_address == '') {
        documentID('address_error').innerHTML = "Person Address is required";
        return false;
    } else {
        documentID('address_error').innerHTML = "";
    }

    if (person_gender == '') {
        documentID('gender_error').innerHTML = "Person Gender Number is required";
        return false;
    } else {
        documentID('gender_error').innerHTML = "";
    }

    if (person_birthday == '') {
        documentID('birthday_error').innerHTML = "Person Birthday Number is required";
        return false;
    } else {
        documentID('birthday_error').innerHTML = "";
    }

//

    var formdata = new FormData();
    formdata.append("person_email", person_email);
    formdata.append("person_country_code", person_country_code);
    formdata.append("person_contact_number", person_contact_number);
    formdata.append("person_country", person_country);
    formdata.append("person_city", person_city);
    formdata.append("person_address", person_address);
    formdata.append("person_gender", person_gender);
    formdata.append("person_birthday", person_birthday);
    xmlhttp.addEventListener("load", function () {
        //alert(xmlhttp.responseText);
        documentID('personal_information').innerHTML = xmlhttp.responseText;
//                            documentID('add_education_form').setAttribute('style', 'display:none');
    }, false);
    xmlhttp.addEventListener("error", function () {
        alert("Upload Failed");
    }, false);
    xmlhttp.addEventListener("abort", function () {
        alert("Upload Aborted");
    }, false);
    xmlhttp.open("POST", url);
    xmlhttp.send(formdata);
    return true;
}

function checkEmail(newEmail, oldEmail, url) {
    if (newEmail == oldEmail) {
        documentID('email_exist_error').innerHTML = '';
    } else {
        reg_email = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        if (newEmail.match(reg_email)) {
            serverPage = url + newEmail;
            xmlhttp.open("GET", serverPage);
            xmlhttp.onreadystatechange = function ()
            {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
                {
//                            alert(xmlhttp.responseText);
                    if (xmlhttp.responseText == 1) {
                        documentID('email_exist_error').innerHTML = "Email Address Exists";
                        var btn = documentID("update_button");
                        btn.disabled = true;
                        btn.setAttribute('style', 'background-color:green');
                    } else {
                        documentID('email_exist_error').innerHTML = '';
                        documentID("update_button").disabled = false;
                    }
                }
            }
            xmlhttp.send(null);
        } else {
            documentID('email_exist_error').innerHTML = "Invalid Email Address";
            var btn = documentID("update_button");
            btn.disabled = true;
            btn.setAttribute('style', 'background-color:green');
        }
    }
}

function checkCurrentDate(date) {
    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth() + 1; //January is 0!
    var yyyy = today.getFullYear();
    if (dd < 10) {
        dd = '0' + dd;
    }
    if (mm < 10) {
        mm = '0' + mm;
    }
    var current_date = yyyy + '-' + mm + '-' + dd;
    if (current_date > date) {
        documentID('birthday_error').innerHTML = '';
        documentID("update_button").disabled = false;
    } else {
        documentID('birthday_error').innerHTML = "Can not Enter date after Today's Date";
        var btn = documentID("update_button");
        btn.disabled = true;
        btn.setAttribute('style', 'background-color:green');
    }
}

function checkAction(url, ID) {
    swal({
        title: "",
        text: "Are you sure you want to Change this Status?",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: '#DD6B55',
        confirmButtonText: 'Yes',
        cancelButtonText: "No",
        closeOnConfirm: true,
        closeOnCancel: true
    },
            function (isConfirm) {
                if (isConfirm) {
                    serverPage = url;
                    xmlhttp.open("GET", serverPage);
                    //                alert(serverPage);
                    xmlhttp.onreadystatechange = function ()
                    {
                        if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
                        {
                            documentID(ID).innerHTML = xmlhttp.responseText;
                        }
                    }
                    xmlhttp.send(null);
                }
            });
}

//------------------------END Personal Information------------------------------


//----------------------- Other Function------------------------

function compareWorkDate(startdateID, endDateID, errorID) {
    var startDate = documentID(startdateID).value;
    var endDate = documentID(endDateID).value;
    var view_status = document.forms['edit_work_experience'].elements['work_currently_here'].value;
    if (startDate && endDate && view_status) {
        if (view_status == 2) {
            if (startDate < endDate) {
                documentID(errorID).innerHTML = '';
            } else {
                documentID(errorID).innerHTML = "Enter date before today and start date";
            }
        } else {
            documentID(errorID).innerHTML = '';
        }
    }
}

function compareAddWorkDate() {
    var startDate = documentID('start_time_period').value;
    var endDate = documentID('end_time_period').value;
    var view_status = document.forms['add_work_experience'].elements['work_currently_here'].value;
    if (startDate && endDate && view_status) {
        if (view_status == 2) {
            if (startDate < endDate) {
                documentID('end_date_error').innerHTML = '';
                documentID('job_end_date_validate').value = '';
            } else {
                documentID('end_date_error').innerHTML = "Enter date before today and after start date";
                documentID('job_end_date_validate').value = '1';
            }
        } else {
            documentID('end_date_error').innerHTML = '';
            documentID('job_end_date_validate').value = '';
        }
    }
}


function checkWorkCurrentDate(date, ID, btn) {
    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth() + 1; //January is 0!
    var yyyy = today.getFullYear();
    if (dd < 10) {
        dd = '0' + dd;
    }
    if (mm < 10) {
        mm = '0' + mm;
    }
    var current_date = yyyy + '-' + mm + '-' + dd;
    if (current_date > date) {
        documentID(ID).innerHTML = '';
        documentID(btn).disabled = false;
    } else {
        documentID(ID).innerHTML = "Can not Enter date after Today's Date";
        var btn = documentID(btn);
        btn.disabled = true;
        btn.setAttribute('style', 'background-color:green');
    }
}

function checkWorkStartCurrentDate(date) {
    var current_date = getCurrentDate();
    if (current_date > date) {
        documentID('start_date_error1').innerHTML = '';
    } else {
        documentID('start_date_error1').innerHTML = "Enter date before today’s Date";
    }
}

function checkAddWorkStartCurrentDate(date) {
    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth() + 1; //January is 0!
    var yyyy = today.getFullYear();
    if (dd < 10) {
        dd = '0' + dd;
    }
    if (mm < 10) {
        mm = '0' + mm;
    }
    var current_date = yyyy + '-' + mm + '-' + dd;
//    alert(current_date);

    if (current_date > date) {
        documentID('start_date_error').innerHTML = '';
        documentID('start_time_period_validate').value = '';
        compareAddWorkDate();
    } else {
        documentID('start_date_error').innerHTML = "Enter date before today’s Date";
        documentID('start_time_period_validate').value = '1';
    }
}

$(document).ready(function () {
    /*
     * @Description         : fires onkeyup event for searching and displaying
     *                        company name suggestion
     * @Developed By        : Md Mashqur Ul Alam
     * @Start DateTime      : 29-12-2016 04:23 PM      
     */
    $(document).on('keyup', 'input[id=profile_company_name]', function () {
        companyNameSuggestion(this.id);
    });
    $(document).on('keyup', 'input[id=company_name]', function () {
        companyNameSuggestion(this.id);
    });
});
/*
 * @Function            : companyNameSuggestion 
 * @Description         : search company name based on user input and displays 
 *                        suggestion
 * @Developed By        : Md Mashqur Ul Alam
 * @Start DateTime      : 02-01-2017
 * @Parameter           : fieldId [id of the input field]
 * @View                : None
 * @Redirect            : None
 * @Return              : NULL    
 * @Status              : Available       
 */

function companyNameSuggestion(fieldId) {
    var url = $('#baseUrl').val() + 'super_admin_profile/search_company_name';
    var searchParam = $('#' + fieldId).val().trim();
    if (searchParam) {
        $.post(url, {search_key: searchParam}, function (data) {
            var companyName = JSON.parse(data);
            var companyArray = [];
            for (var i in companyName) {
                companyArray.push(companyName[i].company_name);
            }
            $('#' + fieldId).autocomplete({
                source: companyArray
            });
        });
    }
}

/*
 -----------@@@RIPON@ Start Changed password field Part----------------------------------
 */

$(document).ready(function () {
    var currentPassStatus; // required for password validation
    var newPassStatus; // required for password validation
    var confPassStatus; // required  for password validation

    /*
     * @Description         : Checks current password match or not in profile
     *                        password change section     *                        
     * @Developed By        : Md Mashqur Ul Alam
     * @Start DateTime      : 29-12-2016 04:23 PM      
     */
    $(document).on('keyup', 'input[id=current_password]', function () {
        var currentPass = $('#current_password').val();
        if (currentPass) {
            var url = $('#baseUrl').val() + 'validate-current-password';
            $.post(url, {current_pass: currentPass}, function (data) {
                if (data === '2') {
                    $('#current_password_error').html('<p class="text-danger">This Password Does Not Match with Your Current Password</p>');
                    currentPassStatus = false;
                } else {
                    $('#current_password_error').empty();
                    currentPassStatus = true;
                }
            });
        }
    });
    /*
     * @Description         : validates new password                     
     * @Developed By        : Md Mashqur Ul Alam
     * @Start DateTime      : 29-12-2016 05:23 PM      
     */
    $(document).on('keyup', 'input[id=new_password]', function () {
        var newPassword = $('#new_password').val();
        if (newPassword.length < 6) {
            documentID('new_password_error').innerHTML = '<p class="text-danger">Minimum six Charecter</p>';
            newPassStatus === false;
        } else if (newPassword.length >= 6) {
            if (/\d/.test(newPassword) && /[a-z]/.test(newPassword)) {
                if (newPassword.length > 32) {
                    documentID('new_password_error').innerHTML = '<p class="text-danger">Password allowed length is 32 charecter</p>';
                    newPassStatus === false;
                } else {
                    $('#new_password_error').empty();
                    newPassStatus = true;
                }
            } else {
                documentID('new_password_error').innerHTML = '<p class="text-danger">Minimum one letter and One Number</p>';
                newPassStatus === false;
            }
        }
    });
    /*
     * @Description         : validates confirm password and update password                  
     * @Developed By        : Md Mashqur Ul Alam
     * @Start DateTime      : 29-12-2016 05:23 PM      
     */
    $(document).on('click', 'button[id=change_password_button]', function () {
        var newPass = $('#new_password').val();
        var confPass = $('#confirm_password').val();
        if (newPass !== confPass) {
            $('#confirm_password_error').html('<p class="text-danger">Confirm Password Did Not Match!</p>');
            confPassStatus = false;
        } else {
            $('#confirm_password_error').empty();
            confPassStatus = true;
        }
        if (currentPassStatus && newPassStatus && confPassStatus) {

            var currentPass = $('#current_password').val();
            var url = $('#baseUrl').val() + 'update-user-password';
            $.post(url,
                    {
                        current_pass: currentPass,
                        new_pass: newPass,
                        conf_pass: confPass
                    },
                    function (data) {
                        console.log(data);
                        $('#passwordChangeMessage').html(data);
                        $('#current_password').val('');
                        $('#new_password').val('');
                        $('#confirm_password').val('');
                    });
        }
    });
    /*
     * @Description         : Cancle the password change                  
     * @Developed By        : Md Mashqur Ul Alam
     * @Start DateTime      : 31-12-2016 05:23 PM      
     */

    $(document).on('click', 'button[id=cancel_password_button]', function () {
        window.location.reload();
    });
});
/*
 -----------@@@RIPON@ End Changed password field Part----------------------------------
 */

/**
 * @Function            : activequizresult 
 * @Description         : Change the status of quiz result to active
 * @Developed By        : Md Mashqur Ul Alam
 * @Start DateTime      : 18-01-17
 * @Parameter           : quiz_result_id
 * @Return              : NULL    
 * @Status              : Available       
 * */
function activequizresult(quiz_result_id) {
    var url = $('#baseUrl').val() + 'super_admin_profile/change_quiz_result_status';
    $.post(url,
            {
                quiz_result_id: quiz_result_id,
                status: 1
            },
            function (data) {
                console.log(data);
                var status = JSON.parse(data);
                if (status === 'ok') {
                    $('#activequizresult').hide();
                    $('#inactivquizresult').show();
                }
            });
}
/**
 * @Function            : inactivequizresult 
 * @Description         : Change the status of quiz result to inactive
 * @Developed By        : Md Mashqur Ul Alam
 * @Start DateTime      : 18-01-17
 * @Parameter           : quiz_result_id
 * @Return              : NULL    
 * @Status              : Available       
 * */
function inactivequizresult(quiz_result_id) {
    var url = $('#baseUrl').val() + 'super_admin_profile/change_quiz_result_status';
    $.post(url,
            {
                quiz_result_id: quiz_result_id,
                status: 0
            },
            function (data) {
                console.log(data);
                var status = JSON.parse(data);
                if (status === 'ok') {
                    $('#inactivquizresult').hide();
                    $('#activequizresult').show();
                }
            });
}

/**
 * @Function            : changeQuizResultPermission 
 * @Description         : Change quiz result permission status
 * @Developed By        : Md Mashqur Ul Alam
 * @Start DateTime      : 19-01-17
 * @Parameter           : quiz_result_id, status, action
 * @Return              : NULL    
 * @Status              : Available       
 * */
function changeQuizResultPermission(quiz_result_id, status, action) {

    var url = $('#baseUrl').val() + 'super_admin_profile/change_quiz_result_permission';
    swal({
        title: "",
        text: "Are you sure you want to " + action + " ?",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: '#DD6B55',
        confirmButtonText: "Yes",
        cancelButtonText: "No",
        closeOnConfirm: true,
        closeOnCancel: true},
            function (isConfirm) {
                if (isConfirm) {
                    $.post(url,
                            {
                                quiz_result_id: quiz_result_id,
                                permission: status
                            },
                            function (data) {
                                var conf = JSON.parse(data);
                                if (conf === 'ok') {
                                    updateQuizPermissionIcon(quiz_result_id, status);
                                }
                            });
                }
            });
}

/**
 * @Function            : updateQuizPermissionIcon 
 * @Description         : Change quiz permission icon after changing status
 * @Developed By        : Md Mashqur Ul Alam
 * @Start DateTime      : 19-01-17
 * @Parameter           : quiz_result_id, status
 * @Return              : NULL    
 * @Status              : Available       
 * */
function updateQuizPermissionIcon(quiz_result_id, status) {    
    switch (status) {
        case 1:
            $('#quizResultPermisionIcon').html(
                    "<a href=\"javascript:void(0)\" "
                    +"onclick=\"changeQuizResultPermission("+quiz_result_id+", 2, \'change quiz result permission\')\" >"                                  
                    +"<i class=\"fa fa-users\" title=\"Public\"></i>&nbsp;&nbsp;"
                    +"</a>"
                    );
            break;
        case 2:
            var baseUrl = $('#baseUrl').val();
            $('#quizResultPermisionIcon').html(
                    "<a href=\"javascript:void(0)\""
                    +"onclick=\"changeQuizResultPermission("+quiz_result_id+", 3, \'change quiz result permission\')\" >"                    
                    +"<img src=\""+baseUrl+"image/dashboard-tt-icon.png\" title=\"TT User\" alt=\"TT User\">&nbsp;&nbsp;"                                
                    +"</a>"
                    );
            break;
        case 3:
            $('#quizResultPermisionIcon').html(
                    "<a href=\"javascript:void(0)\" style=\"color: green\""
                    +"onclick=\"changeQuizResultPermission("+quiz_result_id+",4,\'change quiz result permission\')\">"
                    +"<i class=\"fa fa-link\" title=\"My Link\"></i>&nbsp;&nbsp;"                              
                    +"</a>"
                    );
            break;
        case 4:
            $('#quizResultPermisionIcon').html(
                    "<a href=\"javascript:void(0)\" style=\"color: red\""
                    +"onclick=\"changeQuizResultPermission("+quiz_result_id+",1,\'change quiz result permission\')\" >"                                  
                    +"<i class=\"fa fa-user\" title=\"Only Me\"></i>&nbsp;&nbsp;"
                    +"</a>"
                    );
            break;
            
    }
}

/**
 * @Function            : archieveQuizResult 
 * @Description         : change quiz result status to archive
 * @Developed By        : Md Mashqur Ul Alam
 * @Start DateTime      : 19-01-17
 * @Parameter           : quiz_result_id, status, action
 * @Return              : NULL    
 * @Status              : Available       
 * */
function archieveQuizResult(quiz_result_id, status, action) {

    var url = $('#baseUrl').val() + 'super_admin_profile/change_quiz_result_status';
    swal({
        title: "",
        text: "Are you sure you want to " + action + " ?",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: '#DD6B55',
        confirmButtonText: "Yes",
        cancelButtonText: "No",
        closeOnConfirm: true,
        closeOnCancel: true},
            function (isConfirm) {
                if (isConfirm) {
                    $.post(url,
                            {
                                quiz_result_id: quiz_result_id,
                                status: status
                            },
                            function (data) {
                                var conf = JSON.parse(data);
                                if (conf === 'ok') {
                                    updateQuizDeleteIcon(quiz_result_id, status);
                                }
                            });
                }
            });
}


/**
 * @Function            : updateQuizDeleteIcon 
 * @Description         : change quiz delete icon after changing status
 * @Developed By        : Md Mashqur Ul Alam
 * @Start DateTime      : 19-01-17
 * @Parameter           : quiz_result_id, status
 * @Return              : NULL    
 * @Status              : Available       
 * */

function updateQuizDeleteIcon(quiz_result_id, status){
    $('#quizResultDeleteIcon').html(
            "<a href=\"javascript:void(0)\">"
            +"<i class=\"fa fa-archive\" title=\"Archieved\"></i>"
            +"</a>"
            );
}


/**
 * @Function            : deleteQuizResult 
 * @Description         : permanently delets a quiz result
 * @Developed By        : Md Mashqur Ul Alam
 * @Start DateTime      : 19-01-17
 * @Parameter           : quiz_result_id, status
 * @Return              : NULL    
 * @Status              : Available       
 * */
function deleteQuizResult(quiz_result_id, action){
    var url = $('#baseUrl').val() + 'super_admin_profile/delete_quiz_result';
    swal({
        title: "",
        text: "Are you sure you want to " + action + " ?",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: '#DD6B55',
        confirmButtonText: "Yes",
        cancelButtonText: "No",
        closeOnConfirm: true,
        closeOnCancel: true},
            function (isConfirm) {
                if (isConfirm) {
                    $.post(url,
                            {
                                quiz_result_id: quiz_result_id                                
                            },
                            function (data) {
                                var conf = JSON.parse(data);
                                if (conf === 'ok') {
                                    $('#quizResultDeleteIcon').html(
                                            "<a href = \"javascript:void(0)\" style=\"color: red\">"
                                            +"<i class = \"fa fa-ban\" title = \"Deleted\"></i>"
                                            +"</a>"
                                            );
                                }
                            });
                }
            });
}