// remove "no-js" class and add "js" for JS users
document.getElementsByTagName("html")[0].className = "js";


var openDetails;
var telPattern = /(\+44|\+44\(0\)|0)(1[0-9]{4}[0-9]{4,5}|1[0-9]{3}[0-9]{5,6}|1[0-9]{1}1[0-9]{3}[0-9]{2}[0-9]{2}|11[0-9]{1}[0-9]{3}[0-9]{2}[0-9]{2}|2[0-9]{1}[0-9]{4}[0-9]{2}[0-9]{2}|3[0-9]{2}[0-9]{3}[0-9]{2}[0-9]{2}|3[0-9]{2}[0-9]{3}[0-9]{2}[0-9]{2}|7[0-9]{3}[0-9]{6}|8[0-9]{2}[0-9]{3}[0-9]{2}[0-9]{2}|9[0-9]{2}[0-9]{3}[0-9]{2}[0-9]{2})/;

String.prototype.remove = function (find, replace) {
    var temp = this;
    while (temp.indexOf(find) > -1)
        temp = temp.replace(find, replace);

    return String(temp);
}


function imposeMaxLength(len, text) {
    return (text.length < len);
}

function valTelephoneFormat_ClientValidate(sender, args) {
    args.IsValid = $('#' + $(sender).attr('controltovalidate'))
                    .val().remove(' ', '')
                    .match(telPattern) != null;
}

function isValidDate(d) {
    if (Object.prototype.toString.call(d) !== "[object Date]")
        return false;
    return !isNaN(d.getTime());
}

function DateFormatValidator_ClientValidate(sender, args) {
    args.IsValid = false;
    var dd = $('select.dd');
    var mm = $('select.mm');
    var yyyy = $('select.yyyy');

    var d = dd.val() == "" ? "dd" : dd.val();
    var m = mm.val() == "" ? "mm" : mm.val();
    var y = yyyy.val() == "" ? "yyyy" : yyyy.val();

    if (d != "dd" &&
        m != "mm" &&
        y != "yyyy") {
        
        var date = m + "/" + d + "/" + y;
        try {
            var val = new Date(date);
            args.IsValid = isValidDate(val);
        }
        catch (e) { }
    }
}

