﻿/// <reference path="../Edentity.Global.js" />
/// <reference path="../Cosmo.Global.js" />
/// <reference path="../Cosmo.Modules.js" />
/// <reference path="../External/jquery-1.3.2-vsdoc2.js" />
/// <reference path="../jwselect.js" />

Edentity.RegisterNamespace("Cosmo.Modules.Compliments");

(function(Compliments, $) {

    var CosmoType = 'Compliment',   // Cosmo object type
        Initializing = true,        // Flag to indicate if class is initialized
        SelectedGuy = 0,            // Guy ID selected
		SelectedMood = 0,           // Mood ID selected
		SelectedOccasion = 0,       // Occassion ID selected
		Container = null,           // JQuery module object
		ComplimentID = 0,           // Current compliment jID
		RatingID = 0,               // Rating object jID
		PagerID = 0,                // Pager object jID
		PostsPerPage = 0,           // Posts per page
		Properties = null;          // Modules properties

    Compliments.OnInit = function($container, complimentID, ratingID, pagerID, postsPerPage, moduleProps) {
        Container = $container;
        ComplimentID = complimentID;
        RatingID = ratingID;
        PagerID = pagerID;
        PostsPerPage = postsPerPage;
        Properties = moduleProps;

        initComplimentMe();
        initFeaturedCompliment();
        setFromUrlHash();

        bindDropdown($('#GuyDropdown'), Properties.PickaGuyLabel, Properties.GuysList, 'GUYS', SelectedGuy);
        bindDropdown($('#MoodDropdown'), Properties.PickaMoodLabel, Properties.MoodsList, 'MOODS', SelectedMood);
        bindDropdown($('#OccasionDropdown'), Properties.PickanOccasionLabel, Properties.OccasionsList, 'OCCASIONS', SelectedOccasion);

        bindCompliment();
        bindRated(Properties.FeaturedRatingID, Properties.FeaturedComplimentID);  // Featured compliment rating
        bindList();

        Initializing = false;
    }

    function initComplimentMe() {
        $('#' + Properties.ComplimentMeButtonId, Container).bind('click', function() {
            loadRandomCompliment();
        });
    }

    function initFeaturedCompliment() {
        $('#' + Properties.FeaturedWatchMeID).bind('click', function() {
            loadCompliment(Properties.FeaturedComplimentID);
        });
    }

    function bindCompliment(c) {

        if (c != null) {

            var friendlyTitle = TitleToFriendlyUrl(c.Title);

            ComplimentID = c.ID;
            $('.MainCompliment .VideoDesc', Container).text(c.Title);
            Cosmo.Controls.ComplimentToolbar.Update(ComplimentID);

            var ecardUrl = location.protocol + '//' + location.host + '/' + location.pathname + '?Title=' + friendlyTitle;
            $('#' + Properties.SendToEcardButton).attr('href', Properties.SendToEcardUrl + '?url=' + ecardUrl);

            if (c.PlatformVideoID != '') {
                initThePlatformPlayer(c.PlatformVideoID);
            }

            // Update Omniture values
            if (typeof OmnitureComplete == 'function') {
                AppendToDynamicOmnitureProperites(friendlyTitle);
                AppendOmniVar("prop2", friendlyTitle);
                OmnitureComplete();
            }

            // Update ShareIt links
            if (typeof serviceItems != 'undefined' && serviceItems != null && typeof shareIt != 'undefined' && shareIt != null) {
                if (serviceItems.ShareItems != null && serviceItems.ShareItems.length > 0) {
                    for (var i = 0; i < serviceItems.ShareItems.length; i++) {
                        var item = serviceItems.ShareItems[i];
                        var targetUrl = (item.Encode == 'true' ? escape(ecardUrl) : ecardUrl);
                        item.Url = item.BaseUrl + '?' + item.Query + '=' + targetUrl;
                    }

                    shareIt.Update();
                }
            }
        }

        var addToFaves = new AddToFavourites('#AddToCompFavorites', CosmoType, ComplimentID, Properties.AddtoFavoritesLabel, Properties.RemovefromFavoritesLabel);

        $('.SendEcard').hover(function() {
            $(this).addClass('SendEcardHover');
        }, function() {
            $(this).removeClass('SendEcardHover');
        });

        bindRated(RatingID, ComplimentID);
    }

    function bindDropdown($target, dropdownText, itemArray, selectedItem, initialValue) {
        $target.WSelectBox({
            DefaultText: dropdownText,
            ClearItemText: "--clear--",
            KeyFieldName: "key",
            ValueFieldName: "value",
            Items: itemArray,
            SelectedValue: initialValue,
            SelectImage: Edentity.ResolveUrl("~/Images/Controls/SelectBox-Arrow.png"),
            Horizontal: true,
            onSelectedChange: function(selectedValue, selectedText) {

                if (!Initializing) {
                    if (selectedItem == 'GUYS') {
                        SelectedGuy = selectedValue;
                    } else if (selectedItem == 'MOODS') {
                        SelectedMood = selectedValue;
                    } else {
                        SelectedOccasion = selectedValue;
                    }

                    saveToUrlHash(SelectedGuy, SelectedMood, SelectedOccasion);

                    var pagerProps = {
                        ContainerID: Container.attr('id'),
                        PagerID: PagerID,
                        ComplimentID: ComplimentID,
                        PostsPerPage: PostsPerPage
                    };

                    changePage(pagerProps, 0);
                }
            }
        });
    }

    Compliments.BindPagerEvents = function(containerID, pagerID, complimentID, postsPerPage) {
        var $pager = $("#" + pagerID),
            $pageNums = $("a", $pager),
            pagerProps = {
                ContainerID: containerID,
                PagerID: pagerID,
                ComplimentID: complimentID,
                PostsPerPage: postsPerPage
            };
        $pageNums.each(function() {
            bindPageNumClick($(this), pagerProps);
        });
    }

    function bindRated(ratingID, complimentID) {
        var rated = new Rated('#' + ratingID, CosmoType, complimentID);
        rated.GetRating();
    }

    function bindList() {
        var pagerProps = {
            ContainerID: Container.attr('id'),
            PagerID: PagerID,
            ComplimentID: ComplimentID,
            PostsPerPage: PostsPerPage
        };
        changePage(pagerProps, 0);
    }

    function bindPageNumClick($pageNum, pagerProps) {
        var thisPage = parseInt($pageNum.text(), 10) - 1;
        $pageNum.bind("click", function() {
            $.scrollTo($('.Filters'));
            changePage(pagerProps, thisPage);
            return false;
        });
    }

    function changePage(pagerProps, newPage) {
        var serviceUrl = Edentity.ResolveUrl("~/WebServices/AjaxServices.asmx/GetCompliments");
        var dataStr = "{Guy: " + SelectedGuy + ", Mood: " + SelectedMood + ", Occasion: " + SelectedOccasion +
                        ", PageNum: " + newPage + ", PostsPerPage: " + pagerProps.PostsPerPage + "}";
        Cosmo.WebServices.CallAsmx(serviceUrl, dataStr, function(result) {
            if (result == null || result.d == null || result.d.Compliments == null) return;
            writeResults(result, pagerProps);
            Cosmo.Controls.ClientServerPager.PageChanged(pagerProps.PagerID, newPage, result.d.TotalPages);
            Compliments.BindPagerEvents(pagerProps.ContainerID, pagerProps.PagerID, pagerProps.ComplimentID, pagerProps.PostsPerPage);
        });
    }

    function writeResults(result, pagerProps) {
        var $container = $("#" + pagerProps.ContainerID),
            $listing = $(".Listing", $container).html('');

        jQuery.each(result.d.Compliments, function(i) {

            var c = result.d.Compliments[i];
            var g = c.Guy;
            var thumbnail = $('<div class="Thumbnail"></div>')
                .append($('<img />')
                    .attr("src", (g != null && g.ThumbnailURL != null && g.ThumbnailURL != '' ? g.ThumbnailURL : c.ThumbnailImageURL))
                    .attr("alt", (g != null && g.ThumbnailLabel != null && g.ThumbnailLabel != '' ? g.ThumbnailLabel : c.ThumbnailImageLabel)));

            var properties = $('<div class="Properties"></div>')
                .append($('<p class="Body"></p>')
                    .text(c.Title))
                .append($('<div class="Rating"></div>')
                    .attr('id', 'Rating' + i)
                    .append($('<div class="Left"></div>')
                        .text(Properties.OverallLabel + ":"))
                    .append($('<div class="RatedStars Left"></div>'))
                    .append($('<div class="Clear"></div>')));

            var watchme = $('<div class="WatchMe"></div>')
                .append($('<img class="Hand" />')
                    .attr("src", Properties.WatchMeURL)
                    .bind('click', function() {
                        loadCompliment(c.ID);
                    })
                    .hover(
                        function() {
                            $(this).attr("src", Properties.WatchMeHoverURL);
                        }, function() {
                            $(this).attr("src", Properties.WatchMeURL);
                        }));

            var item = $('<div class="Item"></div>')
                .attr('id', 'Compliment' + c.ID)
                .append(thumbnail)
                .append(properties)
                .append(watchme)
                .append($('<div class="Clear"></div>'));

            $listing.append(item);

            bindRated('Rating' + i, c.ID);
        });

        // Zebra-stripe list
        $listing.each(function() {
            $('.Item:odd', $(this)).addClass('ItemEven');
        });
    }

    function loadCompliment(id) {
        $.scrollTo($('.Compliments'));
        var serviceUrl = Edentity.ResolveUrl("~/WebServices/AjaxServices.asmx/GetCompliment");
        var dataStr = "{ComplimentID: " + id + "}";
        Cosmo.WebServices.CallAsmx(serviceUrl, dataStr, function(result) {
            if (result != null && result.d != null) {
                bindCompliment(result.d);
            }
        });
    }

    function loadRandomCompliment() {
        var serviceUrl = Edentity.ResolveUrl("~/WebServices/AjaxServices.asmx/GetRandomCompliment");
        Cosmo.WebServices.CallAsmx(serviceUrl, "{}", function(result) {
            if (result != null && result.d != null) {
                if (result.d.ID == ComplimentID) {
                    // Ensure the last compliment cannot be played twice in a row
                    loadRandomCompliment();
                } else {
                    bindCompliment(result.d);
                }
            }
        });
    }

    function saveToUrlHash(guy, mood, occasion) {
        window.location.hash = '#' + guy + '|' + mood + '|' + occasion;
    }

    function setFromUrlHash() {
        var hash = window.location.hash;
        if (hash != undefined && hash != null && hash != '' && hash.split('#').length == 2) {
            var ids = hash.split('#')[1].split("|");
            if (ids.length == 3) {
                SelectedGuy = ids[0];
                SelectedMood = ids[1];
                SelectedOccasion = ids[2];
            }
        }
    }

} (Cosmo.Modules.Compliments, jQuery));

