﻿/*

File:		eqtr_functions.js
Project:	DeAgostini Model Space
Created:	03/08/2009

Notes:

*/

$(window).load(
    function () {
        setPromoHeight();
    });


function setPromoHeight() {

    $(".militaryPromo .innerPromo").each(function () {

        var copyArea = $(".copy", this);
        var imageHeight = $(".image img", this).outerHeight();
        var paddingTop = copyArea.css("padding-top").replace("px", "") * 1;
        var paddingBottom = copyArea.css("padding-bottom").replace("px", "") * 1;
        var totalHeight = imageHeight - (paddingBottom + paddingTop);
        copyArea.height(totalHeight);

    });
}


$(function () {

    // Add class to format components in rows
    $(".componentRow .item:first-child").addClass("first");

    // 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,.modelInstructions .extra").each(function () {
        $(this).find("> h3").addClass("showHide");

        if ($(this).parent().hasClass("modelInstructions")) {
            $(this).find("> h3").addClass("open");
        }

        $(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);

                });
            }
        };
    });

    $(".scroller").each(function () {
        createScroller($(this));
    });
});


// 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");
        }
    }
}



// Scroller class
function createScroller(scroller) {

    var scrollerType;

    if ($(scroller).eq(0).hasClass("modelScroller")) {
        scrollerType = "model";
    }

    else if ($(scroller).hasClass("promoScroller")) {
        scrollerType = "promo";
    }

    // 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($(scrlObject).width());

    var scrlPageNum = scrlLength / scrlVisWidth;
    scrlPageNum = Math.round(scrlPageNum);

    // start on first page
    var currPage = 0;
    // Total number of items to scroll through
    var itemNum = $(scrlObject).find(".scrollerItem").length;

    //alert(itemNum);
    // Page Count
    var currentPageNum;
    var totalPageNum = scrlPageNum;

    if (scrollerType == "model") {
        addNumbers();
        addModelControls();
        setupModelButtons();
    }

    if (scrollerType == "promo") {
        //addControls(scrlObject);
		var timerID = null;
		var scrollItems = $(scrlObject).find(".scrollerItem").detach();
		var itemWidth = getItemWidth($(scrlObject).find(".scrollerItem").eq(0));
		setupPromoContainers(scrollItems);	

		function advanceFeature() {
		    movePromoScroller(1, scrollItems);
            timerID = setTimeout(advanceFeature, 5000);
        }
        timerID = setTimeout(advanceFeature, 5000);
    }

    function setupPromoContainers(scrollItems) {
        var virtualScrollItems;
        $(scrlObject).find("ul").remove();
        $(virtualScrollItems).append(scrollItems);
        var listLength = $(scrollItems).length;
        var infiniteContainer = document.createElement("div");
        $(infiniteContainer).addClass("infiniteContainer");
        $(scrlObject).find(".scrollerItems .inner").append(infiniteContainer);
        $(infiniteContainer).append($(scrollItems).eq(currPage));
    }

    // Add next and previous controls to the scroller - INFINITE SCROLLER
    function addPromoControls() {
        // Controls
        var controls = $('<div class="scrollControls">').appendTo(scrlObject);
        // Previous/Next Buttons
        var prevBut = document.createElement("a");
        $(prevBut).addClass("prevBut").text("Previous");
        var nextBut = document.createElement("a");
        $(nextBut).addClass("nextBut").text("Next");
        $(controls).append(prevBut).append(nextBut);
    }

    function setupPromoButtons(scrollItems) {
        $(scrlObject).find(".nextBut,.prevBut").click(function (scrlObject) {

            if (this.className.match(/.End/)) {
                return false;
            }
            else {
                if (this.className.match(/nextBut/)) {
                    var direction = 1;
                }
                else if (this.className.match(/prevBut/)) {
                    var direction = -1;
                }
                movePromoScroller(direction, scrollItems);
                return false;
            }
        });
    }

    function movePromoScroller(direction, scrollItems) {
        $(scrlObject).addClass("moving");
        //alert("moving");
        
        if (direction == -1){
            if (currPage == -1) {
                currPage = itemNum - 1;
            }
            var nextPage = currPage - 1;
            if (nextPage == -1) {
                nextPage = itemNum - 1;
            }
            $(scrlObject).find(".infiniteContainer").eq(0).prepend($(scrollItems).eq(nextPage).addClass("previousItem"));
            $(scrlObject).find(".infiniteContainer").eq(0).find(".previousItem").eq(0).animate({ marginLeft: 0 }, 750, function () {
                $(scrlObject).find(".infiniteContainer").eq(0).find(".previousItem").eq(0).removeClass("previousItem").removeAttr("style");
                $(scrlObject).find(".infiniteContainer").eq(0).find(".scrollerItem").eq(1).detach();
                $(scrlObject).removeClass("moving");
            })
            currPage = currPage - 1;
            
        }

        if (direction == 1) {
            if (currPage == itemNum) {
                currPage = 0;
            }
            var nextPage = currPage + 1;
            if (nextPage == itemNum) {
                nextPage = 0;
            }
            $(scrlObject).find(".infiniteContainer").eq(0).append($(scrollItems).eq(nextPage));
            $(scrlObject).find(".infiniteContainer").eq(0).find(".scrollerItem").eq(0).animate({ marginLeft: -517 }, 750, function () {
                $(scrlObject).find(".infiniteContainer").eq(0).find(".scrollerItem").eq(0).removeAttr("style");
                $(scrlObject).find(".infiniteContainer").eq(0).find(".scrollerItem").eq(0).detach();
                $(scrlObject).removeClass("moving");
            })
            currPage = currPage + 1;
        }
    }
    
    // Add next and previous controls to the scroller
    function addModelControls() {
        // 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");
        if ((currPage + 1) == scrlPageNum) {
            $(nextBut).addClass("nEnd");
        }
        $(controls).append(prevBut).append(nextBut);

        if (scrollerType == "model") {
            var pageCount = "<p class=\"pageCount\">Displaying: page <strong>" + (currPage + 1) + "</strong> of " + scrlPageNum + "</p>";
            $(pageCount).appendTo(controls);
        }
    }

    function setupModelButtons() {
        $(scrlObject).find(".nextBut,.prevBut").click(function (scrlObject) {
            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;
                moveModelScroller(scrlTo, scrlObject);

                // update Page Counter
                var currentPageCount = "Displaying: page <strong>" + (currPage + 1) + "</strong> of " + scrlPageNum;
                $(this).parent().find(".pageCount").eq(0).html(currentPageCount);

                return false;
            }
        });
    }

    function moveModelScroller(clickIndex) {
        var margin = (scrlVisWidth + 6) * clickIndex;
        if (scrollerType == "promo") {
            margin = (scrlVisWidth) * clickIndex;
        }

        $(scrlObject).find("ul").animate({ marginLeft: -margin }, 500);
        updateControls(clickIndex);
    }
    
    // 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;
        return itemWidthTotal;
    }

    // Add a number to each item - Model Scroller
    function addNumbers() {
        // 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++;
        });
    }

    function getScrollPosition() {
        var scrlPos = parseInt($(scrlObject).find("ul").eq(0).css("margin-left")) / scrlVisWidth;
        return scrlPos;
    }

    function updateControls(clickIndex) {
        if (clickIndex == 0) {
            $(scrlObject).find(".prevBut").addClass("pEnd");
            $(scrlObject).find(".nextBut").removeClass("nEnd");
        }
        else if (clickIndex == (scrlPageNum - 1)) {
            $(scrlObject).find(".nextBut").addClass("nEnd");
            $(scrlObject).find(".prevBut").removeClass("pEnd");
        }
        else {
            $(scrlObject).find(".prevBut").removeClass("pEnd");
            $(scrlObject).find(".nextBut").removeClass("nEnd");
        }
    }
}
// End of Scroller function


$(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() {

    });

});

function dateToString() {
    var d, m, y;
    var delimiter = "/";
    var date = null;
    if (arguments.length <= 2) {
        date = new Date(arguments[0]);

        if (arguments[1]) delimiter = arguments[1];
    }
    else {
        date = new Date(arguments[2], arguments[1] - 1, arguments[0]);
        if (arguments[3]) delimiter = arguments[3];
    }

    d = date.getDate();
    m = date.getMonth() + 1;
    y = date.getFullYear();

    return ("0" + d).slice(-2) + delimiter + ("0" + m).slice(-2) + delimiter + y;
}