$(document).ready(function () {

    // Text replacement
    var els = $('#wideBanner h1').add('.cufon');
    Cufon.replace(els);

    if ($('.centerColumnForms .formpod').length > 1)
        childBoxFix('centerColumnForms .formpod');

    // make B2C 'our products' link area same height
    if ($("div.product_choice div.product_highlight").length > 0) {
        childBoxFix('product_highlight');
    }

    // data table results - find us
    if ($("div.findUsTable").length > 0) {
        $('div.findUsTable table').hide().parent().append("<a class=\"viewFindUs\" href=\"#\">Click to view</a>");
        $('div.findUsTable table td:odd').css("text-align", "center");
        $('div.findUsTable table tr:even td').css("background", "#e8edff");
    }

    $('textarea.length-1000').each(function (i, e) {
        var current = $(e);
        current.keypress(function () { return imposeMaxLength(1000, current.val()); });
    });


    $("div.findUsTable a").toggle(
            function () {
                if (openDetails != undefined) {
                    openDetails.prev("table").hide();
                    openDetails.text("Click to view");
                }

                $(this).prev("table").show();
                $(this).prev("table td").css("background", "#FFF");
                $(this).text("close");
                $(this).addClass("closeData");
                openDetails = $(this);

                return false;
            },
            function () {
                $(this).prev("table").hide();
                $(this).text("Click to view");
                return false;
            }
        );

    if ($('#mainimagewrapper div').length > 0 && !($.browser.msie && $.browser.version <= 6)) swapInOut(1, 1, 2);

    if ($('#sitemap').length > 0) shrinkSitemap();

    $('#galleryImages a').attr('rel', 'lightbox-gallery');
    $('.img1[href],.img2[href],.img3[href],.img4[href]').attr('rel', 'lightbox-tagImages');

    var DEFAULT_SEARCH_TEXT = 'Что ищите?';

    $('input.searchText').each(function (i, e) {
        if ($(e).val() == '') $(e).val(DEFAULT_SEARCH_TEXT);
        $(e).focus(function (e) { if ($(this).val() == DEFAULT_SEARCH_TEXT) $(this).val(''); })
        .blur(function (e) { if ($(this).val() == '') $(this).val(DEFAULT_SEARCH_TEXT); });
    });

    var DEFAULT_POSTCODE_TEXT = 'Город';
    $('input.fldPostCode')
        .focus(function (e) { if ($(this).val() == DEFAULT_POSTCODE_TEXT) $(this).val(''); })
        .blur(function (e) { if ($(this).val() == '') $(this).val(DEFAULT_POSTCODE_TEXT); });
    if ($('input.fldPostCode').val() == '') $('input.fldPostCode').val(DEFAULT_POSTCODE_TEXT);

    var hideMenuTimeout = 0;
    var hideTimeout = 200;

    $('#mainmenu dt.menuitem a')
        .mouseover(showMenu)
        .mouseout(function () { hideMenuTimeout = setTimeout(function () { hideMenu(); }, hideTimeout); });
    $('#mainmenu dd')
        .mouseover(function () { clearTimeout(hideMenuTimeout); })
        .mouseout(function () { hideMenuTimeout = setTimeout(function () { hideMenu(); }, hideTimeout); });

    function hideMenu() {
        $('#mainmenu dt.menuitem').css({
            borderWidth: '0px',
            margin: '4px 4px 2px 4px',
            background: ''
        })
        .children().css({ color: '#fff' });
        $('#mainmenu dd').css({ left: '-100000px' });

        $('#mainmenu .selected').css({ background: 'transparent url(/resources/images/background_mainmenu_selected_10x36.gif) repeat-x top left' });

        return false;
    }

    function showMenu() {
        hideMenu();
        clearTimeout(hideMenuTimeout);
        var dt = $(this).parent();
        dt.css({
            borderWidth: '4px 4px 2px 4px',
            margin: '0',
            background: '#ececec url(/resources/images/background_mainmenu_hover_10x36.gif) repeat-x top left'
        })
        .children().css({ color: '#5E5E5E' });

        if (dt.next().length > 0 && dt.next()[0].tagName == 'DD') {
            dt.next()
            .css({
                left: dt.position().left,
                top: dt.position().top + dt.height() + 4
            })
        }

        return false;
    }


    $('#explorelink')
        .mouseover(showExploreMenu)
        .mouseout(function () { hideMenuTimeout = setTimeout(function () { hideExploreMenu(); }, hideTimeout); });
    $('#explorelist')
        .mouseover(function () { clearTimeout(hideMenuTimeout); })
        .mouseout(function () { hideMenuTimeout = setTimeout(function () { hideExploreMenu(); }, hideTimeout); });

    function showExploreMenu() {
        clearTimeout(hideMenuTimeout);
        $t = $(this);
        var newTop = $t.position().top + 35;
        $('#explorelist').css({ left: 'auto', right: '0', top: newTop });
    }

    function hideExploreMenu() {
        $('#explorelist').css({ left: '-10000px', right: 'auto' });
    }

    $('#innerArea').css({ opacity: 0.8 });

    var faderImages = $('.b2cFaderImage').hide();
    if (faderImages.length > 1) setTimeout(function () { swapper(1, null, faderImages); }, 3000);

    $('.product_choice').each(function () {
        var b2cfader = $(this).find('.extraimg');
        if (b2cfader.length > 1) {
            b2cfader.hide().eq(0).show();
            setTimeout(function () { betterswapper(1, b2cfader); }, 2000);
        }
    });
})

window.onload = function () {
    if ($('.pod').length > 0 && $('.b2c').length == 0) childBoxFix('pod');
    else if ($('.pod').length > 0) childBoxFixB2C();
}

