﻿/// <reference path="jquery-ui-1.8rc1/js/jquery-1.4.1-vsdoc.js" />

$(document).ready(function () {
    /*$("#accordion").accordion("option", "active", 0);*/

    //edit profile - edit career history

    //bindDatePickers();

    function bindDatePickers() {
        $.datepicker.setDefaults(
        {
            numberOfMonths: 1,
            showAnim: '',
            changeMonth: true,
            changeYear: true,
            yearRange: '1900:2010',
            dateFormat: 'dd/mm/yy'
        });

        $('#StartDate').datepicker({
            maxDate: '+1',
            onSelect: setMinEndDate,
            onClose: validate
        });

        $('#CourseStartDate').datepicker({
            maxDate: '+1',
            onSelect: academicSetMinEndDate,
            onClose: academicValidate
        });

        $('#EndDate, #CourseEndDate').datepicker({
        });
    }

    //career history form
    //blank end date
    //$('#toPresent').live('click', function () {
    //    $('#EndDate').val('');
    //});

    //$('#EndDate').live('focus', function () {
    //    $('#toPresent').attr('checked', false);
    //});

    function validate() {
        $('#StartDate').valid();
        $('#StartDate').trigger('blur');
    }

    function setMinEndDate() {
        $('#EndDate').datepicker('destroy');
        $('#EndDate').datepicker({
            minDate: $("#StartDate").datepicker('getDate')
        });
    }

    //academic history form
    //blank end date

    function academicValidate() {
        $('#CourseStartDate').valid();
        $('#CourseStartDate').trigger('blur');
    }

    //function academicSetMinEndDate() {
    //    $('#CourseEndDate').datepicker('destroy');
    //    $('#CourseEndDate').datepicker({
    //        minDate: $("#CourseStartDate").datepicker('getDate')
    //    });
    //}


    //form submits


    $('#deleteEmailButton').live('click', function () {

        var newValue = $('input:radio[name=secondaryEmailAddress]:checked').val();
        var newValueParts = $('input:radio[name=secondaryEmailAddress]:checked').attr('id').split("-");

        if (newValue != '') {
            $.post("/MyKiltr/DeleteEmail", {
                email: newValue
            }, function (response) {
                if (response == "1") {
                    $('#emailSecondaryItem-' + newValueParts[1]).remove();
                    if ($('input:radio[name=secondaryEmailAddress]').val() == null) {
                        $('#savePrimaryEmailButton').remove();
                        $('#deleteEmailButton').remove();
                    }
                    notifyUser('Thank you this email(' + newValue + ') has been removed from your account.');
                    refreshProfileCompleteness();
                }
                else
                    notifyUser(response);
                return false;
            });
        } else {
            notifyUser('Please select a valid secondary email to delete.');
            return false;
        }
    });

    $('#addNewEmailButton').live('click', function () {
        var currentValue = $('#NewEmail').val();
        var currentEmailHtml = $('#emailAddressContainer').html();
        var currentListSize = $('#emailAddressContainer li').size();
        var newElementKey = (parseInt(currentListSize));
        if ($('#emailSettingsForm').valid()) {
            $.post("/MyKiltr/AddNewEmail", $('#emailSettingsForm').serialize(), function (response) {
                $('#emailSettingsSection').html(response);
                $('#NewEmail').val('Type your email address');
                refreshProfileCompleteness();
            });
        }
        return false;
    });

    $('#editBasicAccountSettingsButton').live('click', function () {
        if ($("#editBasicAccountSettingsForm").valid()) {
            $.post('/MyKiltr/EditBasicAccountSettings',
				$('#editBasicAccountSettingsForm').serialize(), function (response) {
				    $('#basicAccountSettingsFormContainer').html(response);
				    rebindValidators('#editBasicAccountSettingsForm');
				    $('#displayName').html($('#FirstName').val() + ' ' + $('#Surname').val());
				    $('#displayTitle').html($('#UserProfile_Title').val());
				    if ($('#editBasicAccountSettingsFormErrorCount').val() == "0") {
				        notifyUser('Your basic profile settings were updated successfully');
				        refreshProfileCompleteness();
				    } else {
				        notifyUser('There was a problem updating your profile settings');
				    }
				});
        }
        return false;
    });

    $('#savePrivacySettingsButton').live('click', function () {
        if ($("#editPrivacySettingsForm").valid()) {
            $.post('/MyKiltr/EditPrivacySettings',
				$('#editPrivacySettingsForm').serialize(), function (response) {
				    $('#privacySettingsFormContainer').html(response);
				    rebindValidators('#editPrivacySettingsForm');
				    notifyUser('Your privacy settings were updated successfully');
				});
        }
        return false;
    });

    $('#changePasswordFormSubmitButton').live('click', function () {
        if ($("#changePasswordForm").valid()) {
            $.post('/MyKiltr/ChangePassword',
                $('#changePasswordForm').serialize(),
                function (response) {
                    $('#changePasswordFormContainer').html(response);
                    rebindValidators('#changePasswordForm');
                    if ($('#changePasswordFormErrorCount').val() == "0") {
                        notifyUser('Your password was changed successfully');
                    }
                    else {
                        notifyUser('There was a problem changing your password');
                    }
                });
        }
        return false;
    });



    $('#editLocationSettingsButton').live('click', function () {
        if ($("#editLocationSettingsForm").valid()) {
            $.post('/MyKiltr/EditLocationSettings',
                $('#editLocationSettingsForm').serialize(),
                function (response) {
                    $('#editLocationSettingsFormContainer').html(response);
                    rebindValidators('#editLocationSettingsForm');

                    if ($('#CurrentDisplayLocation').val() == '') {
                        $('#displayLocation').html($('#BaseDisplayLocation').val());
                    }
                    else {
                        $('#displayLocation').html($('#CurrentDisplayLocation').val());
                    }

                    if ($('#editLocationSettingsFormErrorCount').val() == "0") {
                        bindLocationAutoComplete();
                        notifyUser('Your location settings were updated successfully');
                        refreshProfileCompleteness();
                    }
                    else {
                        bindLocationAutoComplete();
                        notifyUser('There was a problem updating your location settings');
                    }
                });
        }
        return false;
    });

    $('#submitJob').live('click', function () {
        if ($("#editCareerHistoryForm").valid()) {
            $('#saveJobFormLoader').show();
            $.post("/MyKiltr/AddPosition", $('#editCareerHistoryForm').serialize(), function (response) {
                $('#careerHistoryFormContainer').html(response);
                rebindValidators('#editCareerHistoryForm');

                //bindDatePickers();
                $('#saveJobFormLoader').hide();
                if ($('#careerHistoryFormErrorCount').val() == "0") {
                    $('#OrganisationName, #JobTitle, #EndDate, #StartDate').val('');
                    var form = $('#editCareerHistoryForm')
                    form.find('.dateValidation').val('ToPresent');
                    form.find('#fromYear').val('Year');
                    form.find('#fromMonth').val('Month');
                    form.find('#toYear').val('Year');
                    form.find('#toMonth').val('Month');
                    form.find('#toPresent').attr('checked', true);
                    form.find('#NoEndMonth').val(true);
                    form.find('#NoStartMonth').val(true);
                    //EnableValidation();
                    notifyUser('Thank you, your period of employment has been added');
                    refreshProfileCompleteness();
                }
                else {
                    notifyUser('There was a problem adding your period of employment');
                }

            });
        }
        return false;
    });

    $('.deleteJob').live('click', function () {
        var parentDiv = $(this).parent();
        var profileParts = parentDiv.attr('id').split('-');

        $('#saveJobFormLoader').show();
        $.post("/MyKiltr/DeletePosition", {
            positionId: profileParts[1]
        }, function (response) {
            $('#careerHistoryFormContainer').html(response);
            rebindValidators('#editCareerHistoryForm');
            //bindDatePickers();
            $('#saveJobFormLoader').hide();
            notifyUser('Thank you, period of employment has been deleted');
            refreshProfileCompleteness();
        });
        return false;
    });

    $('#submitQualification').live('click', function () {
        if ($("#editAcademicHistoryForm").valid()) {
            $('#saveQualificationFormLoader').show();
            $.post("/MyKiltr/AddQualification", $('#editAcademicHistoryForm').serialize(), function (response) {
                $('#academicHistoryFormContainer').html(response);
                rebindValidators('#editAcademicHistoryForm');

                //bindDatePickers();
                $('#saveQualificationFormLoader').hide();
                if ($('#academicHistoryFormErrorCount').val() == "0") {
                    $('#InstitutionName, #Subjects, #Level, #CourseStartDate, #CourseEndDate').val('');
                    var form = $('#editAcademicHistoryForm')
                    form.find('.dateValidation').val('ToPresent');
                    form.find('#fromYear').val('Year');
                    form.find('#fromMonth').val('Month');
                    form.find('#toYear').val('Year');
                    form.find('#toMonth').val('Month');
                    form.find('#AcademicToPresent').attr('checked', true);
                    form.find('#NoEndMonth').val(true);
                    form.find('#NoStartMonth').val(true);
                    //EnableValidation();
                    notifyUser('Thank you, your qualification has been added');
                    refreshProfileCompleteness();
                }
                else {
                    notifyUser('There was a problem adding your qualification');
                }

            });
        } else {
            //alert('not valid');
        }
        return false;
    });

    $('.deleteEducation').live('click', function () {
        var parentDiv = $(this).parent();
        var profileParts = parentDiv.attr('id').split('-');

        $('#saveQualificationFormLoader').show();
        $.post("/MyKiltr/DeleteQualification", {
            qualificationId: profileParts[1]
        }, function (response) {
            $('#academicHistoryFormContainer').html(response);
            rebindValidators('#editAcademicHistoryForm');

            //bindDatePickers();
            $('#saveQualificationFormLoader').hide();
            notifyUser('Thank you, your qualification has been deleted');
            refreshProfileCompleteness();
        });
        return false;
    });


    $('#editSkillsAndInterestsSubmitButton').live('click', function () {
        $('#inlineFormProgress').show();
        $.post("/MyKiltr/UpdateSkillsAndInterests", {
            skillIds: $('#skills').val(),
            interestIds: $('#interests').val()
        }, function (response) {
            $('#skillsAndInterestsFormContainer').html(response);
            $('#inlineFormProgress').hide();
            notifyUser('Thank you, your skills and interests have been updated');
            refreshProfileCompleteness();
        });
        return false;
    });

    //group forms
    $('#editGroupSubmitButton').live('click', function () {
        if ($("#editGroupForm").valid()) {
            $.post('/Group/Save',

            $('#editGroupForm').serialize(),
            function (response) {
                //where has response to go?
                $('#editGroupFormContainer').html(response);
                rebindValidators('#editGroupForm');

                if ($('#editGroupFormErrorCount').val() == "0") {

                    var index = window.location.href.indexOf("/Edit/"); //hack!

                    //don't want to redirect when editing a group
                    if (index == -1) {
                        notifyUser('Group was created successfully');
                        window.location.replace('/Group');
                    }
                    else {
                        notifyUser('Group was updated successfully');
                    }
                }
                else {
                    notifyUser('There was a problem updating the group');
                }
            });
        }
        return false;
    });


    //location drop down
    bindLocationAutoComplete();

}) /* end document ready*/



