function calculatePositionToTop(start, end) {
    for(var i = start; i <= end; i++) {
        var topTop =  $("#section_" + i).offset().top;
        $("#topTop_" + i).val(parseInt(topTop));
    }
}

$(document).on("click", "#btnScrollTop", function(){
    goToByScrollBottom("#section_1");
    $("#sectionNo").val(1);
    $(this).addClass('hidden');
    $("#btnScrollDown").removeClass("hidden");
});

$(document).on("click", "#btnScrollDown", function(){
    var currentSlide = $("#sectionNo").val();
    var lastSlide = $("#totalSectionNo").val();

    if ( currentSlide != lastSlide) {
        var newSlide = parseInt(currentSlide) + 1;
        var elementId = "#section_" + newSlide;
        goToByScrollBottom(elementId);
        $("#sectionNo").val(newSlide);

        if (parseInt(newSlide) == parseInt(lastSlide)) {
            $(this).addClass('hidden');
            $("#btnScrollTop").removeClass("hidden");
        }

    }
});

$(document).ready(function(){
    $.validator.addMethod("RESTRICTIONS", function(value, element) {
        return this.optional(element) || /^([a-zA-Z0-9!?@£"\-'_.%&*()#/+-,:\s]*)$/i.test(value);
    }, "Due to security reasons, we do not accept semi-colons or brackets in our forms.");

    $.validator.addMethod("CHECKPSW", function(value, element) {
        return /[A-Z]/.test(value) // has a uppercase letter
            && /[a-z]/.test(value) // has a lowercase letter
            && /\d/.test(value) // has a digit
    }, "Password must contain at least one digit, one uppercase and one lowercase letter");


    //if you change this breakpoint in the style.css file (or _layout.scss if you use SASS), don't forget to update this value as well
    var MQL = 1170;

    //primary navigation slide-in effect
    if($(window).width() > MQL) {
        var headerHeight = $('.cd-header').height();
        $(window).on('scroll',
            {
                previousTop: 0
            },
            function () {
                var currentTop = $(window).scrollTop();
                //check if user is scrolling up
                if (currentTop < this.previousTop ) {
                    //if scrolling up...
                    if (currentTop > 0 && $('.cd-header').hasClass('is-fixed')) {
                        $('.cd-header').addClass('is-visible');
                    } else {
                        $('.cd-header').removeClass('is-visible is-fixed');
                    }
                } else {
                    //if scrolling down...
                    $('.cd-header').removeClass('is-visible');
                    if( currentTop > headerHeight && !$('.cd-header').hasClass('is-fixed')) $('.cd-header').addClass('is-fixed');
                }
                this.previousTop = currentTop;
            });
    }

    //open/close primary navigation
    $('.cd-primary-nav-trigger').on('click', function(){
        $('.cd-menu-icon').toggleClass('is-clicked');
        $('.cd-header').toggleClass('menu-is-open');

        //in firefox transitions break when parent overflow is changed, so we need to wait for the end of the trasition to give the body an overflow hidden
        if( $('.cd-primary-nav').hasClass('is-visible') ) {
            $('.cd-primary-nav').removeClass('is-visible').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend',function(){
                $('body').removeClass('overflow-hidden');
            });
        } else {
            $('.cd-primary-nav').addClass('is-visible').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend',function(){
                $('body').addClass('overflow-hidden');
            });
        }
    });

});

/**
 * Function to validate the login form
 */
function validateLoginForm(id) {
    $(id).validate({
        rules: {
            '_username': {
                required: true,
                email: true
            },
            '_password': {
                required: true
            }
        },
        messages: {
            '_username': {
                required: 'Email required',
                email: 'Enter a valid email address'
            },
            '_password': {
                required: 'Password required'
            }
        }
    });
}


/**
 * Function to validate the password request form
 */
function validateRequestForm(id) {
    $(id).validate({
        rules: {
            'username': {
                required: true,
                email: 5
            }
        },
        messages: {
            'username': {
                required: 'Email required',
                email: 'Enter a valid email address'
            }
        }
    });
}


/**
 * Function to validate the password reset form
 */
