var sliderInterval = null;
var counterInterval = null;
var isInnerPage = true;
var notificationTimeout = null;
var currentlySliding = false;

function getDigits(str) {
    return str.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
}

function getTemplate(templateId) {
    return $("#" + templateId).children().clone();
}

function hideNotifications() {
    $(".notification:visible").slideUp(function() {
        $(this).remove();
    });
}

function notifyUser(message, timeToShow, callbackFunc) {
    if (notificationTimeout != null) {
        clearTimeout(notificationTimeout);
    }

    if (timeToShow == null) {
        timeToShow = 5000;
    }

    hideNotifications();

    var template = getTemplate("notificationTemplate");
    $(template).find(".notificationBody").html(message);
    $("body").prepend(template);
    $(".notification:first").slideDown();

    notificationTimeout = setTimeout(function() {
        hideNotifications();
        if (callbackFunc != null) {
            callbackFunc();
        }
    }, timeToShow);
}
function loadNextSlider(nextSlider) {
    if (currentlySliding) {
        return;
    }
    currentlySliding = true;
    var currentSlider;
    if ($(".mainSliderItem:visible").length > 0) {
        currentSlider = $(".mainSliderItem:visible");
    } else {
        currentSlider = $(".mainSliderItem:last");

    }
    var currentSliderIndex = currentSlider.index();
    var numberOfSliders = $(".mainSliderItem").length;

    var slideToSide = "left";

    if (currentSliderIndex == numberOfSliders - 1) {
        if (nextSlider == null)
            nextSlider = $(".mainSliderItem:first");
    } else {
        if (nextSlider == null)
            nextSlider = $(".mainSliderItem:eq(" + (currentSliderIndex + 1) + ")");
    }

    var cssProps = {};
    cssProps[slideToSide] = "-685px";
    var oppositeSide = slideToSide == "left" ? "right" : "left";

    currentSlider.animate(cssProps, 1000, function() {
        $(this).css("display", "none");
    });

    nextSlider.css("left", "").css("right", "");
    var nextSliderCssProps = { display: "block"};

    nextSliderCssProps[oppositeSide] = "-685px";
    nextSlider.css(nextSliderCssProps);

    setTimeout(function() {
        var nextSliderAnimationProps = {};
        nextSliderAnimationProps[oppositeSide] = "0";
        nextSlider.animate(nextSliderAnimationProps, 1000, function() {
            currentlySliding = false;
        });

        $(".sliderButtonSelected").removeClass("sliderButtonSelected");
        var selectedSliderButton = $(".sliderButton:eq(" + nextSlider.index() + ")");
        selectedSliderButton.addClass("sliderButtonSelected");
    }, 100);
}

function preloadImage(url, callbackFunc) {
    $('<img />').load(
        function() {
            if (callbackFunc != null) {
                callbackFunc();
            }
        }).attr('src', url);
}

function startSliderInterval() {
    if (sliderInterval != null) {
        clearInterval(sliderInterval);
    }
    sliderInterval = setInterval(function() {
        loadNextSlider();
    }, 12000);
}

var previousCounterNumber = null;
function populateCounter() {
    if (previousCounterNumber == null) {
        var dateString = (new Date().getTime() + "");
        var tenFirstDigits = dateString.substr(0, 9);
        var tenDigitsInt = Math.floor(parseInt(tenFirstDigits) - 122723971);
        previousCounterNumber = tenDigitsInt + "";
    } else {
        previousCounterNumber = (parseInt(previousCounterNumber) + 1) + "";
    }

    $(".counter").find(".counterText").html(getDigits(previousCounterNumber));
    /*    $(".counter").each(function(index, counter) {
     var firstIndex = (index + 1 ) * 2;
     var firstNumber = previousCounterNumber.substr(firstIndex, 1);
     var secondNumber = previousCounterNumber.substr(firstIndex + 1, 1);
     $(counter).find(".counterText").html(firstNumber + secondNumber);
     });*/
}
function isEmpty(str) {
    return str == null || str == "";
}

function fixFooterPosition() {
    if ($(window).height() >= $(document).height()) {
        var top = $(window).height() - $(".footer").height() - 60;
        $(".footer").css({
            position: "absolute",
            top: top + "px",
            left:0
        });
    } else {
        $(".footer").css("position", "");
    }
}

