﻿/***

O2 Priority V5 MVC - HOME
2010 www.aislondon.com

***/
(function ($) {

    /* Scope
    This initialises the namespace if it has not been initialised elsewhere */

    $.priority = $.priority || {};

    /* Global fields
    Any global objects that you need access to are defined here */

    var g_ready = false;
    var g_self = this;

    /* 
    API methods
    If the class has any API methods then put them here
    (methods that can be called directly on objects e.g. $("body").customMethod();
    */
    $.fn.preferences = function () {
        return this.each(function () {
            //alert("API method called on " + this);
        });
    };

    /*Class*/
    $.priority.home = function (options) {
        var c_self = this;
        var c_ready = false;
        c_self.options = $.extend({}, $.priority.home.defaults, options);

        /*
        Instance methods
        */
        c_self.functions = {
            interval: function () {
                /*
                Insert tasks to be repeated at set intervals
                */
                debug("interval event");
                setTimeout(c_self.functions.interval, c_self.options.intervalFrequency);
            },

            initialise: function (context) {
                context.each(function (index) {

                });
            },

            setupHomeScroller: function (initialSetup) {
                debug('setting scroller');
                var eventScroller = $("#event-tile-scroller");
                var scrollerMask = eventScroller.find("#event-tiles-container");
                var scrollerInner = eventScroller.find("#event-tiles-inner");
                var scrollerItemsList = scrollerInner.find(".event-tile-box");

                var scrollerArrows = eventScroller.find(".scrollerArrow a");
                var arrowLeft = eventScroller.find(".scrollerArrow.left a");
                var arrowRight = eventScroller.find(".scrollerArrow.right a");
                var resultsNumBox = $("#results-number p");

                scrollerMask.height('174px');
                eventScroller.css('margin-bottom', '18px');
                //remove any previously made changes -MT
                scrollerInner.css({ left: '0px', width: '712px' });
                scrollerArrows.unbind('click');

                if (scrollerItemsList.length > 4) {
                    var currentScrollPos = 0;
                    var scrollerLength = scrollerItemsList.length;
                    var lastTilesAmount = (scrollerLength - 4) % 3;
                    var lastFullScrollPos = scrollerLength - 7;
                    var noScrollPos = scrollerLength - 4;
                    debug(noScrollPos);

                    scrollerArrows.css({ opacity: 0, display: "block" });
                    arrowLeft.animate({ opacity: .5 }, 900);
                    arrowRight.animate({ opacity: 1 }, 900);

                    var totalInnerWidth = scrollerItemsList.length * c_self.options.scrollerItemWidth + scrollerItemsList.length * c_self.options.scrollerItemMargin;
                    debug(scrollerItemsList.length);

                    scrollerInner.css("width", totalInnerWidth + "px");

                    arrowRight.bind('click', function () {
                        if (currentScrollPos >= 0 && currentScrollPos <= lastFullScrollPos) {
                            scroll(3, "left");
                            currentScrollPos = currentScrollPos + 3;
                        }
                        else if (currentScrollPos > lastFullScrollPos && currentScrollPos < noScrollPos) {
                            scroll(lastTilesAmount, "left");
                            currentScrollPos = currentScrollPos + lastTilesAmount;
                        };
                        if (currentScrollPos == noScrollPos) {
                            $(this).animate({ opacity: .5 }, 300);
                        }
                        arrowLeft.animate({ opacity: 1 }, 300);
                        debug(currentScrollPos);
                        return false;
                    });

                    arrowLeft.bind('click', function () {
                        if (currentScrollPos == noScrollPos && lastTilesAmount != 0) {
                            scroll(lastTilesAmount, "right");
                            currentScrollPos = currentScrollPos - lastTilesAmount;
                        }
                        else if (currentScrollPos <= noScrollPos && currentScrollPos > 0) {
                            scroll(3, "right");
                            currentScrollPos = currentScrollPos - 3;
                        };
                        if (currentScrollPos == 0) {
                            $(this).animate({ opacity: .5 }, 300);
                        }
                        arrowRight.animate({ opacity: 1 }, 300);
                        debug(currentScrollPos);
                        return false;
                    });

                }
                else if (scrollerItemsList.length <= 4) {
                    scrollerArrows.hide();
                };

                //if initial setup call a date filter setup method -MT
                if (initialSetup) {
                    debug("search scroller initial setup");
                    //populate results nr box
                    c_self.functions.setResultsNumber();
                    c_self.functions.setupDateFilter(scrollerInner, scrollerItemsList);
                };

                function scroll(tilesAmount, direction) {
                    if (direction == "left") {
                        var scrollDistance = "-=" + ((c_self.options.scrollerItemWidth + c_self.options.scrollerItemMargin) * tilesAmount);
                        scrollerInner.animate({ left: scrollDistance }, c_self.options.animationSpeed);
                    }
                    else if (direction == "right") {
                        var scrollDistance = "+=" + ((c_self.options.scrollerItemWidth + c_self.options.scrollerItemMargin) * tilesAmount);
                        scrollerInner.animate({ left: scrollDistance }, c_self.options.animationSpeed);
                    };
                };

            },

            setResultsNumber: function (dateText) {
                var scrollerItemsList = $("#event-tiles-inner .event-tile-box");
                var dayMonthText = (dateText && dateText != undefined) ? dateText : "";
                var resultsText = (scrollerItemsList.length % 10 == 1 && scrollerItemsList.length != 11) ? " result found" + dayMonthText : " results found" + dayMonthText; //divide by 10, if 1 left it's 'result' excl. '11'
                var isRecommended = $('#IsRecommended');
                if (isRecommended != null && isRecommended.val() == "True") {
                    $("#results-number .results-note").text("No search results found. How about these?");
                } else {
                    $("#results-number .results-note").text(scrollerItemsList.length + resultsText);
                }
            },

            setupDateFilter: function (eventsListParent, eventsList) {

                var monthFilterBox = $("#month-filter-list");
                var monthFilterCurrent = $("#month-filter-current span");

                var dayFilterBox = $("#month-dates");
                var dayFilterTrigger = $("#month-day-link span");

                var thisSearchMonths = [];

                var clonedEventsList = initialPreset(eventsList); //returns cloned results list with required 'data' objects and prepopulates months and dates containers
                monthsFilterSetup();
                daysFilterSetup();

                toggleSetup($("#month-filter-container"));
                toggleSetup($("#day-filter-container"));

                datesScrollSetup();

                function initialPreset(eventPanelsList) {
                    var month = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
                    var tmpThisSearchMonths = [];
                    var monthDatesInner = $("<div id='month-dates-inner'></div>");

                    eventPanelsList.each(function () {
                        var c_self = $(this);
                        var eventDateFields = c_self.find("input.event-date");
                        var thisEventMonths = [];

                        if ($('input.event-date').length == 0) {                                                    // if there are no dates to highlight in the content
                            $('body.js #search-filter-container').hide();
                        }
                        else {
                            $('body.js #search-filter-container').show();
                        };

                        debug(c_self.find('.event-tile-name a').text() + " panel: amount of date fields - " + eventDateFields.length);

                        if (eventDateFields.length > 0) {

                            eventDateFields.each(function () {
                                var dateValue = this.value.split("/");
                                var strMonthYear = month[dateValue[1] - 1] + "-" + dateValue[2];

                                if ($.inArray(strMonthYear, tmpThisSearchMonths) == -1) {                           // if it's the first time this month is found in search
                                    tmpThisSearchMonths.push(strMonthYear);

                                    var tmpDiv = $("<div class='single-month " + strMonthYear + "'></div>");        // create new div for every month, create 'data' values, append to months wrapper div
                                    tmpDiv.data({ 'eventDates': "", 'monthYear': strMonthYear, 'numMonthYear': dateValue[1] + "/" + dateValue[2] });
                                    monthDatesInner.append(tmpDiv);
                                };

                                if ($.inArray(strMonthYear, thisEventMonths) == -1) {
                                    thisEventMonths.push(strMonthYear);
                                };
                                c_self.data('eventMonths', thisEventMonths);
                                var eventDatesString = c_self.data(strMonthYear) ? (c_self.data(strMonthYear) + "-" + dateValue[0]) : dateValue[0];
                                c_self.data(strMonthYear, eventDatesString);

                                var tmpMonthBox = monthDatesInner.find("." + strMonthYear);
                                var tmpStrDates = tmpMonthBox.data('eventDates');
                                var monthsDatesString = (tmpStrDates != "") ? tmpStrDates + "-" + dateValue[0] : dateValue[0];
                                tmpMonthBox.data('eventDates', monthsDatesString);

                                //debug("month box '" + strMonthYear + "' : dates - " + monthDatesInner.find("." + strMonthYear).data('eventDates'));  //show an array of dates in a single month box
                                //debug(c_self.find('.event-tile-name a').text() + " panel: dates data - " + strMonthYear + ": " + c_self.data(strMonthYear));
                            });
                        };
                        //debug(c_self.find('.event-tile-name a').text() + " panel: months data - " + c_self.data('eventMonths'));

                    });
                    thisSearchMonths = tmpThisSearchMonths;
                    $(dayFilterBox).empty().append($("<div class='scroll-left'>left</div><div class='scroll-right'>right</div>")).append(monthDatesInner); // gets appended 2 times ?

                    return eventPanelsList.clone(true);
                }; //initialPreset;

                function monthsFilterSetup() {
                    monthFilterBox.empty();

                    thisSearchMonths.sort(function (a, b) {
                        var month = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
                        var dateA = a.split("-"); var dateB = b.split("-");
                        a = jQuery.inArray(dateA[0], month).toString();
                        b = jQuery.inArray(dateB[0], month).toString();
                        if (a.length == 1) a = "0" + a;
                        if (b.length == 1) b = "0" + b;
                        a = parseInt(dateA[1] + a); b = parseInt(dateB[1] + b);
                        return b - a;
                    });


                    $.each(thisSearchMonths, function () {
                        var _self = this;
                        var tmpLinkString = _self.split("-");
                        $("<a href='#' class='" + _self + "'>" + tmpLinkString[0] + " " + tmpLinkString[1] + "</a>")
                            .appendTo(monthFilterBox);
                    });
                    $("<a href='#' class='showAll'>Show all</a> ").appendTo(monthFilterBox);

                    monthFilterBox.find("a").click(function () {
                        eventsListParent.empty();
                        var thisText = $.trim($(this).text());
                        var dateScrollBox = dayFilterBox.find("#month-dates-inner"); // get dates container to shift around when months selected
                        if ($(this).hasClass('showAll')) {
                            clonedEventsList.clone(true).appendTo(eventsListParent);
                            monthFilterCurrent.text('All months');
                            dateScrollBox.css('left', '0px');
                            c_self.functions.setResultsNumber();
                        } else {
                            var monthToFilter = $(this).attr('class');

                            var thisMonthsDatesBox = dateScrollBox.find('.single-month').filter('.' + monthToFilter);
                            var posOffset = (dateScrollBox.find('.single-month').index(thisMonthsDatesBox)) * c_self.options.dateFilterBoxWidth;
                            if (posOffset > 0) {
                                dateScrollBox.css('left', '-' + posOffset + 'px');
                            } else if (posOffset == 0) {
                                dateScrollBox.css('left', '0px');
                            };

                            clonedEventsList.each(function (index) {
                                var _eventSelf = $(this);
                                if (_eventSelf.data('eventMonths')) {
                                    $.each(_eventSelf.data('eventMonths'), function (index, value) {
                                        if (monthToFilter == value) _eventSelf.clone(true).appendTo(eventsListParent);    // keep one line pls
                                    });
                                };
                            });
                            monthFilterCurrent.text(thisText);
                            c_self.functions.setResultsNumber(" in " + thisText);
                        };
                        toggleContainer(monthFilterBox);
                        c_self.functions.setupHomeScroller(false);

                        // set GA tracking for months   
                        _gaq.push(['_trackEvent', 'View by', 'Month', thisText]);

                        return false;
                    });
                }; //monthsFilterSetup

                function daysFilterSetup() {
                    var monthDatesInner = $("#month-dates-inner");
                    var monthBoxesList = monthDatesInner.find(".single-month");
                    monthDatesInner.width(c_self.options.dateFilterBoxWidth * monthBoxesList.length);

                    monthBoxesList.each(function () {
                        var _monthBox = $(this);
                        var thisMonthYear = _monthBox.data('monthYear').split("-");
                        var thisMonthYearNum = _monthBox.data('numMonthYear').split("/");

                        $("<h3>" + thisMonthYear[0] + " " + thisMonthYear[1] + "</h3>").appendTo(_monthBox);
                        $("<h3 class='week-days'><span>S</span><span>M</span><span>T</span><span>W</span><span>T</span><span>F</span><span>S</span></h3>").appendTo(_monthBox);

                        var daysThisMonth = 32 - new Date(thisMonthYearNum[1], thisMonthYearNum[0] - 1, 32).getDate();
                        var thisMonthFirstDay = new Date(thisMonthYearNum[1], thisMonthYearNum[0] - 1, 1).getDay();

                        var wrapperDiv = $("<div class='dates-wrapper'></div>");
                        $("<div class='days-lead-space'></div>").width(thisMonthFirstDay * 28).appendTo(wrapperDiv); //add leading space before first day if any 

                        debug(thisMonthYear[0] + " " + thisMonthYear[1] + " got these dates: " + _monthBox.data('eventDates'));
                        var tmpArrMonthsDates = _monthBox.data('eventDates').split("-");
                        for (i = 1; i <= daysThisMonth; i++) {
                            var classToAdd = "inactive";
                            $.each(tmpArrMonthsDates, function (index, value) {
                                if (i + "" == value + "") classToAdd = "active";
                            });
                            $("<a class='" + classToAdd + "' >" + i + "</a>").appendTo(wrapperDiv);
                        };
                        wrapperDiv.find("a.active").bind('click', function () {
                            eventsListParent.empty();
                            var dateToFilter = $.trim($(this).text());
                            var monthToFilter = _monthBox.data('monthYear');
                            debug(dateToFilter + " " + monthToFilter);

                            clonedEventsList.each(function (index) {
                                var _eventSelf = $(this);
                                if (_eventSelf.data(monthToFilter)) {
                                    var tmpThisEventDates = _eventSelf.data(monthToFilter).split("-");
                                    $.each(tmpThisEventDates, function (index, value) {
                                        if (dateToFilter == value) _eventSelf.clone(true).appendTo(eventsListParent);    // keep one line pls
                                    });
                                };
                            });

                            c_self.functions.setResultsNumber(" on " + dateToFilter + " " + thisMonthYear[0] + " " + thisMonthYear[1]);

                            toggleContainer(dayFilterBox);
                            monthFilterCurrent.text("View by month");
                            c_self.functions.setupHomeScroller(false);

                            // set GA tracking
                            _gaq.push(['_trackEvent', 'View by', 'Day', dateToFilter + "-" + monthToFilter]);

                            return false;
                        });
                        wrapperDiv.appendTo($(this));
                    });
                }; //daysFilterSetup

                function toggleSetup(htmlBox) {
                    var toggleLink = htmlBox.find(".toggle-link");
                    var toggleBox = htmlBox.find(".toggle-box");

                    toggleLink
						.unbind('click')
						.bind('click', function () {
						    toggleContainer(toggleBox);
						});
                };
                function toggleContainer(obj) {
                    if (obj.css('display') == 'none') {
                        obj.show();
                        obj.next('div').find('.toggle-link').addClass('open');
                    } else if (obj.css('display') == 'block') {
                        obj.hide();
                        obj.next('div').find('.toggle-link').removeClass('open');
                    }
                };

                function datesScrollSetup() {
                    var dateScrollBox = dayFilterBox.find("#month-dates-inner");
                    var dateScrollLeft = dayFilterBox.find(".scroll-left");
                    var dateScrollRight = dayFilterBox.find(".scroll-right");
                    var maxScrollPos = (1 - $("#month-dates-inner .single-month").length) * c_self.options.dateFilterBoxWidth; //MAX is box width less of single month box width
                    debug(maxScrollPos);
                    dateScrollLeft.click(function () {
                        var currentScrollPos = dateScrollBox.css('left').split("px")[0];
                        debug(currentScrollPos);
                        if (currentScrollPos < 0) {
                            scroll('left');
                        };
                    });

                    dateScrollRight.click(function () {
                        var currentScrollPos = dateScrollBox.css('left').split("px")[0];
                        debug(currentScrollPos);
                        if (currentScrollPos > maxScrollPos) {
                            scroll('right');
                        };
                    });

                    function scroll(direction) {
                        if (direction == "left") {
                            var scrollDistance = "+=" + c_self.options.dateFilterBoxWidth;
                            dateScrollBox.animate({ left: scrollDistance }, c_self.options.animationSpeed);
                        }
                        else if (direction == "right") {
                            var scrollDistance = "-=" + c_self.options.dateFilterBoxWidth;
                            dateScrollBox.animate({ left: scrollDistance }, c_self.options.animationSpeed);
                        };
                    };
                };

                //remove previous changes
                resetMonthsBox();
                resetDaysBox();

                // reset functions
                function resetDaysBox() {
                    dayFilterBox.hide();
                };
                function resetMonthsBox() {
                    monthFilterCurrent.text('View by month');
                    monthFilterBox.hide();
                };
            },

            loadFlashSearch: function () {
                var hideFLashIntro = readCookie('hideFlashIntro');
                var hideFavouritesHint = readCookie('hideFavouritesHint');
                var favHintValue = (hideFavouritesHint && hideFavouritesHint != 'undefined') ? hideFavouritesHint : '';

                var cSearchTerm = readCookie("searchTerm");
                prevSearchTerm = cSearchTerm != 'undefined' ? cSearchTerm : null;

                var userIDfield = $('#header-signup #UserId');
                var userID = userIDfield.length > 0 ? userIDfield.val() : null;

                var sessionId = $("#ApiSessionId");
                var sessionId = sessionId.length > 0 ? sessionId.val() : null;

                var flashAssetsPath = rootPath + "Assets/Specific/HomeFlash/";

				var tmpRootPath = window.location.protocol + "//" + window.location.host + rootPath;
				debug(window.location.protocol + "//" + window.location.host);
				debug(tmpRootPath);
								
                var xmlDataPath = tmpRootPath + "xml/data.xml";
                var xmlConfigPath = tmpRootPath + "xml/config.xml";

                var flashvars = { xml: xmlDataPath, configxml: xmlConfigPath, guid: userID, sessionID: sessionId, flashPath: flashAssetsPath, search: prevSearchTerm, hideFavouritesHint: hideFavouritesHint };
                debug(flashvars);

                var params = {};
                params.allowscriptaccess = "always";
                params.allowFullScreen = "true";
                params.bgcolor = "010C28";
                params.wmode = "opaque";
                params.useExpressInstall = "true";

                var attributes = { id: "ExternalInterface", name: "ExternalInterface" };
                var flashFilePath = flashAssetsPath + 'base.swf';
                var installFilePath = flashAssetsPath + 'expressInstall.swf';

                swfobject.embedSWF(flashFilePath, "ExternalInterface", "968", "437", "10.0.0", installFilePath, flashvars, params, attributes);

                debug('flash search loaded');
            },

            loadHtmlSearch: function (isTakeOver) {
                $('#ExternalInterface').show();
                var htmlSearchBtn = $('#htmlSearchSubmit');
                var searchTextBox = $('input#txtSearch.js-on');

                var cSearchTerm = readCookie('searchTerm');
                var prevSearchTerm = '';
                if (cSearchTerm && cSearchTerm != 'undefined') {
                    var tmpRegExp = /%20/g;
                    var prevSearchTerm = cSearchTerm.replace(tmpRegExp, ' ');
                };

                if (!isTakeOver || isTakeOver != "takeover") {
                    searchTextBox.val(prevSearchTerm);
                    htmlSearchBtn.click();

                    debug('search cookie: /' + prevSearchTerm + '/');
                } else if (isTakeOver == "takeover") {
                    debug('Take over state');
                };

            },

            saveSearchTerm: function () {
                var searchTextBox = $('input#txtSearch.js-on');
                if (searchTextBox.length > 0) {
                    var currentSearch = searchTextBox.val();
                    var tmpRegExp = / /g;
                    currentSearch = currentSearch.replace(tmpRegExp, '%20');

                    eraseCookie('searchTerm');
                    createCookie('searchTerm', currentSearch, 1); // set for an hour
                    //debug('search cookie: /' + currentSearch + '/');
                };
            },

            toggleFlashSearch: function () {
                var displayFlashSearch = readCookie('flashSearch');
                var searchToggleLink = $('#searchToggle');
                //detect iPhone/iPad 
                var usingMobilePhone = ((navigator.userAgent.indexOf('iPhone') != -1) || (navigator.userAgent.indexOf('iPod') != -1) || (navigator.userAgent.indexOf('iPad') != -1) || (navigator.userAgent.match(/Android/i))) ? true : false;

                var takeOverState = $("#IsHomePageTakeover").val() != undefined ? $("#IsHomePageTakeover").val() : "False";
                //takeOverState = false;

                if (!displayFlashSearch && takeOverState == "False" && !usingMobilePhone) {
                    createCookie('flashSearch', 'true', 24 * 30); // set for a month
                    //load flash initially
                    c_self.functions.loadFlashSearch();

                } else if (displayFlashSearch && displayFlashSearch != 'undefined' && takeOverState == "False" && !usingMobilePhone) {
                    if (displayFlashSearch == 'true') {
                        c_self.functions.loadFlashSearch();
                        searchToggleLink.text('HTML version');
                    } else if (displayFlashSearch == 'false') {
                        c_self.functions.loadHtmlSearch();
                        searchToggleLink.text('Flash version');
                    };
                } else if (usingMobilePhone && takeOverState == "False") {  // mobile platforms
                    c_self.functions.loadHtmlSearch();
                } else if (takeOverState != "False") {                       // takeover state
                    c_self.functions.loadHtmlSearch("takeover");
                };

                searchToggleLink.bind('click', function () {
                    debug('flash/html toggle');
                    if (readCookie('flashSearch') == 'true') {
                        eraseCookie('flashSearch');
                        createCookie('flashSearch', 'false', 24 * 30);
                        debug('flash search cookie false');
                    } else if (readCookie('flashSearch') == 'false') {
                        eraseCookie('flashSearch');
                        createCookie('flashSearch', 'true', 24 * 30);
                        debug('flash search cookie true');
                    };
                    return true;
                });

            },

            toggleFavState: function (obj) {
                var classToAdd = obj.hasClass('inactive') ? 'active' : 'inactive';
                var toolTipMsg = (classToAdd == 'inactive') ? 'Click to add to your favourites' : 'Click to remove from your favourites';
                obj.removeClass('inactive active').addClass(classToAdd).attr('title', toolTipMsg);
            },

            preload: function () {
                debug("preload");
                c_self.functions.preloadImages(/*insert array of images here*/);
            },
            preloadImages: function () {
                for (var i = 0; i < arguments.length; i++) {
                    $("<img>").attr("src", arguments[i]);
                }
            }

        };

        /* UTILITY */

        c_self.functions.setupHomeScroller(true);
        c_self.functions.toggleFlashSearch();

        c_ready = true;
    };

    // defaults
    $.priority.home.defaults = {
        scrollerItemWidth: 170,
        scrollerItemMargin: 8,
        dateFilterBoxWidth: 200,
        animationSpeed: 500,
        intervalFrequency: 10000
    };

    // optional - initialise one or more instances of the class
    $(document).ready(function () {

        $.br_home = new $.priority.home();

    });

})(jQuery);

