var dpcAuthorizedUser = false;
var userLoggedIn = false;
Array.prototype.contains = function(element) {
    return $.inArray(element, this) != -1;
};

Array.prototype.remove = function(elementToRemove) {
    return $.grep(this, function(element, index) {
        return (element !== elementToRemove);
    });
};

function Menu() {
    var hightlightedTabCss = "highlightedTab";

    var menuItems = function() {
        return $('.menuOptions li a');
    };

    this.highlight = function(pathname) {
        menuItems().filter(
                function() {
                    return pathname.match("^" + $(this).attr('href'));
                }).last().addClass(hightlightedTabCss);
    };

    this.highlighted = function() {
        return $(".menuOptions ." + hightlightedTabCss);
    }
}

function SectionTitleBar() {

    this.update = function() {
        $(".sectionTitle h1").html(new Menu().highlighted().text());
    }
}

function ExpandCollapse(selector, expandText, collapseText) {
    var expandableNodes = $(selector).find(".expandableOuter");
    var triggerAll = $(selector).find(".triggerAll");

    $.each(expandableNodes, function(index, node) {

        node.collapse = function() {
            $(this).find(".expandable").hide();
            $(this).find(".trigger").text(expandText);
        };

        node.expand = function() {
            $(this).find(".expandable").show();
            $(this).find(".trigger").text(collapseText);
        };

        node.isExpanded = function() {
            return $(this).find(".expandable").is(':visible');
        };

        var that = this;
        $(node).find(".trigger").click(function() {
            that.isExpanded() ? that.collapse() : that.expand();
        });
    });

    expandableNodes.collapse = function() {
        $.each(expandableNodes, function(index, node) {
            node.collapse();
        });
        $(triggerAll).removeClass('expandedAll');
        $(triggerAll).text("VIEW DESCRIPTION FOR ALL PROGRAMMES");
    };

    expandableNodes.expand = function() {
        $.each(expandableNodes, function(index, node) {
            node.expand();
        });
        $(triggerAll).addClass('expandedAll');
        $(triggerAll).text("HIDE DESCRIPTION FOR ALL PROGRAMMES");
    };

    triggerAll.click(function() {
        $(triggerAll).hasClass('expandedAll') ? expandableNodes.collapse() : expandableNodes.expand();
    });

    this.nodes = function() {
        return expandableNodes;
    };

    this.preExpanded = function(selector) {
        var nodes = this.nodes().filter(selector);
        $.each(nodes, function(index, node) {
            node.expand();
        });
    };

    this.expandNodesOfChangeType = function(changeType) {
        $.each(this.nodes(), function(index, node) {
            if ($(this).parent().hasClass(changeType))
                this.expand();
        });
    };
}

function GlobalSearch() {
    this.init = function() {
        $("#imageOnlyChkBox").removeClass("hide");
        var defaultAction = $("#globalSearchForm").attr('action');
        $('#chkIdSearchImagesOnly').click(function() {
            if ($("#chkIdSearchImagesOnly").is(":checked")) {
                $("#globalSearchForm").attr("action", URLS.imageSearch);
            }
            else {
                $("#globalSearchForm").attr("action", defaultAction);
            }
        });
    }
}

function HintText(hintText, triggerElement, hintElement) {
    this.init = function () {
        $(hintElement).removeClass('hide');
        $(hintElement).text(hintText);

        if ($(triggerElement).val() == '') {
            $(hintElement).removeClass('hide');
        } else {
            $(hintElement).addClass('hide');
        }
        $(triggerElement).focus(function() {
            $(hintElement).addClass("hide");
        });

        $(triggerElement).blur(function() {
            if ($(triggerElement).val() == '') {
                $(hintElement).removeClass('hide');
            }
        });
    }
}

