/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie = function (key, value, options) {
    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};
function isValidEmail(email) {
    var regex = /([\w\d\-_]+)(\.[\w\d\-_]+)*@([\w\d\-_]+\.)([\w\d\-_]+\.)*([\w]{2,3})/;
    if (regex.test(email))
        return true;
    else
        return false;
}
function isInteger(input) {
    if (input.match(/^[0-9]+$/)) {
        return true;
    } else {
        return false;
    }
}
function isMoney(input) {
    if (input.match(/^\$?(\d{1,3}(\,\d{3})*|(\d+))(\.\d{2})?$/)) {
        return true;
    } else {
        return false;
    }
}
function goToByScrollByY(y) {
    $('html,body').animate({ scrollTop: y }, 'slow');
}
function goToByScrollById(id) {
    goToByScrollByObj($('#' + id));
}
function goToByScrollByObj(el) {
    $('html,body').animate({ scrollTop: el.offset().top }, 'slow');
}
function goToByScrollByObjOffset(el, offset) {
    $('html,body').animate({ scrollTop: el.offset().top + offset }, 'slow');
}

/* ~~~~~~~~~~~~~ browser upgrade ~~~~~~~~~~~~~*/
$(document).ready(function () {
    //if cookie don't show message again
    if ($.cookie('ie6message') == '1') {
        $('#ie6').hide();
    }
    $('#close_ie6upgrade').mousedown(function () {
        $.cookie('ie6message', '1', { expires: 7 });
        $('#ie6').slideUp();
        return false;
    });
});
function setupTextReset() {
    $('fieldset .form label, .headerSearch label').click(function () {
        if (!$(this).parent().hasClass('check') &&
            !$(this).next().hasClass('jsDisableLabelFade')) {
            $(this).fadeOut(300);
            $(this).next().focus();
        }
    });
    $('fieldset .form input[type="text"], fieldset .form textarea, .headerSearch input').focus(function () {
        if (!$(this).hasClass('jsDisableLabelFade')) {
            $(this).prev('label').fadeOut(300);
        }
    });
    $('fieldset .form input[type="text"], fieldset .form textarea, .headerSearch input').blur(function () {
        if (!$(this).hasClass('jsDisableLabelFade')) {
            var el = $(this);
            //below is a hack for datepicker
            setTimeout(function () {
                if (el.val() == '') {
                    el.prev('label').fadeIn(300);
                }
            }, 300);
        }
    });
    $('fieldset .form input[type="text"], fieldset .form textarea').each(function () {
        if (!$(this).hasClass('jsDisableLabelFade')) {
            if ($(this).val() != '') {
                $(this).prev('label').hide();
            }
        }
    });
}
$(document).ready(function () {
    setupTextReset();
    if ($('.jsAutoScrollingGallery img').length > 1) {
        delayedGalleryScroll();
    }
    function delayedGalleryScroll() {
        setTimeout(function () {
            var currentImg = $('.jsAutoScrollingGallery img:visible');
            var nextImg;
            if (currentImg.next('img').length > 0)
                nextImg = currentImg.next();
            else
                nextImg = $('.jsAutoScrollingGallery img').eq(0);
            currentImg.fadeOut(500);
            nextImg.fadeIn(500, function () {
                delayedGalleryScroll();
            });
        }, 4000);
    }
    $('.socialButtons .tweet').click(function () {
        var url = 'http://twitter.com/share?url=' + encodeURIComponent(window.location);
        if ($(this).attr('href') != '#')
            url = 'http://twitter.com/share?url=' + encodeURIComponent($(this).attr('href'));
        window.open(url, 'twitter', 'width=500,height=400');
        return false;
    });
    $('.socialButtons .facebook').click(function () {
        var url = 'http://www.facebook.com/sharer.php?u=' + encodeURIComponent(window.location);
        if ($(this).attr('href') != '#')
            url = 'http://www.facebook.com/sharer.php?u=' + encodeURIComponent($(this).attr('href'));
        window.open(url, 'facebook', 'width=1000,height=600');
        return false;
    });

    $('.headerSearch .searchMagnifier').click(function (e) {
        e.preventDefault();
        doSearch();
    });
    $('.headerSearch input').keyup(function (e) {
        if (e.keyCode == 13) {
            doSearch();
        }
    });
    function doSearch() {
        window.location = '/search-results.aspx?q=' + $('.headerSearch input').val();
    }
    $('.jsScrollingGallery .btnPrev').click(function (e) {
        e.preventDefault();
        var currentImg = $('.jsScrollingGallery img:visible');
        var nextImg;
        if (currentImg.prev('img').length > 0)
            nextImg = currentImg.prev();
        else
            nextImg = $('.jsScrollingGallery img').eq($('.jsScrollingGallery img').length - 1);
        currentImg.fadeOut(500);
        nextImg.fadeIn(500);
    });
    $('.jsScrollingGallery .btnNext').click(function (e) {
        e.preventDefault();
        var currentImg = $('.jsScrollingGallery img:visible');
        var nextImg;
        if (currentImg.next('img').length > 0)
            nextImg = currentImg.next();
        else
            nextImg = $('.jsScrollingGallery img').eq(0);
        currentImg.fadeOut(500);
        nextImg.fadeIn(500);
    });
    $('.jsSelectLocation').click(function (e) {
        e.preventDefault();
        $('.lightbox').fadeIn(300);
        $('.locationSelector').fadeIn(300);
    });
    $('.closeLightbox').click(function (e) {
        e.preventDefault();
        $('.lightbox').fadeOut(300);
        $('.locationSelector').fadeOut(300);
        $('.requestAppointment').fadeOut(300);
        $('.jsShoppingCart').fadeOut(300);
        $('.jsContactForm').fadeOut(300);
        $('.sendToFriend').fadeOut(300);
        $('.askQuestion').fadeOut(300);
    });


    $(".jsDatePick").datepicker({
        dateFormat: 'dd M yy',
        minDate: new Date(),
        onSelect: function (dateText, inst) { $(this).prev('label').fadeOut(300); }
    });

    //request appointment
    $('.jsRequestAppointmentInit').click(function (e) {
        e.preventDefault();
        $('.lightbox').fadeIn(300);
        $('.requestAppointment').fadeIn(300);

        $('.jsRequestAppointment .jsForm').show();
        $('.jsRequestAppointment .jsSend').show();
        $('.jsRequestAppointment .jsSuccess').hide();
        $('.jsRequestAppointment .jsAjaxLoader').hide();

        var val = '';
        if ($(this).attr('title') != null) {
            val = $(this).attr('title');
        }
        else if ($(this).parent().parent().find('h3').length > 0) {
            val = $(this).parent().parent().find('h3').html();
            val += ' - ' + $(this).parent().find('.time').html();
        }
        $('#tbRATreatments').val(val);
        $('#tbRATreatments').prev('label').hide();
    });
    $('.jsRequestAppointment .jsSend').click(function (e) {
        e.preventDefault();

        //validation
        $('.jsRequestAppointment input, .jsRequestAppointment textarea, .jsRequestAppointment select').removeClass('error');
        $('.jsRequestAppointment .jsError').hide();
        $('.jsRequestAppointment .jsError').html('');
        if ($('#ddlRALocation').val() == '') {
            $('.jsRequestAppointment .jsError').append('Please select where you want to spa<br />');
            $('#ddlRALocation').addClass('error');
        }
        if ($('#tbRAPreferredDate').val() == '') {
            $('.jsRequestAppointment .jsError').append('Please enter the preferred date<br />');
            $('#tbRAPreferredDate').addClass('error');
        }
        if ($('#tbRATreatments').val() == '') {
            $('.jsRequestAppointment .jsError').append('Please enter the treatment(s) required<br />');
            $('#tbRATreatments').addClass('error');
        }
        if ($('#tbRAName').val() == '') {
            $('.jsRequestAppointment .jsError').append('Please enter your name<br />');
            $('#tbRAName').addClass('error');
        }
        if ($('#tbRAEmail').val() == '') {
            $('.jsRequestAppointment .jsError').append('Please enter your email<br />');
            $('#tbRAEmail').addClass('error');
        }
        else if (!isValidEmail($('#tbRAEmail').val())) {
            $('.jsRequestAppointment .jsError').append('Please enter your valid email address<br />');
            $('#tbRAEmail').addClass('error');
        }
        if ($('#tbRAPhone').val() == '') {
            $('.jsRequestAppointment .jsError').append('Please enter your phone number<br />');
            $('#tbRAPhone').addClass('error');
        }


        if ($('.jsRequestAppointment .jsError').html() == '') {
            $('.jsRequestAppointment .jsSend').fadeOut(100, function () {
                $('.jsRequestAppointment .jsAjaxLoader').fadeIn(300);
            });

            $.post("/handlers/RequestAppointment.ashx", { location: $('#ddlRALocation').val(), prefdate: $('#tbRAPreferredDate').val(), preftime: $('#tbRAPreferredTime').val(), treatments: $('#tbRATreatments').val(), name: $('#tbRAName').val(), email: $('#tbRAEmail').val(), phone: $('#tbRAPhone').val() }, function (data) {
                if (!data.Error) {
                    //success!
                    $('.jsRequestAppointment .jsForm').fadeOut(100, function () {
                        $('.jsRequestAppointment .jsSuccess').fadeIn(300);
                    });
                    $('.jsRequestAppointment .jsSuccess').html(data.Message);
                }
                else {
                    $('.jsRequestAppointment .jsAjaxLoader').fadeOut(100, function () {
                        $('.jsRequestAppointment .jsSend').fadeIn(300);
                    });
                    $('.jsRequestAppointment .jsError').fadeIn(300);
                    $('.jsRequestAppointment .jsError').html(data.Message);
                }
            }).error(function () {
                $('.jsRequestAppointment .jsAjaxLoader').fadeOut(100, function () {
                    $('.jsRequestAppointment .jsSend').fadeIn(300);
                });
                $('.jsRequestAppointment .jsError').fadeIn(300);
                $('.jsRequestAppointment .jsError').html('An error had occurred. Please try again later.');
            });
        }
        else {
            $('.jsRequestAppointment .jsError').fadeIn(300);
        }
    });

    //send to friend
    $('.jsSendToFriendInit, .socialButtons .email').click(function (e) {
        e.preventDefault();
        $('.lightbox').fadeIn(300);
        $('.sendToFriend').fadeIn(300);

        $('.sendToFriend .jsForm').show();
        $('.sendToFriend .jsSuccess').hide();
    });
    $('#tbSTFFriendEmail').keyup(function (e) {
        if (e.keyCode == 188 ||
                e.keyCode == 59 ||
                e.keyCode == 13) {
            updateFriendEmail();
        }
    });
    $('#tbSTFFriendEmail').blur(function () {
        if ($(this).val() != '') {
            updateFriendEmail();
        }
    });
    function updateFriendEmail() {
        var emailTo = $('#tbSTFFriendEmail').val().replace(',', '').replace(';', '');
        if (isValidEmail(emailTo)) {
            $('#divSTFFriendEmails').append('<a href="#">' + emailTo + '<span class="icon ir">x</span></a>');
            $('#tbSTFFriendEmail').val('');

            $('#divSTFFriendEmails a').unbind('click');
            $('#divSTFFriendEmails a').bind('click', deleteFriendEmail);
        }
    }

    $('#divSTFFriendEmails a').bind('click', deleteFriendEmail);
    function deleteFriendEmail() {
        $(this).remove();
        return false;
    }

    //media
    $('.archiveMedia').click(function (e) {
        e.preventDefault();
        if (!$(this).next('.jsMediaItems').is(':visible')) {
            $('.jsMediaItems').each(function () {
                if ($(this).is(':visible'))
                    $(this).slideUp();
            });
            $(this).next('.jsMediaItems').slideDown();
        }
    });
});
bindHeaderCartEvents();
function bindHeaderCartEvents() {
    $('.primaryNav a.navCart').bind('click', headerCartClick);
}
function headerCartClick(e) {
    e.preventDefault();
    $('.lightbox').fadeIn(300);
    $('.jsShoppingCart').fadeIn(300);
}

