﻿var PanelInterval = 8000; //the timer interval
var CarouselTimer = 600000; //the timer that will shut down the carousel animation

var t = null;  //used for timer
var tC = null;  //used for timer

function pageInit(e) {
    setYUINav();
    setSearchSubmit();
    setAnimatePanels();
    setScrollPanels();
    setCarousels();
    setImagePopups();
    setFormCheck();
}

function setYUINav() {
    YUI().use("node-menunav", function(Y) {
        if (Y.one("#yui3-nav")) {
            var menu = Y.one("#yui3-nav");
            menu.plug(Y.Plugin.NodeMenuNav);
            menu.get("ownerDocument").get("documentElement").removeClass("yui3-loading");
        }
    });
}

function setCarousels() {
    YUI().use("node", function(Y) {
        if (Y.one('.NextCarousel')) {
            t = setTimeout("fnTimerForNext()", PanelInterval);
            tC = setTimeout("fnTimerForCarouselOff()", CarouselTimer);
            Y.all('.NextCarousel').on('click', moveCarousel);
            Y.all('.PreviousCarousel').on('click', moveCarousel);
            Y.all('#HomeCarouselPanels li').on('click', moveToPanelURL);
        }
    });
}

function fnTimerForCarouselOff() {
    //Kills the timer after a little while, if animation runs forever memory gets used up
    clearTimeout(t);
}

function setSearchSubmit() {
    YUI().use('event-key', function(Y) {
        // store the return value from Y.on to remove the listener later
        if (Y.one('#dnn_HDLayout_Search_txtSearch')) {
            var handle = Y.on('key', function(e) {
                e.halt();
                //if it is not empty go ahead and click the search button
                if (e.target.get("value") != '') {
                    clickSearch(e.target.get("value"))
                };
                // Attach to 'text1', specify keydown, keyCode 13, make Y the context, add arguments
            }, '#dnn_HDLayout_Search_txtSearch', 'down:13');

        }
    });

}

function clickSearch(val) {
    location.href = "/default.aspx?tabid=55&Search=" + val
}

function setImagePopups() {
    YUI().use("node", function(Y) {
        if (Y.one('.pop')) {
            Y.all('.pop').on('click', openPopupWindow);
        }
    });
}

function openPopupWindow(e)
{
    e.preventDefault();

    YUI().use("node", function(Y) {
        var imageID = e.target.get("id");
        if (imageID == '') {
            alert('The a tag must have an id!')
        } else {
            window.open('/ImagePopup.aspx?ImageID=' + imageID, 'popup', 'toolbar=no,location=no,status=yes,menubar=no,scrollbars=no,resizable=no');
        }
    });
}

function fnTimerForNext() {

    YUI().use('node-event-simulate', function(Y) {
        if (Y.one('.NextCarousel')) {

            ndeNexts = Y.all('.NextCarousel')
            
            //could not use all here
            ndeNexts.each(function(node) {
                node.simulate("click");
            });
            
        }
    });

}

function moveToPanelURL(e) {
    YUI().use("node", function (Y) {
        var aElem = e.target.one('a');

        //the user may have clicked on the h1 or h6 tag inside the li
        if (aElem == null) {
            aElem = e.target.get('parentNode').one('a');
        }

        window.location = aElem.get('href');
    });
}

