$(document).ready(function(){

    // global js here

    $("li:nth-child(even)").each(function() {
        $(this).addClass("even");
    });

    $("li:nth-child(odd)").each(function() {
        $(this).addClass("odd");
    });

    $("tr:first-child").each(function() {
        $(this).addClass("first");
    });
    $("tr:last-child").each(function() {
        $(this).addClass("last");
    });

    applyTableStriping();

    /* bold the first and second paras of any article */
    if ($(".article-content p").length !== 0) {
        $('.article-content p:eq(0),.article-content p:eq(1)').addClass('bold');
    }

    $(".go-back").click(function() {
        history.back(); // used for the 404 page
    });

    $(".video-thumbnail").hover(function () {
        $(this).find(".watch").toggleClass("on-hover");
    });
    
});

function applyTableStriping() {
     $("table").each(function() {
        $(this).find("tr").removeClass("even odd"); //remove any existing striping
        $(this).find("tr:nth-child(even)").addClass("even");
        $(this).find("tr:nth-child(odd)").addClass("odd");
    });
}

function countNumOfAllocations(txt) {
    // for carousel...
    //counts number of lower and uppercase characters to calculate whether 1 or 2 lines of text.
    //get number of characters
    var numOfChars = $.trim(txt).length;
    //get number of capitals (if there are any)
    var numOfCaps = $.trim(txt).replace(/[^A-Z]/g,"").length;
    var numOfLowerChars = numOfChars-numOfCaps;
    return numOfLowerChars + 2*numOfCaps;
}

function animateCandy(element, direction) {
        $("#"+element).css({backgroundPosition: "0 0" }).animate({backgroundPosition:""+ direction+"61px 0"}, {duration: 2000, easing: "linear", complete: function() {animateCandy($(this).attr("id"), "-")}});
}

/**
 * NOT CURRENTLY USED
 * This function sets up the 'other' field behaviour for Trial, Registration forms
 * Other field displays if 'other' is selected from the dropdown options
 * @param fieldId - id of the selectbox i.e. '#industry', '#jobTitle'
 */
function attachOtherFieldBehaviour(fieldId) {
        if ($(fieldId+' option:selected').text() === 'Other') {
            $(fieldId+'OtherBox').show();
            $(fieldId+'Wrapper').css("outline", "1px dashed #999");
        }
        $(fieldId).click(function() {
            if ($(fieldId+' option:selected').text() === 'Other') {
                $(fieldId+'OtherBox').show();
                $(fieldId+'Wrapper').css("outline", "1px dashed #999");
            } else {
                $(fieldId+'OtherBox').hide();
                $(fieldId+'Wrapper').css("outline", "none");
                $(fieldId+'Other').val(''); //removes anything entered if user selects another option
            }
        });
}

/* todo rdc - this was used when building the poll originally as 'ece' wasn't logging the user's polling correctly (on DEV atleast), keep until 'ece' tested */
/*function preparePollResultsDisplay() {
            // attach behaviour to poll submit button
            $("#submitPoll").click(function() {
                var exdate = new Date();
                exdate.setDate(exdate.getDate() + 1);
                //the cookie will expire in 24 hours (based on GMT).
                document.cookie = "voted=true;expires=" + exdate.toUTCString();
            });

            if (document.cookie.indexOf("voted=true") != -1) {
            //alert("load cookie (debugging): " + getCookie("voted"));
            $(".voteOptions").hide();
            $(".panswer").show();
            $(".noVoteOptions").show();

            for (var i = 1; i < 3; i++) {
                var bar = document.getElementById("answer_" + i);
                var pixels = 2 * $("#hidden_" + i).text(); // - multipled by 2 (2 pixels for every percentage point (200px wide bar))
                var bg;
                if (i % 2 == 0) {
                    bg = '#296190';
                } else {
                    bg = '#368ed8';
                }
                bar.style.cssText = "background:" + bg + " url(images/pollbar.png) no-repeat " + pixels + "px top;"
            }
        } else {
            $(".voteOptions").show();
            $(".panswer").hide();
            $(".noVoteOptions").hide();
        }
}*/