/******* b2c image swapper **********/
function swapper(intIn, intOut, jqueryCol) {
    var nextImage = (intIn + 1 < jqueryCol.length) ? intIn + 1 : 0;
    $(jqueryCol[intIn]).fadeIn('slow');
    if (intOut != null) $(jqueryCol[intOut]).fadeOut('slow');
    setTimeout(function () { swapper(nextImage, intIn, jqueryCol); }, 3000);
}

function betterswapper(intIn, jqueryCol) {
    console.log(jqueryCol);
    var nextImage = (intIn + 1 < jqueryCol.length) ? intIn + 1 : 0;
    jqueryCol.filter(':visible').fadeOut('slow');
    jqueryCol.eq(intIn).fadeIn('slow');
    setTimeout(function () { betterswapper(nextImage, jqueryCol); }, 3000);
}

/******* box length fixes *************/
function childBoxFix(divClass) {
    var maxHeight = [];
    var pods = $('.' + divClass);
    var count = 0;
    for (var i = 0, len = pods.length; i + 1 < len; i = i + 2) {
        if ($(pods[i]).height() < $(pods[i + 1]).height())
            $(pods[i]).animate({ height: $(pods[i + 1]).height() }, function () { $(this).css("display", "inline"); });
        else
            $(pods[i + 1]).animate({ height: $(pods[i]).height() }, function () { $(this).css("display", "inline"); });
    }

}

function childBoxFixB2C() {
    var maxHeight = [];
    var pods = $('.pod');
    var count = 0;
    for (var i = 0, len = pods.length; i + 1 < len; i = i + 3) {
        var podArray = [];

        if (i + 2 < len) {

            if (($(pods[i]).height() >= $(pods[i + 1]).height()) && ($(pods[i]).height() >= $(pods[i + 2]).height())) podArray = [i, i + 1, i + 2];
            else if (($(pods[i + 1]).height() >= $(pods[i]).height()) && ($(pods[i + 1]).height() >= $(pods[i + 2]).height())) podArray = [i + 1, i, i + 2];
            else if (($(pods[i + 2]).height() >= $(pods[i + 1]).height()) && ($(pods[i + 2]).height() >= $(pods[i]).height())) podArray = [i + 2, i, i + 1];

            if (podArray.length > 0) {
                $(pods[podArray[1]]).animate({ height: $(pods[podArray[0]]).height() });
                $(pods[podArray[2]]).animate({ height: $(pods[podArray[0]]).height() });
            }
        }
        else {
            if ($(pods[i]).height() < $(pods[i + 1]).height()) $(pods[i]).animate({ height: $(pods[i + 1]).height() });
            else $(pods[i + 1]).animate({ height: $(pods[i]).height() });
        }
    }
}

/***********/

/******** Sitemap code *********/
function shrinkSitemap() {
    $('#sitemap>ul>ul').hide();
    $('#sitemap>ul>li').each(
        function () {
            var arrow = $('<img src="/resources/images/arrow_right.gif" />');
            arrow.toggle(
                function () {
                    $(this).attr('src', '/resources/images/arrow_down.gif').parent().next().slideDown();
                    return false;
                },
                function () {
                    $(this).attr('src', '/resources/images/arrow_right.gif').parent().next().slideUp();
                    return false;
                }
            )
            $(this).prepend(arrow)
        }
    );
}


/********* Main image fader ***********/
function swapInOut(index, inIndex, outIndex) {
    var nextImage = (index < 6) ? index + 1 : 1;
    $('#mainimagewrapper').css({ background: 'none' });
    $('#mainfaderimage' + inIndex).css('background-image', 'url(/resources/images/main_images/' + nextImage + '.jpg)');
    $('#mainfaderimage' + inIndex).stop().fadeIn('slow', function () {
        setTimeout(function () { swapInOut(nextImage, outIndex, inIndex); }, 3000);
    });
    $('#mainfaderimage' + outIndex).fadeOut('slow');
}
/******************/