function moveCarousel(e) {
    e.preventDefault();
    
    //do not run this if the animation is running
    if (!e.target.hasClass("Running")) {

        //if prev or next is off then do not fire
        if (!e.target.hasClass("Off")) {

            YUI().use("anim", function(Y) {

                var previousElemClass = '.PreviousCarousel';
                var nextElemClass = '.NextCarousel';
                var liFirstNodeForPrevious = 0; //this is the node in the list that turns of the previous button

                //get the div that contains all the carousel elements
                var nodeCarouselAll = e.target.get('parentNode');

                //if this is the parent then we need to go up one more level
                if (nodeCarouselAll.hasClass("PrevNextW")) {
                    nodeCarouselAll = nodeCarouselAll.get('parentNode');
                    liFirstNodeForPrevious = 1;
                }

                //For the Hero Carousel
                if (nodeCarouselAll.hasClass("HeroCarouselW") || nodeCarouselAll.hasClass("NewsHomeCarouselW")) {
                    //the first node is actually a placeholder so the page looks good when it is first loaded
                    //so we actually check for the second node to disable the previous button

                }

                //add the running class, so the anim does not run if the button or timer goes off
                nodeCarouselAll.one(previousElemClass).addClass("Running");
                nodeCarouselAll.one(nextElemClass).addClass("Running");

                var carouselVisibleWidth = nodeCarouselAll.one(".Carousel").getStyle("width").replace("px", "");

                //get all the lis in the carousel
                var carouselLis = nodeCarouselAll.all('.Carousel li');

                //get the parent ul
                var ulToMove = carouselLis.item(0).get("parentNode");
                //need the id so the anim knows which node to move
                var ulToMoveID = ulToMove.get("id");

                //get the width of the first to determine amount to move
                var liRegion = carouselLis.item(0).get("region");
                var liRegionWidth = liRegion.right - liRegion.left;
                var xPos = 0;

                var liOn = -1;
                var liToBeOn = -1;
                var carouselSize = carouselLis.size()

                //get the li that is currently displayed
                for (i = 0; i < carouselSize; i++) {
                    if (carouselLis.item(i).hasClass("on")) {
                        liOn = i;
                    }
                }

                //reset the width before and after animation
                var ulStandardWidth = carouselVisibleWidth * (carouselSize + 1)
                var ulStandardWidthPlusOneMore = carouselVisibleWidth * (carouselSize + 2)

                //determines which we go
                if (e.target.hasClass(previousElemClass.replace(".", ""))) {
                    xPos = ulToMove.getX() + liRegionWidth;
                    liToBeOn = liOn - 1;
                } else {
                    xPos = ulToMove.getX() - liRegionWidth;
                    liToBeOn = liOn + 1;
                    if (nodeCarouselAll.one(previousElemClass).hasClass("Off")) {
                        nodeCarouselAll.one(previousElemClass).removeClass("Off");
                    }
                }

                var yPos = ulToMove.getY();

                var enableDisableCheck = function() {

                    YUI().use("node", function(Y) {
                        //remove the li that was on
                        carouselLis.item(liOn).toggleClass('on');

                        if (liToBeOn == 0 || liToBeOn == carouselSize - 1) {
                            //drop the node that was moved
                            carouselLis.item(iPositionToClone).remove();

                            //reset the animation
                            ulToMove.setStyle("left", resetLeftStyle);
                            ulToMove.setStyle("width", ulStandardWidth);
                        }

                        nodeCarouselAll.one(previousElemClass).removeClass("Running");
                        nodeCarouselAll.one(nextElemClass).removeClass("Running");

                    });
                }

                //add the on class to the one coming in        
                carouselLis.item(liToBeOn).toggleClass('on');

                if (liToBeOn == 0 || liToBeOn == carouselSize - 1) {
                    var resetLeftStyle = ulToMove.getStyle("left").replace("px", "");
                    ulToMove.setStyle("width", ulStandardWidthPlusOneMore);

                    (liToBeOn == 0) ? iPositionToClone = carouselSize - 1 : iPositionToClone = 0;

                    //clone either the first or last one in the node list
                    var ndeClone = carouselLis.item(iPositionToClone).cloneNode('deep');

                    //if we are going backwards do a little bit extra
                    //to make sure everything is lining up correctly
                    if (liToBeOn == 0) {
                        ulToMove.insert(ndeClone, 0);
                        ulToMove.setStyle("left", resetLeftStyle - liRegionWidth);
                        xPos = xPos - liRegionWidth;
                    } else {
                        ulToMove.append(ndeClone);
                    }

                }

                var anim = new Y.Anim({
                    node: '#' + ulToMoveID,
                    duration: 0.8,
                    easing: Y.Easing.easeIn,
                    to: { xy: [xPos, yPos] }
                });

                anim.once('end', enableDisableCheck);
                resetCarouselTimer();
                anim.run();

            });
        }
    }
}

