﻿$(document).ready(function() {

    // Do site drop down
    $('.siteSelect').change(function() {
        if ($(this).attr('value') != '-1') {
            window.location.href = $(this).attr('value');
        }
    });

    // Prevent default submit
    $('#ctl00_ctl00_ContentPlaceHolderPageFrame_ContentPlaceHolderMain_btnSubmit').click(function(e) {
        e.preventDefault();

        Twycross.SendEnquiryForm();
    });

    $('.subscribeSubmit').click(function(e) {
        e.preventDefault();

        Twycross.SendSubscribeForm();
    });
});

function validateEmail(elementValue) {
    var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    return emailPattern.test(elementValue);
}

var LinkURLs = function(s) {
    var m = /(https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w\/_\.]*(\?\S+)?)?)?)/;
    return s.replace(m, '<a href="$1">$1</a>')
}

function kslideshow() {
    var ULcontainer = 'div.carouselHolder ul',
	nextItem = '.nextLi',
	prevItem = '.prevLi',
	playItem = '.play',
	stopItem = '.stop',
	autoSlide = false,
	pagination = false,
	liWidth = '290',
	slideSpeed = '10000',
	visibleSlides = '3',
	liPerSlide = '3'
    var rema = (($(ULcontainer).children('li').length) % 3)
    if (parseInt(rema % 3) != 0) {
        var i;
        var minLi = 3 - rema
        for (i = 0; i < minLi; i++) {
            $(ULcontainer).find('li:last').after('<li>&nbsp;</li>')
        }
    }

    ///////////////////////////////////////////
    // No changes needed beyond this point////

    //Width of container
    var widthOfContainer = liWidth * visibleSlides + "px"
    $(ULcontainer).parent().css('width', widthOfContainer)
    $(ULcontainer).children('li').css({ 'width': liWidth, 'overflow': 'hidden' })

    var liNum = $(ULcontainer).children().length;
    var liNearLast = (liNum - visibleSlides) * liWidth;

    if (autoSlide) playSlide();

    if (pagination) {
        var ULcontainerPosition = $(ULcontainer).css('left');
        lpagination = $(ULcontainer).children('li').length / liPerSlide;
        $(ULcontainer).parent().after('<div class="slidePagination"><ul></ul></div>');
        for (i = 0; i < lpagination; i++) {
            $('.slidePagination').children('ul').append('<li' + '>' + '<a href=\"#\">' + (i + 1) + '</a></li>')
        }

        $('.slidePagination').children('ul').children('li').click(function() {
            $(ULcontainer).animate({
                left: (-liWidth * $(this).index()) * liPerSlide + "px"
            }, slideSpeed)

        });

    }

    function nextSlide() {
        var ULcontainerPosition = $(ULcontainer).css('left');

        if ($(ULcontainer).is(':animated')) {
            return false
        }

        if (parseFloat(ULcontainerPosition) <= parseFloat("-" + liNearLast + "px")) {
            $(ULcontainer).css('left', -liNearLast)
            for (i = 0; i < liPerSlide; i++) {
                $(ULcontainer).children('li:first').clone().appendTo(ULcontainer)
                $(ULcontainer).children('li:first').remove()
            }

            $(ULcontainer).animate({
                left: "+=" + liWidth * liPerSlide + "px"
            }, 0, function() {
                $(ULcontainer).animate({
                    left: "-=" + liWidth * liPerSlide + "px"
                }, slideSpeed)
            });
        }
        else {
            $(ULcontainer).animate({
                left: "-=" + liWidth * liPerSlide + "px"
            }, slideSpeed)
        }
    } //end next slide

    function prevSlide() {
        var ULcontainerPosition = $(ULcontainer).css('left');

        if ($(ULcontainer).is(':animated')) {
            return false
        }

        if (ULcontainerPosition == "0px") {
            for (i = 0; i < liPerSlide; i++) {
                $(ULcontainer).children('li:last').clone().prependTo(ULcontainer)
                $(ULcontainer).children('li:last').remove()
            }

            $(ULcontainer).animate({
                left: "-=" + liWidth * liPerSlide + "px"
            }, 0, function() {
                $(ULcontainer).animate({
                    left: "+=" + liWidth * liPerSlide + "px"
                }, slideSpeed)
            });

        }
        else {
            $(ULcontainer).animate({
                left: "+=" + liWidth * liPerSlide + "px"
            }, slideSpeed)
        }

    } //end prevSlide

    function playSlide() {
        playing = setInterval(function() { nextSlide(); }, slideSpeed);
    } //end playSlide

    function stopSlide() {
        clearInterval(playing);
    } //end stopSlide

    $(ULcontainer).hover(function() { stopSlide(); }, function() {
        // playSlide(); 
    });
    $(nextItem).hover(function() { stopSlide(); }, function() {
        // playSlide(); 
    });
    $(prevItem).hover(function() { stopSlide(); }, function() {
        //    playSlide(); 
    });

    $(nextItem).click(function() {
        stopSlide();
        nextSlide();
    });

    $(prevItem).click(function() {
        stopSlide();
        prevSlide();
    });
    var playing
    $('.play').click(function() {
        playSlide();
    });

    $('.stop').click(function() {
        stopSlide();
    });
} //end kslideshow

