var addthis_pub = "";




/*
var slideInCTA = function(el) {
	
console.log(el);
	
var myFx = new Fx.Slide(el, {
duration: 700,
transition: Fx.Transitions.Sine.easeIn,
mode: "horizontal"
});
	
myFx.hide();
myFx.slideIn();
	
}
*/

function RefreshSearch(e) {

    new Request({
        url: "/product-directory/product-filter-ajax/",
        data: {
            "filteruri": GetFilterUrl(),
            "page": GetPageNumber()
        },
        onComplete: function(response) {
            $$('#products-ajax-wrapper').set('html', response);
            addPagingEvents();
        }
    }).send();

}

function GetFilterUrl() {

    var className = "categoryFilter"

    var products = "products/"
    var href = location.href.substring((location.href.indexOf(products) + products.length));

    //remove querystring
    if (href.indexOf("?") > 0) {
        href = href.substring(0, href.indexOf("?"));
    }

    var filterUri = href

    var all = document.all ? document.all : document.getElementsByTagName('*');
    for (var e = 0; e < all.length; e++)
        if (all[e].className == className) {
        if (!all[e].value == "") {
            filterUri = filterUri + all[e].value
        }
    }
    return filterUri;
}

function addPagingEvents() {
    $$('.pagenumbers li').each(function(el) {
        el.addEvent('click', function(e) {
            //add to querystring to page number for this page link (making it compatible with Browser History)
            window.location.hash = "/?page=" + gup("page", el.getElements('a')[0]);
            RefreshSearch();
            new Event(e).stop();
        });
    });
}

/* http://www.netlobo.com/url_query_string_javascript.html */
function gup(name, url) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(url);
    if (results == null)
        return "";
    else
        return results[1];
}

function GetPageNumber() {
    return gup("page", window.location.href);

}

var FancyTips = new Class({
    initialize: function(elements, options) {
        this.setOptions({
            "tipcontents": ".tipcontents"
        }, options);

        elements.each(function(element) {
            contents_element = element.getElement(this.options.tipcontents);
            if (contents_element) {
                var currentTitle = element.getProperty("title");
                element.setProperty("title", currentTitle + " :: " + contents_element.innerHTML);
            }
        }, this);

        this.tips = new Tips(elements, options);
    }
});
FancyTips.implement(new Options);

