window.addEvent("domready", function() {

    new SmoothScroll({ "links": $$(".scroll") });

    $$(".volatile").each(function(el) {
        $(el).addEvent("focus", function() {
            if (this.value == this.getProperty("title")) {
                this.value = "";
            }
        });
    });

    $$("a[rel*='external']").each(function(a) {
        $(a).setProperty("target", "_blank");
        $(a).setProperty("title", "This link opens in a new window");
    });

    $$(".disable").addEvent("click", function(e) {
        new Event(e).stop();
    });

    if ($$('.fielderror').length > 0) {
        var scroll = new Fx.Scroll(window, { wait: false, duration: 1200, transition: Fx.Transitions.Quad.easeInOut });
        scroll.toElement($$('.fielderror')[0]);
    }

    if ($('calendarContent')) {
        carousel = new SimpleSlideShow.Carousel($('calendarContent'), {
            startIndex: 0,
            slides: $$('#calendarContent li'),
            nextLink: 'calNext',
            prevLink: 'calPrev',
            wrap: true,
            disabledLinkClass: 'disabled'
        });

        carousel.addEvent('onNext', function() {
            showProduct(prevNextOrReset('u'));
        });

        carousel.addEvent('onPrev', function() {
            showProduct(prevNextOrReset('d'));
        });

        carousel.addEvent('onSlideDisplay', function(num) {
            if (num != index) {
                carousel.show(index);
            }
        });

        if ($$('#calendarContent li').length == 1) {
            $("calNext").set('styles', { 'display': 'none' });
        }
        showProduct(0);


    }

    // $$("#content .textfield, #content select, #content textarea").addEvents({
    //      "focus": function() { this.setStyle("border-color", "#003C52"); },
    //      "blur": function() { this.setStyle("border-color", "#c8c8c8"); }
    //  });

    if ($("videoPlayer")) {
        var flash = new FlashObject("/_images/flash/videoplayer.swf", "videoPlayerFlash", "470", "300", "9", "#ffffff");
        flash.addParam("menu", "false");
        flash.addParam("quality", "high");
        flash.addParam("allowFullScreen", "true");
        if ($("fileuri")) {
            flash.addVariable("videopath", $("fileuri").innerHTML);
        }
        /*if ($("imageuri")) {
        flash.addVariable("imagepath", "$("imageuri").innerHTML);
        }*/


        flash.write("videoPlayer");
    }

    $$(".productCalendar tr").each(function(el) {

        el.addEvent("mouseover", function() {
            el.addClass("highlight");
        });

        el.addEvent("mouseout", function() {
            el.removeClass("highlight");
        });

    });

    $$(".coursePricing tr").each(function(el) {

        el.addEvent("mouseover", function() {
            el.addClass("highlight");
        });

        el.addEvent("mouseout", function() {
            el.removeClass("highlight");
        });

    });

    /*   var loaderalert = $$('h1')[0];
    var origtext = $$('h1')[0].innerHTML;
    if($$(".calendarControls span"))
    {
    loaderalert = $$(".calendarControls span")[0]; 
    origtext = $$(".calendarControls span")[0].innerHTML;
    }
    var loadingHTML = 'Loading...'; */
    var dateToShow = new Date();

    if ($$(".productDetailsCalendar a.nextMonth")[0]) {
        $$("a.nextMonth")[0].addEvent('click', function(e) {
            new Event(e).stop();
            var nextDate = dateToShow.clone().increment('month', 3);
            var urlInd = '/products/product-dates/?StartDate=' + nextDate.format("%Y-%m-%d") + '&ProductID=' + $("ProductID").innerHTML;
            var datestable = $("_productCourses"); //$$(".productDetailsCalendar table")[0]; // IE8 bug-- only seems to like certain HTML even though it was made in xsl. Container divs FTW it seems.
            new Request.HTML({
                "url": urlInd,
                "onRequest": function() {
                    //   loaderalert.set("html", loadingHTML);
                },
                "onSuccess": function(nl, el, hutmull) {
                    datestable.set("html", hutmull);
                    //   loaderalert.set("html", origtext);
                    refreshToggleButton($$("a.previousMonth")[0], dateToShow.increment('month', 3));
                    createToolTips();
                },
                "onFailure": function() {
                    // alert("FAIL");
                }
            }).get();
        });
    }

    if ($$(".productDetailsCalendar a.previousMonth")[0]) {
        $$("a.previousMonth")[0].addEvent('click', function(e) {
            new Event(e).stop();
            var prevDate = dateToShow.clone().decrement('month', 3);
            var urlInd = '/products/product-dates/?StartDate=' + prevDate.format("%Y-%m-%d") + '&ProductID=' + $("ProductID").innerHTML;
            var datestable = $("_productCourses"); //$$(".productDetailsCalendar table")[0];
            new Request.HTML({
                "url": urlInd,
                "onRequest": function() {
                    // loaderalert.set("html", loadingHTML);
                },
                "onSuccess": function(nl, tableEl, hutmull) {
                    datestable.set("html", hutmull);
                    //    loaderalert.set("html", origtext);
                    refreshToggleButton($$("a.previousMonth")[0], dateToShow.decrement('month', 3));
                    createToolTips();
                },
                "onFailure": function() {
                    // alert("FAIL");
                }
            }).get();
        });
    }

    var arrDates = [];

    if ($$("._modes a.nextMonth")[0]) {
        $$("a.nextMonth").each(function(el, index) {
            arrDates[index] = new Date(); //only gets created here
            el.addEvent('click', function(e) {
                new Event(e).stop();
                var nextDate = arrDates[index].clone().increment('month', 3);
                var parentContainerDiv = el.getParent().getParent();
                var FormatID = parentContainerDiv.id.replace('container_PF_', '');
                var urlInd = '/products/product-mode-dates/?StartDate=' + nextDate.format("%Y-%m-%d") + '&ProductFormatID=' + FormatID;
                var datestable = $$("#" + parentContainerDiv.id + " ._productCoursesContainer")[0];
                new Request.HTML({
                    "url": urlInd,
                    "onRequest": function() {
                        //     loaderalert.set("html", loadingHTML);
                    },
                    "onSuccess": function(nl, tableEl, hutmull) {
                        datestable.set("html", hutmull);
                        //       loaderalert.set("html", origtext);
                        refreshToggleButton($$("._modes a.previousMonth")[index], arrDates[index].increment('month', 3));
                        createToolTips();
                    }

                }).get();
            });
        });
    }

    if ($$("._modes a.previousMonth")[0]) {
        $$("a.previousMonth").each(function(el, index) {

            el.addEvent('click', function(e) {
                new Event(e).stop();
                var prevDate = arrDates[index].clone().decrement('month', 3);
                var parentContainerDiv = el.getParent().getParent();
                var FormatID = parentContainerDiv.id.replace('container_PF_', '');
                var urlInd = '/products/product-mode-dates/?StartDate=' + prevDate.format("%Y-%m-%d") + '&ProductFormatID=' + FormatID;
                var datestable = $$("#" + parentContainerDiv.id + " ._productCoursesContainer")[0];
                new Request.HTML({
                    "url": urlInd,
                    "onRequest": function() {
                        //        loaderalert.set("html", loadingHTML);
                    },
                    "onSuccess": function(nl, tableEl, hutmull) {
                        datestable.set("html", hutmull);
                        //       loaderalert.set("html", origtext);
                        refreshToggleButton(el, arrDates[index].decrement('month', 3));
                        createToolTips();

                    },
                    "onFailure": function() {
                        // alert("FAIL");
                    }
                }).get();
            });
        });
    }

    createToolTips();



    if ($('CopyInvoiceDetails')) {
        $('CopyInvoiceDetails').addEvent('click', function(e) {

            var arrTitles = ['Title', 'FirstName', 'LastName', 'CompanyName', 'Department', 'JobTitle', 'AddressLine1', 'AddressLine2', 'TownCity', 'County', 'Postcode', 'Telephone', 'EmailAddress'];
            arrTitles.each(function(item, index) {
                if ($('Invoice' + item)) {
                    $('Contact' + item).value = $('Invoice' + item).value;
                }
            });
        });
    }


    if ($('CopyContactDetails')) {
        $('CopyContactDetails').addEvent('click', function(e) {

            var arrTitles = ['Title', 'FirstName', 'LastName', 'CompanyName', 'Department', 'JobTitle', 'AddressLine1', 'AddressLine2', 'TownCity', 'County', 'Postcode', 'Telephone', 'EmailAddress'];
            arrTitles.each(function(item, index) {
                if ($('Contact' + item)) {
                    $('Delegate_1_' + item).value = $('Invoice' + item).value;
                }
            });
        });
    }

    var arrDels = ['delegate1', 'delegate2', 'delegate3', 'delegate4'];

    if ($('DelegateNumber')) {

        if (Number($('DelegateNumber').getSelected()[0].value) > 0) {
            showHideDelegates(Number($('DelegateNumber').getSelected()[0].value));
        } else {
            arrDels.each(function(item, index) {
                $(item).set('styles', { 'display': 'none' });
            });
        }

        $('DelegateNumber').addEvent('change', function(e) {
            showHideDelegates(Number($('DelegateNumber').getSelected()[0].value));
        });
    }


    function showHideDelegates(numToShow) {
        var counter = 1;
        arrDels.each(function(item, index) {
            $(item).set('styles', { 'display': 'none' });
        });
        arrDels.each(function(item, index) {
            if (counter <= numToShow) {
                $(item).set('styles', { 'display': 'block' });
            }
            counter++;
        });
    }


});