function AgiController(map) {
    this._map = new google.maps.Map2(document.getElementById(map));
    this._map.setUIToDefault();

    this._markers = [];
    this._info = [];

    this._pointer = new GIcon(G_DEFAULT_ICON);
    this._pointer.shadow = "";
    this._pointer.iconSize = new GSize(29, 29);
    this._pointer.iconAnchor = new GPoint(11, 12);
}

AgiController.prototype.setCenter = function (inLat, inLon, inType) {
    this._map.setCenter(new GLatLng(inLat, inLon), inType);
}

AgiController.prototype.add = function (obj) {
    this._info.push(obj);
}

AgiController.prototype.addMarkers = function (inArray) {
    for (var i in inArray) {
        if (typeof (inArray[i]) != "object") continue;
        var markerIcon = new GIcon(this._pointer);

        if (inArray[i][3].type == "Plant") markerIcon.image = "/resources/images/map_plant_icon.png";
        else if (inArray[i][3].type == "Stockist") markerIcon.image = "/resources/images/map_stockists_icon.png";
        else if (inArray[i][3].type == "PlantSalesOffice") markerIcon.image = "/resources/images/map_PlantSalesOffice_icon.png";
        else if (inArray[i][3].type == "PlantStockist") markerIcon.image = "/resources/images/stockistplants.png";
        else markerIcon.image = "/resources/images/map_sales_icon.png";

        var markerVars = { icon: markerIcon, title: inArray[i][0] };
        var position = new GLatLng(inArray[i][2], inArray[i][1])
        var marker = new GMarker(position, markerVars);

        this.addInfoWindow(marker, inArray[i][3]);

        this._map.addOverlay(marker);

        this._markers.push(marker);
        this._info.push(inArray[i][3]);
    }
}

AgiController.prototype.addInfoWindow = function (marker, myInfo) {
    var me = this;
    GEvent.addListener(marker, 'click', function () {
        var data = me.buildMarkerContent(myInfo);
        marker.openInfoWindowTabsHtml(data);
    });
}

AgiController.prototype.showClickedInfoWindow = function (index) {
    var marker = this._markers[index];
    var markerInfo = this._info[index];
    var data = this.buildMarkerContent(markerInfo);
    marker.openInfoWindowTabsHtml(data);
}

AgiController.prototype.buildMarkerContent = function (data) {
    var content = '<strong>' + data.name + '</strong><br />';
    if (data.address) content += nl2br(data.address, true);
    if (data.tel) content += '<br />Tel: <em>' + data.tel + '</em>';
    if (data.fax) content += '<br />Fax: <em>' + data.fax + '</em>';
    if (data.email) content += '<br />Email: <a href="mailto:' + data.email + '"><em>' + data.email + '</em></a>';
    if (data.web) content += '<br />Website: <a target="_blank" href="' + data.web + '"><em>' + data.web + '</em></a>';

    var tabs = [];

    tabs[0] = this.makeTab("Location", content);

    var showTab = false;
    for (var i in data.additionalData) {
        showTab = true;
        break;
    }

    if (showTab) {
        var tabData = this.makeTabData(data.additionalData);
        tabs[1] = this.makeTab("Products", tabData);
    }


    return tabs;
}

AgiController.prototype.makeTab = function (name, content) {
    return new GInfoWindowTab(name, content);
}

AgiController.prototype.makeTabData = function (data) {
    var retval = "";
    var counter = 0
    for (var i in data) {
        counter++;
        retval += "<tr><td>" + i + '</td><td style="padding-left:4px;">' + data[i] + "</td></tr>";
        if (counter % 11 == 0) retval += '</table><table style="float:left; margin-left:12px;">';
    }

    var width = 200;
    if (counter > 11)
        width = 400;
    retval = '<div style="width:' + width + 'px;"><table style="float:left;">' + retval;
    retval += "</table></div>";
    return retval;
}

