﻿var PanelInterval = 7000; //the timer interval
var CarouselTimer = 560000; //the timer that will shut down the carousel animation

var t = null;  //used for timer
var tC = null;  //used for timer

function pageInit(e) {
    //use this to call any js that needs to run once the dom is loaded
    //set the top
    setYUINav();
    //set the carousel on the homepage
    setCarousels();
    //set the carousel on the homepage
    setSearchBox();    
    //set the enter key will submit a search
    setSearchSubmit();    
    //set form submission
    setFormCheck();
}

function setYUINav() {
    YUI().use("node-menunav", function(Y) {
        if (Y.one("#yui3-nav")) {
            //	Retrieve the Node instance representing the root menu
            //	(<div id="yui3-nav">) and call the "plug" method
            //	passing in a reference to the MenuNav Node Plugin.

            var menu = Y.one("#yui3-nav");

            menu.plug(Y.Plugin.NodeMenuNav);

            //	Show the menu now that it is ready

            menu.get("ownerDocument").get("documentElement").removeClass("yui3-loading");
            Y.one("#yui3-nav").removeClass("menu-loading");
        }
    });
}

function setCarousels() {
    YUI().use("node", function(Y) {
        if (Y.one(".carouselW .carousel")) {
            t = setTimeout("fnTimerForNext()", PanelInterval);
            tC = setTimeout("fnTimerForCarouselOff()", CarouselTimer);
            Y.all(".controller span").on("click", moveCarousel);
        }
    });
}

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('#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
            }, '#txtSearch', 'down:13');

        }
    });

}

function clickSearch(val) {
    location.href = "/Search_Results.aspx?Search=" + val;
}

function fnTimerForNext() {

    YUI().use("node-event-simulate", function(Y) {
        if (Y.one(".carouselW .carousel")) {
            controllerLinks = Y.all(".controller span");
            var carouselSize = controllerLinks.size();
            var itemToMove = 0;

            //determine which panel is active
            for (i = 0; i < carouselSize; i++) {
                if (controllerLinks.item(i).hasClass("on")) {
                    if (i < carouselSize - 1) {
                        itemToMove = i + 1;
                    }

                    //simulate the click
                    controllerLinks.item(itemToMove).simulate("click");
                }
            }
        }
    });

}


function moveCarousel(e) {
    //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("on")) {
            YUI().use("anim", function(Y) {

                //the ul to be animated
                var ulToMove = Y.one(".carousel ul");
                var ulCurrentX = ulToMove.getX();
               
                //who was clicked
                var idOfClickedNode = e.target.get("id");
                var controllerLinks = Y.all(".controller span");

                //add the running class so the animation will complete before anything else can happen
                controllerLinks.addClass("Running");

                //get all the lis in the carousel
                var carouselLis = ulToMove.all("li");

                //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 = idOfClickedNode - 1;
                var carouselSize = controllerLinks.size()

                for (i = 0; i < carouselSize; i++) {
                    if (controllerLinks.item(i).hasClass("on")) {
                        liOn = i;
                    }
                }

                //turn off the old one
                carouselLis.item(liOn).toggleClass("on");
                controllerLinks.item(liOn).toggleClass("on");

                //now turn on the on that was clicked.
                carouselLis.item(liToBeOn).toggleClass("on");
                controllerLinks.item(liToBeOn).addClass("on");

                iPanelsToMove = liToBeOn - liOn;

                //might be jumping multiple panels
                iWidthToMove = Math.abs(iPanelsToMove * liRegionWidth);

                //the updated position for the ul
                if (iPanelsToMove > 0) {
                    xPos = ulCurrentX - iWidthToMove;
                } else {
                    xPos = ulCurrentX + iWidthToMove;
                }

                var yPos = ulToMove.getY();

                var enableDisableCheck = function() {
                    YUI().use("node", function(Y) {
                        //remove this so the code knows the animation stopped
                        controllerLinks.removeClass("Running");
                    });
                }

                //add the on class to the one coming in        
                carouselLis.item(liToBeOn).toggleClass("on");

                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 setSearchBox() {
    YUI().use("node", function(Y) {
        if (Y.one('#txtSearch')) {
            Y.one('#txtSearch').on('click', clearData);
        }
    });
}

function clearData(e) {
    YUI().use("node", function(Y) {
        if (e.target.getAttribute('value') == 'search') {
            e.target.setAttribute('value', '');
        }
    });
}

function setFormCheck() {
    YUI().use("node", function(Y) {
        if (Y.one('.submit')) {
            Y.one('.submit').on('click', checkData);
        }
    });
}

function checkData(e) {

    var cntrls = [
                    { id: "first_name", ErrorMessage: "First Name is required.", CheckedWith: "NotEmpty" }
                    , { id: "last_name", ErrorMessage: "Last Name is required.", CheckedWith: "NotEmpty" }
                    , { id: "company", ErrorMessage: "Company is required.", CheckedWith: "NotEmpty" }
                    , { id: "email", ErrorMessage: "A valid Email Address is required.", CheckedWith: "checkEmail" }
                    , { id: "phone", ErrorMessage: "Phone Number is required.", CheckedWith: "NotEmpty" }
                    
                ];

    return ValidateControls(cntrls, "ErrorMessage", e);
}

function ValidateControls(cntrls, elemErrorMessage, e) {

    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) {
        e.preventDefault();
    }
}

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;
}