$('.location').live('click', function () {
    $(this).val("");
    ClearLocation($(this));
    ClearLocation($(this).parent().children('.delimitedlocation'));
});

function bindLocationAutoComplete() {
    $(".location").autocomplete({
        minLength: 3,
        source: function (request, response) {
            $.ajax({
                //url: 'http://ws.geonames.org/searchJSON',
                url: 'http://ws.geonames.net/searchJSON',
                dataType: "jsonp",
                minLength: 1,
                data: {
                    featureClass: "P",  //P = City
                    style: "full",
                    // If you need to filter on one or more specific country: use country: 'US', or two contries country:'SE,US'
                    //country: 'US',
                    maxRows: 10,
                    name_startsWith: request.term,
                    username: "kiltr"
                },
                success: function (data) {
                    if ($("#currentLocationFriendly").data("is_open") == true) {
                        $("#currentLocationFriendly").data("selecting",true);
                    }
                    response($.map(data.geonames, function (item) {
                        //map the data into a response that will be understood by the autocomplete widget
                        return {
                            //city, area, country
                            value: item.name + (item.adminName1 ? "," + item.adminName1 : "") + "," + item.countryName + "," + item.lat + "," + item.lng + "," + item.countryCode,
                            label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + " (" + item.countryName + ")"
                        }
                    }))
                }
            })
        },
        focus: function (event, ui) {
            $(event.target).val(ui.item.label);
            StoreFullLocation(ui.item.value, $(this));
            return false;
        },
        select: function (event, ui) {
            StoreFullLocation(ui.item.value, $(this));
            $(this).val(ui.item.label);
            $(this).data("selecting", true);
            return false;
        },
        open: function () {
            //$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
            $("body").css("padding-top", "-5px");
        },
        close: function () {
            if ($("#currentLocationFriendly").data("is_open") == true) {
                if ($(this).data("selecting") != true) {
                    $("#my-profile-card").hide();
                }
            }
            $(this).data("is_open", false);
            $(this).data("selecting", false);
        }
    });
}