function validateResetForm(id) {
    $(id).validate({
        rules: {
            'fos_user_resetting_form[plainPassword][first]': {
                required: true,
                minlength: 5
            },
            'fos_user_resetting_form[plainPassword][second]': {
                required: true,
                equalTo: "#fos_user_resetting_form_plainPassword_first"
            }
        },
        messages: {
            'fos_user_resetting_form[plainPassword][first]': {
                required: 'Please enter your account\'s new password',
                minlength: 'Enter at least 5 characters'
            }
            ,
            'fos_user_resetting_form[plainPassword][second]': {
                required: 'Please confirm password',
                minlength: 'Enter at least 5 characters',
                equalTo: 'Passwords don\'t match'
            }
        }
    });
}

/** Function to validate the step 1 register form register form */
function validateRegisterStep1Form(id) {
    $(id).validate({
        rules: {
            'register[email]' : {
                required: true,
                email: true,
                remote: Routing.generate('app_web_register_check_email')
            },
            'register[plainPassword]': {
                required: true,
                minlength: 7,
                CHECKPSW: true,
                RESTRICTIONS: true
            }
        },
        messages: {
            'register[email]': {
                required: "Email address required",
                email: "Email address not valid",
                remote: "This email address already used"
            },
            'register[plainPassword]': {
                required: "Password required",
                minlength: "Password must be at least 7 characters"
            }

        }
    });
}

/**
 * Function to validate the register step 2 form
 */
function validateRegisterForm(id) {
    $(id).validate({
        rules: {
            'fos_user_registration_form[firstName]': {
                required: true,
                RESTRICTIONS: true
            },
            'fos_user_registration_form[lastName]': {
                required: true,
                RESTRICTIONS: true
            },
            'fos_user_registration_form[email]' : {
                required: true,
                email: true,
                remote: Routing.generate('app_web_user_check_email')
            },
            'fos_user_registration_form[plainPassword][first]': {
                required: true,
                minlength: 7,
                RESTRICTIONS: true,
                CHECKPSW: true
            },
            'fos_user_registration_form[plainPassword][second]': {
                required: true,
                equalTo: "#fos_user_registration_form_plainPassword_first"
            },
        },
        messages: {
            'fos_user_registration_form[firstName]': {
                required: "First name required"
            },
            'fos_user_registration_form[lastName]': {
                required: "Surname required"
            },
            'fos_user_registration_form[email]': {
                required: "Email address required",
                email: "Email address not valid",
                remote: "This email address already used"
            },
            'fos_user_registration_form[plainPassword][first]': {
                required: "Password required",
                minlength: "Password must be at least 7 characters"
            },
            'fos_user_registration_form[plainPassword][second]': {
                required: "Confirm password",
                equalTo: "Passwords do not match"
            },
            'fos_user_registration_form[address]': {
                required: "Address required"
            },
            'fos_user_registration_form[postcode]': {
                required: "Post code required"
            }

        }
    });
}

function toggleSubmenu(button) {
    var open  = button.attr('data-open');
    if ( open == 0 ) {
        $("#menuArrow").html('<i class="fa fa-angle-up" aria-hidden="true"></i>');
        button.attr('data-open', 1);
        $("#subMenu").show();
    } else {
        $("#menuArrow").html('<i class="fa fa-angle-down" aria-hidden="true"></i>');
        button.attr('data-open', 0);
        $("#subMenu").hide();
    }
}

function validateDoctorForm(id) {
    $(id).validate({
        rules: {
            'user[email]': {
                required: true,
                email: true,
                remote: Routing.generate('app_web_user_check_email')
            },
            'user[firstName]': {
                required: true
            },
            'user[lastName]' : {
                required: true
            },
            'user[address]': {
                required: true
            },
            'user[postcode]': {
                required: true
            },
            'user[phone]': {
                number: true
            },
            'user[country]' : {
                required: true
            },
            'user[expertise]' : {
                required: true
            },
            'user[description]' : {
                required: true
            },
            'user[education]' : {
                required: true
            },
            'user[languages]' : {
                required: true
            }
        },
        messages: {
            'user[firstName]': {
                required: "First name required"
            },
            'user[lastName]': {
                required: "Surname required"
            },
            'user[email]': {
                required: "Email address required",
                email: "Email address not valid",
                remote: "This email address already used"
            },
            'user[address]': {
                required: "Address required"
            },
            'user[postcode]': {
                required: "Post code required"
            },
            'user[country]': {
                required: "Select country"
            },
            'user[expertise]': {
                required: "Select expertise"
            },
            'user[description]': {
                required: "Description required"
            },
            'user[education]': {
                required: "Education required"
            }

        }
    });
}


