jQuery(document).ready(function () {

    var browserIE = getInternetExplorerVersion();
    var osMac = getIfMac();

    var FF = getIfFF();
    var WK = getIfWebkit();

    if (osMac) {
        if (($('#ProductDetails .ChooseOne li a').length > 0) && (WK)) {
            $('#ProductDetails .ChooseOne li a').css('background-position', 'right 3px');
        }
        if ($('#ProductDetails ul.FindOutMore li a').length > 0) {
            $('#ProductDetails ul.FindOutMore li a').css('background-position', 'right 5px');
        }
    }
    if (WK) {
        $('#Search').css('top', '2px');
    }
    if (browserIE > 7) {
        $('#Search').css('top', '2px');
    }
    if (FF) {
        $('#Search').css('bottom', '2px');
    }



    if ($('#Breadcrumbs').length > 0) {
        $('#Breadcrumbs li:last-child').addClass('last-child').addClass('active').find('a').removeAttr('href').replaceWith(function () { return $(this).text() });
    }




    if ($('#CartList .cartItem').length == 0) {
        $('.cartSubHeader').eq(1).remove();
    }

    if ($('#Products .ShadeSection').length > 5) {
        var len = $('#Products .ShadeSection').length;
        $('.ShadeSection').css('width', '170px');
        $('.ShadeSection').css('border', 'none');
    }

    if ($('#left_0_linkCollection').length > 0) {
        if ($('#left_0_linkCollection').text() == "") {
            $('#left_0_linkCollection').remove();
        }
    }

    $('#PrimaryNavigation .Sublists ul:first-child').addClass('first-child');
    $('#PrimaryNavigation .Sublists ul:last-child').addClass('last-child');
    $('#PrimaryNavigation li .Dropdown .Sublists li:first-child').addClass('first-child');

    $('#PrimaryNavigation li').hover(function () {  // hover action for primary navigation
        $(this).addClass('active');
    }, function () {
        $(this).removeClass('active');
    });

    if ($('#SecondaryNavigation').length > 0) {
        $('#SecondaryNavigation').find('li.active').parent().parent().addClass('activeMain');

    }

    $('#TopNavigation li.separator:last').remove();
    //$('#Buzz #LandingPageNavigation ul:last').addClass('floatUnder');
    $('#FooterNavigationB li:first-child').addClass('first-child');

    if ($('#LandingPageNavigation').length > 0) {
        $('#LandingPageNavigation ul li:first-child').addClass('first-child');
    }

    if ($('.ItemList').length > 0) {
        $('.ItemList li:nth-child(even)').addClass('even');
    }


    if ($('a.btnQuickLook').length > 0) {
        $("a.btnQuickLook").fancybox({
            "overlayOpacity": 0.8,
            "overlayColor": "#FFF",
            "padding": 0
        });
    }

    if ($('#Landing #TertiaryNavigation').length > 0) {
        $('#Landing #TertiaryNavigation li a').hover(function () {
            $(this).children('img').toggle();

        });
    }


    //    if (($('#Products #Landing').length > 0) || ($('#Products #right_0_PanelCollections').length > 0)) {
    if (($('#WhyAlmay').length > 0) || ($('#Buzz').length > 0) || ($('#MakeupTips').length > 0)) {
        $('.MainImage').removeClass('Show');
        $('#TertiaryNavigation').removeClass('Hover');
    }

    //----------------------------------------------------------------
    //       Landing Hover action   
    $('.Hover li').hover(function () {
        $('.Show img').stop(true, true).hide();
        $('.Show img').eq($(this).index()).stop(true, true).fadeIn("fast");
    }, function () { //do nothing on hover OUT
    });
    //use this here instead of on the li so mousing between the list items doesn't flash the default image excessively
    $('.Hover').hover(function () { //do nothing on hover IN
    }, function () {
        $('.Show img').stop(true, true).hide();
        $('.DefaultImage').stop(true, true).fadeIn("fast");
    });


    if ($('#Show2').length > 0) {
        $('#Show2 .ShadeSwatch').eq(0).show();
    }
    $('#Hover2 .ShadeSection .Shades').hover(function () {
        var id = $(this).parent().index();
        //id = (id - 2) / 4;
        $('#Show2 .ShadeSwatch').stop(true, true).hide();
        $('#Show2 .ShadeSwatch').eq(id).stop(true, true).fadeIn("fast");
    }, function () { //do nothing on hover OUT
    });


    //------------------------------------------------------------------
    //      Carousel initialization        
    if (jQuery('#MainCarousel').length > 0) {
        jQuery('#MainCarousel').jcarousel({
            scroll: 1
        });
    }
    if ($('.ArrowsMax3 li').length <= 3) {
        $('.ArrowsMax3').parent().parent().children('.jcarousel-prev').css('opacity', '0');
        $('.ArrowsMax3').parent().parent().children('.jcarousel-next').css('opacity', '0');
    }


    if ($('.ArrowsMax2 li').length <= 2) {
        $('.ArrowsMax2').addClass('HideArrows');
    }


    if ($('.ArrowsMax3 li').length <= 3) {
        $('.ArrowsMax3').addClass('HideArrows');
    }
    if ($('.ArrowsMax4 li').length <= 4) {
        $('.ArrowsMax4').addClass('HideArrows');
        //$('.ArrowsMax4').parent().parent().addClass('HideArrows');
    }

    if ($('.ArrowsMax5 li').length <= 5) {
        $('.ArrowsMax5').addClass('HideArrows');
    }
    if ($('.ArrowsMax5b li').length <= 5) {
        $('.ArrowsMax5b').addClass('HideArrows');
    }

    if (jQuery('#mycarousel3').length > 0) {
        jQuery('#mycarousel3').jcarousel({
            scroll: 1
        });
    }

    if (jQuery('#BuzzSlider').length > 0) {
        jQuery('#BuzzSlider').jcarousel({
            scroll: 1,
            auto: 10,
            wrap: 'last'
        });
    }

    if (jQuery('#Ambassador').length > 0) {
        jQuery('#Ambassador #favs').jcarousel({
            scroll: 1
        });
    }

    if (jQuery('#ProductsUsed').length > 0) {
        jQuery('#ProductsUsed').jcarousel({
            scroll: 1
        });
    }

    if (jQuery('#tabcarousel').length > 0) {
        jQuery('#tabcarousel').jcarousel({
            scroll: 3,
            initCallback: tabcarousel_initCallback
        });
    }

    //    if (jQuery('#AmbassadorVideos').length > 0) {
    //        jQuery('#AmbassadorVideos').jcarousel({
    //            scroll: 1
    //        });
    //    }

    //    function tabcarousel_initCallback(carousel) {
    //        jQuery('.FindOutMore li a').bind('click', function () {
    //        var content = $(this).text();
    //        var cl = $('.SimpleTabs2 li:contains("' + content + '")').attr('id');
    //        carousel.scroll(jQuery.jcarousel.intval(cl));
    //        
    //        return false;
    //        });



    if (jQuery('#AmbassadorGallery').length > 0) {
        jQuery('#AmbassadorGallery').jcarousel({
            scroll: 1,
            wrap: 'last',
            itemVisibleOutCallback: {
                onAfterAnimation: function (c, o, i, s) {
                    $('#AmbassadorGallery .jcarousel-item').removeClass('active');
                    //++i;
                    $('#AmbassadorGallery .jcarousel-item:eq(' + i + ')').addClass('active');
                }
            }
        });
    }

    if (jQuery('#ProductCategorySlider').length > 0) {
        jQuery('#ProductCategorySlider').jcarousel({
            scroll: 1
        });
    }
    if (jQuery('#SealsCarousel').length > 0) {
        jQuery('#SealsCarousel').jcarousel({
            scroll: 1
        });
    }


    if (jQuery('#CarouselPanels2').length > 0) {
        jQuery("#CarouselPanels2").jcarousel({
            scroll: 1,
            auto: 5,
            wrap: 'last',
            initCallback: mycarousel_initCallback,
            // This tells jCarousel NOT to autobuild prev/next buttons
            buttonNextHTML: null,
            buttonPrevHTML: null,
            itemVisibleInCallback: {
                onAfterAnimation: function (c, o, i, s) {
                    --i;
                    jQuery('.jcarousel-control a').removeClass('active');
                    jQuery('.jcarousel-control a:eq(' + i + ')').addClass('active');
                }
            }
        });
    }


    //add numeric id's to tabs so can jump from another place on the page

    $('.NumberList>li').each(function (index, value) {
        var plusOne = index + 1;
        $(this).attr('id', plusOne);
    });

    //add classes dynamically

    $('.NumberDivs>div').each(function (index, value) {
        var plusOne = index + 1;
        $(this).addClass('' + plusOne);
    });


    //-----------------------------------------//
    //		         TABS	            	 //		

    $('.TabContents .Contents').hide();
    //set active tab on load
    $('.tabulation #1').addClass('active');
    $('.TabContents .1').show();  //after classes have been added    



    //make tab & content active when tab is clicked
    $('.tabulation li').click(function () {
        $('.tabulation li').removeClass('active');
        $(this).addClass('active');
        var cl = $(this).attr('id');
        $('.Contents').hide();
        $('.TabContents .' + cl).show();

        //$('.HowTo ul.sub li').removeClass('active'); //PR
        //$('.HowTo ul.sub li').eq(cl - 1).addClass('active'); //product recommender
    });

    //--------------------------------------------------------------------
    //          simple tabs                
    if ($('.SimpleTabs').length > 0) {
        $('.SimpleTabs>li').eq(0).addClass('active');
        $('.SimpleContent>div').eq(0).show();
    }



    $('.SimpleTabs>li').click(function () {
        $('.SimpleTabs>li').removeClass("active");
        $(this).addClass("active");
        $('.SimpleContent>div').hide();
        $('.SimpleContent>div').eq($(this).index()).show();
    });




    //-------------------------------------------------------------------
    //          minimizer                     
    if ($(".ExpandTitle").length > 0) {

        $(".InnerContent").hide();
        $(".InnerContent:first").show();
        $(".ExpandTitle:first .expander").hide();
        $(".ExpandTitle:first .minimizer").show();
        $(".ExpandTitle:first").addClass('active');

        $(".ExpandTitle").click(function () {
            //$(this).toggleClass('active');
            if ($(this).hasClass('active')) {
                $(this).removeClass('active');
            } else {
                $(".ExpandTitle").removeClass('active');
                $(this).addClass('active');
            }

            var item = $(this).next().html();
            $(".InnerContent").each(function () { //needed to prevent multiple from opening at once
                if (item != $(this).html()) {
                    if (!$(this).is(':hidden')) {
                        $(this).stop(true, true).slideToggle(400);
                        $(this).prev().children('img').toggle();
                    }
                }
            });
            $(this).next().stop(true, true).slideToggle(400);
            $(this).children('img').toggle();
        });
    }
    //-------------------------------------------------------------------
    //              videos                      

    //$('#AmbassadorVideos li:first-child').addClass("active");
    //$('#Video .Main .Content .Blurb li:first-child').addClass("active");


    $('#Ambassador .MainTabs li:eq(1)').click(function () {
        LoadAmabassadorGallery();
    });
    if ($('#gallery_container2').parent('div').is(':visible')) {
        LoadAmabassadorGallery();
    }
    function LoadAmabassadorGallery() {
        if (!$('#myGallery2').hasClass("initialized")) {
            $('#myGallery2').galleryView({
                filmstrip_position: 'bottom',
                transition_interval: '0',
                show_panel_nav: 'false',
                panel_scale: 'nocrop',
                frame_height: 60,
                frame_width: 95,
                frame_opacity: 0.8,
                panel_width: 600,
                panel_height: 337
            });
            $('#myGallery2').addClass("initialized");
        }
    }

    $('#AmbassadorVideos li').click(function () {
        if ($('.projekktor').length > 0) {
            var player = $('.projekktor').attr('id');
            projekktor(player).setActiveItem($(this).index());
            VideoSetActive(projekktor(player).getItemIdx());
        }

        changeYoutubeVideo($(this).index());
    });

    $('#AmbassadorVideos li:first-child').click(function () {

        if ($('.projekktor').length > 0) {
            var player = $('.projekktor').attr('id');
            projekktor(player).setPlay();
            VideoSetActive(projekktor(player).getItemIdx());
        }

        changeYoutubeVideo($(this).index());
    });

    //stop video if user clicks on a tab
    $('#Ambassador .MainTabs li').click(function () {
        if ($('.projekktor').length > 0) {
            var player = $('.projekktor').attr('id');
            projekktor(player).setStop();
        }

        if ($(this).attr("id") == '1') {
            changeYoutubeVideo('0');
        }
        else {
            removeAllVideos();
        }
    });

    //stop video if user clicks on a tab
    $('#HowTo .MainTabs li').click(function () {
        if ($('.projekktor').length > 0) {
            var player = $('.projekktor').attr('id');
            projekktor(player).setStop();
        }

        var index = $(this).index();
        changeYoutubeVideo(index);
    });

    //stop video if user clicks on a tab
    $('#ProductDetails #tabcarousel li').click(function () {
        if ($('.projekktor').length > 0) {
            $('.projekktor').each(function () {
                var player = $(this).attr('id');
                projekktor(player).setStop();
            });
        }
        //removeAllVideos();
    });


    //stop video if user clicks on a tab
    $('#ProductDetails #dropdownList li').click(function () {
        if ($('.projekktor').length > 0) {
            $('.projekktor').each(function () {
                var player = $(this).attr('id');
                projekktor(player).setStop();
            });
        }
        //removeAllVideos();
    });

    /*
    //videos page
    $('#SecondaryNavigation li.active ul li').click(function () {

    projekktor("player_a").setActiveItem($(this).index());
    VideoSetActive(projekktor("player_a").getItemIdx());

    });
    $('#SecondaryNavigation li.active ul li:first-child').click(function () {
    projekktor("player_a").setPlay();
    VideoSetActive(projekktor("player_a").getItemIdx());
    });
    */
    //-----------------------------------------//
    //          gallery                         //
    if ($('#AmbassadorGallery').length > 0) {
        $('.Gallery li:first-child').addClass("active");
        $('#AmbassadorGallery li:first-child').addClass("active");
    }
    $('#AmbassadorGallery li').click(function () {
        GallerySetActive($(this).index());
    });


    if (browserIE == -1) {
        $('#PrimaryNavigation>li').hover(function () {
            EqualHeightDropdown($(this));
        }, function () { }
        );
    }

    if ($('#LandingPageNavigation').length > 0) {
        EqualHeightLanding($('#LandingPageNavigation'));
    }
    /*
    if ($('#HowTo .TabContents').length > 0) {
    EqualHeightTips($('.TabContents'));
    }
    */

});                                                                                                                                                                //end on ready