bindCartEvents();
function bindCartEvents() {
    $('#divShoppingCartInner a.remove').bind('click', cartItemRemoveClick);
    $('#divShoppingCartInner input.quant').bind('change', cartItemQtyChange);
    $('#divShoppingCartInner #ddlCartDelivery, #divShoppingCartInner .freightDDL').bind('change', cartFreightChange);
    $('#ddlCartCurrency').bind('change', cartCurrencyChange);
    $('#aCartCheckout').bind('click', cartCheckout);

    if ($('#spanCartLoader').length > 0) {
        var cl = new CanvasLoader('spanCartLoader');
        cl.setColor('#000000'); // default is '#000000'
        cl.setShape('roundRect'); // default is 'oval'
        cl.setDiameter(34); // default is 40
        cl.setDensity(12); // default is 40
        cl.setSpeed(1); // default is 2
        cl.setFPS(8); // default is 24
        cl.show(); // Hidden by default
    }
}
function cartCurrencyChange(e) {
    var el = $(this);
    $('#divShoppingCartInner .jsError').hide();
    $('#divShoppingCartInner .jsError').html('');

    $('#aCartCheckout').fadeOut(100, function () {
        $('#divShoppingCartInner .jsAjaxLoader').fadeIn(300);
    });
    $('#aCartCheckout').show();
    $.post("/handlers/Cart.ashx?r=" + Math.floor(Math.random() * 10000000), { op: 'currencyChange', currency: el.val() }, function (data) {
        if (!data.Error) {
            //success!
            $('#divShoppingCartInner .jsAjaxLoader').fadeOut(100);
            $('.primaryNav li.cart').html(data.CartStatusHTMLOutput);
            $('#divShoppingCartInner').html(data.CartHTMLOutput);
            bindHeaderCartEvents();
            bindCartEvents();
        }
        else {
            $('#divShoppingCartInner .jsAjaxLoader').fadeOut(100);
            $('#divShoppingCartInner .jsError').fadeIn(300);
            $('#divShoppingCartInner .jsError').html(data.ErrorMessage);

            if (data.CartStatusHTMLOutput != '')
                $('.primaryNav li.cart').html(data.CartStatusHTMLOutput);
            if (data.CartHTMLOutput != '')
                $('#divShoppingCartInner').html(data.CartHTMLOutput);
            bindHeaderCartEvents();
            bindCartEvents();
        }
    }).error(function () {
        $('#divShoppingCartInner .jsAjaxLoader').fadeOut(100, function () {
            $('#aCartCheckout').fadeIn(300);
        });
        $('#divShoppingCartInner .jsError').fadeIn(300);
        $('#divShoppingCartInner .jsError').html('An error had occurred. Please try again later.');
    });
}
function cartItemRemoveClick(e) {
    e.preventDefault();
    var el = $(this);
    var cartItemId = el.parents('tr').find('.hfItemId').val();

    $('#divShoppingCartInner .jsError').hide();
    $('#divShoppingCartInner .jsError').html('');

    $('#aCartCheckout').fadeOut(100, function () {
        $('#divShoppingCartInner .jsAjaxLoader').fadeIn(300);
    });

    $.post("/handlers/Cart.ashx?r=" + Math.floor(Math.random() * 10000000), { op: 'removeitem', itemid: cartItemId }, function (data) {
        if (!data.Error) {
            //success!
            $('#divShoppingCartInner .jsAjaxLoader').fadeOut(100);
            $('.primaryNav li.cart').html(data.CartStatusHTMLOutput);
            $('#divShoppingCartInner').html(data.CartHTMLOutput);
            bindHeaderCartEvents();
            bindCartEvents();
        }
        else {
            $('#divShoppingCartInner .jsAjaxLoader').fadeOut(100, function () {
                $('#aCartCheckout').fadeIn(300);
            });
            $('#divShoppingCartInner .jsError').fadeIn(300);
            $('#divShoppingCartInner .jsError').html(data.ErrorMessage);
        }
    }).error(function () {
        $('#divShoppingCartInner .jsAjaxLoader').fadeOut(100, function () {
            $('#aCartCheckout').fadeIn(300);
        });
        $('#divShoppingCartInner .jsError').fadeIn(300);
        $('#divShoppingCartInner .jsError').html('An error had occurred. Please try again later.');
    });
}
function cartItemQtyChange(e) {
    var el = $(this);
    var cartItemId = el.parents('tr').find('.hfItemId').val();

    el.removeClass('error');
    $('#divShoppingCartInner .jsError').hide();
    $('#divShoppingCartInner .jsError').html('');
    $('#aCartCheckout').show();
    if (!isInteger(el.val())) {
        $('#divShoppingCartInner .jsError').append('Please enter a valid quantity<br />');
        el.addClass('error');
    }
    else if (parseInt(el.val()) <= 0) {
        $('#divShoppingCartInner .jsError').append('Please enter a valid quantity<br />');
        el.addClass('error');
    }

    if ($('#divShoppingCartInner .jsError').html() == '') {
        $('#aCartCheckout').fadeOut(100, function () {
            $('#divShoppingCartInner .jsAjaxLoader').fadeIn(300);
        });

        $.post("/handlers/Cart.ashx?r=" + Math.floor(Math.random() * 10000000), { op: 'updatequantity', itemid: cartItemId, qty: el.val() }, function (data) {
            if (!data.Error) {
                //success!
                $('#divShoppingCartInner .jsAjaxLoader').fadeOut(100);
                $('.primaryNav li.cart').html(data.CartStatusHTMLOutput);
                $('#divShoppingCartInner').html(data.CartHTMLOutput);
                bindHeaderCartEvents();
                bindCartEvents();
            }
            else {
                $('#divShoppingCartInner .jsAjaxLoader').fadeOut(100, function () {
                    $('#aCartCheckout').fadeIn(300);
                });
                $('#divShoppingCartInner .jsError').fadeIn(300);
                $('#divShoppingCartInner .jsError').html(data.ErrorMessage);
            }
        }).error(function () {
            $('#divShoppingCartInner .jsAjaxLoader').fadeOut(100, function () {
                $('#aCartCheckout').fadeIn(300);
            });
            $('#divShoppingCartInner .jsError').fadeIn(300);
            $('#divShoppingCartInner .jsError').html('An error had occurred. Please try again later.');
        });
    }
    else {
        $('#divShoppingCartInner .jsError').fadeIn(300);
        $('#aCartCheckout').fadeOut(300);
    }
}
function cartFreightChange(e) {
    var el = $(this);

    $('#divShoppingCartInner .jsError').hide();
    $('#divShoppingCartInner .jsError').html('');

    $('#aCartCheckout').fadeOut(100, function () {
        $('#divShoppingCartInner .jsAjaxLoader').fadeIn(300);
    });
    $('#aCartCheckout').show();
    $.post("/handlers/Cart.ashx?r=" + Math.floor(Math.random() * 10000000), { op: 'freightChange', freightLocation: el.val() }, function (data) {
        if (!data.Error) {
            //success!
            $('#divShoppingCartInner .jsAjaxLoader').fadeOut(100);
            $('.primaryNav li.cart').html(data.CartStatusHTMLOutput);
            $('#divShoppingCartInner').html(data.CartHTMLOutput);
            bindHeaderCartEvents();
            bindCartEvents();
        }
        else {
            $('#divShoppingCartInner .jsAjaxLoader').fadeOut(100);
            $('#divShoppingCartInner .jsError').fadeIn(300);
            $('#divShoppingCartInner .jsError').html(data.ErrorMessage);

            if(data.CartStatusHTMLOutput != '')
                $('.primaryNav li.cart').html(data.CartStatusHTMLOutput);
            if(data.CartHTMLOutput != '')
                $('#divShoppingCartInner').html(data.CartHTMLOutput);
            bindHeaderCartEvents();
            bindCartEvents();
        }
    }).error(function () {
        $('#divShoppingCartInner .jsAjaxLoader').fadeOut(100, function () {
            $('#aCartCheckout').fadeIn(300);
        });
        $('#divShoppingCartInner .jsError').fadeIn(300);
        $('#divShoppingCartInner .jsError').html('An error had occurred. Please try again later.');
    });
}
function cartCheckout(e) {
    if ($('#divShoppingCartInner .jsError').html() != '') {
        return false;
    }
}