function valComments_ClientValidate(oSender, args) {
    args.IsValid = true;
    if ($.trim($('textarea.fldComments').val()).length > 1000)
        args.IsValid = false;
}

function valEmail_ClientValidate(oSender, args) {
    args.IsValid = true;
    if ($.trim($('input.fldTelephone').val()).length < 1)
        if ($.trim($('input.fldEmail').val()).length < 1)
            args.IsValid = false;
}

function valTelephone_ClientValidate(oSender, args) {
    args.IsValid = true;
    if ($.trim($('input.fldEmail').val()).length < 1)
        if ($.trim($('input.fldTelephone').val()).length < 1)
            args.IsValid = false;
}

function valOptIn_ClientValidate(oSender, args) {
    var input = $('input.cbxOptin');
    var val = (null !== input.val());
    args.IsValid = val;
}

String.prototype.nl2br = function (removeEmpty) {
    if (removeEmpty)
        return this.split("\n").clean('').join("<br/>");
    return this.split("\n").join("<br/>");
};

function nl2br(data, removeEmpty) {
    if (removeEmpty)
        return data.split("\n").clean('').join("<br/>");
    return data.split("\n").join("<br/>");
};

Array.prototype.clean = function (deleteValue) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == deleteValue) {
            this.splice(i, 1);
            i--;
        }
    }
    return this;
};


/** jQuery defaultText plugin **/
$.fn.defaultText = function (options) {
    var opts = $.extend({}, $.fn.defaultText.defaults, options);
    return this.each(function () {
        var self = $(this);
        var theType = self.attr('type');

        if (self.val() == '' || self.val() == opts.text) {
            if (theType == 'password') {
                var inputEvent = function () {
                    self.hide();
                    $('<input type="text" name="password" value="Password" class="text" />').insertAfter(self).focus(function () {
                        $(this).remove();
                        self.show().focus();
                    });
                }
                inputEvent();
                self.blur(function () { if (self.val() == '' || self.val() == opts.text) inputEvent(); });
            }

            self.css(opts.defaultCss).val(opts.text);
        }

        self.focus(function () {
            if (self.val() == opts.text) self.css(opts.editCss).val('');
        });
        self.blur(function () { if (self.val() == '' || self.val() == opts.text) self.css(opts.defaultCss).val(opts.text); });
    });
};
$.fn.defaultText.defaults = {
    text: 'Текст',
    editCss: { color: '#b3b3b3' },
    defaultCss: { color: '#676767' }
}
$(function () {
    $('.form input.username').defaultText({ text: 'Пользователь' });
    $('.form input.location').defaultText({ text: 'Город' });
    $('.form input.password').defaultText({ text: '' });
});

// Bradstone find installer accordion
function accordion() {
    var data = $('.accordionContainer .installerData').hide();
    var button = $('.accordionContainer .tableRow .buttonLess')
        .click(function () {
            var thedata = $(this).parent().parent().next('.installerData');
            if (!thedata.is(':visible')) thedata.slideDown('slow');
            else thedata.slideUp('fast');

            data.filter(':visible').not(thedata).slideUp('fast');
            return false;
        });

    button.parent().click(function (e) {
        if ($(e.target).hasClass('buttonLess')) return false;
        $(this).find('.buttonLess').trigger('click');
    })
};

// Bradstone terms and conditions popup
$(function () {
    var tcLink = $('.bradstoneAssured .termsandconditions');
    var content = $('<div class="tcpopup"></div>').load(tcLink.attr('href'));
    tcLink.click(function (e) {
        e.preventDefault();
        content.appendTo('body');
        $('.close').click(function () {
            content.remove();
        })
    });
    /* xform ie fixes */
    $('.xForm table#id_matrix input[type="radio"], .xForm table#id_matrix input[type="checkbox"]').css({ border: 0 });
    $('.xForm table#id_matrix input[type="submit"]').addClass('submitButton');
});


