$(document).ready(function() {
    var fullWidth = $(window).width();
    var fullHeight = $(window).height();

    $(".rmItem:contains('My Programme')").addClass('menu-programme');
    setNaviItem();

    jQuery.fn.exists = function() { return jQuery(this).length > 0; }
    if ($('.social-box-M').exists()) resetSocialBox();
    if ($('.imageHolder').exists()) {

        $('.imageHolder').cycle({
            fx: "fade",
            pager: ".pagination"
        });

        $('.btn-pause').toggle(function() {
            $('.imageHolder').cycle('pause');
            $(this).addClass('btn-play'); return false;
        }, function() {
            $('.imageHolder').cycle('resume');
            $(this).removeClass('btn-play'); return false;
        });
    }

    if ($('.bg-calculate-scale').exists()) $('.bg-calculate-scale .cursor-now').css('left', getNowPosition($('.bg-calculate-scale .cursor-now input').val()) + 'px');

    $(window).resize(function() {
        fullWidth = $(window).width();
        fullHeight = $(window).height();
        $('.bg-overlay,.module-popup-bg').css({ 'width': fullWidth, 'height': fullHeight });
        $('.overlay,.module-popup-box').css({ 'left': (fullWidth - 760) / 2 > 0 ? (fullWidth - 760) / 2 : 0, 'top': (fullHeight - 510) / 2.5 > 0 ? (fullHeight - 510) / 2.5 : 0 });
        if ($('.social-box').exists()) floatSocialBox();
    });

    $('.btnFindUs, .btn-findoutmore').click(function() {
        window.open($('a.findUs').attr('href'));
        return false;
    });

    $('.btnBuyNow').click(function() {
        window.open($('a.buyNow').attr('href'));
        return false;
    });

    $('input.error').each(function() {
        $(this).focus(function() {
            $(this).next('label.error').css({ 'visibility': 'visible' });
        });
        $(this).blur(function() {
            $(this).next('label.error').css({ 'visibility': 'hidden' });
        });
    });

    //
    $('ul.date-buttons li input.active-button').parent().addClass('actived');
    
    // BEGIN: FUNCTIONS FOR TOP FORM SHOWING AND HIDING
    $('.btnSignUp, .btn-closeAll').click(function() {
        var $togglePanel = $('.topFormBox');
        if ($togglePanel.hasClass('expand')) {
            $togglePanel.slideUp().removeClass('expand');
            $('.btnSignUp').parent('ul').removeClass('actived');
        }
        else {
            $togglePanel.show().addClass('expand');
            $('.btnSignUp').parent('ul').addClass('actived');
        }
        //$('.btnSignUp').parent('ul').toggleClass('actived');
    });

    var objHide, objShow;
    $('.btn-existing').click(function() {
        $('#noneClient').hide();
        $('.customerOptions').slideUp('', function() { $('.exsisting').slideDown(); });
        objShow = ".customerOptions";
        objHide = ".exsisting";

    });

    $('.btn-instore').click(function() {

        $('#noneClient').hide();
        $('.customerOptions').slideUp('', function() { $('.instore').slideDown(); });
        objShow = ".customerOptions";
        objHide = ".instore";
    });

    $('.btn-online').click(function() {
        $('#noneClient').hide();
        $('.customerOptions').slideUp('', function() { $('.online').slideDown(); });
        objShow = ".customerOptions";
        objHide = ".online";
    });

    $('.findPw').click(function() {
        $('#noneClient').hide();
        $('.exsisting').slideUp('', function() { $('.forgottenPassword').slideDown(); });
        objShow = ".exsisting";
        objHide = ".forgottenPassword";
    });

    $('.btn-backToOption').click(function() {

        $(objHide).hide();
        $(objHide).slideUp();
        $(objShow).slideDown();
        objHide = objShow;
        objShow = ".customerOptions"; // for the close button in Forgot Password section
    });

    $('.btn-none').click(function() {
        $('#noneClient').slideDown();
    });

    $('.btn-hideThis').click(function() {
        $(this).parent().slideUp();
    });
    // BEGIN: input box onFocus
    $('input:text,textarea').each(function() {
        $(this).click(function() {
            $(this).addClass('onFocus');
        });

        $(this).blur(function() {
            $(this).removeClass('onFocus');
        });
    });

    // BEGIN: functions for popup
    $('.bg-overlay').css({ 'width': fullWidth, 'height': fullHeight });
    $('.overlay').css({ 'left': (fullWidth - 760) / 2 > 0 ? (fullWidth - 760) / 2 : 0, 'top': (fullHeight - 510) / 2.5 > 0 ? (fullHeight - 510) / 2.5 : 0 });

    $('.btn-popup-close').click(function() {
        $('.bg-overlay,.overlay').fadeOut();
        if (jQuery.browser.msie && parseInt(jQuery.browser.version) == 6 && $('.bg-overlay').css('display') == 'block') {
            $('html,body').css('overflow', 'auto');
        }
    });

    $('.popupContent').hide();

    $('.show-bmi-calculator').click(function() {
        showPopup('#popup-calculater');
        setHeight(heightValue);
        setWeight(weightValue);
        setHeightRange();
        setWeightRange();
        $('#calculate-result').hide();
        $('#calculate-form').show();
        $('.module-content-container #popup-calculater').css('background-position', 'left 270px');
    });

    $('.btn-set-goal').click(function() {
        showPopup('#SetGoal');
    });

    $('.module-popup input.btn-close').click(function() {
        $('.module-popup').fadeOut('', function() { $('.module-popup-box').css('opacity', '0'); });
    });


    //BEGIN: BMI setting up
    $('#calculate-result').hide();
    var heightValue = $('#height').val();
    var weightValue = $('#weight').val();

    setHeight(heightValue);
    setWeight(weightValue);

    $("select#weight").change(function() {
        weightValue = $(this).val();
        setWeight(weightValue);
        setWeightRange();
        $('.select-weight').parent().find(':input.text').each(function() {
            $(this).removeClass('error');
            $(this).next('label.error').hide();
        });
    });

    $('select#height').change(function() {
        heightValue = $(this).val();
        setHeight(heightValue);
        setHeightRange();
        $('.select-height').parent().find(':input.text').each(function() {
            $(this).removeClass('error');
            $(this).next('label.error').hide();
        });
    });

    $('.btn-clear').click(function() {
        setHeight(heightValue);
        setWeight(weightValue);
        $('.form-calculate').parent().find(':input.text').each(function() {
            $(this).removeClass('error');
            $(this).next('label.error').hide();
        });
    });

    $('.btn-recalculate').click(function() {
        setHeight(heightValue);
        setWeight(weightValue);
        $('#calculate-result').hide();
        $('#calculate-form').show();
        $('.module-content-container #popup-calculater').css('background-position', 'left 270px');
    });

    $('input.height1').keyup(function() {
        $('.value-height1').text($('input.height1').val());
    });

    $('input.height2').keyup(function() {
        $('.value-height2').text($('input.height2').val());
    });

    $('input.weight1').keyup(function() {
        $('.value-weight1').text($('input.weight1').val());
    });

    $('input.weight2').keyup(function() {
        $('.value-weight2').text($('input.weight2').val());
    });

    $('.form-calculate input.text').each(function() {
        var temptValueOriginal, temptValue;
        $(this).click(function() {
            temptValueOriginal = $(this).val();
            temptValue = temptValueOriginal.trim().toLowerCase();
            if (temptValue == "feet" || temptValue == "inches" || temptValue == "centimetres" || temptValue == "stone" || temptValue == "pounds" || temptValue == "kilograms")
                $(this).val('');
            if ($(this).hasClass('error')) $(this).next('label.error').css({ 'visibility': 'visible' });
        });
        $(this).blur(function() {
            if ($(this).val().trim() == '') { $(this).val(temptValueOriginal); }
            if ($(this).hasClass('error')) $(this).next('label.error').css({ 'visibility': 'hidden' });
        });
    });
    // Start: for Registeration form
    $("#genderSelect").change(onGenderSelectChange);
    $("#heightMetric").hide();
    $("#weightMetric").hide();
    $('#btn-editProfile').click(function() {
        if ($('#btn-editProfile').text() == 'View my profile') {
            $('.topFormBox').slideDown();
            $(".signUpForm").slideDown();
            $('#btn-editProfile').text('Close my profile');
        }
        else {
            $('.topFormBox').slideUp();
            $(".signUpForm").slideUp();
            $('#btn-editProfile').text('View my profile');
        }
    });

    // End: for Registeration form
});
// Start: for Registeration form
function buildFormToolTips() {
    $('span.inlinerror').hide();
    $("div.error input, div.error select, div.error textarea").focus(function() {
        if ($(this).parents("div").hasClass('error')) {
            $(this).closest('div.error').find('span.inlinerror').show();
            $(this).blur(function() {
                $(this).closest('div.error').find('span.inlinerror').hide();
            });
        }
    });
}

