﻿/*

File:		eqtr_functions.js
Project:	DeAgostini Model Space
Created:	03/08/2009

Notes:

*/

$(function() {
    // initialise google link tracking
    setGoogleLinks();

    // Model Gallery
    $(".modelGallery a").click(function() {
        var imageLink = $(this).attr("href");
        $(".modelGallery .mainImage img").attr("src", imageLink);
        return false;
    });

    // Model Information Show/Hide
    $(".modelInformation .modelDetails .extra").each(function() {
        $(this).find("> h3").addClass("showHide");
        $(this).find(".showHide").click(function() {
            var extraContent = $(this).parent().find(".extraContent").eq(0);
            $(this).toggleClass("open");
            $(extraContent).each(function() {
                $(this).slideToggle(400);
            });
        });
    });

    // Model Information Show/Hide - HMS VICTORY
    $(".modelInstructions .extra").each(function() {
        $(this).find("> h3").addClass("showHide open"); // its open by default, so add open class to header
        $(this).find(".showHide").click(function() {
            var extraContent = $(this).parent().find(".extraContent").eq(0);
            $(this).toggleClass("open");
            $(extraContent).each(function() {
                $(this).slideToggle(400);
            });
        });
    });


    // Zebra stripes on Tutorial Categories list
    $("#content .subContent .tutorialCategories li:nth-child(2n)").addClass("even");


    // Dynamic Label text on email signup form
    $("#footer .emailSignup input[type=text]").each(function() {
        var labelVal = $("#footer .emailSignup label").text();
        $(this).each(function() {
            createText(labelVal, $(this));
        });
        // Removal of text on user-focus
        $(this).focus(function() {
            removeText(labelVal, $(this));
        });
        // Restoration of default text on input blur, if no user input.
        $(this).blur(function() {
            restoreText(labelVal, $(this));
        });
    });

    // Dynamic Label text on site search form
    //    $("#header .siteSearch input[type=text]").each(function() {
    //    var labelVal = $("#header .siteSearch label").text();
    //        $(this).each(function() {
    //            createText(labelVal, $(this));
    //        });
    //        // Removal of text on user-focus
    //        $(this).focus(function() {
    //            removeText(labelVal, $(this));
    //        });
    //        // Restoration of default text on input blur, if no user input.
    //        $(this).blur(function() {
    //            restoreText(labelVal, $(this));
    //        });
    //    });




    // Advertising Scroller
    $(".adImageScroller").each(function() {

        var innerContainer = $(this).find(".adScrollerInner").eq(0);

        var imageCount = $(this).find(".adImage").length;
        var innerWidth = (300 * imageCount) + 300;
        $(innerContainer).css("width", innerWidth);


        // Delay on initial image
        setTimeout(moveAdBanner, 7000);

        // Move Image and repeat after delay
        function moveAdBanner() {
            if (imageCount > 1) {
                $(innerContainer).animate({ marginLeft: -300 }, 1000, function() {
                    $(this).find(".adImage").eq(0).appendTo(this);
                    $(this).css("margin-left", "0");
                    setTimeout(moveAdBanner, 7000);

                });
            }
        };
    });
});


// Create default text for text field on page load
function createText(defVal, thisObj) {
    var inpType = thisObj.attr("type");
    if (inpType != "submit") {

        if (thisObj.attr("value") == defVal || thisObj.attr("value").length == 0) {

            thisObj.attr("value", defVal);
            thisObj.addClass("empty");
        }
    }
}

// Remove default text on focus. Ignore user-inserted text
function removeText(defVal, thisObj) {
    var inpType = thisObj.attr("type");
    if (inpType != "submit") {
        var currVal = thisObj.attr("value");
        if (currVal == defVal) {
            thisObj.attr("value", "");
            thisObj.removeClass("empty")
        }
    }
}

// Restore default text on focus. Ignore user-inserted text
function restoreText(defVal, thisObj) {
    var inpType = thisObj.attr("type");
    if (inpType != "submit") {
        var currVal = thisObj.attr("value");
        if (currVal != undefined && currVal != '') {
            thisObj.attr("value", currVal);
        }
        else if (currVal == undefined || currVal == '') {
            thisObj.attr("value", defVal);
            thisObj.addClass("empty");
        }
    }
}