function resetCarouselTimer() {
    clearTimeout(t);
    t = setTimeout("fnTimerForNext()", PanelInterval);
}



function setAnimatePanels() {
    YUI().use('anim', function(Y) {

        var animPanel = new Y.Anim({
            from: { height: 0 },
            to: { height: 0 },
            easing: Y.Easing.easeOut,
            duration: .5
        });

        var onClick = function(e) {
            e.preventDefault();
            var heightTo = 0;
            var heightFrom = 0;

            var nodeParent = e.target.get('parentNode');
            
            //The sibling node of the .AnimC node
            var nodeToAnimate = nodeParent.next();
            var scrollHeight = nodeToAnimate.get('scrollHeight');
            var nodeHeight = nodeToAnimate.getStyle('height').replace('px', '');

            if (nodeHeight == '0') {
                heightTo = scrollHeight;
            } else {
                heightFrom = scrollHeight;
                var togglerHTML = '+'
            }

            animPanel.set('from.height', heightFrom);
            animPanel.set('to.height', heightTo);
            animPanel.set('node', nodeToAnimate)
            animPanel.run();
            nodeParent.toggleClass('AnimCOpen');
            nodeToAnimate.toggleClass('AnimPOpen')

        };

        Y.all('.AnimC .toggler').on('click', onClick);

    });
}

function setScrollPanels() {
    YUI().use('anim', function(Y) {

        var animScroll = new Y.Anim({
            to: { scroll: [0, 400] },
            easing: Y.Easing.easeOut,
            duration: 1.5
        });

        var onClick = function(e) {
            e.preventDefault();
            var node = e.target;
            var idClicked = node.get("id")
            var idToScrollTo = idClicked.replace("_scroller_a", "_scroller");

            var nodeToScroll = Y.one('#' + idToScrollTo);
            var nodeToScrollParent = nodeToScroll.get('parentNode');

            var nodeToScrollParentChilren = nodeToScrollParent.all('li');
            var nodeOn = -1;
            var nodeToBeOn = -1;
            var amountToScroll = 0;

            for (i = 0; i < nodeToScrollParentChilren.size(); i++) {
                if (nodeToScrollParentChilren.item(i).hasClass("on")) {
                    nodeOn = i;
                }

                if (nodeToScrollParentChilren.item(i).get("id") == idToScrollTo) {
                    nodeToBeOn = i;
                }

                if (nodeOn != -1 && nodeToBeOn != -1) {
                    break;
                }

                if (nodeOn != -1 && nodeToBeOn == -1) {
                    amountToScroll = amountToScroll + nodeToScrollParentChilren.item(i).get('offsetHeight');
                }

                if (nodeOn == -1 && nodeToBeOn != -1) {
                    amountToScroll = amountToScroll - nodeToScrollParentChilren.item(i).get('offsetHeight');
                }

            }

            //Calculate the duration of the animation
            var iNodeToScrollHeight = nodeToScroll.get('offsetHeight');
            //get the position scrolling to divided by the height
            //divide that by 2 to speed up the animation some.
            var drt = ((Math.abs(nodeToScroll.getY()) / iNodeToScrollHeight < 1) ? 1 : Math.abs(nodeToScroll.getY()) / iNodeToScrollHeight) / 2;

            nodeToScrollParent.setStyle('height', iNodeToScrollHeight);
            animScroll.set('node', nodeToScrollParent)
            animScroll.set('to', { scroll: [0, amountToScroll] });
            animScroll.set('duration', drt);
            animScroll.run();
        };


        Y.all('.AnimS .scroller').on('click', onClick);

    });
}