window.addEvent("domready", function() {

    /* digital products (podcasts etc...) product - tip */


    $$(".filter .filtered li a").each(function(el) {
        el.addEvent('click', function() {
            this.addClass('active');
        });
    });

    if ($("bannerCarouselContainer")) {

        var slideIndicators = $$(".carouselControls ul#slideIndicators li.slide");
        var slidePrev = $$(".carouselControls li.previous");
        var slideNext = $$(".carouselControls li.next");



        var slideshow = new MooSlideshow("bannerCarousel", "#bannerCarousel li", {
            "wait": 5000,
            "fxDuration": 1000,
            "onChange": function(index) {
                if (!$(slideIndicators[index])) return;
                slideIndicators.each(function(el) { el.removeClass("selected"); });
                slideIndicators[index].addClass("selected");
            }
        });

        slideIndicators.each(function(el, index) {
            el.addEvent("click", function(e) {
                slideshow.jumpTo(index);
            });
        });

        slideNext.each(function(el) {
            slideshow.next();
        });

        slidePrev.each(function(el) {
            slideshow.previous();
        });

        $$("ul.carouselControls li a.toggle").each(function(el) {

            el.addEvent("click", function(e) {
                new Event(e).stop();

                if (slideshow.paused) {
                    slideshow.start();
                    el.removeClass("play").addClass("pause");
                    el.setHTML("Pause");
                } else {
                    slideshow.stop();
                    el.removeClass("pause").addClass("play");
                    el.setHTML("Play");
                }

            });
        });

    }




    //play video preview
    if ($("videoPlayer")) {
        var flash = new FlashObject("/_images/flash/podcast_video.swf", "videoPlayer", "205", "272", "9", "#ffffff");
        flash.addParam("menu", "false");
        flash.addParam("quality", "high");
        flash.addVariable("videopath", "/_images/flash/000009607398_HDFlashVideo.flv")
        flash.write("videoPlayer");
    }


    //play sample files on podcast listings
    if ($("samplePodCast")) {

        var flash = new FlashObject("/_images/flash/podcast_sample.swf", "samplePodCast", "650", "20", "9", "#838D94");
        flash.addParam("menu", "false");
        flash.addParam("quality", "high");
        flash.addParam("WMode", "opaque");
        //flash.addVariable("videopath", "");
        flash.addVariable("imagepath", "/_images/general/blank.gif");
        flash.addVariable("autoplay", "true");
        flash.write("samplePodCast");


        $$(".sampleLink").each(function(el) {

            el.addEvent("click", function(e) {
                new Event(e).stop();
                //Refresh player with new m4a link
                flash.addVariable("videopath", el.getProperty("rel"));
                flash.write("samplePodCast");
            });
        });
    }

/*
    new Accordion($$(".podcastlink"), $$(".podcastinfo"), { "alwaysHide": true, "show": -1 });

    $$(".podcasts .podcastlink").each(function(el) {
        el.addEvent("click", function(e) {
            new Event(e).stop();
        });
    });
*/
    var viewSeries = $("series");

    if (viewSeries) {

        var togglers = $$(".keystageselect li h3 a");
        var elements = $$(".keystageselect li div");

        togglers.addEvent("click", function(e) {
            new Event(e).stop();
        });

        new Accordion(togglers, elements, { "alwaysHide": true, "show": -1 });

        var customLinkLeft = new Fx.Slide("seriesboxleft", {
            "duration": 500,
            "transition": Fx.Transitions.linear,
            "onStart": function() {

                var expandImage = $("expandseriesimgleft");

                if (expandImage.hasClass("expanded")) {

                    expandImage.setAttribute("src", "/_images/general/expand-series.gif");
                    expandImage.removeClass("expanded")

                } else {

                    expandImage.setAttribute("src", "/_images/general/collapse-series.gif");
                    expandImage.addClass("expanded")

                }

            }
        });

        $('expandseriesleft').addEvent("click", function(e) {

            new Event(e).stop();
            customLinkLeft.toggle();

        });

        if ($("expandseriesimgleft").hasClass("expanded")) {
            customLinkLeft.show();
            $("expandseriesimgleft").setAttribute("src", "/_images/general/collapse-series.gif");
        }
        else {
            customLinkLeft.hide();
            $("expandseriesimgleft").setAttribute("src", "/_images/general/expand-series.gif");
        }

        if ($('keystageleft') && $('seriesleft')) {
            $$('#keystageleft a').each(function(el) {
                el.addEvent("click", function(e) {
                    var productcategoryid = el.getProperty("id").substring(el.getProperty("id").indexOf("_") + 1);


                    new Request({
                        url: "/product-directory/series-ajax/",
                        data: {
                            "productcategoryid": productcategoryid,
                            "page": 1,
                            "side": "left"
                        },
                        onComplete: function(response) {
                            $('seriesboxleft').set('html', response);

                            var expandImage = $("expandseriesimgleft");

                            if (expandImage.hasClass("expanded")) {

                                customLinkLeft.hide();
                                customLinkLeft.show();
                                expandImage.setAttribute("src", "/_images/general/collapse-series.gif");
                                expandImage.addClass("expanded")

                            } else {

                                customLinkLeft.hide();
                                expandImage.setAttribute("src", "/_images/general/expand-series.gif");
                                expandImage.removeClass("expanded")

                            }

                            initializePaging(customLinkLeft, customLinkRight);

                        }
                    }).send();

                });
            });

        }

        var customLinkRight = new Fx.Slide("seriesboxright", {
            "duration": 500,
            "transition": Fx.Transitions.linear,
            "onStart": function() {

                var expandImage = $("expandseriesimgright");

                if (expandImage.hasClass("expanded")) {

                    expandImage.setAttribute("src", "/_images/general/expand-series.gif");
                    expandImage.removeClass("expanded")

                } else {

                    expandImage.setAttribute("src", "/_images/general/collapse-series.gif");
                    expandImage.addClass("expanded")

                }

            }
        });

        $('expandseriesright').addEvent("click", function(e) {

            new Event(e).stop();
            customLinkRight.toggle();

        });

        if ($("expandseriesimgright").hasClass("expanded")) {
            customLinkRight.show();
            $("expandseriesimgright").setAttribute("src", "/_images/general/collapse-series.gif");
        }
        else {
            customLinkRight.hide();
            $("expandseriesimgright").setAttribute("src", "/_images/general/expand-series.gif");
        }

        if ($('keystageright') && $('seriesright')) {
            $$('#keystageright a').each(function(el) {
                el.addEvent("click", function(e) {
                    var productcategoryid = el.getProperty("id").substring(el.getProperty("id").indexOf("_") + 1);

                    new Request({
                        url: "/product-directory/series-ajax/",
                        data: {
                            "productcategoryid": productcategoryid,
                            "page": 1,
                            "side": "right"
                        },
                        onComplete: function(response) {
                            $('seriesboxright').set('html', response);

                            var expandImage = $("expandseriesimgright");

                            if (expandImage.hasClass("expanded")) {

                                customLinkRight.hide();
                                customLinkRight.show();
                                expandImage.setAttribute("src", "/_images/general/collapse-series.gif");
                                expandImage.addClass("expanded")

                            } else {

                                customLinkRight.hide();
                                expandImage.setAttribute("src", "/_images/general/expand-series.gif");
                                expandImage.removeClass("expanded")

                            }

                            initializePaging(customLinkLeft, customLinkRight);
                        }
                    }).send();

                });
            });

        }


        initializePaging(customLinkLeft, customLinkRight);

    }

    /*
    var myHorizontalSlide = new Fx.Slide('horizontal_slide', {mode: 'horizontal'});
	
	$("horizontal_slide").setStyle("display", "none");
	
	myHorizontalSlide.slideIn();
	
	$('h_slidein').addEvent('click', function(e){
    e.stop();
    myHorizontalSlide.slideIn();
    });
    */
    /*
    if ($("ctaNav")) {
		
		var myChain = new Chain();
		
		$("ctaNav").getElements("a").each(function(el){
		
			//el.slide('hide');
			
			myChain.chain(function(){ slideInCTA(el);});
			
		});
		
		console.log(myChain);

		/*var runChain = function() { 
    myChain.callChain();
    runChain = $clear(timer);
    }
		
		myChain.callChain.periodical(700);
		
	}
    */

    new FancyTips($$(".tip a"), {
        "tipcontents": "span",
        "maxTitleChars": 100,
        "offsets": { "x": 15, "y": -100 }
    });
/**/
    if ($('buyDigitalProducts')) {
        var togglers = $$(".toggle");
        var elements = $$(".podCastAccordian");

        togglers.addEvent("click", function(e) {
            new Event(e).stop();
        });

        new Accordion(togglers, elements, { 
			alwaysHide: true, 
			show: -1,
			onActive: function(toggler) { toggler.removeClass("expand").addClass("collapse"); },
			onBackground: function(toggler) { toggler.removeClass("collapse").addClass("expand"); } 
        });
    }

    $$(".revisionplanner div").each(function(fs) {
        var spinner = fs.getElement(".spinner");
        if (spinner) {
            new MooSpinner(spinner, {
                "increment": fs.getElement(".add"),
                "decrement": fs.getElement(".minus"),
                "minimum": 0,
                "maximum": 9
            });
        }
    });

    new SmoothScroll({ "links": $$(".scroll") });

    $$(".volatile").each(function(el) {
        $(el).addEvent("focus", function() {
            if (this.value == this.title) {
                this.value = "";
            }
        });
    });

    $$("a[rel*='external']").each(function(a) {
        $(a).setProperty("target", "_blank");
    });

    /*	if($$(".banner .images")){
    var slideshow = new MooSlideshow($$(".banner")[0], $$(".images li"), {
    "wait": 5000,
    "fxDuration": 1000
    });
    }
	
*/
    var section = -1;

    if ($("subnav")) {
        $$("#subnav img").each(function(el, index) {
            if (el.hasClass("selected")) {
                section = index;
            }
        });
        $$("#subnav ul").each(function(el, index) {
            if (el.hasClass("subnav")) {
                if ($ES("li a.selected", el).length > 0) {
                    section = index;
                }
            }
        });
    }

    new Accordion(
					$$("#subnav .topLevel"),
					$$("#subnav li div"),
					{
					    "alwaysHide": true,
					    "show": section,
					    "onActive": function(el) {
					        el.getParent().addClass("close")
					    },
					    "onBackground": function(el) {
					        el.getParent().removeClass("close")
					    }
					});

    /*
    if ($$(".latestnews")[0]) {
    var newsTicker = new Ticker($$(".latestnews ul")[0], {
    "interval": 5000
    });
    }
    */
    $$(".socialize").addEvent("click", function(e) {
        new Event(e).stop();
        addthis_url = location.href;
        addthis_title = document.title;
        addthis_click(this);
    });


    $$(".categoryFilter").each(function(el) {
        /*	el.addEvent("change", function(e){
		
		   $("categoryFilterForm").submit();	    
		    
		});
        */


        el.addEvent("change", function(e) {
            RefreshSearch();
        });

    });

    if ($('categoryFilterForm')) {
        RefreshSearch();
        addPagingEvents();
    }



    if ($("printpage")) {
        $("printpage").addEvent("click", function(e) {
            window.print();
        });
    }

    if ($("RegistrationStepOneManual") && $("RegistrationType_Manual") && $("JobTitle") && $("EstablishmentName")) {

        countrySelector();

        if ($("RegistrationType_Manual").value != "Teacher") {


            $("JobTitle").addClass("hiddenfield");

            $("label_JobTitle").addClass("hiddenfield");


            $("EstablishmentName").addClass("hiddenfield")

            $("label_EstablishmentName").addClass("hiddenfield");

        }

        if ($("RegistrationType_Manual").value == "Teacher") {

            $("label_JobTitle").set("text", "Job Title: *");
            $("label_EstablishmentName").set("text", "Establishment Name: *");

        }


        $("RegistrationType_Manual").addEvent("change", function() {


            if ($("RegistrationType_Manual").value == "Teacher") {


                $("JobTitle").removeClass("hiddenfield");

                $("label_JobTitle").removeClass("hiddenfield");



                $("EstablishmentName").removeClass("hiddenfield")

                $("label_EstablishmentName").removeClass("hiddenfield");


                $("label_JobTitle").set("text", "Job Title: *");

                $("label_EstablishmentName").set("text", "Establishment Name: *");


            }

            else {

                $("JobTitle").addClass("hiddenfield");

                $("label_JobTitle").addClass("hiddenfield");



                $("EstablishmentName").addClass("hiddenfield")

                $("label_EstablishmentName").addClass("hiddenfield");


            }

        });
    }

    if ($("AddressFormFrontEnd")) {

        countrySelector();

    }

    if ($$(".bannerSlideshow")[0]) {
        var slideshow = new MooSlideshow($$(".bannerSlideshow")[0], $$(".bannerSlideshow li"), {
            "wait": 4000,
            "fxDuration": 2000
        });
    }

    initializeChildren();

    ScrollToError();

});