function fadeInOut() {
    var ULcontainer = '.fadeHolder ul',
	autoSlide = true,
	liWidth = '906',
	intervalSpeed = '7000'

    // No changes needed beyond this point

    $(ULcontainer).find('li:first').addClass('current')
    $(ULcontainer).find('li').not(':first').fadeIn(1).fadeOut(1)

    if ($(ULcontainer).children().length == 1) { return false; }

    if (autoSlide) kautoSlideplay();

    function kautoSlideplay() {
        kautoSlide = setInterval(function() { kfadeNext(); }, intervalSpeed);
    }

    function kautoSlidepause() {
        clearInterval(kautoSlide);
    }

    function kfadeNext() {
        var currentLI = $(ULcontainer).find('.current').index();
        var totalLI = $(ULcontainer).find('li:last').index()

        if (currentLI == totalLI) {
            $(ULcontainer).find('.current').fadeOut(2000).removeClass('current')
            $(ULcontainer).find('li:first').addClass('current').fadeIn(1000)
        }
        else {
            $(ULcontainer).find('.current').fadeOut(2000).removeClass('current').next('li').addClass('current').fadeIn(1000)
        }
    }
    $(ULcontainer).hover(function() { kautoSlidepause() }, function() { kautoSlideplay() });
} //fadeshow