function setFormCheck() {
    YUI().use("node", function(Y) {
        if (Y.one('.submit')) {
            Y.one('.submit').on('click', checkData);
        }

        if (Y.one('.Register')) {
            Y.one('.Register').on('click', checkDataForPerformace);
        }
    });
}

function checkData(e) {
    e.preventDefault();
    
    var cntrls = [
                    { id: "FirstName", ErrorMessage: "First Name is required.", CheckedWith: "NotEmpty" }
                    ,{ id: "LastName", ErrorMessage: "Last Name is required.", CheckedWith: "NotEmpty" }
                    ,{ id: "Company", ErrorMessage: "Company is required.", CheckedWith: "NotEmpty" }
                    ,{ id: "EmailAddress", ErrorMessage: "A valid Email Address is required.", CheckedWith: "checkEmail" }
                    ,{ id: "Whitepapers", ErrorMessage: "Please check a White Paper.", CheckedWith: "checkWhitePaperIsSelected" }
                    ,{ id: "CountrySelect", ErrorMessage: "Please select a Country.", CheckedWith: "checkSelectBoxFirstNotSelected" }
                ];

    return ValidateControls(cntrls, "ErrorMessage");
}

function checkDataForPerformace(e) {
    e.preventDefault();

    var cntrls = [
                    { id: "FirstName", ErrorMessage: "First Name is required.", CheckedWith: "NotEmpty" }
                    , { id: "Telephone", ErrorMessage: "Last Name is required.", CheckedWith: "NotEmpty" }
                    , { id: "EmailAddress", ErrorMessage: "A valid Email Address is required.", CheckedWith: "checkEmail" }
                    , { id: "BestTimeToContact", ErrorMessage: "Please check a White Paper.", CheckedWith: "NotEmpty" }                   
                ];

    return ValidateControlsForPerformance(cntrls);
}

function ValidateControls(cntrls, elemErrorMessage) {

    var blnReturn = false;
    var HTMLErrorMessage = ''
    
    for (i = 0; i < cntrls.length; i++) {

        var blnPass = eval(cntrls[i].CheckedWith + '({id:"' + cntrls[i].id + '"})')
        
        if (blnPass) {
            //ClearFlagError(cntrls[i].id)
        } else {
            if (HTMLErrorMessage == '') {
                HTMLErrorMessage += "<dt>There were errors reported on the form submission</dt>";
            }

            HTMLErrorMessage += "<dd><span>&raquo;</span>" + cntrls[i].ErrorMessage + "</dd>";            
            //FlagError(cntrls[i].id)
        }
    }

    if (HTMLErrorMessage == '') {
        if (elemErrorMessage) {
            YUI().use('node', function(Y) {
                var ndeErrors = Y.one('#' + elemErrorMessage);
                ndeErrors.setStyle("display", "none");
                ndeErrors.set('innerHTML', '');
            });

            blnReturn = true
        }
    } else {
        if (elemErrorMessage) {
            YUI().use('node', function(Y) {
                var ndeErrors = Y.one('#' + elemErrorMessage);
                ndeErrors.setStyle("display", "block");
                ndeErrors.set('innerHTML', HTMLErrorMessage);
            });

        }
    }

    if (blnReturn) {
        YUI().use('node', function(Y) {
            ndeForm = Y.one('form');
            TabID = Y.one('input[name=TabIDForResult]').get('value');
            ndeForm.setAttribute('action', '/default.aspx?tabid=' + TabID)
            ndeForm.submit();
        });
    }
}