function initializeChildren() {
    if ($("newsletterprefchildren") && $("newsletterprefchildcount")) {
        if ($("newsletterprefchildcount").value == 0) {
            //If javascript is enabled then append a child age select dropbox to the form in Position 1
            $("newsletterprefchildcount").value = 1;
            createChildDropdown(1).injectAfter($("newsletterprefchildcount"));
        }

        $$(".newsletterprefdone").each(function(el) {
            el.removeEvents("click");
        });
        $$(".newsletterpreflast").each(function(el) {
            el.addEvent("click", function(e) {


                el.removeClass("newsletterpreflast");
                el.addClass("newsletterprefdone");

                var childcount = $("newsletterprefchildcount").value;

                childcount++;

                $("newsletterprefchildcount").value = childcount;

                createChildDropdown(childcount).injectAfter(el);

                initializeChildren();

                el.removeEvents("click");

            });
        });
    }

}

function initializePaging(customLinkLeft, customLinkRight) {
    $$('#seriesboxleft .pagenumbers li a').each(function(el) {
        el.addEvent("click", function(e) {
            var pagingid = el.getProperty("id")

            var pagingarray = pagingid.split("_");

            if (pagingarray.length == 2) {
                var page = pagingid.substring(pagingid.indexOf("_") + 1);
                var productcategoryid = null;
            }
            else {
                var page = pagingid.substring(pagingid.indexOf("_") + 1, pagingid.lastIndexOf("_"));
                var productcategoryid = pagingid.substring(pagingid.lastIndexOf("_") + 1);
            }

            new Event(e).stop();

            new Request({
                url: "/product-directory/series-ajax/",
                data: {
                    "productcategoryid": productcategoryid,
                    "page": page,
                    "side": "left"
                },
                onComplete: function(response) {
                    $('seriesboxleft').set('html', response);

                    var expandImage = $("expandseriesimgleft");

                    if (expandImage.hasClass("expanded")) {

                        customLinkLeft.hide();
                        customLinkLeft.show();
                        expandImage.setAttribute("src", "/_images/general/collapse-series.gif");
                        expandImage.addClass("expanded")

                    } else {

                        customLinkLeft.hide();
                        expandImage.setAttribute("src", "/_images/general/expand-series.gif");
                        expandImage.removeClass("expanded")

                    }

                    initializePaging(customLinkLeft, customLinkRight);
                }
            }).send();

        });
    });
    $$('#seriesboxright .pagenumbers li a').each(function(el) {
        el.addEvent("click", function(e) {
            var pagingid = el.getProperty("id")

            var pagingarray = pagingid.split("_");

            if (pagingarray.length == 2) {
                var page = pagingid.substring(pagingid.indexOf("_") + 1);
                var productcategoryid = null;
            }
            else {
                var page = pagingid.substring(pagingid.indexOf("_") + 1, pagingid.lastIndexOf("_"));
                var productcategoryid = pagingid.substring(pagingid.lastIndexOf("_") + 1);
            }

            new Event(e).stop();

            new Request({
                url: "/product-directory/series-ajax/",
                data: {
                    "productcategoryid": productcategoryid,
                    "page": page,
                    "side": "right"
                },
                onComplete: function(response) {
                    $('seriesboxright').set('html', response);

                    var expandImage = $("expandseriesimgright");

                    if (expandImage.hasClass("expanded")) {

                        customLinkRight.hide();
                        customLinkRight.show();
                        expandImage.setAttribute("src", "/_images/general/collapse-series.gif");
                        expandImage.addClass("expanded")

                    } else {

                        customLinkRight.hide();
                        expandImage.setAttribute("src", "/_images/general/expand-series.gif");
                        expandImage.removeClass("expanded")

                    }

                    initializePaging(customLinkLeft, customLinkRight);
                }
            }).send();

        });
    });

}

