// preload colorized spiff images
// this prevents a delay in the effect
// when the user rolls over for the first time
/*
var img01 = new Image();
var img02 = new Image();
var img03 = new Image();
img01.src = '/static/images/bkg_column_1_active.png';
img02.src = '/static/images/bkg_column_2_active.png';
img03.src = '/static/images/bkg_column_3_active.png';
*/
// an array of possible background images (located at images/features/)
//var featureArray = ['/static/images/features/bkg_feature_1.jpg', '/static/images/features/bkg_feature_2.jpg'];

function getUrlParams() {
    var params = {};
    window.location.search.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(str, key, value) {
        params[key] = value;
    });

    return params;
}

var urlParams = getUrlParams();
var urlHash = window.location.hash;

function toggleTab(tab) {
    // remove the active class from any element that has it,
    // and then apply active class to current selected element
    $('#tabs li').removeClass('active');
    tab.addClass('active');

    // remove active class from any content divs that have it,
    // then apply active class to current selected element's
    // corresponding content div
    
    $('#tabPanes li > div.active').removeClass('active');
    $('#tabPanes li > div.wrapper').eq(tab.index()).addClass('active');
}

$('document').ready(function() {
    // functionality for "spiff" rollovers

    //alert(urlHash + " -- " + urlParams.id);
    $('#home .spiff').bind('mouseenter', function() {
        $(this).css('background-image', 'url(' + encodeURI($(this).attr("bgrolloverimage")) + ')');
    });
    $('#home .spiff').bind('mouseleave', function() {
        $(this).css('background-image', 'url(' + encodeURI($(this).attr("bgimage")) + ')');
    });

    $("div.clickable").click(function() {
        if ($(this).attr("internal") === 'true') {
            window.location = $(this).attr("url");
        } else {
            window.open($(this).attr("url"), '_blank');
        }
        return false;
    });

    $("div.clickablespiff").click(function() {
        var ga = $(this).attr("ga");
        _gaq.push(['_trackEvent', 'Spiff', 'clicked', ga]);
        if ($(this).attr("internal") === 'true') {
            window.location = $(this).attr("url");
        } else {
            window.open($(this).attr("url"), '_blank');
        }
        return false;
    });
    /*
    $('#home .spiff').bind('mouseenter', function() {
    var currentImg = $(this).css('background-image');
    currentImg = currentImg.replace('.png', '_active.png');
    $(this).css('background-image', currentImg);
    });

    $('#home .spiff').bind('mouseleave', function() {
    var currentImg = $(this).css('background-image');
    currentImg = currentImg.replace('_active.png', '.png');
    $(this).css('background-image', currentImg);
    });
    */

    $('#home .spiff').bind('click', function() {
        // Something to happen when a spiff is clicked
    });

    // turn link functionality for off
    // this is because no links are pointed anywhere
    // during development
    //$('a').bind('click', function() {
    //    return false;
    //});

    // functionality for tabs
    $('#tabs li').bind('click', function() {
        // get the index (zero-based) of the selected element
        //var tabIndex = $(this).index();
        toggleTab($(this));
    });

    $('.toggleTab').bind('click', function() {
        toggleTab($('#' + $(this).attr('tabid')));
    });

    if ($('#' + urlParams.tabid).length) {
        toggleTab($('#' + urlParams.tabid));
    }

    $('#navigation li').bind('mouseenter', function() {
        var index = $(this).index();

        $('#navigationMenu').show();
        $('#navigationMenu div.active').removeClass('active');
        $('#navigationMenu div').eq(index).addClass('active');
        $('#navigation a.active').removeClass('active');
        $(this).children('a').addClass('active');
    });

    $('#navigationMenu').bind('mouseleave', function() {
        $('#navigationMenu').hide();
    });

    $('#navigationWrapper').bind('mouseleave', function() {
        $('#navigationMenu').hide();

        $('#navigation a.active').removeClass('active');
    });

    $('#textSize a').bind('click', function() {
        $('#textSize a.active').removeClass('active');
        $(this).addClass('active');
    });

    $('#btn_login').bind('mouseenter', function() {
        $(this).hide();
        $('#login_rollover').show();
    });

    $('#login_rollover').bind('mouseleave', function() {
        $(this).hide();
        $('#btn_login').show();
    });

    $(".defaultSubmit").each(function(index) {
        $(this).closest('form').bind('keypress', function(e) {
            if (e.keyCode == 13) {
                $(this).trigger('click');
            }
        })
    });

    $(".defaultClick").keyup(function(event) {
        if (event.keyCode == 13) {
            $(this).find(".defaultClickButton:first").click();
        }
    });

    $('#btn_submit').click(function(event) {
        var query = $('input[id=searchField]');
        //alert(query.val());
        if (query.val().length < 1)
            return false;
        else {
            window.location.href = "/search-results?query=" + query.val();
        }

    });

    $('input[id=searchField]').bind('keypress', function(e) {
        if (e.keyCode == 13) {
            e.preventDefault();
            var query = $('input[id=searchField]');
            //alert(query.val());
            if (query.val().length < 1)
                return false;
            else {
                window.location.href = "/search-results?query=" + query.val();
            }
        }
    });


    if (jQuery().selectBox) {
        $("select:not(.originalSelect)").selectBox();
    }


    if (jQuery().inFieldLabels) {
        $('label').inFieldLabels();
    }
});

jQuery.fn.center = function() {
    this.css("position", "absolute");
    this.css("top", ($(window).height() - this.height()) / 2 + $(window).scrollTop() + "px");
    this.css("left", ($(window).width() - this.width()) / 2 + $(window).scrollLeft() + "px");
    return this;
}