function ListingCarousel(elementId) {
    this.embed = function() {
        if ($("#" + elementId).length == 0) {
            return
        }
        var flashVars = { "dateRange":encodeURIComponent($("#DateSelectorParams").text()) };
        var params = {
            "width":"676",
            "height":"107",
            "align":"middle",
            "id":elementId,
            "quality":"high",
            "wmode":"opaque",
            "bgcolor":"#FFFFFF",
            "name":elementId,
            "allowScriptAccess":"always",
            "allowFullScreen": "false",
            "src": URLS.listingCarousel
        };
        swfobject.embedSWF(
                URLS.listingCarousel,
                elementId,
                "676",
                "107",
                "9.0.115",
                null,
                flashVars,
                params,
                null,
                null
                );
    }
}
function Lightbox(element) {

    this.init = function (callback) {
        var overlayTarget = $("#ImageOverlay");
        if (overlayTarget.size() != 0) {
            if (element.length > 0) {
                element.overlay({
                    mask: {
                        color: '#000',
                        loadSpeed: 200,
                        opacity: 0.4
                    },
                    left:'center',
                    onBeforeLoad: function() {

                        // grab wrapper element inside content
                        var wrap = this.getOverlay().find(".contentWrap");
                        overlayTarget.css("left", 0).css("top", 0);
                        var urlForLightboxHtml = this.getTrigger().attr("href").replace("/display/", "/lightbox/display/");

                        var successCallback = function(data) {
                            wrap.html(data);
                            callback();
                        };

                        $.ajax({
                            async: false,
                            cache: true,
                            dataType: 'html',
                            url: urlForLightboxHtml,
                            success: successCallback,
                            error: function(data) {
                                wrap.html(data.responseText);
                            }
                        });
                    },
                    fixed:false,
                    closeOnClick:false,
                    target: overlayTarget

                });
            }
        }
    }
}

function SearchFilter(element) {

    this.init = function () {
        element.change(function() {
            if (element.val() != 'press') {
                $('#FilterTags').addClass('hide');
            }
            else {
                $('#FilterTags').removeClass('hide');
            }
        });
    }
}

function isSessionIdentityCookiePresent() {
    return $.cookies.get('C4_Identity_Session');
}

function setDpcAuthorizedUser(state) {
    dpcAuthorizedUser = state;
}

function isDpcAuthorizedUser() {
    return dpcAuthorizedUser;
}

function setUserLoggedIn(state) {
    userLoggedIn = state;
}

function isUserLoggedIn() {
    return userLoggedIn;
}

function SignInBar() {
    this.update = function(onSuccessCallback) {

        var successCallback = function(loginProfile) {
            setDpcAuthorizedUser(false);
            var loginUrl = '';
            if (loginProfile.loginState == 'NOT_LOGGED_IN') {
                $('#loginBar').removeClass('hide');
                $('#registerBar').addClass('hide');
                $('#usernameBar').addClass('hide');
                loginUrl = $('#loginBar a[class~="login"]').attr("href");
            }
            else if (loginProfile.loginState == 'LOGGEDIN') {
                $('#loginBar').addClass('hide');
                $('#registerBar').removeClass('hide');
                $('#usernameBar').addClass('hide');
                loginUrl = $('#registerBar a[class~="registerForPress"]').attr("href");
                setUserLoggedIn(true);
            }
            else if (loginProfile.loginState == 'LOGGED_IN_AUTHORISED') {
                $('#loginBar').addClass('hide');
                $('#registerBar').addClass('hide');
                $('#usernameBar').removeClass('hide');
                $('#displayName').text(loginProfile.user.displayName);
                setUserLoggedIn(true);
                setDpcAuthorizedUser(true);
            }
            onSuccessCallback(loginUrl);
        };

        if (isSessionIdentityCookiePresent()) {
            $.ajax({
                async: true,
                cache: true,
                dataType: 'json',
                url: URLS.authorization + "?_=" + $.cookies.get('C4_Identity_Session'),
                success: successCallback
            });
        } else {
            var loginUrl = $('#loginBar a[class~="login"]').attr("href");
            onSuccessCallback(loginUrl);
        }
    }
}

function LoginProtected(triggerElement, loginUrl) {
    this.init = function(callback) {
        if (isDpcAuthorizedUser()) {
            callback();
            return;
        }

        $(triggerElement).click(function() {
            $U.redirectTo(loginUrl);
            return false;
        });
    }
}