var gaTracking = {
    trackingEnabled: false
}
var trackCat = {
    link: 'Link',
    button: 'Button',
    radio: 'RadioButton'
}
var trackType = {
    click: 'Click'
}
function doTrack(cat, type, opt_label) {
    try {
        if (gaTracking.trackingEnabled && pageTracker) {
            pageTracker._trackEvent(cat, type, opt_label);
        }
        else {
            console.log("trackEvent: " + cat + ", " + type + ", " + opt_label);
        }
    }
    catch (err) {
    }
}

// End: for Registeration form
function resetSocialBox() {
    var spaceLeft = $('.leftColumn').offset().left;
    spaceLeft > 90 ? $('.social-box-M').addClass('social-box-V') : $('.social-box-M').addClass('social-box-H');
    $('.social-box-V .horizontal, .social-box-H .vertical').hide();
}

function floatSocialBox() {
    var spaceLeft = $('.leftColumn').offset().left;
    if (spaceLeft > 90) {
        $('.social-box-M').removeClass('social-box-H').addClass('social-box-V');
        $('.social-box-M .horizontal').slideUp();
        $('.social-box-M .vertical').slideDown();
        $('.social-box-V').fadeIn();
    }
    else {
        $('.social-box-M').removeClass('social-box-V').addClass('social-box-H');
        $('.social-box-M .vertical').slideUp();
        $('.social-box-M .horizontal').slideDown();
        $('.social-box-V').fadeOut();
    }
}
//set up Navigation
function setNaviItem() {

    var currentURL = String(window.location).toLowerCase().split('/');
    var currentItemSelected = currentURL[3].split('.')[0];
    
    $('#Navigation ul.rmHorizontal > li.rmItem').each(function() {
        var currentItem = $(this).find('span:first').text().toLowerCase().replace(' ', '');
        if ($.trim(currentItem).indexOf(currentItemSelected) >= 0) { $(this).addClass('selected'); }
    });

    var currentProgramme = currentURL[currentURL.length-1].split('.')[0];
    $('.my-programme-box a.' + currentProgramme).addClass('selected');
}