function StoreFullLocation(fullLocation, locationTextBox) {
    //syncs what's in the baseLocation/currentLocation text boxes with their corresponding hidden fields
    //note the autocomplete widget seems to change dots in ids to underscores
    //var locationTextBoxId = locationTextBox.attr("id");
    //if (locationTextBoxId == "UserProfile_BaseLocation") {

    locationTextBox.parent().children('.delimitedlocation').val(fullLocation);
    //}
    //else if (locationTextBoxId == "currentLocation") {
    //  $('#fullCurrentLocation').val(fullLocation);
    //}
}

function ClearLocation(locationElementToClear) {
    locationElementToClear.val("");
}







//see http://stackoverflow.com/questions/4968575/dynamic-partial-view-jquery-form-hijack-client-validation-not-working
function rebindValidators(parentFormSelector) {
    $.validator.unobtrusive.parse(parentFormSelector);
    $(parentFormSelector).validate();
}

function refreshProfileCompleteness() {
    $.get("/MyKiltr/GetProfileCompleteness", function (response) {
        var profileDiv = $('.ProfilePi');
        profileDiv.html(response);
        profileDiv.attr('class', 'profileComplete' + response);
       

    });
}

// Changes a image's src
// 1) reloads the current image 
// OR 
// 2) changes the src completely
function reload_image(img_id, new_src) {
    img_id = img_id || '#default_image_id';
    img_id = jQuery(img_id);
    new_src = new_src || '';

    if (img_id) {
        old_src = jQuery(img_id).attr('src') || '';

        // No change in source we'll have to add random data to the url to refresh the image
        if (new_src == '' || old_src == new_src) {
            if (old_src.indexOf('?') == -1) {
                old_src += '?';
            } else {
                old_src += '&';
            }
            old_src += '__rnd=' + Math.random();
            img_id.attr('src', old_src);
        } else {
            img_id.attr('src', new_src);
        }
    }
}