var urlParams = {};

(function () {
    var e,
			a = /\+/g,  // Regex for replacing addition symbol with a space
			r = /([^&=]+)=?([^&]*)/g,
			d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
			q = window.location.search.substring(1);

    while (e = r.exec(q))
        urlParams[d(e[1])] = d(e[2]);
})();

function VideoSetActive(index) {
    $('#SecondaryNavigation li.active ul li').removeClass('active');
    $('#SecondaryNavigation li.active ul li:eq(' + index + ')').addClass('active');
    $('#AmbassadorVideos li').removeClass('active');
    $('#AmbassadorVideos li:eq(' + index + ')').addClass('active');
    //$('#Video .Blurb li').removeClass('active');
    //$('#Video .Blurb li:eq(' + index + ')').addClass('active');
}

function GallerySetActive(index) {
    $('.Gallery li').removeClass('active');
    $('.Gallery li:eq(' + index + ')').addClass('active');
    $('#AmbassadorGallery li').removeClass('active');
    $('#AmbassadorGallery li:eq(' + index + ')').addClass('active');
}




/**
* We use the initCallback callback to assign functionality to the controls
*/
function mycarousel_initCallback(carousel) {
    jQuery('.jcarousel-control a').bind('click', function () {
        carousel.scroll(jQuery.jcarousel.intval(jQuery(this).text()));
        return false;
    });

};