function ValidateControlsForPerformance(cntrls) {

    var blnReturn = false;
    var HTMLErrorMessage = ''

    for (i = 0; i < cntrls.length; i++) {

        var blnPass = eval(cntrls[i].CheckedWith + '({id:"' + cntrls[i].id + '"})')

        YUI().use('node', function (Y) {

            var ndeInput = Y.one('#' + cntrls[i].id);
            var ndeLabel = ndeInput.previous();

            if (blnPass) {
                ndeLabel.removeClass("Error");
            } else {
                if (HTMLErrorMessage == '') {
                    HTMLErrorMessage += "<dt>There were errors reported on the form submission</dt>";
                }

                HTMLErrorMessage += "<dd><span>&raquo;</span>" + cntrls[i].ErrorMessage + "</dd>";
                ndeLabel.addClass("Error");
            }

        });
    }

    //Now check the radio buttons
    YUI().use('node', function (Y) {
        ndeCBoxes = Y.all(".ContactMeByW input");
        var tmpValue = false;

        //:checked psuedo-class not working in IE   
        ndeCBoxes.each(function (node) {
            if (node.get('checked')) tmpValue = node.get('value');
        });

        //if the tmpValue is no longer false then it found a checked box
        if (tmpValue != false) {
            Y.one(".ContactMeByW").removeClass("Error");
        } else {
            HTMLErrorMessage += "<dd><span>&raquo;</span></dd>";
            Y.one(".ContactMeByW").addClass("Error");
        }

    });

    if (HTMLErrorMessage == '') {       
            blnReturn = true
    } else {
        alert("Please complete all the required fields.");
    }

    if (blnReturn) {
        YUI().use('node', function (Y) {
            ndeForm = Y.one('form');
            TabID = Y.one('input[name=TabIDForResult]').get('value');
            ndeForm.setAttribute('action', '/default.aspx?tabid=' + TabID)
            ndeForm.submit();
        });
    }
}



function FlagError(elemID) {
    YUI().use('node', function(Y) {
        var ndeFlagSib = Y.one('#' + elemID).next();
        ndeFlagSib.addClass("Show");
    });
}

function ClearFlagError(elemID) {
    YUI().use('node', function(Y) {
        var ndeFlagSib = Y.one('#' + elemID).next();
        ndeFlagSib.removeClass("Show");
    });
}

function NotEmpty(params) {

    var elem = document.getElementById(params.id);

    str = elem.value.replace(/^\s+|\s+$/g, "");

    if (str == '') {
        return false;
    } else {
        return true;
    }
}

function checkEmail(params) {

    var elem = document.getElementById(params.id);

    strng = elem.value;

    if (strng == "") {
        return false;
    }

    var emailFilter = /^.+@.+\..{2,3}$/;

    if (!(emailFilter.test(strng))) {
        return false;
    }
    else {
        //test email for illegal characters
        var illegalChars = /[\(\)\<\>\,\;\:\\\"\[\]]/

        if (strng.match(illegalChars)) {
            return false;
        }
    }

    return true;
}

function checkWhitePaperIsSelected(params) {

    var blnPass = false;

    YUI().use('node', function(Y) {
        var ndeWhitePaper = Y.one('#' + params.id);

        if (ndeWhitePaper) {
            ndeCBoxes = ndeWhitePaper.all('input[type=checkbox]');

            var tmpValue = false;

            //:checked psuedo-class not working in IE   
            ndeCBoxes.each(function(node) {
                if (node.get('checked')) tmpValue = node.get('value');
            });
            
            //if the tmpValue is no longer false then it found a checked box
            if (tmpValue != false) { blnPass = true; }

        } else {
            //if the node wrapper is not on the form then skip the check
            blnPass = true;
        }

    });

    return blnPass;

}

function checkSelectBoxFirstNotSelected(params) {

    var blnPass = false;

    YUI().use('node', function(Y) {
        var ndeSelectBox = Y.one('#' + params.id);

        if (ndeSelectBox) {
            selIndex = ndeSelectBox.get('selectedIndex'); 
            
            //if the tmpValue is no longer false then it found a checked box
            if (selIndex > 0) { blnPass = true; }

        } else {
            //if the node wrapper is not on the form then skip the check
            blnPass = true;
        }

    });

    return blnPass;

}