function createChildDropdown(idNum) {

    var div = new Element("div", {

        "class": "newsletterpreflast"

    });

    var label = new Element("label", {

        "for": "C140_" + idNum

    });

    var ending

    switch (idNum) {
        case 1: ending = "st"; break;
        case 2: ending = "nd"; break;
        case 3: ending = "rd"; break;
        default: ending = "th"; break;
    }

    label.set("text", "Child " + idNum + ":");

    label.injectInside(div);

    var select = new Element("select", {

        "id": "C140_" + idNum,
        "name": "C140_" + idNum

    });


    var option0 = new Element("option", { "value": "" });
    option0.set("text", "Please Select");

    var option666 = new Element("option", { "value": "C689" });
    option666.set("text", "Reception (Age 5)");

    var option1 = new Element("option", { "value": "C699" });
    option1.set("text", "Year 1 (Age 6)");

    var option2 = new Element("option", { "value": "C700" });
    option2.set("text", "Year 2 (Age 7)");

    var option3 = new Element("option", { "value": "C701" });
    option3.set("text", "Year 3 (Age 8)");

    var option4 = new Element("option", { "value": "C702" });
    option4.set("text", "Year 4 (Age 9)");

    var option5 = new Element("option", { "value": "C703" });
    option5.set("text", "Year 5 (Age 10)");

    var option6 = new Element("option", { "value": "C704" });
    option6.set("text", "Year 6 (Age 11)");

    var option7 = new Element("option", { "value": "C705" });
    option7.set("text", "Year 7 (Age 12)");

    var option8 = new Element("option", { "value": "C706" });
    option8.set("text", "Year 8 (Age 13)");

    var option9 = new Element("option", { "value": "C707" });
    option9.set("text", "Year 9 (Age 14)");

    var option10 = new Element("option", { "value": "C708" });
    option10.set("text", "Year 10 (Age 15)");

    var option11 = new Element("option", { "value": "C709" });
    option11.set("text", "Year 11 (Age 16)");

    var option12 = new Element("option", { "value": "C710" });
    option12.set("text", "Year 12 (Age 17)");

    var option13 = new Element("option", { "value": "C711" });
    option13.set("text", "Year 13 (Age 18)");

    option0.injectInside(select);
    option666.injectInside(select);
    option1.injectInside(select);
    option2.injectInside(select);
    option3.injectInside(select);
    option4.injectInside(select);
    option5.injectInside(select);
    option6.injectInside(select);
    option7.injectInside(select);
    option8.injectInside(select);
    option9.injectInside(select);
    option10.injectInside(select);
    option11.injectInside(select);
    option12.injectInside(select);
    option13.injectInside(select);

    select.injectInside(div)

    var clear = new Element("div", {

        "class": "clear"

    });

    clear.set("text", " ");

    clear.injectInside(div);

    return div;

};