/**
 * Function to init the avatar uploader
 * */
function initUserAvatarUploader( url ) {

    //pluploader function
    var uploader = new plupload.Uploader({
        runtimes: 'html5,flash,silverlight,html4',
        browse_button: 'pickfiles', // you can pass in id...
        container: document.getElementById('imageContainer'), // ... or DOM Element itself
        url: '' + url + '',
        flash_swf_url: "/bundles/appadmin/pluploader/Moxie.swf",
        silverlight_xap_url: "/bundles/appadmin/pluploader/Moxie.xap",
        multi_selection: false,

        filters: {
            max_file_size: '100mb',
            mime_types: [
                {title: "Image files", extensions: "jpg,gif,png,jpeg"}
            ]
        },

        init: {
            PostInit: function () {
                document.getElementById('filelist').innerHTML = '';
            },

            FilesAdded: function (up, files) {
                uploader.start();
                $("#filelist").html("");
                plupload.each(files, function (file) {
                    //document.getElementById('filelist').innerHTML += '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ') <b></b></div>';

                    file_html = '<div id="' + file.id + '" class="row">' +
                        '<div class="col-md-6">' + file.name + ' (' + plupload.formatSize(file.size) + ')</div>' +
                        '<div class="col-md-6">' +
                        '<div class="progress progress-striped active">' +
                        '<div class="progress-bar progress-bar-success"  role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%">' +
                        '<span class="sr-only">0% Complete</span>' +
                        '</div>' +
                        '</div>' +
                        '</div>' +
                        '</div>'
                    document.getElementById('filelist').innerHTML += file_html;

                });
//                while(up.files.length > 1) {
//                    up.removeFile(up.files[0]);
//                }
                up.refresh();
            },

            UploadProgress: function (up, file) {
                //document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
                var elem = $(document).find('#' + file.id + ' .progress-bar');
                $(elem).attr('aria-valuenow', file.percent);
                $(elem).css('width', file.percent + '%');
            },

            Error: function (up, err) {
                document.getElementById('filelist').innerHTML += "\nError #" + err.code + ": " + err.message;
            }
        }
    });
    uploader.init();
    //Show uploaded file
    uploader.bind('FileUploaded', function (up, file, info) {
        var obj = $.parseJSON(info.response);

        if ( obj.success == false ) {
            alert("File type not allowed!");
        } else {
            var html = '<img class="img-responsive" src="' + obj.file_path + '" border="0">';

            $("#imagesContainer").html(html);

            $('#' + file.id).remove();
        }


    });
}

function validatePatientForm(id) {
    $(id).validate({
        rules: {
            'user[email]': {
                required: true,
                email: true,
                remote: Routing.generate('app_web_user_check_email')
            },
            'user[firstName]': {
                required: true
            },
            'user[lastName]' : {
                required: true
            },
            'user[phone]': {
                number: true
            },
            'user[country]' : {
                required: true
            }
        },
        messages: {
            'user[firstName]': {
                required: "First name required"
            },
            'user[lastName]': {
                required: "Surname required"
            },
            'user[email]': {
                required: "Email address required",
                email: "Email address not valid",
                remote: "This email address already used"
            },
            'user[country]': {
                required: "Select country"
            }

        }
    });
}