function tabcarousel_initCallback(carousel) {
    jQuery('.FindOutMore li a').bind('click', function () {
        var content = $(this).text();
        var cl = $('.SimpleTabs2 li:contains("' + content + '")').attr('id');
        carousel.scroll(jQuery.jcarousel.intval(cl));
        var objDiv = document.getElementById("ProductDetails");
        window.scrollTo(0, objDiv.scrollHeight);
        return false;
    });


    jQuery('#dropdownList li').live('click', function () {
        carousel.scroll(jQuery.jcarousel.intval($(this).index()));
        return false;
    });
}

/*clear the search input*/
function clickclear(thisfield, defaulttext) {
    if (thisfield.value == defaulttext) {
        thisfield.value = "";
    }
}

function clickrecall(thisfield, defaulttext) {
    if (thisfield.value == "") {
        thisfield.value = defaulttext;
    }
}
function ReplaceNav(num) {
    $('.NavBuzz .Sublists ul:eq(' + num + ') li').each(function () {
        var i = $(this).index();
        var sideNavIndex = i - 1;
        if (i > 0) {
            var url = "#" + i;
            $(this).find('a').attr('href', url).attr('rel', 'coda-slider-1').attr('class', 'xtrig');
            //alert($('#SecondaryNavigation ul:eq(' + num + ') li:eq(' + sideNavIndex + ')').find('a').text());
            $('#SecondaryNavigation ul:eq(' + num + ') li:eq(' + sideNavIndex + ')').find('a').attr('href', url).attr('rel', 'coda-slider-1').attr('class', 'xtrig');
        }
    });
}