function BasketEnabler(basket) {
    this.init = function() {
        $(basket.getAll()).each(function() {
            markAdded(this);
        });

        if (basket.isFull()) {
            $('a.addToCart').toggleClass('addToCart disabledAddToCart');
            $('a.disabledAddToCart').removeAttr('title');
            $U.disableClickOn($('a.disabledAddToCart'));
        }

        handleAdditionToBasket();
        handleRemovalFromBasket();
        handleClearBasket();
    };

    function handleAdditionToBasket() {
        $('a.addToCart').click(function() {
            var imageId = $(this).attr('value');

            basket.add(imageId);
            markAdded(imageId);

            if (basket.isFull()) {
                $U.redirectTo(URLS.imageBasket);
            }

            // stop event bubbling
            return false;
        });
    }

    function handleRemovalFromBasket() {
        $('a.removeFromCart').click(function() {
            basket.remove($(this).attr('value'));
        });
    }

    function handleClearBasket() {
        $('a.clearBasket').click(function() {
            basket.removeAll();
        });
        $('a#logout').click(function() {
            basket.removeAll();
        });

    }

    function markAdded(imageId) {
        $('a[value=' + imageId + '][class~="addToCart"]').each(function() {
            $(this).toggleClass('addToCart addedToCart');
            $(this).attr("title", "Added to Basket");
            $U.disableClickOn($(this));
        });
    }
}

function ImageBasket(basketMaxSize, listener) {
    var that = this;

    this.add = function(imageId) {
        var imagesInBasket = getImages();
        if (imagesInBasket.contains(imageId))
            return;

        imagesInBasket.push(imageId);
        setImages(imagesInBasket);

        notify();
    };

    this.remove = function(imageId) {
        setImages(getImages().remove(imageId));

        notify();
    };

    this.getAll = function() {
        return getImages();
    };

    this.removeAll = function() {
        setImages([]);

        notify();
    };

    this.isFull = function() {
        return getImages().length == basketMaxSize;
    };

    function getImages() {
        var imageIds = $.cookies.get(BASKET_CONSTANTS.basketCookie);
        return ((imageIds == null) || (imageIds.length == 0)) ? [] : imageIds.split(",");
    }

    function setImages(imagesInBasket) {
        if (imagesInBasket.length === 0)
            $.cookies.del(BASKET_CONSTANTS.basketCookie);
        else
            $.cookies.set(BASKET_CONSTANTS.basketCookie, imagesInBasket.join(","));
    }

    function notify() {
        listener.fireBasketSizeUpdated(getImages().length, that.isFull());
    }

    notify();
}

function BasketStatus() {
    this.fireBasketSizeUpdated = function(basketSize, isBasketFull) {
        var message = basketSize;
        if (isBasketFull) {
            message = "FULL";
            $("#basketFullmessage").removeClass('hide');
        } else {
            $("#basketFullmessage").addClass('hide');
        }
        $("#basketSize").html(message);
    }
}

var BASKET_CONSTANTS = {
    basketLimit: 40,
    basketCookie: 'basketImages'
};

var URLS = {
    imageSearch: "/info/press/images/search",
    authorization: "/info/press/authorization",
    listingCarousel: "/static/info/flash/browseByDate.swf",
    imageBasket: "/info/press/images/basket",
    listing : "/info/press/listing"
};

var $U = {
    applyCufon : function() {
        var c4CufonText = {
            fontFamily:"C4CufonText"
        };
        var c4HeadingCufonText = {
            fontFamily:"C4CufonHeading"
        };
        Cufon.replace('h1,h2,h3,h4', c4HeadingCufonText);
        Cufon.replace('h4.subTitle', c4CufonText);
    },

    refreshCufon: function() {
        Cufon.refresh();
    },

    redirectTo: function(url) {
        window.location.href = url;
    },

    disableClickOn: function(jQueryElement) {
        jQueryElement.unbind('click');
        jQueryElement.click(function(event) {
            event.preventDefault();
        });
    }
};