function setHeight(height) {
    if (height == 'imperial') { $('.form-calculate input.height2').show().val('Inches'); $('#calculate-result .value-height-imperial').show(); $('#calculate-result .value-height-metric').hide(); $('.form-calculate input.height1').css('width', '50px').val('Feet'); }
    if (height == 'metric') { $('.form-calculate input.height2').val('0').hide(); $('.form-calculate input.height1').css('width', '110px').val('Centimetres'); $('#calculate-result .value-height-metric').show(); $('#calculate-result .value-height-imperial').hide(); }
}

function setWeight(weight) {
    if (weight == 'imperial') { $('.form-calculate input.weight2').show().val('Pounds'); $('#calculate-result .value-weight-imperial').show(); $('#calculate-result .value-weight-metric').hide(); $('.form-calculate input.weight1').css('width', '50px').val('Stone'); }
    if (weight == 'metric') { $('.form-calculate input.weight1').css('width', '110px').val('Kilograms'); $('.form-calculate input.weight2').val('0').hide(); $('#calculate-result .value-weight-imperial').hide(); $('#calculate-result .value-weight-metric').show(); }
}

function setWeightRange() {
    if ($("#weight").val().toLowerCase() == 'imperial') {

        $(".form-calculate input.weight1").rules("add", {
            digits:true,
            range: [3, 34]
        });
        $(".form-calculate input.weight2").rules("add", {
            required: true,
            digits: true,
            range: [0, 13]
        });
    }
    else {
        $(".form-calculate input.weight1").rules("add", {
            number: true,
            range: [23, 230]
        });
        $(".form-calculate input.weight2").rules("remove");
    }
}