$(function () {
    // most viewed/commented tabs on blog section
    var mostTabs = $('.blog .mosts .tabs');
    mostTabs.find('li').click(function (e) {
        e.preventDefault()
        if ($(this).find('h3').length > 0) {
            // This tab is already active, do nothing.
            return false;
        } else {
            // set this tab to the active state and deactivate the other tab.
            $(this).parent().find('li h3 a').unwrap();
            $(this).find('a').wrap('<h3>');
            //hide the currently visible tab page and show the currently hidden one
            if ($(this).hasClass('one')) {
                mostTabs.parent().find('.page2').hide();
                mostTabs.parent().find('.page1').show();
            } else {
                mostTabs.parent().find('.page1').hide();
                mostTabs.parent().find('.page2').show();
            }
        }
    });

    //Tooltips on share icons
    $("#rightcol .shareLinks li:not(.gplus)").hover(
        function () {
            var link = $(this).find('a:not(.gplus)');
            if (link.length > 0) {
                link.data('tooltip', link.attr('title'));
                tdata = link.data('tooltip');
                link.attr('title', '');
                var tt = $('<div class="tooltip"><span>' + tdata + '</span><div class="arrow"></div></div>').appendTo($(this));
                $(this).css('cursor', 'pointer');
            }
        },
        function () {
            var link = $(this).find('a:not(.gplus)');
            if (link.length > 0) {
                tdata = link.data('tooltip');
                link.attr('title', tdata);
                $(this).find('.tooltip').remove();
            }
        }
    );
});


/*
 *      Sustainability pages
 */
$(window).load(function () {

    if ($('.sustainabilityHome #podsWrap').length) {
        // store original positions of sliding divs
        $("div.podBlock div").each(function (i, el) {
            var origPos = $(el).position().top;
            $(el).data("origPos", origPos);
        });

        $('.sustainabilityHome div.podBlock')
            .hover(
                function (e) {
                    var newPos = $(this).find('div').data('origPos') - 75;
                    $(this).find('div').stop().animate({ 'top': newPos }, 200);
                },
                function (e) {
                    var origPos = $(this).find('div').data('origPos');
                    $(this).find('div').stop().animate({ 'top': origPos }, 200);
                });
    }

    if ($("#centercol.sustainabilitySubpage").length) {
        // Centre the central pod images
        $("#centralPodsWrap a").each(function (i, el) {
            var img = $(el).find('img');
            if (img.width() < 88) { img.css({ 'right': ((88 - img.width()) / 2) }); } else { img.width('88px'); }   // set width if too big (for IE6)
            if (img.height() < 150) img.css({ 'top': ((150 - img.height()) / 2) });
        });
    }
});

$(function () {
    if ($(".AIaccordian").length) {
        $(".AIaccordian").AIaccordian();
            $('.AIaccordian table').each(
                function () {
                    //$(this).find('th:not(:last-child)').addClass('dark');
                    //$(this).find('td:not(:last-child)').addClass('dark');
                    $(this).find('tr:even').addClass('dark');
                }
            );
    }

    // temp fix for broken navigation -> 
    //if ($("#mainmenu dt").length == 23) $("#mainmenu dt").slice(-4).hide();
});