function Contacts() {
    function showRegisterMessageForNonDPCRegisteredUser(contactModuleId) {
        $('#RegisterForDPC' + contactModuleId).removeClass('hide');
        $('#RegisterForDPC' + contactModuleId).addClass('contactLogin message');
        $('#ContactLogin' + contactModuleId).addClass('hide');
    }

    this.init = function() {
        if (isSessionIdentityCookiePresent()) {

            $("input[name=ContactModuleId]").each(function () {
                var contactModuleId = $(this).val();
                var urlForContacts = "/info/press/restricted/contacts/display/contact-module-id/" + contactModuleId;

                function fetchContacts() {
                    var fetchContactCallback = function(data) {
                        var dataObject = $(data);
                        var divContactModuleId = "#cms\\:" + contactModuleId;
                        $(divContactModuleId).replaceWith(dataObject.html());
                    };

                    $.ajax({
                        async: false,
                        cache: true,
                        dataType: 'html',
                        url: urlForContacts,
                        success: fetchContactCallback
                    });
                }

                if (isUserLoggedIn()) {
                    if (isDpcAuthorizedUser()) {
                        fetchContacts();
                    }
                    else {
                        showRegisterMessageForNonDPCRegisteredUser(contactModuleId);
                    }
                }
            });
        }


    }
}

function ShowJsVisibleElements() {
    this.trigger = function() {
        $('.jsVisible').removeClass('hide');
    }
}

function ExternalLink() {
    this.openInNewWindow = function() {
        $('a[href^="http"]:not([href*=".channel4.com/info"]):not([href *=".channel4.com/4me"])').attr("target", "_blank");
    }
}

function ListingFilterByContent() {
    var filterByContentCookieName = 'filterListingsBy';
    this.init = function() {
        $('#MoviesOnly').click(function() {
            $.cookies.set(filterByContentCookieName, "movies");
            $('.programme').not('.movie').addClass('hide');
        });
        $('#AllProgrammes').click(function() {
            $.cookies.del(filterByContentCookieName);
            $('.programme').removeClass('hide');
        });
        filterListingsByCookieValue();
    };

    var filterListingsByCookieValue = function() {
        var filterCookieValue = $.cookies.get(filterByContentCookieName);
        if (filterCookieValue === "movies") {
            $('#MoviesOnly').click();
        }
        else {
            $('#AllProgrammes').click();
        }
    };
}

/**
 * Event Tracking Controller JavaScript
 */
function Tracking() {
    this.trackEvents = function(social_network, obj) {
        var s = s_gi(self.s_account);
        s.trackingServer = 'webstat.channel4.com';

        s.linkTrackVars='eVar31,events';
        s.linkTrackEvents='event46';
        s.eVar31='Corporate Portal: Info: ' + social_network;
        s.events='event46';
        s.tl(obj,'o',s.eVar31);
    };
}

/* Print and Share */
function SocialToolbar() {
    this.init = function() {
        $(".socialToolbar").each( function(){
            // Print page
            $(this).find("#print a").click( function(e){
                var h = window.location.href.split("#");
                var pageUrl = h[0];
                var suffixPrintOption = pageUrl.indexOf("?") > 0 ? "&print=true" : "?print=true";
                var w = window.open(pageUrl + suffixPrintOption,"infoprinter","height=480,width=640,menubar=yes,scrollbars=yes");
                e.preventDefault();
            });

            // Share via Facebook
            $(this).find("#facebook a").click( function(e){
                new Tracking().trackEvents("Facebook",this);
                var w = window.open($(this).attr("href"),"infosharer","height=350,width=640,menubar=no,toolbar=no");
                e.preventDefault();
            });

            // Share via Twitter
            $(this).find("#twitter a").click( function(e){
                new Tracking().trackEvents("Twitter",this);
                var w = window.open($(this).attr("href"),"infosharer");
                e.preventDefault();
            });

            // Share via Mail
            $(this).find("#mailto a").click( function(e){
                new Tracking().trackEvents("Mailto",this);
                return true;
            });
        });

    }
}