function setHeightRange() {
    if ($("#height").val().toLowerCase() == 'imperial') {
        $(".form-calculate input.height1").rules("add", {
            digits: true,
            range: [3, 7]
        });
        $(".form-calculate input.height2").rules("add", {
            digits: true,
            required: true,            
            range: [0, 11]
        });
    }
    else {
        $(".form-calculate input.height1").rules("add", {
            number: true,
            range: [91, 244]
        });
        $(".form-calculate input.height2").rules("remove");
    }
}
function CalculateBMI() {
    //when all input boxes are validated    
        var bmi = 0, calHeight, tempHeight, calWeight, lowWeight, highWeight, loseMax, loseMin, loseMaxSt, loseMaxLb, loseMinSt, loseMinLb;
        var currentWeightLabel = $(".form-calculate select#weight").val();
        var currentHeightLabel = $(".form-calculate select#height").val();
        var currentHeight1 = parseFloat($('.form-calculate input.height1').val());
        var currentHeight2 = parseFloat($('.form-calculate input.height2').val());
        var currentWeight1 = parseFloat($('.form-calculate input.weight1').val());
        var currentWeight2 = parseFloat($('.form-calculate input.weight2').val());
        
        if (currentWeightLabel == 'imperial') { calWeight = (currentWeight1 * 14 + currentWeight2) / 2.2; }
        else calWeight = currentWeight1;

        if (currentHeightLabel == 'imperial') { calHeight = ((currentHeight1 * 12 + currentHeight2) * 2.54) / 100; }
        else calHeight = currentHeight1 / 100;

        bmi = Math.round((calWeight / (calHeight * calHeight)) * 1000) / 1000;
        $('#calculate-result .label-bmi').text(bmi);
        
        lowWeight = Math.round(20 * calHeight * calHeight);
        highWeight = Math.round(25 * calHeight * calHeight);
        
        

        if (bmi < 20) { nowLeft = 114 - (20 - bmi) * 8 <= (-25) ? (-25) : (114 - (20 - bmi) * 8); $('#calculate-result .label-target span').text('gain'); loseMin = Math.round(lowWeight - calWeight); loseMax = Math.round(highWeight - calWeight); }
        if (bmi >= 20 && bmi <= 30) { nowLeft = 114 + (bmi - 20) * 29; if (bmi >= 25) { $('#calculate-result .label-target span').text('lose'); loseMin = calWeight - highWeight; loseMax = calWeight - lowWeight; } else { $('#calculate-result .label-target span').text(''); loseMax = highWeight; loseMin = lowWeight; } }
        if (bmi > 30) { nowLeft = (410 + (bmi - 30) * 8) >= 545 ? 545 : (410 + (bmi - 30) * 8); $('#calculate-result .label-target span').text('lose'); loseMin = calWeight - highWeight; loseMax = calWeight - lowWeight; }

        var txtLoseMin, txtLoseMax,rangeMin,rangeMax;
        if (currentWeightLabel == 'imperial') {
            rangeMinSt = Math.floor(lowWeight * 2.2 / 14);
            rangeMinLb = Math.round(lowWeight * 2.2 - rangeMinSt * 14);
            rangeMaxSt = Math.floor(highWeight * 2.2 / 14);
            rangeMaxLb = Math.round(highWeight * 2.2 - rangeMaxSt * 14);
            
            loseMaxSt = Math.floor(loseMax * 2.2 / 14);
            loseMaxLb = Math.round(loseMax * 2.2 - loseMaxSt * 14);
            loseMinSt = Math.floor(loseMin * 2.2 / 14);
            loseMinLb = Math.round(loseMin * 2.2 - loseMinSt * 14);

            txtLoseMin = loseMinSt + ' St ' + loseMinLb + ' lb';
            txtLoseMax = loseMaxSt + ' St ' + loseMaxLb + ' lb';

            rangeMin = rangeMinSt + ' st ' + rangeMinLb + ' lb';
            rangeMax = rangeMaxSt + ' st ' + rangeMaxLb + ' lb';
        }
        else {
            rangeMin = Math.floor(lowWeight);
            rangeMax = Math.floor(highWeight) + ' Kg';
            txtLoseMin = loseMin;
            txtLoseMax = loseMax + ' Kg';
        }
        var healthyRange = rangeMin + ' - ' + rangeMax;
        $('#calculate-result .label-target label.weight-min').text(txtLoseMin);
        $('#calculate-result .label-target label.weight-max').text(txtLoseMax);
        
        if (bmi < 20 || bmi > 25) {
            if (bmi < 20) {
                $('#calculate-result span.pre-title').html('<p>Your BMI indicates that you are in the Underweight range.</p>The good news is that the Tony Ferguson Freedom programme can help you reach a healthy weight range and maintain it. ');                
            }
            else if (bmi > 25) {
            $('#calculate-result span.pre-title').html('<p>Your BMI indicates that you need to lose <strong>' + txtLoseMin + ' - ' + txtLoseMax + ' to be within your healthy weight range of ' + healthyRange + '</strong>.</p>The good news is that the Tony Ferguson Weightloss programme can help you reach your healthy weight range and maintain it. ');
            }
        }
        else {
            $('#calculate-result span.pre-title').html('<p>Your BMI indicates that you are within <strong>your healthy weight range of ' + healthyRange + '</strong>.</p>The good news is that the Tony Ferguson Freedom programme can help you maintain it. ');
        }

        $('#calculate-result .cursor-now').css('left', nowLeft + 'px');
        $('#calculate-form').hide();
        $('#calculate-result').show();
        
        $('.module-content-container #popup-calculater').css('background-position', 'left 220px');

    }

    var $currentPopup; //Keeps the reference to the last popup displayed
    
    function showPopup(currentPopupName) {
        $('.module-popup').fadeIn('slow');
        if ($currentPopup != null) {
            $currentPopup.hide();
        }
        $currentPopup = $(currentPopupName);
        $currentPopup.show();
        $('.module-popup-bg').css({ width: $(window).width(), height: $(window).height(), background: '#000', opacity: 0.75 });
        $('.module-popup-box').css({
            left: ($(window).width() - $('.module-popup-box').width()) / 2,
            top: ($(window).height() - $('.module-popup-box').height() - 50) / 2
        });
        $('.module-popup-box').animate({
            opacity: 1
        }, 2000
        );    
    }

function getNowPosition(BMI) {
    var tabOffsetLeft;
    if (BMI < 20) tabOffsetLeft = 114 - (20 - BMI) * 8 <= (-25) ? (-25) : (114 - (20 - BMI) * 8);
    if (BMI >= 20 && BMI <= 30) tabOffsetLeft = 114 + (BMI - 20) * 29;
    if (BMI > 30) tabOffsetLeft = (410 + (BMI - 30) * 8) >= 545 ? 545 : (410 + (BMI - 30) * 8);
    return tabOffsetLeft;
}

