﻿Cufon.replace('h1, h2, h3', { hover: true });

$(function () {
    $('#clientPanelButton, #callbackPanelButton').bind('click', function () {
        var btt = $(this);
        var cnt = btt.parent();
        var other = (btt.is('#clientPanelButton')) ? $('#callbackPanelButton') : $('#clientPanelButton');

        if (btt.is('.expanded')) {
            btt.removeClass('expanded');
            cnt.stop().animate({ 'marginTop': '83px' }, 'fast');
        }
        else {
            btt.addClass('expanded');
            other.removeClass('expanded');
            var trgt = $(btt.attr('href'));
            trgt.show();
            $(other.attr('href')).hide();
            cnt.stop().animate({ 'marginTop': '23px' }, 'fast', function () {
                trgt.find('input')[0].focus()
            });

        }
        return false;
    });
    $('#footerClient').click(function () {
        if (!$('#carousel').length) {
            self.scrollTo(0, 0);
            $('#clientPanelButton').trigger('click');
            return false;
        }
    });

    var hsh = self.location.hash;
    if (hsh != '' && $(hsh + 'Button').length) {
        $(hsh + 'Button').trigger('click');
    }

    var currentPanel = 0;
    var panelsTotal = 0;
    var carouselTimer = 0;
    var carouselCancelled = 0;
    function carouselInit() {
        $('#carousel').find('img').css({ 'opacity': '.6' });
        $('#carousel').css({ 'overflow': 'hidden' });
        $('<a href="#" id="hPrev"></a>').click(function () { carouselAnim(true); cancelTimer(); return false }).appendTo($('#carousel')).hide();
        $('<a href="#" id="hNext"></a>').click(function () { carouselAnim(); cancelTimer(); return false }).appendTo($('#carousel'));
        panelsTotal = $('#carousel .panel').length;
        $('#carousel').bind({
            'mouseenter': pauseTimer,
            'mouseleave': carouselAuto
        })
        $(document).keydown(function (e) {
            switch (e.keyCode) {
                case 37:
                    $('#hPrev').trigger('click');
                    break;
                case 39:
                    $('#hNext').trigger('click');
                    break;
            }
        })
        $(window).load(carouselAuto);
    }

    function carouselAnim(vs) {
        currentPanel = (vs) ? currentPanel - 1 : currentPanel + 1;
        if (currentPanel <= 0 || currentPanel == panelsTotal) { $('#hPrev').hide(); currentPanel = 0; }
        else $('#hPrev').show();
        if (currentPanel == panelsTotal - 1) $('#hNext').hide();
        else $('#hNext').show();
        $('#panelsContainer').stop().animate({ 'marginLeft': (currentPanel * -940) + 'px' });
    }

    function carouselAuto() {
        if (carouselCancelled) return
        pauseTimer();
        carouselTimer = setInterval(function () { carouselAnim() }, 7000);
    }
    function pauseTimer() {
        if (carouselTimer) clearInterval(carouselTimer);
    }
    function cancelTimer() {
        pauseTimer();
        carouselCancelled = 1;
    }

    if ($('#carousel').length) {
        carouselInit()
    }
    else if ($('#slider').length) { sliderInit() }

    function sliderInit() {
        $('<div class="container">').append($('<a href="#" id="vPrev"></a>').click(function () { return false })).insertBefore($('#slider'));
        $('<div class="container">').append($('<a href="#" id="vNext"></a>').click(function () { carouselAnim(); cancelTimer(); return false })).insertAfter($('#slider'));
    }

    $('a[rel="external"]').attr('target', 'externalWindow')
    /* .find('img').parent().css({'position':'relative'}).bind({
        'mouseenter': function () {
            $(this).append('<span class="externalLinkTag">Go to the website</span>');
        },
        'mouseleave': function () {
            $(this).find('.externalLinkTag').remove();
        }
    }) */

    $.extend($.validator.messages, {
        required: "Required field",
        email: "Invalid email"
    });

    $('#clientLogin').validate();

    $('#callBack, #contactForm').submit(function () {

        var callback = ($(this).is('#callBack')) ? true : false;

        if ($(this).validate().form()) {
            var data = callback ? {
                "callbackEMAIL": $('#callbackEmail').val(),
                "callbackNAME": $('#callbackName').val(),
                "callbackNUMBER": $('#callbackNumber').val()
            } : {
                "contactTITLE": $('#contactTitle').val(),
                "contactNAME": $('#contactName').val(),
                "contactSURNAME": $('#contactSurname').val(),
                "contactEMAIL": $('#contactEmail').val(),
                "contactNUMBER": $('#contactNumber').val(),
                "contactMESSAGE": $('#contactMessage').val()
            };
            data = $.toJSON(data);
            var theForm = this;
            $.ajax({
                type: "POST",
                url: callback ? "Contact.aspx/RequestCallback" : "Contact.aspx/ContactUs",
                contentType: "application/json; charset=utf-8",
                data: data,
                dataType: "json",
                success: function (d) {
                    successFn(d);
                    theForm.reset();
                },
                error: errorFn
            });
        }
        return false;
    });
    function successFn(data) {
        if (data.d == "OK") {
            openSubmitResult('<p>Thank you for your query.<p><p class="small">It has been sent successfully and <br />we\'ll get back to you as soon as possible.</p>');
        } else {
            openSubmitResult("<p>Failed to submit the form.<p><p class=\"small\">Please retry and contact <br /><a href=\"mailto:talk@crothorne.com\">talk@crowthorne.com</a> <br />if problems persist.</p>");
        }
    }
    function errorFn() {
        openSubmitResult("<p>Failed to submit the form.<p><p class=\"small\">Please retry and contact <br /><a href=\"mailto:talk@crothorne.com\">talk@crowthorne.com</a> <br />if problems persist.</p>");
    }

    function openSubmitResult(msg) {
        $('<div id="overlay"></div><div id="formMessage"><div id="closeButton">X</div>' + msg + '</div>').appendTo($('body'));
        $('#overlay, #closeButton').bind('click', closeSubmitResult);
    }
    function closeSubmitResult() {
        $('#overlay, #formMessage').empty().remove();
    }
});

/* Google Analytics */
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-24364638-1']);
_gaq.push(['_trackPageview']);

(function () {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