function createToolTips() {

    var myTips = new Tips('.tooltips', {
        offset: { 'x': 15, 'y': 0 },
        className: 'tooltipContainer',
        fixed: false,
        hideDelay: 500,
        showDelay: 50
    });

    $$('.tooltipContainer').each(function(el) {
        el.setStyles({
            'opacity': '0.85'
        });
    });
}

function refreshToggleButton(button, currentDate) {
	
	var prevDate = currentDate.clone().decrement('month', 3);
	var bPast = false;
	var now = new Date();

	if (prevDate.getFullYear() < now.getFullYear())
	{
		bPast = true;
	}
	
	if (prevDate.getFullYear() == now.getFullYear() && prevDate.getMonth() < now.getMonth())
	{
		bPast = true;
	}
	
	if (bPast){
		button.set('styles', { 'display': 'none' });
	}
	else
	{
		button.set('styles', { 'display': 'block' });
	}
}


function showProduct(num) {

    var visLink = $$('.upcomingList li a')[0];
    var productLinks = $$('#calendarContent li ._productLink');
    if (productLinks[num]) {
        if (productLinks[num].innerHTML.length > 85) {
            visLink.innerHTML = productLinks[num].innerHTML.substr(0, 85) + '...';
        } else {
            visLink.innerHTML = productLinks[num].innerHTML;
        }
        visLink.href = productLinks[num].href;
    }
    if(num==0){
      $("calPrev").set('styles', { 'display': 'none' });
    }else{
      $("calPrev").set('styles', { 'display': 'block' });
    }
}

var index = 0;
function prevNextOrReset(dir) {

    if (dir == 'u' && index == ($$('#calendarContent li').length-1)) {
        index = 0;
    } else if(dir == 'd' && index == 0){
        index = $$('#calendarContent li').length;
    } else if (dir == 'u') {
        index++;
    } else if (dir == 'd') {
        index--;
    }
    return index;
}