function searchOnClick(searchpage) {
    // when the user clicks on the search box, this is called.
    var strsearch = document.forms[0].Search.value;
    if (strsearch.length > 3 && strsearch != "SEARCH") {
        document.forms[0].__VIEWSTATE.value = "";
        document.forms[0].action = searchpage;
        document.forms[0].submit();
    }
    else {
        if (strsearch.length == 0) {
            alert("Please enter a search term.");
        }
        else {
            alert("Please enter a search term of a least 4 characters.");
        }
        document.forms[0].Search.focus();
    }

}

function searchOnEnter(searchpage, event) {
    var key = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    if (key == 13) {
        searchOnClick(searchpage);
    }
}



function EqualHeightDropdown(group) {

    var tallest = 0;

    $(group).children('.Dropdown').children('.Sublists').children('ul').each(function () {

        var thisHeight = $(this).height();
        if (thisHeight > tallest) {
            tallest = thisHeight;
        }

    });

    $(group).children('.Dropdown').children('.Sublists').children('ul').each(function () {

        $(this).height(tallest);
    });

}

function EqualHeightLanding(group) {

    var tallest = 0;

    $(group).children('ul').each(function () {

        var thisHeight = $(this).height();
        if (thisHeight > tallest) {
            tallest = thisHeight;
        }

    });

    $(group).children('ul').each(function () {

        $(this).height(tallest);
    });

}
function EqualHeightTips(group) {

    var tallest = 0;
    $(group).children('.Contents').each(function () {

        var thisHeight = $(this).height();
        if (thisHeight > tallest) {
            tallest = thisHeight;
        }

    });

    $(group).children('.Contents').each(function () {

        $(this).height(tallest);
    });

}