function validateAppointmentForm(id) {
    $(id).validate({
        rules: {
            'appointment[patientName]': {
                required: true,
                RESTRICTIONS: true
            },
            'appointment[email]': {
                required: true,
                email: true
            },
            'appointment[location]' : {
                required: true,
                RESTRICTIONS: true
            },
            'appointment[appointmentDate]': {
                required: true
            },
            'appointment[start]': {
                required: true,
                RESTRICTIONS: true
            },
            'appointment[notes]': {
                RESTRICTIONS: true
            }
        },
        messages: {
            'appointment[patientName]': {
                required: "Patient name required"
            },
            'appointment[email]': {
                required: "Email address required",
                email: "Email address not valid"
            },
            'appointment[location]': {
                required: "Location required"
            },
            'appointment[appointmentDate]': {
                required: "Date required"
            },
            'appointment[start]': {
                required: "Time required"
            }

        }
    });
}

function validateAppointmentRequestForm(id) {
    $(id).validate({
        rules: {
            'appointment_request[appointmentDate]': {
                required: true
            },
            'appointment_request[start]': {
                required: true,
                RESTRICTIONS: true
            },
            'appointment_request[notes]': {
                RESTRICTIONS: true
            }
        },
        messages: {
            'appointment_request[location]': {
                required: "Location required"
            },
            'appointment_request[appointmentDate]': {
                required: "Date required"
            },
            'appointment_request[start]': {
                required: "Time required"
            }

        }
    });
}

function validateCancelForm(id){
    $(id).validate({
        rules: {
            'cancel_appointment[cancelReason]': {
                required: true
            }
        },
        messages: {
            'cancel_appointment[cancelReason]': {
                required: "Reason required"
            }

        }
    });
}

function validateNewsletterForm(id) {
    $(id).validate({
        rules: {
            'newsletter[email]': {
                required: true,
                email: true
            }
        },
        messages: {
            'newsletter[email]': {
                required: "Email required",
                email: "Invalid email address"
            }
        },

        submitHandler: function(form) {
            $.ajax({
                type: "POST",
                url: Routing.generate('app_web_newsletter_form'),
                data: $("#newsletterForm").serialize(),
                dataType: 'json',
                success: function (resp) {
                    var html = '';
                    if (resp.success) {
                        html = '<div class="alert alert-success">'+ resp.message +
                            '</div>';
                        $("#newsletterContainer").html(html);
                    } else {
                        html = '<div class="alert alert-danger">'+ resp.message +
                            '</div>';
                        $("#newsletterContainer").prepend(html);
                    }

                }
            });
        }

    });
}

/**
 * Function to scroll to anchor
 */
function goToByScroll(id){

    $('html,body').animate({scrollTop: $(id).offset().top }, 300);
}

function goToByScrollBottom(id){

    $('html,body').animate({scrollTop: $(id).offset().top }, 700);
}

function

goToByScrollSearch(id){

    $('html,body').animate({scrollTop: $(id).offset().top - 60 }, 300);
}

/**
 * Function to validate the contact form
 * */
function validateContactForm(id) {
    $(id).validate({
        rules: {
            'contact[name]': {
                required: true
            },
            'contact[email]' : {
                required: true,
                email: true
            },
            'contact[phone]': {
                required: true,
                number: true
            },
            'contact[message]': {
                required: true,
                minlength: 5
            }
        },
        messages: {
            'contact[name]': {
                required: "Name is required"
            },
            'contact[email]': {
                required: "Email address is required",
                email: "Email address not valid"
            },
            'contact[message]': {
                required: "Details are required",
                minlength: "Please enter more details"
            },
            'contact[phone]': {
                required: "Phone is required",
            }
        },

        submitHandler: function(form) {

            $("#errorMessage").remove();

            $.ajax({
                type: "POST",
                url: Routing.generate('app_web_contact_form'),
                data: $("#contactForm").serialize(),
                dataType: 'json',
                success: function (resp) {
                    var html = '';
                    if (resp.success) {
                        html = '<div class="alert alert-success">'+ resp.message +
                            '</div>';
                        $("#contactFormContainer").html(html);
                    } else {
                        html = '<div id="errorMessage" class="alert alert-danger">'+ resp.error +
                            '</div>';
                        $("#securityErrorDisplay").prepend(html);
                    }

                }
            });
        }

    });
}