//
// Hide the page content if the url has a hash indicating that new content
// is to be dynamically loaded immediately
//
if (location.hash) {
  var head = document.getElementsByTagName("head")[0];    
  var cssNode = document.createElement("link");
  cssNode.type = "text/css";
  cssNode.rel = "stylesheet";
  cssNode.href = "/css/hideSlider.css";
  cssNode.media = "screen";
  cssNode.id = "hideSlider"
  head.appendChild(cssNode);
}

var currentPageSelector;
var BodyController = $('#ctl00_MasterBody');

$(function() {

    var SLIDE_ANIMATION_TIME = 1000;
    var FADE_ANIMATION_TIME = 500;

    var CAROUSEL_ID_EXTRACT = /id_(\d+)/;
    var HASH_URL_EXTRACT = /(\d+)_(.+)/;
    var URL_PATH_EXTRACT = /[a-z]+:\/\/[a-zA-Z0-9-\.]+(\/.*)/;
    //
    // Used on the index select box to determine the slide
    // position which should be opened
    //
    var BODY_CARE_URL = "bodycare";
    var FACIAL_CARE_URL = "facialcare";

    //
    // Append to urls to generate page contact for the slider
    // i.e. without the head/footer 
    //
    var SLIDER_URL_APPEND = "js=1";

    var MENU_LINK_CLASS = "menuLink";

    var SLIDE_OPTIONS_SHOW = { width: 'show' };
    var SLIDE_OPTIONS_HIDE = { width: 'hide' };

    //
    // Opacity change causes visual artifacts in IE (6 to 8), so
    // only implement slide if a non-IE browser is used.
    //
    if (!$.browser.msie) {
        SLIDE_OPTIONS_SHOW.opacity = "show";
        SLIDE_OPTIONS_HIDE.opacity = "hide";
    }

    //
    // Retrieve once, use many
    //
    var menu = $(".menu");
    var menuItems = $(".menu > .menuItem");
    var slideLayer = $(".slideLayer");
    var slideLayerContent = $(".slideLayer > .slideLayerContent");

    //
    // For the purpose of the history we need to keep track of the initail
    // slide s
    // 
    var initialSlideState = null;

    //
    // Initialise the menu slider
    //
    function initSlider() {

        //
        // Attach an event to each of the links (tabs) in the menu
        //
        $(".menuItem a", menu).click(function() {
            var li = this.parentNode;
            closeSlider(this.href, li);
            return false;
        });
        return;
    }

    //
    // Return the index of a list element irrespective of the position of the
    // page content.  Needed because the page content is inserted inside the
    // menu, so the index of menu elements changed depending on the positioning
    // of the content
    //
    function fixIndex(slideLayer, menuIndex) {
        var slideLayerIndex = slideLayer.index();
        return (slideLayerIndex > menuIndex ? menuIndex + 1 : menuIndex);
    }


    //
    // Close the slider and dynamically load the content specified by the url.
    // list element parameter indicates where in the menu the new layer content
    // should be inserted.
    //
    function closeSlider(url, li) {


        //
        // Fix the height of the menu to prevent window scroll bar appearing/
        // disappearing whilst content is transitioning.  Height is restored to 
        // auto in the openSlider callback.
        //
        menu.height(slideLayerContent.height());

        //
        // Simple object to store process completion info.
        //
        var slideInfo = { li: li, url: url };

        //
        // Update the url hash so we can get back to the page via javascript.
        // Don't manipulate the hash if we're reopening the initial page
        //
        if (location.href.indexOf(url) < 0) {
            location.hash = fixIndex(slideLayer, $(li).index()) + "_" +
              (url.indexOf("/") > 0 ?
                 url.substr(location.host.length + url.lastIndexOf(location.host)) :
                 url);
        } else {
            location.hash = "";
        }

        currentUrl = location.pathname + location.search + location.hash;

        //
        // Start loading ajax immediately.  js parameter is appended to
        // anchor url to instruct the server to return only the part of 
        // the page to display within the slider, rather than the complete
        // page.
        //

        if (BodyController.hasClass(currentPageSelector))
            BodyController.removeClass(currentPageSelector);
        currentPageSelector = ""; //reset 


                $.get(url + (url.indexOf("?") >= 0 ? "&" : "?") + SLIDER_URL_APPEND, function(data) {
                    slideInfo.data = data;
                    //alert("data: " + data);
                    openSlider(slideInfo);
                });


        //$(window.location).attr('href', url);
        //
        // Close the slider
        //
        slideLayer.animate(SLIDE_OPTIONS_HIDE, SLIDE_ANIMATION_TIME, function() {
            slideInfo.animationComplete = true;
            openSlider(slideInfo);
	
	    //
            // TODO - scroll to top of page on change?
            //
            // window.scrollTo(0,0);
        });


        return;

    }

    //
    // The opening of the slider is contingent on the completion of 2 
    // asychronous processes.  openSlider() is called on the completion
    // of each (the closing of the slider, and the loading of the data)
    // but the main part of the function only executes when both are
    // complete.
    //
    function openSlider(slideInfo) {

        if (slideInfo.animationComplete) {
           
            $("#hideSlider").remove();
            slideLayerContent.html(slideInfo.data);

            //CBW - this is the point we decide to edit the body class selector, depending on the page served

            if (slideInfo.li) {
                slideLayer.insertAfter(slideInfo.li);
            } else {
                //
                // If no list element is specified, place at start of menu
                //
                slideLayer.insertBefore(menu[0].firstChild);
            }
            menu.height("auto");
            slideLayer.animate(SLIDE_OPTIONS_SHOW, SLIDE_ANIMATION_TIME);

            //
            // Change the class of the page body tag to reflect the new 
            // section.  Necessary for slide layer backgrounds
            //
            // Video page opens in the home page section, but must omit the 
            // home page class to prevent the background image displaying
            //
            if (slideInfo.url.toLowerCase().indexOf("video") < 0) {
                var cls = $(slideInfo.li).children(":first").attr("rel");
                $("body").attr("class", cls);
            } else {
                $("body").attr("class", "");
            }

            if (currentPageSelector) {
                if (!BodyController.hasClass(currentPageSelector)) {

                    $('#ctl00_MasterBody').addClass(currentPageSelector);

                }
            }

            //
            // Run any initialisation functions
            //
            initAfterSlide();
        }
        return;
    }


    //
    // Initialise quotes carousel.  Tried to use jCarousel, but it uses 
    // relative positioning, which causes interference with the slider
    // on IE (relatively positioned elements remain visible even when the 
    // slider is closed) - hence the hand rolled solution.
    //
    function initCarousel() {
        var scroller = $("#yourActsScroller");
        if (scroller.length) {

            $('#scrollerNext, #scrollerPrev').click(function() {
                if ($("#yourActsScroller > li").length == 1) {

                    CAROUSEL_ID_EXTRACT.test($("#yourActsScroller ul > li:first").attr("class"));
                    var id = RegExp.$1;

                    //
                    // Post used instead of $.getJSON to work around .net issues
                    //
                    $.ajax({
                        type: "POST",
                        url: "/moments.asmx/GetPageOfMoments",
                        dataType: "json",
                        data: "{'firstId':'" + id + "', 'direction':'" +
                              (this.id == "scrollerNext" ? "next" : "prev") + "'}",
                        contentType: "application/json; charset=utf-8",
                        success: function(data) {
                            updateCarousel(scroller, data);
                        }
                    });

                }
                return false;
            });
        }
        return;
    }


    //
    // Ajax callback to update the quotes carousel
    //
    function updateCarousel(list, dat) {
        var scrollBlock = $(document.createElement("li")).addClass("scrollBlock");
        var ul = $(document.createElement("ul"));
        scrollBlock.append(ul);

        var data = dat.d
        for (var ii = 0; ii < data.Results.length; ++ii) {

            var li = $(document.createElement("li")).addClass("entry").addClass("id_" + data.Results[ii].Id);
            var bq = $(document.createElement("blockquote"));
            var sig = $(document.createElement("div")).addClass("signature");

            bq.html(data.Results[ii].Text);
            sig.html(data.Results[ii].Name);

            li.append(bq);
            li.append(sig);
            ul.append(li);
        }

        var currentBlock = list.children(":first");

        //
        // Fade in/out
        //
        scrollBlock.fadeOut(0).hide();
        list.append(scrollBlock);
        currentBlock.fadeOut(FADE_ANIMATION_TIME, function() {
            scrollBlock.fadeIn(FADE_ANIMATION_TIME);
            currentBlock.remove();
        });
        return;
    }

    function initScienceOfSoftnessTabs() {
        $('#whatMakesSkinSoftBreakdown').attr('class', 'js');
        $('#keyPieceTabsNavigation li a').click(function() { $('#keyPieceTabs').attr('class', this.hash.toString().substring(1)); pageTracker._trackPageview("/science/" + this.hash.toString().substring(1)); return false; });
    }


    //
    // Javascript to manage home page product search box
    //
    function initProductSearch() {
        $(".productSearch").change(function() {

            var url = $(this).val();
            //
            // Fix the url if includes the host. 
            //
            if (URL_PATH_EXTRACT.test(url)) {
                url = RegExp.$1;
            }
            if (url && url.toLowerCase().indexOf(BODY_CARE_URL) >= 0) {
                closeSlider(url, $(".menuBodyCare")[0]);
            } else {
                closeSlider(url, $(".menuFacialCare")[0]);
            }
        });
        return;
    }

    //
    // Show/hide share link on rewarding softness confirmation page
    //
    function initialiseShareLink() {
        $(".shareLink").toggle(
        function() { $("#shareOptions").show("fast") },
        function() { $("#shareOptions").show("fast") }
      );
        return;
    }


    //
    // Array of functions to execute when the slider opens.  This 
    // will initiate, for example, the code to change the "moments"
    // display, and the code to operate the product selector on the
    // home page.
    //
    var intialisationFunctions = [];

    //
    // Execute slide content initalisation functions
    //
    function initAfterSlide() {
        for (var ii = 0; ii < intialisationFunctions.length; ++ii) {
            intialisationFunctions[ii]();
        }
        return;
    }


    //
    // Make product lists clickable in their entirety
    //
    function initialiseProductListLinks() {
        if ($.browser.version > 5) {
            $(".productList li").click(function(e) {
                slideLink($("a:first", this)[0]);
                return false;
            });
        }
        return;
    }

    function initialiseFlashVideoContent() {
        if (!$.browser.msie || $.browser.version >= 8) {
            if ($("#videoContainer").length == 1) {
                //initialise flash video here for IE
                //alert('video container');
                swfobject.embedSWF("http://www.youtube.com/v/nsA3nJmx-Cs&hl=en&fs=1", "videoContainerInner", "386", "641", "9.0.0", "expressInstall.swf");
            }
        }
        return;
    }


    intialisationFunctions.push(initCarousel);
    intialisationFunctions.push(initProductSearch);
    intialisationFunctions.push(initialiseShareLink);
    intialisationFunctions.push(initialiseProductListLinks);
    intialisationFunctions.push(initialiseFlashVideoContent);
    intialisationFunctions.push(initScienceOfSoftnessTabs);

    initAfterSlide();


    //
    // Open a link in the slider
    //
    function slideLink(a) {
        var url = a.href;
        if (URL_PATH_EXTRACT.test(a.href)) {
            url = RegExp.$1;
        }
        if (a.rel) {
            var menuIndex = parseInt(a.rel);
            var li = null;
            if (menuIndex) {
                li = menuItems.eq(menuIndex - 1);
            }
        }
        closeSlider(url, li);
        return false;
    }


    //
    // Slider code is only executed once, but never for IE6 (code works
    // but the effect is too slow and unsightly to use in production.)
    //
    if (!$.browser.msie || $.browser.version > 6) {
        initSlider();

        //
        // Ensure all links within the site operate via the slider.
        //

        
        $('a:not(.popup)').live("click", function() {
            //
            // TODO disable slider link for video page for IE6&7
            //
            if ($.browser.msie && $.browser.version < 8) {
                if (this.href.indexOf("video") >= 0) return;
            }

            //flat url calls for the below anchors, this will force SSL from the back-end
            if (this.href.indexOf("momentsofsoftness/add.aspx") >= 0) return;
            if (this.href.indexOf("contact.aspx") >= 0) return;

            //
            // Exclude menu items - they're special cases handled elsewhere - and external links
            //
            if (!$(this).hasClass(MENU_LINK_CLASS) && this.href.indexOf(location.host) >= 0) {
                slideLink(this);
                return false;
            }

        });
    }


    //
    // Extract the url and list element index from the hash
    //
    function getHashDetails(hash) {
        hash = hash || location.hash;
        if (hash && HASH_URL_EXTRACT.test(hash)) {
            var li = $(".menu > .menuItem")[parseInt(RegExp.$1) - 1];
            var url = RegExp.$2;
            return { url: url, li: li };
        }
    }

    //
    // If location.hash indicates that another url should be loaded, do so
    // immediately.
    //
    var hashDetails = getHashDetails();
    if (hashDetails) {
        closeSlider(hashDetails.url, hashDetails.li);
    } else {
        $("#hideSlider").remove();
    }


    //
    // Attempt to enable back functionality with the sliders. 
    // When the url is changed via the closeSlider function,
    // currentUrl is also updated.  If these two ever differ,
    // it implies that the url has been modified by an external
    // mechanism i.e. the back or forward button, so we manipulate 
    // the slider to follow suite.
    //


    var originalUrl = location.pathname + location.search;
    var originalTab = slideLayer[0].previousSibling;
    var currentUrl = location.pathname + location.search + location.hash;
    //
    // TODO Comment back in and test
    //
    if (false) window.setInterval(
      function() {
          var url = location.pathname + location.search + location.hash;

          if (url != currentUrl) {
              var hashDetails = getHashDetails(url);
              if (hashDetails) {
                  currentUrl = url;
                  closeSlider(hashDetails.url, hashDetails.li);
              } else {
                  closeSlider(originalUrl, originalTab);
              }
          }
      },
      100
    );

    var onEditCallback = function(remaining) {
        $('p.charsRemaining').text("Characters remaining: " + remaining);

        if (remaining > 0) {
            $(this).css('border', '1px solid #8EABD5');
        }
    }

    var onLimitCallback = function() {
        $(this).css('border', '1px solid #FF0000');
    }

    $('textarea[maxlength]').limitMaxlength({
        onEdit: onEditCallback,
        onLimit: onLimitCallback
    });



});