function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
    var rv = -1; // Return value assumes failure.
    if (navigator.appName == 'Microsoft Internet Explorer') {
        var ua = navigator.userAgent;
        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null)
            rv = parseFloat(RegExp.$1);
    }
    return rv;
}
function getIfMac() {

    if (navigator.userAgent.indexOf('Mac') != -1) {
        //alert("true");
        return true;
    }
    else {
        //alert("false");
        return false;
    }
}
function getIfFF() {

    if (navigator.userAgent.indexOf('Mozilla') != -1) {
        //alert("ff");
        return true;
    }
    else {
        return false;
    }
}
function getIfWebkit() {

    if ((navigator.userAgent.indexOf('Chrome') != -1) || (navigator.userAgent.indexOf('Safari') != -1)) {
        //alert("webkit");
        return true;
    }
    else {
        return false;
    }
}
function checkVersion() {
    var msg = "You're not using Internet Explorer.";
    var ver = getInternetExplorerVersion();

    if (ver > -1) {
        if (ver >= 8.0)
            msg = "You're using a recent copy of Internet Explorer."
        else
            msg = "You should upgrade your copy of Internet Explorer.";
    }
    alert(msg);
}

function alertFullscreen(data) {
    var browserIE = getInternetExplorerVersion();
    //alert(data + " " + browserIE); 

    //var player = $('.projekktor').attr('id');
    if (browserIE == 7) {
        if (data) {
            //if they open
            projekktor('player_a').setPause();
            projekktor('player_a').setFullscreen(false);
            OpenNewWindow(); //send the position
        }
        else {
            //if they close it, send the position back
        }
    }

}

//function VideoWindow() {
//    //var playerMain = $('.projekktor').attr('id');

//    return $('.view').html();
//}


function OpenNewWindow() {
    var newWin;
    var pageContent;
    var newWinName;
    var newWinSettings;
    //var position = plr;
    var parentwindow = self.parent;

    pageContent = "<html><head><title>Almay Videos</title><link rel='stylesheet' href='http://almaydev.squeaky.com/css/styles.css' type='text/css' media='screen' /><script src='https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js'></script><script type='text/javascript' src='http://almaydev.squeaky.com/scripts/projekktor.min.js'><script type='text/javascript' src='http://almaydev.squeaky.com/scripts/functions.js'></script>";


    newWin = window.open('/vdo.html', '', 'status=no,toolbar=no,menubar=yes,location=no,scrollbars=no,resizable=yes');

    //newWin.document.write(pageContent);

    //newWin.document.close();

}