// Ships Scroller Component
$(function() {


    var scrl = $(".shipScroller").eq(0);

    var demoScroller = new scroller(scrl);

    // scroller Class
    function scroller(scroller) {

        // Variables
        // - DOM object
        var scrlObject = scroller;

        //---[ Dimensions ]---//
        // Get width of scroll item, including margins
        // Get first item
        var scrlItem = $(scrlObject).find("li").eq(0);
        // get width of first item
        var scrlItemWidthTotal = getItemWidth(scrlItem);
        // No of scroll items 
        var scrlItemNum = $(scrlObject).find("li").length;
        // Total width of scroll items
        var scrlLength = scrlItemWidthTotal * scrlItemNum;
        // set width of scroll container
        $(scrlObject).find("> ul").eq(0).css("width", scrlLength);

        var scrlVisWidth = parseInt($(scrl).width());

        var scrlPageNum = scrlLength / scrlVisWidth;
        scrlPageNum = Math.round(scrlPageNum);

        // start on first page
        currPage = 0;

        // Add numbers to each Model
        var count = 1;
        var listItems = $(scrlObject).find("li").each(function() {
            var itemNumber = "<p class=\"number\ num" + count + "\">" + count + "</p>";
            $(itemNumber).appendTo(this);
            count++;
        });

        // Controls
        var controls = $('<div class="scrollControls">').appendTo(scrlObject);

        // Previous/Next Buttons
        var prevBut = document.createElement("a");
        $(prevBut).addClass("prevBut").addClass("pEnd").text("Previous");
        var nextBut = document.createElement("a");
        $(nextBut).addClass("nextBut").text("Next");

        // Page Count
        var currentPageNum;

        var totalPageNum = scrlPageNum;

        var pageCount = "<p class=\"pageCount\">Displaying: page <strong>" + (currPage + 1) + "</strong> of " + scrlPageNum + "</p>";
        $(pageCount).appendTo(controls);

        $(controls).append(prevBut).append(nextBut);

        // Find width of DOM object including padding, borders and margins
        function getItemWidth(widthItem) {
            // get width including padding + borders
            var itemWidth = parseInt($(scrlItem).outerWidth());
            // get left and right margins
            var itemWidthMarginLeft = parseInt($(scrlItem).css("margin-left"));
            var itemWidthMarginRight = parseInt($(scrlItem).css("margin-right"));
            // total width of scroll item
            var itemWidthTotal = itemWidth + itemWidthMarginLeft + itemWidthMarginRight;
            return itemWidthTotal;
        }

        function getScrollPosition() {
            var scrlPos = parseInt($(scrlObject).find("ul").eq(0).css("margin-left")) / scrlVisWidth;
            return scrlPos;
        }

        function moveScroller(clickIndex) {
            var margin = (scrlVisWidth + 4) * clickIndex;
            $(scrlObject).find("ul").animate({ marginLeft: -margin }, 300);
            updateControls(clickIndex);
        }

        function updateControls(clickIndex) {
            if (clickIndex == 0) {
                $(".prevBut").addClass("pEnd");
                $(".nextBut").removeClass("nEnd");
            }
            else if (clickIndex == (scrlPageNum - 1)) {
                $(".nextBut").addClass("nEnd");
                $(".prevBut").removeClass("pEnd");
            }
            else {
                $(".prevBut").removeClass("pEnd");
                $(".nextBut").removeClass("nEnd");
            }
        }


        $(".nextBut,.prevBut").click(function() {
            if (this.className.match(/.End/)) {
                return false;
            }
            else {
                if (this.className.match(/nextBut/)) {
                    var direction = 1;
                }
                else {
                    var direction = -1;
                }
                var scrlTo = currPage + direction;
                currPage = scrlTo;
                moveScroller(scrlTo);

                // update Page Counter
                var currentPageCount = "Displaying: page <strong>" + (currPage + 1) + "</strong> of " + scrlPageNum;
                $(this).parent().find(".pageCount").eq(0).html(currentPageCount);

                return false;



            }
        });
    }
});