var Twycross = new function() {

    this.validateEmail = function(s) {
        var str = s;

        var atPos = str.indexOf("@")
        var stopPos = str.lastIndexOf(".")

        if (atPos == -1 || stopPos == -1 || (stopPos < atPos) || (stopPos - atPos == 1)) {
            return false;
        }
        else {
            return true;
        }
    }

    // Clears validation styles
    this.ClearValidation = function() {
        $('input').each(function() {
            if ($(this).hasClass('errorInput')) {
                $(this).removeClass('errorInput');
            }
        })

        $('select').each(function() {
            if ($(this).hasClass('errorInput')) {
                $(this).removeClass('errorInput');
            }
        })
    }


    this.SendEnquiryForm = function () {
        // Clear validation styles
        Twycross.ClearEnquiryForm();

        if (Twycross.ValidateEnquiryForm()) {
            // Grab values
            var areaID = "-1";
            var area = "N/A";
            var hear = "N/A";

            // Areas of Enquiry
            $('input[NAME=enquiry]').each(function () {
                if ($(this).attr('checked')) {
                    area = $(this).next('label').html();
                    areaID = $(this).val();
                }
            });

            // How did you hear about us
            if ($('#ddlHear').val() != '-1') {
                hear = $('#ddlHear option:selected').text()
            }

            $.ajax({
                url: '/Modules/Contact/Ajax.aspx/SendEnquiryEmail',
                //data: JSON.stringify(data),
                data: '{"firstname": "' + $('#txtFirstName').val() + '","lastname": "' + $('#txtLastName').val() + '","email": "'
                    + $('#txtEmail').val() + '","phone": "' + $('#txtPhone').val() + '","areaID": ' + areaID + ',"area": "' + area
                    + '","enquiry": "' + $('#txtEnquiry').val() + '","hearID": ' + $('#ddlHear').val() + ',"hear": "' + hear + '"}',
                type: "POST",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                cache: false,
                async: false,
                success: function () {

                    // hide form and show confirmation text
                    $('.onlineForm').hide();
                    $('#divConfirm').show();
                }
            });
        }
    }

    this.ClearEnquiryForm = function () {
        // Clear validation styling
        $('#txtFirstName').removeClass('errorInput');
        $('#txtLastName').removeClass('errorInput');
        $('#txtEmail').removeClass('errorInput');
        $('#txtPhone').removeClass('errorInput');
        $('#txtEnquiry').removeClass('errorInput');
        $('.errorGuide').hide();
    }

    this.ValidateEnquiryForm = function () {
        var message = '';

        // Name
        if ($('#txtFirstName').val() == '') {
            message = message + '<li>' + SiteLabel.TXT1080 + '</li>'
            $('#txtFirstName').addClass('errorInput');
        }
        if ($('#txtLastName').val() == '') {
            message = message + '<li>' + SiteLabel.TXT1081 + '</li>'
            $('#txtLastName').addClass('errorInput');
        }

        // Email Address
        if ($('#txtEmail').val() == '') {
            // Missing
            message = message + '<li>' + SiteLabel.TXT1082 + '</li>'
            $('#txtEmail').addClass('errorInput');
        }
        else {
            // Invalid
            if (!Twycross.validateEmail($('#txtEmail').val())) {
                message = message + '<li>' + SiteLabel.TXT1086 + '</li>'
                $('#txtEmail').addClass('errorInput');
            }
        }

        // Phone Number
        if ($('#txtPhone').val() == '') {
            message = message + '<li>' + SiteLabel.TXT1127 + '</li>'
            $('#txtPhone').addClass('errorInput');
        }

        // Your Enquiry
        if ($('#txtEnquiry').val() == '') {
            message = message + '<li>' + SiteLabel.TXT1126 + '</li>'
            $('#txtEnquiry').addClass('errorInput');
        }

        if (message != '') {
            $('.errorGuide ul').html(message);
            $('.errorGuide').show();
            return false;
        }
        else {
            return true;
        }
    }

    this.SendSubscribeForm = function() {
        Twycross.ClearSubscribeForm();

        // If all mandatory fields have been filled, then send the form
        if (Twycross.ValidateSubscribeForm()) {
            $.ajax({
                url: '/Modules/Contact/Ajax.aspx/SubmitSubscribeForm',
                data: '{"firstName": "' + $('#txtFirstName').val() + '","lastName": "' + $('#txtLastName').val() + '","email": "' + $('#txtEmailAddress').val()
                    + '","phone": "' + $('#txtPhone').val() + '","countryID": ' + $('#ddlCountry').val() + ',"countryName": "' + $('#ddlCountry :selected').text()
                    + '","address1": "' + $('#txtAddress1').val() + '","address2": "' + $('#txtAddress2').val() + '","address3": "' + $('#txtAddress3').val()
                    + '","postcode": "' + $('#txtPostCode').val() + '"}',
                type: "POST",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                cache: false,
                async: false,
                success: function(response) {
                    // hide form and show confirmation text
                    $('.onlineForm').hide();
                    $('#divConfirm').show();
                }
            });
        }
    }

    this.ClearSubscribeForm = function() {
        $('#txtFirstName').removeClass('errorInput');
        $('#txtLastName').removeClass('errorInput');
        $('#txtEmailAddress').removeClass('errorInput');
        $('#txtConfirmEmail').removeClass('errorInput');
    }

    this.ValidateSubscribeForm = function() {
        var message = '';

        // First name
        if ($('#txtFirstName').val() == '') {
            message = message + '<li>' + SiteLabel.TXT1080 + '</li>'
            $('#txtFirstName').addClass('errorInput');
        }

        // Last name
        if ($('#txtLastName').val() == '') {
            message = message + '<li>' + SiteLabel.TXT1081 + '</li>'
            $('#txtLastName').addClass('errorInput');
        }

        // Email Address
        if ($('#txtEmailAddress').val() == '') {
            // Missing
            message = message + '<li>' + SiteLabel.TXT1082 + '</li>'
            $('#txtEmailAddress').addClass('errorInput');
        }
        else {
            // Invalid
            if (!Twycross.validateEmail($('#txtEmailAddress').val())) {
                message = message + '<li>' + SiteLabel.TXT1086 + '</li>'
                $('#txtEmailAddress').addClass('errorInput');
            }
        }

        // Confirm email address
        if ($('#txtConfirmEmail').val() == '') {
            // Missing
            message = message + '<li>' + SiteLabel.TXT1131 + '</li>'
            $('#txtConfirmEmail').addClass('errorInput');
        }
        else {
            // Doesn't match
            if ($('#txtConfirmEmail').val() != $('#txtEmailAddress').val()) {
                message = message + '<li>' + SiteLabel.TXT1132 + '</li>'
                $('#txtEmailAddress').addClass('errorInput');
                $('#txtConfirmEmail').addClass('errorInput');
            }
        }

        if (message != '') {
            $('.errorGuide ul').html(message);
            $('.errorGuide').show(0, function() {
                $('.ecomLock').height($(document).height())
            });
            return false;
        }
        else {
            return true;
        }
    }
}

function homeEqualHeights() {
    delay = setTimeout(function doThis() {
        hl = $('div.homeLeft > .homeLeftBody');
        hr = $('div.homeRight > .homeRightBody');
        ('hl ' + hl.height() + '    ' + 'hr ' + hr.height())
        if (hl.height() > (hr.height() + 14)) {
            hr.css('minHeight', hl.height() - 14);
        }
        else if (hl.height() < (hr.height() + 14)) {
            hl.css('minHeight', hr.height() + 14);
        }
    }, 500)
}