function countrySelector() {
    if ($("AddressPostCodeSelector_1")) {

        $("AddressCountryIDUK").addClass("hiddenfield");

        $("label_AddressCountryIDUK").addClass("hiddenfield");


        $("AddressCountryIDOverseas").addClass("hiddenfield")

        $("label_AddressCountryIDOverseas").addClass("hiddenfield");

    }

    if ($("AddressPostCodeSelector_1").checked) {


        $("AddressCountryIDUK").removeClass("hiddenfield");

        $("label_AddressCountryIDUK").removeClass("hiddenfield");

    }

    if ($("AddressPostCodeSelector_2").checked) {


        $("AddressCountryIDOverseas").removeClass("hiddenfield");

        $("label_AddressCountryIDOverseas").removeClass("hiddenfield");

    }


    $("AddressPostCodeSelector_1").addEvent("change", function() {

        $("AddressCountryIDUK").removeClass("hiddenfield");

        $("label_AddressCountryIDUK").removeClass("hiddenfield");

        $("AddressCountryIDOverseas").addClass("hiddenfield");

        $("label_AddressCountryIDOverseas").addClass("hiddenfield");

        $("label_AddressCountryIDUK").set("text", "Country: *");

    });

    $("AddressPostCodeSelector_2").addEvent("change", function() {


        $("AddressCountryIDUK").addClass("hiddenfield");

        $("label_AddressCountryIDUK").addClass("hiddenfield");

        $("AddressCountryIDOverseas").removeClass("hiddenfield");

        $("label_AddressCountryIDOverseas").removeClass("hiddenfield");

        $("label_AddressCountryIDOverseas").set("text", "Country: *");

    });
}


function ScrollToError() {
    var errors = $$(".fielderror");

    if (errors[0]) {
        var elid = errors[0].getProperty('id');

        if (elid) {
            var myFx = new Fx.Scroll(window).toElement(elid);
        }
    }
}
/*
function ScrollToError() 
{                
var coords = FindAnchor("error");
scrollTo(coords.x , coords.y);
}

function FindAnchor(anchorName) {
var anchor;
        
for(var i=0;i<window.document.anchors.length;i++)
{            
if(window.document.anchors[i].name==anchorName) 
{             
anchor=window.document.anchors[i];                   
}
}
if (document.layers) 
{
return { x: anchor.x, y: anchor.y };
}
else if (document.getElementById) 
{
var coords = {x: 0, y: 0 };
while (anchor) 
{
coords.x += anchor.offsetLeft;
coords.y += anchor.offsetTop;
anchor = anchor.offsetParent;
}
return coords;
}
}
        
*/