// 2.0 Frontend ======================================================================
var Frontend = {

    // 2.1 Frontend.Default ======================================================
    Default: (function () {

        //This Init function is called on every page on the site.
        function init() {

            //Place general init functions here or else add to DocReadyMgr using Header.DocReadyMgr.AddFunction("functionName(params)")
            Header.DocReadyMgr.Run();
            Frontend.Header.Init();
            Frontend.LightBox.Init();
            Tracking.GoogleAnalytics.Init();
        }

        //This init function is called only on the homepage
        function homepageInit() {

        }

        return {
            init: init,
            homepageInit: homepageInit
        }

    })(),


    StaffSearch: (function () {

        function Init() {
            listType();
            rowHover();
        }

        function listType() {
            $("a.swapView").click(function () {

                $("div.categories").hide();
                var indexNo = $(this).index() - 1;
                $("div.categories").eq(indexNo).show();

                return false;
            });
        }

        function rowHover() {
            $("div.categories li").hover(function () {
                $(this).css('backgroundColor', '#F7F7F7');
            }, function () {
                $(this).css('backgroundColor', '#FFFFFF');
            });
        }

        return {
            Init: Init
        }
    })(),

    // 2.3 Frontend.LightBox ======================================================
    LightBox: (function () {

        var $cbox;

        function Init() {
            $cbox = $('#colorbox');

            $("a[rel='lightbox']").each(
				function () {
				    $(this).colorbox({
				        initialWidth: 1,
				        initialHeight: 1,
				        transition: "elastic",
				        title: function () {
				            return $(this).attr('title');
				            //return "test title";
				        },
				        onComplete: function () {
				            SetDescriptionAndHeight($(this));

				        },
				        onCleanup: function () {

				        }
				    });
				}
			);

            $("a[rel='lightbox-content']:not(#colorbox a[rel='lightbox-content'])").live('click', function () {
                $.colorbox({
                    href: $(this).attr('href'),
                    innerWidth: 500,
                    innerHeight: 200,
                    title: $(this).attr('title'),
                    onComplete: function () {
                        $cbox.find('.offscreen').removeClass('offscreen').addClass('onscreen');
                        SetDescriptionAndHeight($(this));
                    },
                    onCleanup: function () {
                        $cbox.find('.onscreen').removeClass('onscreen').addClass('offscreen');
                    }
                });
                return false;
            });

            $("a > span[class='lightbox-content']:not(#colorbox a > span[class='lightbox-content'])").live('click', function () {
                $.colorbox({
                    href: $(this).parent().attr('href'),
                    innerWidth: 500,
                    innerHeight: 200,
                    title: $(this).parent().attr('title'),
                    onComplete: function () {
                        $cbox.find('.offscreen').removeClass('offscreen').addClass('onscreen');
                        SetDescriptionAndHeight($(this));
                    },
                    onCleanup: function () {
                        $cbox.find('.onscreen').removeClass('onscreen').addClass('offscreen');
                    }
                });
                return false;
            });

        }

        function SetDescriptionAndHeight(elm) {
            var description = elm.parent().find('p:first').text();
            $("#cboxDescription").remove();
            var $content;
            if (description != '') {
                $("#cboxLoadedContent").after('<div id="cboxDescription">' + description + '</div>');
                var heightIncrease = $("#cboxTitle").height() > 39 ? ($("#cboxTitle").height() - 39) : 0;
                if (heightIncrease != 0) {
                    $("#cboxLoadedContent").css({ 'margin-top': 20 + heightIncrease });
                }
                heightIncrease += $('#cboxDescription').height();
                $content = $('#cboxContent');
                $content.height($content.height() + heightIncrease);

                $cbox.css({ 'top': ($cbox.css('top').replace('px', '') - (heightIncrease / 2)) + 'px' });
                $('#cboxWrapper').height($('#cboxWrapper').height() + heightIncrease);
                $('#colorbox').height($('#colorbox').height() + heightIncrease);
            } else {
                var heightIncrease = $("#cboxTitle").height() > 39 ? ($("#cboxTitle").height() - 39) : 0;
                if (heightIncrease != 0) {
                    $("#cboxLoadedContent").css({ 'margin-top': 20 + heightIncrease });
                    $content = $('#cboxContent');
                    $content.height($content.height() + heightIncrease);
                    $cbox.css({ 'top': ($cbox.css('top').replace('px', '') - (heightIncrease / 2)) + 'px' });
                    $('#cboxWrapper').height($('#cboxWrapper').height() + heightIncrease);
                    $('#colorbox').height($('#colorbox').height() + heightIncrease);
                }
            }
        }

        return {
            Init: Init
        }
    })(),


    // 2.4 Frontend.Carousel ======================================================
    Carousel: (function () {

        function Init() {
            $('#gallery-navigation').terousel({
                ajaxPage: true
            });
            $('#gallery-navigation li').tooltip();
        }

        return {
            Init: Init
        }
    })(),

    // 2.5 Frontend.LocationMap ===================================================
    LocationMap: (function () {

        function Init(map, mapZoom, latitude, longitude, markers) {

            //MAP
            var latlng = new google.maps.LatLng(latitude, longitude);
            var myOptions = { zoom: mapZoom, center: latlng, mapTypeControl: true, mapTypeId: google.maps.MapTypeId.ROADMAP };
            var map = new google.maps.Map(document.getElementById(map), myOptions);

            //MARKER
            for (index in markers) {
                addMarker(markers[index]);
            }

            function addMarker(data) {
                var marker = new google.maps.Marker({ position: new google.maps.LatLng(data.lat, data.lng), map: map, title: "View details of " + data.name, icon: data.markerImage });

                google.maps.event.addListener(marker, "click", function () { window.location.href = data.URL; });
            }
        }

        return { Init: Init }
    })(),



    // 2.10 Rotator ==================================================================
    Rotator: (function () {
        var current_index = 0;
        var interval = '';
        var delay_sec = 8;
        var interval_sec = 5;
        var $items;
        var numItems;

        function Init() {
            $('.rotator').each(function () {
                var $rotator = $(this);
                $rotator.find('li').first().addClass("first");

                numItems = $rotator.find('li').length;
                if (numItems > 1) {
                    $rotator.find('ul').css({ 'width': $rotator.width(), 'position': 'relative', 'overflow': 'hidden', 'top': '0', 'left': '0' });

                    $items = $rotator.find('.items li');
                    $items.css({ 'width': $rotator.width(), 'height': $rotator.height(), 'position': 'absolute' });

                    $rotator.append('<div class="rotator-nav"><ul class="pages"></ul></div>');
                    var $controls = $rotator.find('.rotator-nav');
                    for (var i = 0; i < numItems; i++) {
                        $controls.find('.pages').append('<li class="page-num"><a class="sprite item-index" href="#" rel="' + i + '">' + (i + 1) + '</a> </li>');
                    }
                    $rotator.find('ul.pages').width(numItems * (5 + $rotator.find('li.page-num:first').width() + 10));

                    BindControls($items, $controls);
                }
                $("a.item-index[rel=0]").addClass("active");
            });

            if (numItems > 1) SetTimer();
        }

        function BindControls($items, $controls) {
            var $itembuttons = $controls.find('.item-index');

            $itembuttons.each(function () {
                var $this = $(this);
                $this.click(function () {
                    var index = $this.attr('rel');
                    ShowItemAt(index, 0);
                    DelayTimer();
                    return false;
                });
            });
        }


        function ShowItemAt(index, dir) {

            if (current_index != index) {

                var $currentItem = $items.eq(current_index); //.filter(':visible');
                var $nextItem = $items.eq(index);

                var endpos = (dir === 'left') ? '100%' : '-100%';

                if (dir === 0) {
                    endpos = current_index > index ? '100%' : '-100%';
                }

                var $currentPage = $("a.item-index[rel=" + current_index + "]");
                var $newPage = $("a.item-index[rel=" + index + "]");
                $currentPage.removeClass("active");
                $newPage.addClass("active");

                current_index = index;

                $nextItem.stop().css({ 'left': '0', 'z-index': '1' });
                $currentItem.css({ 'left': '0', 'z-index': '20' });

                $nextItem.show();
                $currentItem.animate({ 'left': endpos }, 500, function () {
                    $currentItem.hide();
                });

                //$items.hide();
                //$items.eq(index).show();

            }
        }


        function moveNext() {
            var index = parseInt(current_index) + 1;
            if (current_index >= $items.length - 1)
                index = 0;
            ShowItemAt(index, 'right');
        }

        function DelayTimer() {
            window.clearInterval(interval);
            var restart = window.setTimeout('Frontend.Rotator.StartAuto();', delay_sec * 1000);
        }

        function SetTimer() {
            window.clearInterval(interval);
            interval = window.setInterval('Frontend.Rotator.Rotate();', interval_sec * 1000);
        }

        return { Init: Init, Rotate: moveNext, StartAuto: SetTimer }
    })(),

    // 2.10b Image gallery ===========================================================

    ImageGallery: (function () {
        var current_index = 0;
        var interval = '';
        var delay_sec = 8;
        var interval_sec = 5;
        var $items;
        var numItems;

        function Init() {

            $('.image-gallery').each(function () {
                var $rotator = $(this);
                numItems = $rotator.find('.set').length;

                $rotator.find('ul').css({ 'height': $rotator.find('li:first img').height(), 'position': 'relative', 'overflow': 'hidden', 'top': '0', 'left': '0' });
                if (numItems > 1) {

                    $items = $rotator.find('.items .set');
                    $items.addClass('no-bottom-margin');

                    $rotator.append('<ul class="list-inline divide-top text-center pages rel"></ul>');
                    var $controls = $rotator.find('.pages');
                    $controls.append('<li><a class="action brd4px curved10 abs prev" href="#">&laquo;</a></li>');
                    for (var i = 0; i < numItems; i++) {
                        $controls.append('<li class="page-num"><a class="btn btn-black item-index" href="#" rel="' + i + '">' + (i + 1) + '</a> </li>');
                    }
                    $controls.append('<li><a class="action brd4px curved10 abs next" href="#">&raquo;</a></li>');

                    BindControls($items, $controls);
                } else {
                    $rotator.addClass('mar-bot-30');
                }
            });
        }
        function BindControls($items, $controls) {
            var $itembuttons = $controls.find('.item-index');
            var $next = $controls.find('.next');
            var $prev = $controls.find('.prev');

            $itembuttons.each(function () {
                var $this = $(this);
                $this.click(function () {
                    var index = $this.attr('rel');
                    ShowItemAt(index, 0);
                    return false;
                });
            });
            $next.click(function () {
                moveNext();
                return false;
            });
            $prev.click(function () {
                var index = parseInt(current_index) - 1;
                if (current_index <= 0)
                    index = $items.length - 1;
                ShowItemAt(index, 'left');
                return false;
            });
        }

        function ShowItemAt(index, dir) {

            if (current_index != index) {

                var $currentItem = $items.eq(current_index); //.filter(':visible');
                var $nextItem = $items.eq(index);

                var endpos = (dir === 'left') ? '100%' : '-100%';

                if (dir === 0) {
                    endpos = current_index > index ? '100%' : '-100%';
                }

                current_index = index;

                $nextItem.stop().css({ 'left': '20px', 'z-index': '1' });
                $currentItem.css({ 'left': '20px', 'z-index': '20' });

                $nextItem.show();
                $currentItem.animate({ 'left': endpos }, 500, function () {
                    $currentItem.hide();
                });
            }
        }

        function moveNext() {
            var index = parseInt(current_index) + 1;
            if (current_index >= $items.length - 1)
                index = 0;
            ShowItemAt(index, 'right');
        }

        return { Init: Init }
    })(),

    // 2.11 Header ===================================================================

    Header: (function () {
        function Init() {
            $("input#search").focus(function () {
                if ($(this).val() == "Search") {
                    $(this).val("");
                }
            });
            $("input#search").blur(function () {
                if ($(this).val() == "") {
                    $(this).val("Search");
                }
            });
            $("#siteSearch").submit(function () {
                var $searchField = $("input#search");
                if ($searchField.val() == "" || $searchField.val() == "Search") {
                    $searchField.addClass("searchError");
                    return false;
                } else {
                    $searchField.remove("searchError");
                    return true;
                }
            });

            //            $.reject({
            //                reject: { msie5: true, msie6: true} // Reject all renderers for demo 
            //            });

        }



        function FauxPlaceholder() {
            if (!ElementSupportAttribute('input', 'placeholder')) {
                $("input[placeholder]").each(function () {
                    var $input = $(this);
                    $input.after('<input id="' + $input.attr('id') + '-faux" style="display:none;" type="text" value="' + $input.attr('placeholder') + '" />');
                    var $faux = $('#' + $input.attr('id') + '-faux');

                    $faux.show().attr('class', $input.attr('class')).attr('style', $input.attr('style'));
                    $input.hide();

                    $faux.focus(function () {
                        $faux.hide();
                        $input.show().focus();
                    });

                    $input.blur(function () {
                        if ($input.val() === '') {
                            $input.hide();
                            $faux.show();
                        }
                    });
                });
            }
        }

        function ElementSupportAttribute(elm, attr) {
            var test = document.createElement(elm);
            return attr in test;
        }

        return { Init: Init }
    })(),

    // 2.10 Rotator ==================================================================
    TrentsTravelRegistration: (function () {

        function Init() {

            //button click - call function
            $("#btnCustValidation").click(function () {
                $("#custValidationError").html("").hide();

                if ($("#custValidation .contourField input.text").val() != '') {
                    validateCustomerNumber();
                } else {
                    $("#custValidationError").text("Please enter your customer number").show();
                }
                return false;
            });

        }

        function validateCustomerNumber() {
            var custNo = $("#custValidation .contourField input.text").val();

            var urlString = '/base/restExt/CheckCustomerNumber/' + custNo + '.aspx';

            $.ajax({
                url: urlString,
                success: function (data) {
                    var returnValue = $(data).children('value').text();

                    switch (returnValue) {
                        case "1":
                            activateForm();
                            break;
                        case "error":
                            $("#custValidationError").html("There was an error when valiating your customer number.<br />Please restart your browser and try again.<br />We apologise for any inconvenience caused.").show();
                            break;
                        default:
                            $("#custValidationError").html("Please check the number entered as it does not appear to be correct.<br />If it is valid please call us on 03 353 8699 to advise of the issue.<br />We apologise for any inconvenience caused.").show();
                            break;
                    }
                }

            });

        }

        function activateForm() {
            //hide customer number field
            $("#custValidation").slideToggle();

            //show form
            $("#custForm").show();
        }

        return { Init: Init }
    })(),


     // 2.10 Rotator ==================================================================
    WebshopApplication: (function () {

        function Init() {

            //button click - call function
            $("#btnCustValidation").click(function () {
                $("#custValidationError").html("").hide();

                if ($("#custValidation .contourField input.text").val() != '') {
                    validateCustomerNumber();
                } else {
                    $("#custValidationError").text("Please enter your customer number").show();
                }
                return false;
            });

        }

        function validateCustomerNumber() {
            var custNo = $("#custValidation .contourField input.text").val();

            var urlString = '/base/restExt/CheckCustomerNumber/' + custNo + '.aspx';

            $.ajax({
                url: urlString,
                success: function (data) {
                    var returnValue = $(data).children('value').text();

                    switch (returnValue) {
                        case "1":
                            activateForm();
                            break;
                        case "error":
                            $("#custValidationError").html("There was an error when valiating your customer number.<br />Please restart your browser and try again.<br />We apologise for any inconvenience caused.").show();
                            break;
                        default:
                            $("#custValidationError").html("Please check the number entered as it does not appear to be correct.<br />If it is valid please call us on 03 353 8699 to advise of the issue.<br />We apologise for any inconvenience caused.").show();
                            break;
                    }
                }

            });

        }

        function activateForm() {
            //hide customer number field
            $("#custValidation").slideToggle();

            //show form
            $("#custForm").show();
        }

        return { Init: Init }
    })()

};

// 3.0 Tracking ======================================================================
Tracking = {

    // 3.1 Tracking.GoogleAnalytics ======================================================
    GoogleAnalytics: (function () {

        function Init() {
            var filetypes = /\.(zip|exe|pdf|doc*|xls*|ppt*|mp3)$/i;
            $('a').each(function () {
                var href = $(this).attr('href');

                if ((href.match(/^https?\:/i)) && (!href.match(document.domain))) {
                    $(this).click(function () {
                        var extLink = href.replace(/^https?\:\/\//i, '');
                        pageTracker._trackEvent('External', 'Click', extLink);
                    });
                } else if (href.match(/^mailto\:/i)) {
                    $(this).click(function () {
                        var mailLink = href.replace(/^mailto\:/i, '');
                        pageTracker._trackEvent('Email', 'Click', mailLink);
                    });
                } else if (href.match(filetypes)) {

                    $(this).click(function () {
                        var extension = (/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined;
                        var filePath = href.replace(/^https?\:\/\/(www.)mydomain\.com\//i, '');
                        pageTracker._trackEvent('Download', 'Click - ' + extension, filePath);
                    });
                }
            });
        }
        return { Init: Init }

    })()
};


jQuery(document).ready(function () {
    Frontend.Default.init();
});