/* only used for poll debugging purposes... */
function getCookie(c_name) {
        if (document.cookie.length > 0) {
            var c_start = document.cookie.indexOf(c_name + "=");
            if (c_start != -1) {
                c_start = c_start + c_name.length + 1;
                var c_end = document.cookie.indexOf(";", c_start);
                if (c_end == -1) c_end = document.cookie.length;
                return decodeURI(document.cookie.substring(c_start, c_end));
            }
        }
        return "";
}

function focusOnFirstFormField(parentElement) {
        $(parentElement + " :input:visible:enabled:first").focus();
}

/* article carousel*/

var counter = 1;
var carouselInterval = "";
var numOfImages = 0;

$(document).ready(function() {
    if ($(".article-carousel").length != 0) {
        numOfImages = $(".article-carousel").length;
        // assuming that there is at least one image
        $("#articleCarousel_1").show();
        $(".article-carousel").mouseover(function() {
            clearInterval(carouselInterval);
        });
        $(".article-carousel").mouseout(function() {
            setIntervalForCarousel(numOfImages);
        });
        // test that there is more than one image - if so then run the carousel
        if (numOfImages > 1) {
            // if more than one image then add the image navigation
            $(createNavigation(numOfImages)).insertAfter(".carousel-image");
            setIntervalForCarousel(numOfImages);
        } else {
            // if only one image then reduce the height of the containing div
            $(".article-carousel").css("height", "270px").css("min-height", "270px");
            // and hide the navigation layer
            $(".prev").hide();
            $(".next").hide();
        }
        applyImgFocusStyling();
    }

    // apply hover events
    $(".carousel-nav").live("mouseover", function() {
        $(".article-carousel").hide(); // hide all images
        $(".carousel-nav").css("background", "#fff").css("color", "#333");
        var index = parseInt($(this).attr("class").split("_")[1]);
        $(".img_" + index).css("background", "#5291d6").css("color", "#fff");
        $("#articleCarousel_" + index).show(); // show the selected image
        // set counter to new index
        counter = index;
    });

    // apply click events
    $(".next").live("click", function() {
        var index = parseInt($(this).parent().parent().attr("id").split("_")[1]);
        var nextIndex = index + 1;
        if (nextIndex > numOfImages) {
            nextIndex = 1;
        }
        $(this).parent().parent().hide();
        $("#articleCarousel_" + nextIndex).show();
        $(".img_" + index).css("background", "#fff").css("color", "#333");
        $(".img_" + nextIndex).css("background", "#5291d6").css("color", "#fff");
        counter = nextIndex;
    });

    // apply click events
    $(".prev").live("click", function() {
        var index = parseInt($(this).parent().parent().attr("id").split("_")[1]);
        var prevIndex = index - 1;
        if (prevIndex < 1) {
            prevIndex = numOfImages;
        }
        $(this).parent().parent().hide();
        $("#articleCarousel_" + prevIndex).show();
        $(".img_" + index).css("background", "#fff").css("color", "#333");
        $(".img_" + prevIndex).css("background", "#5291d6").css("color", "#fff");
        counter = prevIndex;
    });

});

function carouselAutoPlay(numOfImages) {
    $(".carousel-nav").css("background-color", "#fff");
    $(".carousel-nav").css("color", "#333");
    $("#articleCarousel_" + counter).hide();
    if (counter < numOfImages) {
        ++counter;
        applyImgFocusStyling();
        $("#articleCarousel_" + counter).show();
    } else if (counter === numOfImages) {
        counter = 1;
        applyImgFocusStyling();
        $("#articleCarousel_" + counter).show();
    }
}

function setIntervalForCarousel(numOfImages) {
    carouselInterval = window.setInterval(function() {
        carouselAutoPlay(numOfImages)
    }, 5000);
}

function createNavigation(numOfPages) {
    var navString = "<span class=\"carousel-nav-bar\">";
    for (var i = 1; i <= numOfPages; i++) {
        if (i === 1) {
            navString = navString + "<a class=\"carousel-nav first-nav img_" + i + "\">" + i + "</a>";
        } else {
            navString = navString + "<a class=\"carousel-nav img_" + i + "\">" + i + "</a>";
        }
    }
    navString = navString + "</span>";
    return navString;
}

function applyImgFocusStyling() {
    $(".img_" + counter).css("background-color", "#5291d6");
    $(".img_" + counter).css("color", "#fff");
}