function showSmallContactUsForm(contactUsForm) {
    $(".contactUsForm").animate({ top: "0"}, 500);
}
function hideSmallContactUsForm(contactUsForm) {
    $(".contactUsForm").animate({ top: "-180px"}, 500);
}
function populateCounterTimer() {
    counterInterval = setTimeout(function() {
        populateCounter();
        populateCounterTimer();
    }, Math.floor(Math.random() * 3000));
}
function initApp() {
    fixFooterPosition();
    $(window).resize(function() {
        fixFooterPosition();
    });

    if ($(".slider").is(":visible")) {
        preloadImage("img/firstSliderImage.png", function() {
            loadNextSlider();
        });

        startSliderInterval();
    }


    populateCounter();
    populateCounterTimer();


    var counterHeight;
    if (isInnerPage) {
        $(".triplaySloganLogos").css("display", "none");
        counterHeight = "75px";
    } else {
        counterHeight = "210px";
    }
    $(".counterAndLogosWrapper").animate({top: counterHeight}, 1000);


    $(".contactSubmit").click(function() {
        var contactObject = {}
        contactObject.firstName = $(".contactFirstNameInput").val();
        contactObject.lastName = $(".contactLastNameInput").val();
        contactObject.title = $(".contactTitle").val();
        contactObject.company = $(".contactCompany").val();
        contactObject.email = $(".contactEmail").val();
        contactObject.url = $(".contactURL").val();
        contactObject.phone = $(".contactPhone").val();
        contactObject.corporatePresence = $(".contactCorporatePresenceSelect").val();
        contactObject.typeOfPartner = $(".contactPartnerSelect").val();
        contactObject.other = $(".contactOther").val();
        contactObject.comment = $(".contactCommentTextarea").val();


        if (isEmpty(contactObject.firstName)) {
            notifyUser("Invalid first name entered");
            return;
        }

        if (isEmpty(contactObject.lastName)) {
            notifyUser("Invalid last name entered");
            return
        }

        if (isEmpty(contactObject.title)) {
            notifyUser("Invalid title entered");
            return;
        }

        if (isEmpty(contactObject.company)) {
            notifyUser("Invalid company name entered");
            return;
        }

        if (!isEmail(contactObject.email)) {
            notifyUser("Invalid e-mail address entered");
            return;
        }

        if (isEmpty(contactObject.typeOfPartner)) {
            notifyUser("Please select a Type of partner item");
            return;
        }

        $(".contactSubmit").fadeOut("slow");
        notifyUser("Request sent. Thank you for your feedback.");

        contactObject.contactType = "long";

        $.post("callback.php", contactObject, function(response) {
            console.log(response);
        });

    });

    $(".submitSmallContactUs").click(function() {
        var contactObject = { contactType: "short" }

        contactObject.name = $(".smallContactName").val();
        contactObject.company = $(".smallContactCompany").val();
        contactObject.email = $(".smallContactEmail").val();
        contactObject.inquiry = $(".smallInquirySelect").val();
        contactObject.comment = $(".smallCommentArea").val();


        if (isEmpty(contactObject.name)) {
            notifyUser("Invalid name entered");
            return;
        }

        if (isEmpty(contactObject.company)) {
            notifyUser("Invalid company name entered");
            return;
        }

        if (!isEmail(contactObject.email)) {
            notifyUser("Invalid email entered");
            return;
        }

        hideSmallContactUsForm();
        notifyUser("Contact us request sent");

        $.post("callback.php", contactObject);
    });

    $(".notificationXButton").live("click", function() {
        hideNotifications();
    });

    $(".sliderButton").click(function() {

        var that = $(this);
        if (!that.hasClass("sliderButtonSelected")) {
            loadNextSlider($(".mainSliderItem:eq(" + that.index() + ")"));
            startSliderInterval();
        }
    });

    $(".logo").click(function() {
        window.location.href = "/";
    });

    $(".mainMenu").click(function() {
        var parent = $(this).parent();
        var subMenuContainer = parent.find(".upperMenuSubMenu");

        var currentMenu = $(".menuItemSelected");
        currentMenu.find(".menuItemText").removeClass("bold");
        currentMenu.removeClass("menuItemSelected").addClass("menuItem");
        currentMenu.parent().find(".upperMenuSubMenu").slideUp("");


        if (!subMenuContainer.is(":visible")) {
            var menuItem = parent.find(".menuItem");
            menuItem.removeClass("menuItem").addClass("menuItemSelected");
            parent.find(".mainMenu .menuItemText").addClass("bold");
            subMenuContainer.slideDown();
        }
    });

    $(".contactUsButton").live("click", function() {
        var contactUsForm = $(this).parent();
        var contactOffset = contactUsForm.offset();
        if (contactOffset.top < 0) {
            showSmallContactUsForm();
        } else {
            hideSmallContactUsForm();
        }
    });
}

function isEmail(emailStr) {
    var checkTLD = 1;
    var knownDomsPat = /^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
    var emailPat = /^(.+)@(.+)$/;
    var specialChars = "\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
    var validChars = "\[^\\s" + specialChars + "\]";
    var quotedUser = "(\"[^\"]*\")";
    var ipDomainPat = /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
    var atom = validChars + '+';
    var word = "(" + atom + "|" + quotedUser + ")";
    var userPat = new RegExp("^" + word + "(\\." + word + ")*$");
    var matchArray = emailStr.match(emailPat);

    if (emailStr.indexOf("%") >= 0)
        return false;

    if (matchArray == null) {
        return false;
    }
    var user = matchArray[1];
    var domain = matchArray[2];

    for (i = 0; i < user.length; i++) {
        if (user.charCodeAt(i) > 127) {
            return false;
        }
    }
    for (i = 0; i < domain.length; i++) {
        if (domain.charCodeAt(i) > 127) {
            return false;
        }
    }
    if (user.match(userPat) == null) {
        return false;
    }

    var IPArray = domain.match(ipDomainPat);
    if (IPArray != null) {
        for (var i = 1; i <= 4; i++) {
            if (IPArray[i] > 255) {
                return false;
            }
        }
        return true;
    }
    var atomPat = new RegExp("^" + atom + "$");
    var domArr = domain.split(".");
    var len = domArr.length;
    for (i = 0; i < len; i++) {
        if (domArr[i].search(atomPat) == -1) {
            return false;
        }
    }
    if (checkTLD && domArr[domArr.length - 1].length != 2 &&
        domArr[domArr.length - 1].search(knownDomsPat) == -1) {
        return false;
    }
    return len >= 2;
}