$(function() {
    ///////////////////////
    // Tablet tab panels //
    ///////////////////////

    // Add "selected" class to the first tab (li) in the tablet
    $(".tablet").each(function() {
        $(this).contents().find("li").each(function(e) {
            if (e < 1) {
                $(this).addClass("selected");
            }
            else { }
        })
    });

    // Make first panel visible and hides others //
    $(".tablet").each(function() {
        $(this).contents().find(".section").each(function(e) {
            if (e < 1) {
            }
            else { $(this).hide(); }
        });
    });

    // On tab click, show corresponding panel and hide others
    $(".tablet .controls a").click(function() {
        // Find position of clicked tab in array of tabs
        var currListItem = $(this).parent();
        var tabIndex = $(this).parent().parent().find('> *').index(currListItem);

        $(this).parents(".tablet").eq(0).find(".section").each(function() {
            // Find position of each content section in array of sections
            var sectionIndex = $(this).parent().find('> *').index(this);
            // If index of content section matches index of clicked tab -> Show Content
            if (tabIndex == sectionIndex) {
                $(this).show();
            }
            // Otherwise hide content
            else { $(this).hide(); }
        });
        // Set "selected" class on clicked tab (li) 
        $(this).parents(".tablet").eq(0).find(".controls a").each(function() {
            $(this).parents("li").eq(0).removeClass("selected");
        });
        $(this).parents("li").eq(0).toggleClass("selected");
        // Disable link
        $(this).blur();
        return false;
    });
});


$(function() {
    // Features Carousel //

    // Setup

    $(".featureCarousel ul li").eq(0).addClass("active");

    $(".featureCarousel ul li").each(function() {

        var intro = $(this).find("p.intro").eq(0).text();

        // Create overlay from exising content and add to feature
        var heading = $(this).find("h2").eq(0).text(); ;
        var featImage = $(this).find("p.featImage").eq(0);
        var overlay = document.createElement("div");
        $(overlay).addClass("overlay");
        var overlayIntro = document.createElement("p");
        var overlayAnchor = document.createElement("a");
        if (intro) {
            $(overlayIntro).text(intro);
            $(overlay).append(overlayIntro);
        }

        //$(this).append(featImage);
        $(this).find("a").eq(0).append(overlay);

        $(".featureCarousel ul li").eq(0).addClass("active");
        $(".homepage .featureCarousel ul li").eq(0).removeClass("active");
    });

    $(".featureCarousel ul li:last").addClass("last");

    $(".featureCarousel ul li").hover(function() {
        $(".featureCarousel ul li").removeClass("active");
        $(this).addClass("active");
    }, function() {

    });

});

// google link tracking code. Uses jquery
function setGoogleLinks() {

    // Variable for urls that are NOT external
    // Reg Exp matching. Urls are delimited by the pipe | and dots are escaped with \.
    // Most bases are covered with location.host, but there are the situations
    // where it might link to a sub-domain e.g. www.site.com --> secure.site.com
    // For sub-domain cases you just need the domain part of the url and it will be matched for all subdomains
    var onsiteUrls = location.host;

    // Variable for download file extensions. Assumes that the file type is at the end of the href.
    // Uses reg exp. File types are delimited by the pipe |
    var downloadDocTypes = "(pdf|doc|docx)$";

    // The page that the link was requested from. Removes any leading or ending forward slash
    var pageLocation = unescape(location.pathname.replace(/(^\/)|(\/$)/g, ""));

    // regular expression for external site testing
    var site = new RegExp(onsiteUrls, "ig");
    // regular expression for downloads
    var download = new RegExp(downloadDocTypes, "ig");

    $("a").each(function(e) {
        // Local variable for holding the action. Don't need to change. Current actions handled are
        // mailto, download and external
        var action = "";

        // don't track for javascript links and bookmarks
        if (this.href.match(/(^javascript)|(^#)/) || !this.href) return true;

        // mailto
        if (this.href.match(/mailto/ig)) {
            action = "mailto";
        }
        // download
        else if (this.href.match(download)) {
            action = "download";
        }
        // external link
        else if (!this.href.match(site)) {
            action = "external";
        }

        // if there is an action identified add a click event handler.
        if (action) {

            // use the href of the link as an identifier. Strip out the http protocol from the front and trailing forward slash
            var thisLink = this.href.replace(/http[s]*:\/\/|\/$/g, "");
            var googlePageview = "/" + action + " / " + thisLink + " / " + pageLocation;

            $(this).click(function() {

                // debugging for FF and safari
                //                console.info(action);
                //                return false;
                // End debug

                /* Can use pageview or event tracking or both. */

                // Use page view to track links
                pageTracker._trackPageview(googlePageview);

                // Use event tracking to track links
                pageTracker._trackEvent("Links", action, "TO: " + thisLink + "; FROM: " + pageLocation);
            });
        }
    });
}