$.fn.exists = function() {
    return this.length !== 0;
}

function randomizeBackground() {
    var size = $('.featureContent').size()
    var index = Math.floor(Math.random() * size);

    var featureContent = $('.featureContent').eq(index);

    $('<img />')
        .attr('src', featureContent.attr("bgimage"))
        .load(function() {
            $('#wrapper').css('background-image', 'url(' + encodeURI($(this).attr('src')) + ')');
            featureContent.show();
        });
}

function initDefinitionList() {
    $('dt').bind('click', function() {
        if ($(this).hasClass('open')) {
            $(this).removeClass('open').next('dd').slideToggle();
        } else {
            $('dt').removeClass('open');
            $(this).addClass('open').next('dd').slideToggle();
        }
    });
}

function initOverlay() {
    animateOverlayIn();

    $('li.hotspot').bind('mouseover', function() {
        var img = $(this).children('img').attr('src');
        var text = $(this).children('img').attr('alt');

        $('div.info img').attr('src', img);
        $('div.info p').text(text);

        $('div.info').css('display', 'block');
    });

    $('a.close').bind('click', function() {
        animateOverlayOut();
    });

    $('#overlay').bind('click', function() {
        animateOverlayOut();
    });

    /* $('li.hotspot').bind('mouseout', function () {
    $('div.info').css('display', 'none');
    }); */
}

function animateOverlayIn() {
    var dialogWidth = parseInt($('#dialog').css('width'));

    $('#overlay').css({
        'height': $(document).height(),
        'display': 'block'
    });

    $('#dialog').css('display', 'block');

    $('#dialog').css({
        'left': ($(window).width() - dialogWidth) / 2,
        'top': $(window).scrollTop() + 60
    });

    $('#overlay').stop().animate({
        'opacity': 0.8
    }, 500, function() {
        $('#dialog').animate({
            'opacity': 1
        });
    });

}

function animateOverlayOut() {
    $('#dialog').stop().animate({
        'opacity': 0
    }, 250, function() {
        $('#dialog').css('display', 'none');
        $('#overlay').stop().animate({
            'opacity': 0
        }, 250, function() {
            $('#overlay').css('display', 'none');
        });
    });
}

function popitup(url) {
    newwindow = window.open(url, 'name', 'height=600,width=650,scrollbars=yes');
    if (window.focus) { newwindow.focus() }
    return false;
}


//begin jsddm
var timeout = 500;
var closetimer = 0;
var ddmenuitem = 0;

function jsddm_open() {
    jsddm_canceltimer();
    jsddm_close();
    ddmenuitem = $(this).find('ul').eq(0).css('visibility', 'visible');
}

function jsddm_close() {
    if (ddmenuitem) ddmenuitem.css('visibility', 'hidden');
}

function jsddm_timer() {
    closetimer = window.setTimeout(jsddm_close, timeout);
}

function jsddm_canceltimer() {
    if (closetimer) {
        window.clearTimeout(closetimer);
        closetimer = null;
    }
}

$(document).ready(function() {
    $("#jsddm li:first a:first").click(function(e) {
        e.preventDefault();
    });
    $('#jsddm > li').bind('mouseover', jsddm_open);
    $('#jsddm > li').bind('mouseout', jsddm_timer);
});
document.onclick = jsddm_close;
//end jsddm





$(document).ready(function() {
    $('#liCoupons').click(function() {
        //$.blockUI({ message: '<h1> Processing...</h1>' });
        $.ajax({
            type: "POST",
            url: "/services/WellnessService.asmx/Coupons",
            data: "", // I wouldn't prefer passing webmethod name here
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                $('#resultsCoupn').html(msg.d);
            },
            error: ajaxFailed
            //error

        });
    });

    $('#liLibrary').click(function() {
        //$.blockUI({ message: '<h1> Processing...</h1>' });
        $.ajax({
            type: "POST",
            url: "/services/WellnessService.asmx/Resources",
            data: "", // I wouldn't prefer passing webmethod name here
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                $('#resultResources').html(msg.d);
            },
            error: ajaxFailed
            //error

        });
    });

    $('#liProducts').click(function() {
        //$.blockUI({ message: '<h1> Processing...</h1>' });
        $.ajax({
            type: "POST",
            url: "/services/WellnessService.asmx/Products",
            data: "", // I wouldn't prefer passing webmethod name here
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                $('#resultProducts').html(msg.d);
            },
            error: ajaxFailed
            //error

        });
    });

    $('#liPreferences').click(function() {
        //$.blockUI({ message: '<h1> Processing...</h1>' });
        $.ajax({
            type: "POST",
            url: "/services/WellnessService.asmx/Newsletters",
            data: "", // I wouldn't prefer passing webmethod name here
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                $('#resultNewsletters').html(msg.d);
            },
            error: ajaxFailed
            //error

        });
    });

    $('#liAccount').click(function() {
        //$.blockUI({ message: '<h1> Processing...</h1>' });
        $.ajax({
            type: "POST",
            url: "/services/WellnessService.asmx/MyAccount",
            data: "", // I wouldn't prefer passing webmethod name here
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                $('#resultMyAccount').html(msg.d);
            },
            error: ajaxFailed
            //error

        });
    });
    function ajaxFailed(xmlRequest) {
        alert(xmlRequest.status + ' \n\r ' +
              xmlRequest.statusText + '\n\r' +
              xmlRequest.responseText);
    }
});      