$(function () {
    if ($("#interactionElementWrap").length) {
        var iE = $("#interactionElementWrap");

        // $('.formpod .podContent', iE).hide();
        $('.formpod').each(
            function () {
                if (!$(this).find('h3').hasClass('open')) {
                    $(this).find('.podContent').hide();
                }
            }
        );

        $('h3', iE)
            .css({ 'cursor': 'pointer' })
            .click(function (e) {
                if ($(this).hasClass('open')) {
                    $(this).removeClass('open').next('.podContent').slideUp();  // close it
                } else {
                    $(this).addClass('open').next('.podContent').slideDown();   // open it
                }
            });
    }


    /* PRODUCT PAGE */

    $('div.tabs').hide();
    $('div.tab1').show();
    $('a.tab1').attr('id', 'active');
    $('div.swatch').hide();
    $('div.summary').hide();
    $('span.titles').css({ 'height': '25px' });


    // open animation
    $('a.open').hover(function () {
        $(this).animate({ 'top': '-3px' }, 200);
    }, function () {
        $(this).animate({ 'top': '0px' }, 200)

    });

    // add to basket animation
    $('a.add').hover(function () {
        $(this).animate({ 'top': '-3px' }, 200);
    }, function () {
        $(this).animate({ 'top': '0px' }, 200)

    });

    // add to basket animation
    $('a.download').hover(function () {
        $(this).animate({ 'top': '-3px' }, 200);
    }, function () {
        $(this).animate({ 'top': '0px' }, 200)

    });


    /* CASE STUDIES */
    $('div.case-studies').css({ 'width': '145px' });
    $('div.case-studies ul li').css({ 'color': '#fff' });


    //ie6 z-index issue
    var zIndexNumber = 1000;

    $("div.tabs div").each(function () {
        $(this).css('zIndex', zIndexNumber);
        zIndexNumber -= 10;
    });


    $('div.case-studies div.image').hover(function () {

        // find summary within the div.image area, create popup
        $(this).parent().find('div.summary').fadeIn(800);
        $("div.case-studies div.summary").css({

            "position": "absolute",
            "left": "150px",
            "top": "50px",
            "background-color": "#888",
            "padding": "10px",
            "width": "300px",
            "z-index": "999999999",
            "color": "#fff"


        });


    }, function () {
        $(this).parent().find('div.summary').fadeOut(800);
    });


    /* TAB AREA */
    $('a.tab2').one("click", function (event) {

        var max = $('div.swatch').length;
        for (i = 0; i <= max; i++) {
            $('div.swatch').delay(200).eq(i).fadeIn(800);
        }

    });


    // tabbing system 
    $('ul.tab-nav a').click(function () {

        var myClass = $(this).attr("class");

        $(this).attr('id', 'active');
        $('ul.tab-nav a').not(this).removeAttr('id');

        $('div.tabs').not('div.' + myClass).hide();
        $('div.' + myClass).show();
        return false; // Prevent browser from visiting `#`

    });

    $('span.titles').hover(function () {
        $(this).animate({
            height: '55px'
        }, 400)
    }, function () {

        $(this).animate({
            height: '25px'
        }, 400);

    });


    /* GALLERY */

   // $('div.image').prepend('<div class="image-large"></div>');
    $("div.image-large").css({
        "position": "absolute",
        "left": "150px",
        "top": "20px",
        "background-color": "#fff",
        "border": "1px solid #D3D3D3",
        "padding": "15px",
        "width": "auto",
        "z-index": "9999999999",
        "color": "#888"

    });

    $('div.image-large').hide();

    // for each image in the gallery append _large. on the popup
    //$('div.gallery div.image-large').each(function () {
      //  var imgsrc = $(this).next().attr('src').replace('.', '_large.');
       // $(this).prepend('<img src=' + imgsrc + ' />');

//    });

    // on hover open lightbox
    $('div.gallery div.image').hover(function () {
        $(this).next().delay('300').fadeIn('200');
        $(this).children().eq(1).animate({ opacity: 0.7 }, 1000);


    }, function () {
        $(this).next().fadeOut('100');
        $(this).children().eq(1).animate({ opacity: 1 }, 200);
    });


    /* SLIDESHOW */


    // slider counters
    var count = 0;
    var info = 1;
    var max = $('div.feature-image').length;

    // Preset area
    $('div.feature-image').hide();
    $('div.feature-image:first').show();

    $('div.feature').prepend('<a href="#" class="pause">pause</a>');
    $('div.feature').prepend('<a href="#" class="left">left</a>');
    $('div.feature').prepend('<a href="#" class="right">right</a>');
    $('div.feature-info').prepend('<div class="img-info"></div>');


    // pause button
    $('a.pause').toggle(function () {
        $('a.left').slideUp();
        $('a.right').slideUp();
        clearInterval(myInterval);
        $('a.pause').css('background', 'url(/resources/images/product/play.gif) no-repeat');

    }, function () {
        $('a.left').slideDown();
        $('a.right').slideDown();
        slideshow();
        $('a.pause').css('background', 'url(/resources/images/product/pause.gif) no-repeat');
    });


    slideshow();

    // left arrow function
    $('a.left').click(function () {


        // set timeout on the button
        setTimeout(function () {
            clearInterval(myInterval);
            slideshow();
            return false;
        }, 3000);

        // check to see if the image count is less than the maximum
        if (count > 0) {
            clearInterval(myInterval);
            $('div.feature-image').eq(count).stop(true, true).fadeOut('400');
            count--;
            $('div.feature-image').eq(count).stop(true, true).delay('400').fadeIn('1000');
            info--;
            $('div.img-info').html(info + ' of ' + max + ' | ');


        }

    });


    // right arrow function
    $('a.right').click(function () {


        // set timeout on the button
        setTimeout(function () {
            clearInterval(myInterval);
            slideshow();
            return false;
        }, 3000);

        // check to see if the image count is less than the maximum
        if (count < max - 1) {
            clearInterval(myInterval);
            $('div.feature-image').eq(count).stop(true, true).fadeOut('400');

            count++;
            $('div.feature-image').eq(count).stop(true, true).delay('400').fadeIn('1000');
            info++;
            $('div.img-info').html(info + ' of ' + max + ' | ');


        }

    })




    // main slideshow function
    function slideshow() {

        // start info (x of x images) on 1
        $('div.img-info').html(info + ' of ' + max + ' | ');

        myInterval = window.setInterval(function () {

            info++;
            $('div.img-info').html(info + ' of ' + max + ' | ');

            // increment the (x of x images) info area
            if (info > max) {
                info = 1;
                $('div.img-info').html(info + ' of ' + max + ' | ');
            } else {
                $('div.img-info').html(info + ' of ' + max + ' | ');
            }

            $('div.feature-image').eq(count).stop(true, true).fadeOut('400');

            if (count == max - 1) {

                $('div.feature-image').eq(max).stop(true, true).fadeOut('400')
                $('div.feature-image').eq(0).stop(true, true).delay('400').fadeIn('1000')

                count = 0;
                clearInterval(myInterval);
                slideshow();
            } else {
                count++;
                $('div.feature-image').eq(count).stop(true, true).delay('400').fadeIn('1000')
            }


        }, 4000);


    }


});

