// remove "no-js" class and add "js" for JS users
document.getElementsByTagName("html")[0].className = "js";

//Keyword search default
$(function () {
    $('#centercol .mediaSearch .mediaSearchBottom input:first').defaultText({ text: "Keyword search", editCss: { color: '#676767'} });
});

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');

    $('input[type="text"]').each(function (i, el) {
        if ($(el).hasClass('searchText')) $(this).val('Search this site');
        if ($(this).val() == "") return false;
        $(this)
            .data('defaultText', $(this).val())
            .focus(function (e) { if ($(this).val() == $(this).data('defaultText')) $(this).val(''); })
            .blur(function (e) { if ($(el).val() == '') $(el).val($(this).data('defaultText')); });
    });


    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) {
    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: 'Enter text here',
    editCss: { color: '#444' },
    defaultCss: { color: '#676767' }
}
$(function () {
    $('.form input.username').defaultText({ text: 'Username' });
    $('.form input.location').defaultText({ text: 'Town, city or postcode' });
    $('.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) {
        $('html, body').animate({ scrollTop: 0 }, '1000');
        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');
                }
            );
    }
});

$(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 */
    $(function () {
        var pp = $('#product-page');
        if (!pp.length) return;

        var productPage = {
            run: function () {
                this.tabs = pp.find('.tabs');
                this.tabNav = pp.find('.tab-nav');

                this.tabNav.click(this.onTabNavClick);
                //pp.find('.add').click(this.saveState);

                this.restoreState(); // check for cookies and restore state is present
                this.showFormDialogue();

                this.initGalleryTitleHeights();
            },
            setActiveTab: function (n) {
                this.tabs.hide().eq(n - 1).show();
                this.tabNav.find('li a').attr('id', '').eq(n - 1).attr('id', 'active');

            },
            onTabNavClick: function (e) {
                e.preventDefault();
                var n = $(e.target).closest('li').index();
                productPage.setActiveTab(n + 1);
                productPage.saveState(n + 1);
                productPage.initGalleryTitleHeights();
            },
            saveState: function (index) {
                var hiddenField = $('.tab-content input[name*="hdnTabTracker"]');
                if (hiddenField.length > 0) {
                    hiddenField.val(index);
                } else {
                    this.saveStateInCookie(e);
                }
            },
            saveStateInCookie: function (e) {
                e.preventDefault();
                var state = {
                    tabIndex: $(e.target).closest('.tabs').index(),
                    scrollTop: $(window).scrollTop()
                }
                $.cookie('ai_product_tabIndex', state.tabIndex);
                $.cookie('ai_product_scrollTop', state.scrollTop);
                $(e.target).next('.addHidden').click(); // retrigger default
            },
            restoreState: function () {
                var hiddenField = $('.tab-content input[name*="hdnTabTracker"]');
                console.log(hiddenField);
                if (hiddenField.length > 0) {
                    this.setActiveTab(parseInt(hiddenField.val()));
                } else {
                    if (!$.cookie('ai_product_tabIndex')) {
                        this.setActiveTab(1);
                        return;
                    } else {
                        this.setActiveTab($.cookie('ai_product_tabIndex'));
                        $('html, body').animate({ scrollTop: $.cookie('ai_product_scrollTop') }, 1000);
                        // job done : remove the cookies
                        $.cookie('ai_product_tabIndex', null);
                        $.cookie('ai_product_scrollTop', null);
                    }
                }
            },
            showFormDialogue: function () {
                var brochure = this.getParameterByName('brochure');
                if (brochure) {
                    this.setActiveTab(this.tabs.length);
                    return;
                }
                var casestudy = this.getParameterByName('case');
                if (casestudy) {
                    var n = $('li a.tab5', this.tabNav).parent().index() + 1;
                    this.setActiveTab(n);
                    return;
                }
            },
            getParameterByName: function (name) {
                if (!name) return;
                name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
                var regexS = "[\\?&]" + name + "=([^&#]*)";
                var regex = new RegExp(regexS);
                var results = regex.exec(window.location.href);
                return (!results) ? 0 : decodeURIComponent(results[1].replace(/\+/g, " "));
            },
            initGalleryTitleHeights: function () {
                var h = 0;
                var titles = $('#gallery span.title');
                titles.each(function (i, el) {
                    if ($(el).height() > h) h = $(el).height();
                });
                if (h) titles.css('height', h);
            }
        }
        productPage.run();

        /* GALLERY */
        // on hover open lightbox
        $('div.gallery div.image, div.swatch div.image').hover(
            function () {
                var nxt = $(this).next();
                if (nxt.find('img').attr('src') == '') return;
                nxt.show();
            },
            function () { $(this).next().hide(); }
        );

        /* 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 = $(this)
            if (!$this.hasClass('formDialogue')) {
                $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);
            }

        });

        $('span.titles').hover(
            function () {
                $(this).animate({ height: '55px' }, 400)
            },
            function () {
                $(this).animate({ height: '25px' }
            , 400);
            });
    });
});

/* 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.Please note that the resulting legal contract is between you and the Bradstone Assured approved member, and is subject to the terms and conditions of that member.  They will advise you of these conditions themselves.</p>" +
"<p>You should carefully review their terms and conditions applying to the purchase of your product and/or services.  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);
});

/***************************************
*
*              Slideshow
*
***************************************/
var AggSlides = {
    el: null,
    ui: null,
    timer: null,
    paused: false,
    pos: 1,
    slides: [],
    run: function () {
        this.el = $('div.feature');
        this.slides = $('.feature-image', this.el);
        if ($('div.feature').find('img').length > 1)
            this.el.prepend('<a class="right" href="#">right</a><a class="left" href="#">left</a><a class="pause" href="#">pause</a>');
        this.slides.first().addClass('active');
        $('.left, .right', this.el).click(this.onNavClick);
        this.pauseBtn = $('.pause', this.el);
        this.pauseBtn.click(this.onPauseClick);
        this.play();
    },
    play: function () {
        this.timer = setInterval(this.changeSlide, 4000);
        this.paused = false;
        this.pauseBtn.removeClass('paused');
    },
    pause: function () {
        clearInterval(this.timer);
        this.paused = true;
        this.pauseBtn.addClass('paused');
    },
    changeSlide: function (e, n) {
        if (!n) n = AggSlides.nextSlide();
        AggSlides.slides.removeClass('active').eq(n - 1).addClass('active');
    },
    nextSlide: function () {
        this.pos = (this.pos == this.slides.length) ? 1 : this.pos + 1;
        return this.pos;
    },
    previousSlide: function () {
        (this.pos == 1) ? this.pos = this.slides.length : this.pos--;
        return this.pos;
    },
    onNavClick: function (e) {
        AggSlides.pause();
        if ($(e.target).hasClass('right')) {
            AggSlides.changeSlide(null);
        } else {
            AggSlides.changeSlide(null, AggSlides.previousSlide());
        }
    },
    onPauseClick: function (e) { (AggSlides.paused) ? AggSlides.play() : AggSlides.pause(); }
};
$(function () { AggSlides.run(); });

/***************************************
*
*              Media and Resources
*
***************************************/
// Popup help boxes
var infoLinks = {
    init: function () {
        $('div.info-link').click(this.showInfo);
    },
    showInfo: function (e) {
        e.preventDefault();
        var html = $(e.target).html();
        var box = $('<div class="info-pop-up"><a class="close" href="#"></a>' + html + '</div>');
        $('body').append(box);
        box.css({
            left: $(e.target).offset().left - 290,
            top: $(e.target).offset().top - 5
        }).stop().fadeIn('slow');
        $('.close', box).click(infoLinks.closeInfo);
    },
    closeInfo: function (e) {
        e.preventDefault();
        $('.info-pop-up').stop().fadeOut('slow', function () {
            $(this).remove
        });
    }
};
$(function () { infoLinks.init(); });

// Media search results page
var msr = {
    run: function () {
        this.items = $('div.mediaItem:visible');
        if (!this.items.length) return;

        this.setTitleHeightsByRow();
        this.initAddToBasketBtn();
        this.initEmailBtn();

        if ($('#centercol.tds').length) {
            this.initSelectDocType();
            $('#centercol').find('.documentTypeSelect').change(this.initSelectDocType);
        }
    },
    setTitleHeightsByRow: function () {
        var rowH = 14, rowItems = [];

        //inner function for checking if the media item has the same parent
        var isSameParent = function (el1, el2) {
            if ($(el1).parent('div').is($(el2).parent('div'))) return true;
            return false;
        };


        var lastElem = null; //for keeping track of last item traveresed
        var currRowWidth = null;

        this.items.each(function (i, el) {
            $item = $(el);

            if (lastElem == null) currRowWidth = $item.outerWidth();
            else currRowWidth = currRowWidth + $item.outerWidth();

            if (lastElem == null) lastElem = $item;

            parentWidth = $item.parent('div').width(); //parent div's width - paddingleft and right



            if ($(el).closest('#tech.tabs').length) return true;    // skip this iteration if technical doc within product page tab

            //start of a new row
            if (!isSameParent(lastElem, el) || currRowWidth >= parentWidth) {
                rowH = 14;                       // reset the vars
                //this is now a new row
                rowItems = [];
                rowItems.push(el);
                currRowWidth = $item.outerWidth();
            }
            else {
                rowItems.push(el);  // add to existing row otherwise
            }


            rowH = ($('h4', this).height() > rowH) ? $('h4', this).height() : rowH;   // keep track of tallest title height
            for (var x = 0; x < rowItems.length; x++) {
                $(rowItems[x]).find('h4').css('height', rowH);          // set all title heights for this row to highest val
            }

        });
    },
    initAddToBasketBtn: function () {
        this.items.each(function (i, el) {
            if ($(el).hasClass('in-basket')) {
                $(el).append($('<div class="in-basket-div"></div>'));
                $(el).find('.add').css({ 'opacity': '0.4' });
            }
            if ($(el).find('.open, .download').attr('href')) {
                $(el).find('input.add').unbind('click').click(msr.onAddToBasketClick);
            } else {
                $(el).find('.buttons input, .buttons a').css({ 'opacity': '0.4', 'cursor': 'default' }).attr('disabled', 'disabled').unbind('click').click(function (e) { return false; });
            }
        });
        // Add chapter mini-buttons (brochure details page)
        var chapters = $('#mediaDetailWrap').find('.chapterList li:not(".first")');
        chapters.each(function (i, el) {
            $(el).find('input.add').unbind('click').click(msr.onAddToBasketClick);
        });
    },
    onAddToBasketClick: function (e) {
        var mItem, doc;
        if (!$(e.target).closest('.chapterList').length) {
            // Standard add to basket button
            mItem = $(e.target).closest('.mediaItem');
            doc = msr.getDocumentDetails(mItem);
        } else {
            // Add brochure chapter button
            mItem = $(e.target).closest('li');
            doc = {
                pageid: mItem.attr('id').replace('_', ''),
                title: mItem.find('label').html().trim(),
                url: mItem.find('.url').val(),
                type: msr.getDocumentType(mItem),
                image: mItem.find('.imgsrc').val()
            };
        }
        if (mItem.hasClass('in-basket')) return false;      // disable buttons for items already in basket

        mItem.data('docDetails', doc);
        if (!$(e.target).closest('#tech.tabs').length) mItem.append($('<div class="loading"></div>'));

        $.ajax({
            url: '/resources/documentbasket.asmx/AddToBasket',
            type: "POST",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: '{ "doc" : { "DocumentUrl": "' + doc.url + '", "PageID" : "' + doc.pageid + '", "DocumentTitle": "' + doc.title + '", "DocType" : "' + doc.type + '", "DocumentImage" : "' + doc.image + '" }}',
            success: function (data, textStatus, jqXHR) {
                if (data.d) {
                    msr.onAddToBasketSuccess(mItem, data, textStatus, jqXHR);
                } else {
                    msr.onAddToBasketFail(mItem, data, textStatus, jqXHR);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) { alert('Error adding to the basket: ', textStatus, errorThrown); }
        });
        return false;
    },
    onAddToBasketSuccess: function (mediaItem, data, textStatus, jqXHR) {
        mediaItem
            .find('.loading').remove().end()
            .find('.add').css({ 'opacity': '0.4' });

        mediaItem.addClass('in-basket').append($('<div class="in-basket-div"></div>'));
        var docBasketCount = $('#optionsmenu').find('.basket span.count');
        var n = parseInt(docBasketCount.html(), 10) + 1;
        docBasketCount.html(n);

        // add item to basket pod
        var doc = mediaItem.data('docDetails');
        var item = $('<li>').addClass(mediaItem.attr('rel')).append('<span>' + doc.title + '</span>').append('<a href="' + doc.url + '" target="_blank" class="issuu-link-hijacked">View</a>');

        var pod = $('#documentBasketPod');
        var docList = $('ul.docs li', pod);
        if (docList.length == 1 && docList.first().hasClass('empty')) docList.first().remove();
        $('ul.docs', pod).append(item);

        docb.initScroll();      // re-initialise the scroll on the document basket pod
    },
    onAddToBasketFail: function (mediaItem, data, textStatus, jqXHR) {
        mediaItem.find('.loading').remove();
        alert('ERROR: Add to basket failed.');
        console.log('ADD TO BASKET FAIL!----------------');
        console.log(data);
        console.log(textStatus);
        console.log(jqXHR);
        console.log('--------------------------------------');
    },
    initEmailBtn: function () {
        this.items.each(function (i, el) {
            $(el).find('input.email').unbind('click').click(msr.onEmailClick);
        });
    },
    onEmailClick: function (e) {
        e.preventDefault();

        //$('.mediaSearch select').hide();

        var mItem = $(e.target).closest('.mediaItem');
        var doc = msr.getDocumentDetails(mItem);

        // create email document for dialogue
        var emailForm = $('<div class="formWrap">')
            .append('<input type="submit" class="greenBtn" value="Send Email">')
            .append('<div class="formRow"><label for="email1">Enter email address</label><input type="text" name="email1" id="email1" /></div>')
            .append('<div class="formRow"><label for="email2">Confirm email address</label><input type="text" name="email2" id="email2"  /></div>');
        var formDialogue = $('<div>').addClass('formDialogue')
            .append('<input type="submit" class="close" value="Close" />')
            .append('<h2>Files by email</h2>')
            .append('<p>You have chosen to receive the following file(s) via email:</p>')
            .append(doc.title)
            .append(emailForm);

        var t = $(e.target).offset().top - 260;
        $('#centercol').prepend(formDialogue);
        formDialogue.data('docDetails', doc).css('top', t);


        //$('html, body').animate({ scrollTop: 0 }, 500);

        $('input[type=submit]', emailForm).click(msr.onEmailSubmit);
        $('input[type=submit].close', formDialogue).click(function () {
            $('.mediaSearch select').show();
            formDialogue.remove();
            return false;
        });
    },
    onEmailSubmit: function (e) {
        var form = $(e.target).closest('.formWrap');

        // validation
        var e1 = $('#email1', form).val();
        var e2 = $('#email2', form).val();
        if (!e1.length || !e2.length) {
            msr.showEmailFormFeedback(form, 'Please type your email address into both fields.');
            return false;
        }
        if (e1 != e2) {
            msr.showEmailFormFeedback(form, 'The email addresses you provided do not match. Please try again.');
            return false;
        }

        var doc = $(e.target).closest('.formDialogue').data('docDetails');
        $.ajax({
            url: '/resources/documentbasket.asmx/EmailDocument',
            type: "POST",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: '{ "doc" : { "DocumentUrl": "' + doc.url + '", "PageID" : "' + doc.pageid + '", "DocumentTitle": "' + doc.title + '", "DocType" : "' + doc.type + '" }, "recipient" : "' + e1 + '" }',
            success: function (data, textStatus, jqXHR) {
                if (!data.d.Success) {
                    // fail
                    msr.showEmailFormFeedback(form, data.d.Message);
                } else {
                    // success
                    var fd = form.closest('.formDialogue');
                    fd.html('<input class="close" type="submit" value="Close"><span class="ThankYou">Thank you. Your file will be emailed to you shortly.<br />Please close this dialogue box to send further emails.</span>');
                    $('input[type=submit].close', fd).click(function () {
                        $('.mediaSearch select').show();
                        fd.remove();
                        return false;
                    });
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                var form = $(e.target).closest('.formWrap');
                msr.showEmailFormFeedback(form, textStatus + errorThrown);
            }
        });
        return false;
    },
    showEmailFormFeedback: function (form, message) {
        $('p.errorMsg', form).remove();
        form.append('<div class="clear"></div><p class="errorMsg">' + message + '</p>').hide().fadeIn();
    },
    getDocumentDetails: function (mediaItem) {
        var doc = {
            pageid: mediaItem.attr('id').replace('_', ''),
            title: mediaItem.find('h4 a').html().trim(),
            url: mediaItem.find('.open, .download').attr('href'),
            type: msr.getDocumentType(mediaItem),
            image: mediaItem.find('.image img').attr('src')
        };
        return doc;
    },
    getDocumentType: function (mItem) {
        var type;
        switch (mItem.attr('rel')) {
            case "casestudy": type = "0"; break;
            case "technical": type = "1"; break;
            case "brochure": type = "2"; break;
            case "image": type = "3"; break;
            default: type = "";
        }
        return type;
    },
    initSelectDocType: function (e) {
        var target = (e) ? $(e.target) : $('#centercol').find('.documentTypeSelect');
        var hdr = target.closest('.mediaSearch').find('.mediaSearchHeader');
        var val = target.val();
        var string = target.find('option[value=' + val + ']').text();

        hdr.removeClass('cad nbs tds');

        var searchTitle = (val > 0) ? string : 'Technical information search';
        hdr.find('h3').html(searchTitle);

        var classname;
        if (string.match(/cad/i)) classname = 'cad';
        if (string.match(/nbs/i)) classname = 'nbs';
        if (string.match(/tech/i)) classname = 'tds';
        hdr.addClass(classname);
    }
}
$(function () {
    msr.run();
    var $tab = $('#product-page').find('ul.tab-nav');
    $($tab.find('a[href="#case"]')
        .add($tab.find('a[href="#brochure"]'))
        .add($tab.find('a[href="#swatch"]'))
        .add($tab.find('a[href="#gallery"]')))
            .click(function () {
        setTimeout("msr.run()",200);
    });
});

// Document Basket pod
var docb = {
    run: function () {
        this.elem = $('#documentBasketPod');
        this.docsList = $('ul.docs', this.elem);
        if (!this.docsList.length) return;

        this.pos = 0;
        this.scrollPanel = $('div.scroll', this.elem);
        $('.scrollBtn', this.elem).click(docb.onScrollClick);        // event listeners
        this.setScrollPanelHeight();
        this.initScroll();
    },
    setScrollPanelHeight: function () {
        var lis = $('li', this.docsList);
        lis.each(function (i, el) {
            if (($(this).position().top + $(this).height()) > docb.scrollPanel.height()) {
                docb.scrollPanel.height($(this).position().top);    // set height of scroll panel to match top of this element
                return false;
            }
        });
    },
    initScroll: function () {
        if (!this.elem.length) return;
        if (this.docsList.height() < this.scrollPanel.height()) return;
        var scrollBtns = $('.scrollBtn', this.elem);
        scrollBtns.removeClass('hidden');                                                   // show scroll buttons
        if (this.pos == 0) { scrollBtns.filter('.up').addClass('hidden'); }          // at the start? hide up button
        // move the ul
        var newTop = $('li', this.docsList).eq(this.pos).position().top * -1;
        this.docsList.animate({ 'top': newTop + 'px' }, 200);
        // at end? hide the down button
        var last = $('li:last', this.docsList);
        var lastItemBottom = (last.position().top + last.height()) + newTop;
        if (lastItemBottom < this.scrollPanel.height()) scrollBtns.filter('.down').addClass('hidden');
    },
    onScrollClick: function (e) {
        e.preventDefault();
        docb.pos += ($(e.target).hasClass('down')) ? 1 : -1;
        docb.initScroll();
    }
}
$(function () { docb.run(); });

// slide in text on case studies
var csHover = {
    init: function () {
        $('.caseStudies #media_centre_results .image').add('#product-page #case .mediaItem .image').hover(this.showText, this.hideText)
            .find('div').click(this.viewCaseStudyPage);
    },
    showText: function (e) {
        var text = $(e.target).closest('.image').find('div');
        var mt = text.outerHeight() * -1;
        text.stop().animate({ 'top': mt }, 300);
    },
    hideText: function (e) {
        var text = $(e.target).closest('.image').find('div');
        text.stop().animate({ 'top': '0px' }, 300);
    },
    viewCaseStudyPage: function (e) {
        var lnk = $(e.target).closest('.image').find('a');
        if (lnk.attr('target') == '_blank') {
            window.open(lnk.attr('href'));            
        } else {
            window.location.href = lnk.attr('href');
        }
        return false;
    }
};
$(function () { csHover.init(); });

// Interface for selecting all/individual chapters on brochure detail page
var chaptrs = {
    init: function () {
        this.ch = $('.chapterList li input[type="checkbox"]');
        this.ch.change(this.onChange);
        if (!chaptrs.ch.filter(':selected').length) this.selectAllChapters();     // "Full brochure" set to checked by default
    },
    onChange: function (e) {
        var selectAllClicked = $(e.target).closest('li').hasClass('first');
        if (selectAllClicked) {
            ($(e.target).is(":checked")) ? chaptrs.selectAllChapters() : chaptrs.unselectAllChapters();
        } else {
            if (chaptrs.ch.first().is(":checked")) chaptrs.unselectAllChapters();
            $(e.target).attr('checked', 'checked');     // Individual chapter clicked, select it
        }
    },
    selectAllChapters: function () {
        this.ch.attr('checked', 'checked').closest('li').css({ 'opacity': 0.5 });
        this.ch.first().closest('li').css({ 'opacity': 1 });
    },
    unselectAllChapters: function () {
        this.ch.removeAttr('checked').closest('li').css({ 'opacity': 1 });
        this.ch.first().closest('li').css({ 'opacity': 0.5 });
    }
};
$(function () { chaptrs.init(); });

// Modal pop-up for media item email button
var eb = {
    init: function () {
        $('input.email').click(eb.onClick);

        if ($('.formDialogue').length) this.hideMediaSearch();
    },
    onClick: function (e) {
    },
    hideMediaSearch: function () {
        //$('.mediaSearch, .PagingContainer, .mediaItem').hide()
        //$('.formDialogue').closest('.mediaItem').show();

        //$('#centercol').height($('.formDialogue').height()+100);
    }
}
$(function () { eb.init(); });

// Make the (optional) large bg image stick to the bottom of the viewport when scrolling on long pages
$.fn.stickyBg = function (offset) {
    return this.each(function () {
        var bg = $(this);
        $(window).scroll(function () {
            var scrolledBeyondBG = ($(window).scrollTop() + $(window).height() - offset > bg.height());
            (scrolledBeyondBG) ? bg.addClass('fixed-to-bottom') : bg.removeClass('fixed-to-bottom');
        });
        $(window).trigger('scroll');
    });
}
$(function () { $('#body-bg-image').stickyBg( $('.header').innerHeight() ); });

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g,""); }
String.prototype.ltrim = function() { return this.replace(/^\s+/,""); }
String.prototype.rtrim = function () { return this.replace(/\s+$/, ""); }


/*
* Reusable Components for Popups
*/
var _Popup = {};                //Factory for generating full markup for popups
var _DocumentFactory = {};      //Factory for creating document objects

//Singleton static object for creation of any popup
(function (o) {
    //Generic popup
    o.getGeneric = function (innerHtml) {
        var formDialogue = $(document.createElement('div')).addClass('formDialogue')
            .append('<input type="submit" class="close" value="Close" />')
            .append(innerHtml);
        return formDialogue;
    },

    //Get an email Dialouge form
    //docArr must be an array of document names to display i.e. ['doc1', 'doc2', 'doc3']
    o.getEmail = function (docArr) {
        var heading = $('<h2>Files by email</h2>').add('<p>You have chosen to receive the following file(s) via email:</p>')
        var emailForm = $(document.createElement('div'))
            .addClass('formWrap')
            .append('<input type="submit" class="greenBtn" value="Send Email">')
            .append('<div class="formRow"><label for="email1">Enter email address</label><input type="text" name="email1" id="email1" /></div>')
            .append('<div class="formRow"><label for="email2">Confirm email address</label><input type="text" name="email2" id="email2"  /></div>');

        // create email document for dialogue
        var innerHtml = heading;

        for (var i = 0; i < docArr.length; i++) {
            innerHtml = innerHtml.add('<span style="display: block;">' + docArr[i] + '</span>');
        }

        innerHtml = innerHtml.add(emailForm);

        //return the email form
        return this.getGeneric(innerHtml);
    }
})(_Popup);      //Popup

//singleton DocumentFactory
(function (factory) {
    factory.getDoc = function (pageid, title, url, type) {
        return {    
                    PageID: pageid,
                    DocumentTitle: title,
                    DocumentUrl: url,
                    DocType: type
                };
    };
})(_DocumentFactory);

//singleton Email Popup factory
_Popup.Email = {};
(function (em) {

    var emailForm = null;

    em.New = function (container, docs) {
        if (emailForm != null) {
            emailForm.remove();
            emailForm = new _Email(container, docs);
            emailForm.render();
        }
        else {
            emailForm = new _Email(container, docs);
        }

        emailForm.render();
    };

    var _Email = function (container, docs) {
        var documents = docs;
        var form = null;
        var _this = this;

        /* Publically accesible */
        //remove the popup
        this.remove = function () {
            $(form).remove();
            form = null;
            //chainable
            return this;
        };

        //render the popup
        this.render = function () {
            if (form == null) {
                form = $(_Popup.getEmail(docNames));
                $(container).append(form);
                attachHandlers();
            }
            //chainable
            return this;
        };

        /* Private */
        var showError = function (message) {
            removeError();
            form.append('<div class="clear"></div><p class="errorMsg">' + message + '</p>').hide().fadeIn();
        };


        var removeError = function () {
            $('p.errorMsg', form).remove();
        };

        var attachCloseHandler = function () {
            $(form).find('.close').click(function (e) {
                e.preventDefault();
                _this.remove();
            });
        };

        var submitHandler = function (e) {
            e.preventDefault();
            // validation
            var e1 = $('#email1', form).val();
            var e2 = $('#email2', form).val();
            if (!e1.length || !e2.length) {
                showError('Please type your email address into both fields.');
                return false;
            }
            if (e1 !== e2) {
                showError('The email addresses you provided do not match. Please try again.');
                return false;
            }

            send(e1);
        };

        var send = function (em) {
            $.ajax({
                url: '/resources/documentbasket.asmx/EmailDocuments',
                type: "POST",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                data: '{ "docs": ' + JSON.stringify(docs) + ' , "recipient": "' + em + '"  }',
                success: function (data, textStatus, jqXHR) {
                    if (!data.d.Success) {
                        // fail
                        showError(data.d.Message);
                    } else {
                        // success
                        var fd = form.closest('.formDialogue');
                        fd.html('<input class="close" type="submit" value="Close"><span class="ThankYou">Thank you. Your file will be emailed to you shortly.<br />Please close this dialogue box to send further emails.</span>');
                        $('input[type=submit].close', fd).click(function (e) {
                            e.preventDefault();
                            fd.remove();
                            return false;
                        });
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    showError(textStatus + errorThrown);
                }
            });
        };

        var attachHandlers = function () {
            attachCloseHandler();
            $(form).find('input.greenBtn[type="submit"]').click(submitHandler);
        };

        //return document names in an array
        var docNames = (function () {
            var names = [];

            for (var i = 0; i < docs.length; i++) {
                names.push(docs[i].DocumentTitle);
            }
            return names;
        })(docs);

        return this;
    };

    return this;
})(_Popup.Email);


$(function () {


    //chapter list email notification
    var chapterList = (function () {

        //elems needed
        var container = $('div.chapterList');
        var emailBtn = container.find('input[type="submit"]').last();

        emailBtn.click(function (e) {
            e.preventDefault();
            var $this = $(this);
            var chkList = container.find('ul').find('input[type="checkbox"]');

            //get chekboxes that are checked
            var checked = chkList.filter(':checked');

            if (checked.length > 0) {
                //this will have the array of data to be sent.
                var dataArr = [];
                var item;
                var toAdd;
                
                for (var i = 0; i < checked.length; i++) {
                    item = eval("(" + $(checked[i]).siblings('input[type=hidden]').first().val() + ")");
                    toAdd = _DocumentFactory.getDoc(item.pageid, item.title, item.url, "Brochure");
                    if (checked[i] === chkList[0]) {
                        dataArr.push(toAdd);
                        //the array of data about to get sent
                        _Popup.Email.New('#centercol', dataArr);
                        return;
                    }
                    else
                        dataArr.push(toAdd);
                }

                //the array of data about to get sent
                _Popup.Email.New('#centercol', dataArr);
            }
        });

    })();
});