/* Script specifically for /our-businesses/bradstone/installation-service/garden-driveway-landscaper/installer-network/assured-enquiry-form/ */
var termsAndConditions =
"<p>Bradstone Assured members are subject to regular quality checks and assessments and are required to abide by the Bradstone Assured approved terms and conditions of membership at all times.</p>" +
"<p>Each Bradstone Assured approved member is directly responsible for the management of the relationship with their customers and any enquiries.</p>" +
"<p>Claims or suggestions should be addressed directly to the relevant Bradstone Assured approved member providing the relevant products or services.</p>"; //put terms and conditions here

function loadTermsAndConditions(e) {
    e.preventDefault();
    if ($('#termsAndConditionsContainer').length == 0) {
        $(document.body).append(
			"<div id='termsAndConditionsContainer' class='tcpopup'>" +
				"<title>" +
						"Terms and conditions" +
				"</title>" +
				"<div class='termsContainer' id='#inquiryConditions'>" +
					"<div class='close'></div>" +
						"<h1>" +
							"<span>Terms and conditions</span>" +
						"</h1>" +
						"<div style='font-size:1.5em;'>" + termsAndConditions + "</div>" +
				"</div>" +
			"</div>"
		);

        $('#termsAndConditionsContainer .close').click(function () {
            $('#termsAndConditionsContainer').remove();
        });
    }
}
$(function () {
    $('#installer-enquiry a.tcLink').click(loadTermsAndConditions);
});

