﻿/// <reference name="MicrosoftAjax.js"/>

Type.registerNamespace("TipsCommunity");

TipsCommunity.HumanySearch = function(element) {
    TipsCommunity.HumanySearch.initializeBase(this, [element]);
    this._totalItems = 0;
    this._isSearching = false;
    this._$templatesContainer = null;
    this._targetPager = null;
    this._specialLinkNavigateUrl = null;
    this._specialLinkText = null;
}

TipsCommunity.HumanySearch.prototype = {
    initialize: function() {
        TipsCommunity.HumanySearch.callBaseMethod(this, 'initialize');
        
        // Listen to user typing in the target textbox
        $addHandlers(this.get_targetTextBox(), { 'keyup' : this.onTargetTextBoxKeyUp }, this);
        
        // Bind auto close behaviour
        if (this.get_autoClose())
        {
            $addHandlers(document, { 'click' : function() { Sys.UI.DomElement.setVisible(this.get_element(), false); } }, this);
            $addHandlers
            (
                this.get_targetTextBox(), 
                { 
                    'click' : function (e) { e.stopPropagation(); }, // This is to prevent the click-handler above from setting visibility to false just after it was set to true
                    'focus' : function() { Sys.UI.DomElement.setVisible(this.get_element(), true); } 
                },
                this
            );
        }
        
        // Bind pager events (if available)
        if (this.get_targetPager() != null)
        {
            this.get_targetPager().add_pageSelected(this.onPageSelected);
            this.get_targetPager().set_visibilityMode(Sys.UI.VisibilityMode.collapse);
        }
        
        // Perform startup search
        if (this.get_startupSearch())
        {
            this.startHumanySearch();
        }
    },
    dispose: function() {
        //Add custom dispose actions here
        TipsCommunity.HumanySearch.callBaseMethod(this, 'dispose');
    },
    startHumanySearch: function(keepShowingPager) {
        // Validate searchfield and other conditions
        if (this.get_targetTextBox().value == '' || this.get_targetTextBox().value == this.get_initialText())
        {
            return;
        }
        if (this.get_isSearching())
        {
            this.set_scheduledSearch(true);
            return;
        }

        // Prepare the new search
        this.set_isSearching(true);
        remainingSearchesCounter++;
        if (this.get_targetPager() != null && !keepShowingPager)
        {
            // Property set_visible doesn't collapse here for some reason, had to use jQuery
            $(this.get_targetPager().get_element()).hide();
        }

        // Show loading section
        var
            $humanySearch = $(this.get_element()),
            $templateTop = this.get_$templatesContainer().find('div.top'),
            $templateLoading = this.get_$templatesContainer().find('div.center-loading'),
            $templateBottom = this.get_$templatesContainer().find('div.bottom'),
            $nextSection;
        $nextSection = $templateTop.clone();
        $nextSection.find('h3').html(humanySearchTypeHeadings[this.get_searchType().toLowerCase()]);
        $humanySearch.empty();
        $humanySearch.append($nextSection);
        $humanySearch.append($templateLoading.clone());
        $humanySearch.append($templateBottom.clone());
            
        if (this.get_autoClose())
        {
            // Control has been set to autoclose mode, so the top element must always be redisplayed
            Sys.UI.DomElement.setVisible(this.get_element(), true);
        }

        // Insert the humany script that will initiate the search
        var scriptID = 'humany-temporary-script' + this.get_id();
        $('#' + scriptID).remove();
        var oScript = document.createElement("script");
        oScript.id = scriptID;
        oScript.type = 'text/javascript';
        oScript.src = String.format
        (
            "http://fritidsresor.humany.com/community/{0}/queryProcessor.php?entry={1}&callerClientID={2}&pageNumber={3}&pageSize={4}&type={5}",
            tuiBrandId == 1 ? 'se' : tuiBrandId == 2 ? 'dk' : tuiBrandId == 4 ? 'no' : 'fi',
            this.get_targetTextBox().value,
            this.get_id(),
            this.get_targetPager() != null ? this.get_targetPager().get_pageNumber() : 1,
            this.get_targetPager() != null ? this.get_targetPager().get_pageSize() : 1,
            this.get_searchType().toLowerCase()
        );
        $(document.body).append(oScript);
    },
    onTargetTextBoxKeyUp: function(e) {
        if (e.keyCode == Sys.UI.Key.enter)
        {
            // Trust outer logic to start the search when pressing Enter, and abort the currently scheduled search
            abortMethodInvocation(this);
        }
        else if (e.keyCode == Sys.UI.Key.up || e.keyCode == Sys.UI.Key.right || e.keyCode == Sys.UI.Key.down || e.keyCode == Sys.UI.Key.left || e.keyCode == Sys.UI.Key.pageUp || e.keyCode == Sys.UI.Key.pageDown)
        {
            // Just ignore
            return;
        }
        else if (e.keyCode == Sys.UI.Key.backspace || e.keyCode == Sys.UI.Key.space || e.keyCode > 31)
        {
            // Valid character pressed
            scheduleMethodInvocation(this, "startHumanySearchGlobal", 50, this.get_id()); 
        }
    },
    onPageSelected: function(sender, args) {
        var thisRef = $get(sender.get_element().associatedSearchID).control;
        thisRef.startHumanySearch(true);
    },
    get_$templatesContainer: function() {
        if (this._$templatesContainer == null)
        {
            this._$templatesContainer = $("#humany-search-templates-container");
        }
        return this._$templatesContainer;
    },
    get_targetTextBox: function() {
        return this._targetTextBox;
    },
    set_targetTextBox: function(value) {
        this._targetTextBox = value;
    },
    get_targetPager: function() {
        return this._targetPager;
    },
    set_targetPager: function(value) {
        this._targetPager = value;
    },
    get_initialText: function() {
        return this._initialText;
    },
    set_initialText: function(value) {
        this._initialText = value;
    },
    get_autoClose: function() {
        return this._autoClose;
    },
    set_autoClose: function(value) {
        this._autoClose = value;
    },
    get_startupSearch: function() {
        return this._startupSearch;
    },
    set_startupSearch: function(value) {
        this._startupSearch = value;
    },
    get_searchType: function() {
        return this._searchType;
    },
    set_searchType: function(value) {
        this._searchType = value;
    },
    get_scheduledSearch: function() {
        return this._scheduledSearch;
    },
    set_scheduledSearch: function(value) {
        this._scheduledSearch = value;
    },
    get_isSearching: function() {
        return this._isSearching;
    },
    set_isSearching: function(value) {
        this._isSearching = value;
    },
    get_faqLink: function() {
        return this._faqLink;
    },
    set_faqLink: function(value) {
        this._faqLink = value;
    },
    get_specialLinkNavigateUrl: function() {
        return this._specialLinkNavigateUrl;
    },
    set_specialLinkNavigateUrl: function(value) {
        this._specialLinkNavigateUrl = value;
    },
    get_specialLinkText: function() {
        return this._specialLinkText;
    },
    set_specialLinkText: function(value) {
        this._specialLinkText = value;
    }
}
TipsCommunity.HumanySearch.registerClass('TipsCommunity.HumanySearch', Sys.UI.Control);



var 
    humanySearchTypeHeadings,
    remainingSearchesCounter = 0;
    
Sys.Application.add_init
(
    function ()
    {
        humanySearchTypeHeadings = 
        {
            "suggest" : globalResourceTextInstance.tipsSearching,
            "country" : globalResourceTextInstance.tipsCountries,
            "destination" : globalResourceTextInstance.tipsDestinations,
            "tiptarget" : globalResourceTextInstance.tipsTipWordInSearch,
            "member" : globalResourceTextInstance.tipsMembers,
            "faq" : globalResourceTextInstance.tipsFaq
        };
    }
);



/* Called globally from a scheduled timeout from each search control */
function startHumanySearchGlobal(clientID)
{
    var thisRef = $get(clientID).control;
    if (thisRef.get_targetPager() != null)
    {
        thisRef.get_targetPager().set_pageNumber(1);
    }
    thisRef.startHumanySearch();
}


/* Humany callback */
function callback(data) 
{
    var 
        thisRef = $get(data.callerClientID).control,
        targetPager = thisRef.get_targetPager(),
        url,
        $humanySearch = $(thisRef.get_element());

    if (targetPager != null)
    {
        targetPager.beginUpdate();
        targetPager.set_totalItems(data.totalItems);
        targetPager.endUpdate();
        
        // Property set_visible doesn't collapse here for some reason, had to use jQuery
        if (targetPager.get_totalPages() > 1 && thisRef.get_visible())
        {
            $(targetPager.get_element()).show();
        }
        else
        {
            $(targetPager.get_element()).hide();
        }
    }

    if (data.totalItems == 0)
    {
        $humanySearch.find('div.center img').remove();
        $humanySearch.find('div.center').html(globalResourceTextInstance.tipsSearchNoResult);
    }
    else
    {
        $humanySearch.empty();

        var 
            item,
            thisType = thisRef.get_searchType().toLowerCase(),
            lastType = null,
            isSuggest = thisRef.get_searchType() == 'Suggest',
            $templateTop = thisRef.get_$templatesContainer().find('div.top'),
            $templateCenter = thisRef.get_$templatesContainer().find('div.center:first'),
            $templateBottom = thisRef.get_$templatesContainer().find('div.bottom'),
            $templateDivider = thisRef.get_$templatesContainer().find('div.divider'),
            $templateDividerHeading = thisRef.get_$templatesContainer().find('div.divider-heading'),
            $nextSection;

        for (var i = 0; i < data.items.length; i++) 
        {
            item = data.items[i];
            
            if (thisRef.get_scheduledSearch())
            {
                remainingSearchesCounter--;
                thisRef.set_isSearching(false);
                thisRef.set_scheduledSearch(false);
                thisRef.startHumanySearch();
                return;
            }

            // TODO: It would be better if humany just sent this information back to us so we don't need this logic
            if (isSuggest)
            {
                // Only need to determine type of each individual item when in 'Suggest' search type mode
                thisType = typeof item.strAlias != 'undefined' ? 'member' : typeof item.locationType != 'undefined' ? (item.locationType == 'TipTarget' ? 'tiptarget' : item.locationType == 'Country' ? 'country' : 'destination') : 'faq';
            }

            // Top, divider or heading section
            if (thisType != lastType)
            {
                // Last search hit type differs from this type - begin a new heading
                $nextSection = i == 0 ? $templateTop.clone() : $templateDividerHeading.clone();

                if (isSuggest)
                {
                    $nextSection.find('h3').html(humanySearchTypeHeadings[thisType]); 

                    if (thisType != 'country') // 'Country' is topmost and should display a close-button instead of a number of tips text
                    {
                        var
                            pagesizeOfType = 1,
                            totalOfType = 1;
                        
                        switch (thisType)
                        {
                            case 'member':
                                pagesizeOfType = data.pagesizeMember;
                                totalOfType = data.totalMember;
                                break;
                            case 'tiptarget':
                                pagesizeOfType = data.pagesizeTiptarget;
                                totalOfType = data.totalTiptarget;
                                break;
                            case 'country':
                                pagesizeOfType = data.pagesizeCountry;
                                totalOfType = data.totalCountry;
                                break;
                            case 'destination':
                                pagesizeOfType = data.pagesizeDestination;
                                totalOfType = data.totalDestination;
                                break;
                            case 'faq':
                                // TODO: Not implemented by Humany yet?
                                break;
                        }

                        $nextSection.find('div.right').html
                        (
                            String.format
                            (
                                "{0} {1} {2} {3}",
                                globalResourceTextInstance.tipsShowing,
                                pagesizeOfType,
                                globalResourceTextInstance.tipsOfLowerCase,
                                totalOfType
                            )
                        );
                    }
                }
                else 
                {
                    $nextSection.find('h3 a').html(humanySearchTypeHeadings[thisType]); 

                    if (targetPager != null)
                    {
                        var 
                            currentItemNumberStart = (targetPager.get_pageNumber() - 1) * targetPager.get_pageSize() + 1,
                            currentItemNumberEnd = Math.min(currentItemNumberStart + targetPager.get_pageSize() - 1, targetPager.get_totalItems());

                        $nextSection.find('div.right').html
                        (
                            String.format
                            (
                                "{0} {1} - {2} {3} <a href='javascript:void(0)' class='all-hits' title='{4}'>{4}</a>",
                                globalResourceTextInstance.tipsShowing,
                                currentItemNumberStart,
                                currentItemNumberEnd,
                                globalResourceTextInstance.tipsOfLowerCase,
                                targetPager.get_totalItems()
                            )
                        );
                    }
                }
            }
            else
            {
                $nextSection = $templateDivider.clone();
            }
            $humanySearch.append($nextSection);
            if (thisRef.get_searchType() == 'Suggest')
            {
                // Important to call show() AFTER the section has been appended to the DOM
                $nextSection.find('a.close').show().click
                ( 
                    function (e) 
                    {
                        e.preventDefault();
                        Sys.UI.DomElement.setVisible(thisRef.get_element(), false);
                        $clearHandlers(thisRef.get_targetTextBox()); // TODO: This unfortunately clears ALL handlers on the subject
                    }
                );
            }
            else
            {
                $nextSection.find('a.all-hits').click
                ( 
                    function (e)
                    {
                        e.preventDefault();
                        var handler = thisRef.get_events().getHandler('showAllHitsClick');
                        if (handler) handler(thisRef, Sys.EventArgs.Empty);
                    } 
                );
            }

            
            // Center section
            $nextSection = $templateCenter.clone();
            $nextSection.addClass(thisType + '-template');
            switch (thisType)
            {
                case 'country' :
                case 'destination' :
                    $nextSection.find('h4 a').html(item.strName).attr('href', item.standardLocationViewUrl);
                    $nextSection.find('div.frame-small img').attr('src', item.locationType == 'Country' ? String.format('/TipsCommunity/Includes/Images/Banners/Large/{0}/{1}.png', item.strCountryCode.charAt(0), item.strCountryCode) : item.thumbnailUrl);
                    $nextSection.find('p.other-info').html(String.format('{0} {3} | {1} {4} | {2} {5}', item.numberOfTips, item.numberOfAuthors, item.numberOfPhotos, globalResourceTextInstance.tipsTip, globalResourceTextInstance.tipsTippers, globalResourceTextInstance.tipsImages));
                    break;
                case 'tiptarget' :
                    $nextSection.find('h4 a').html(item.strName).attr('href', item.standardLocationViewUrl);
                    $create(TUI.Web.UI.WebControls.Rating, { 'imageSize' : TUI.Web.UI.WebControls.RatingStarImageSize.small, 'ratedValue' : item.averageRating == '' ? 0 : item.averageRating, 'allowRating' : false }, null, null, $nextSection.find('span.rating-target').get(0));
                    $nextSection.find('div.frame-small img').attr('src', item.thumbnailUrl);
                    $nextSection.find('p.other-info').html(item.breadCrumbText);
                    $nextSection.find('span.category').html(globalResourceTextInstance.categoryNames[item.categoryName]).addClass(item.categoryName.toLowerCase());        
                    break;
                case 'member' :
                    $nextSection.find('h4 a').html(item.strAlias).attr('href', item.strHomePageUrl);
                    $nextSection.find('div.frame-small img').attr('src', item.strAvatarUrl);
                    $nextSection.find('p.other-info').html(String.format('{0} {2} | {1} {3}', item.numberOfTips, item.numberOfPhotos, globalResourceTextInstance.tipsTip, globalResourceTextInstance.tipsImages));
                    break;
                case 'faq' :
                    $nextSection.empty();
                    $nextSection.html(String.format("<a href='{0}' title='{1}'>{1}</a>", thisRef.get_faqLink(), item.userinput));
                    break;
            }
            $humanySearch.append($nextSection);            
            
            // Bottom section
            if (i == data.items.length - 1)
            {
                $nextSection = $templateBottom.clone();
                if (thisRef.get_specialLinkNavigateUrl() != null && thisRef.get_specialLinkText() != null)
                {
                    $nextSection.find('a').html(thisRef.get_specialLinkText()).attr('title', thisRef.get_specialLinkText()).attr('href', thisRef.get_specialLinkNavigateUrl() + '?searchPhrase=' + encodeURI(thisRef.get_targetTextBox().value));
                }
                $humanySearch.append($nextSection);
            }
            
            lastType = thisType;
        }  
    }
    
    if (thisRef.get_autoClose())
    {
        // Control has been set to autoclose mode, so the top element must always be redisplayed
        Sys.UI.DomElement.setVisible(thisRef.get_element(), true);
    }
    
    thisRef.set_isSearching(false);
    remainingSearchesCounter--;
    
    if (thisRef.get_scheduledSearch())
    {
        thisRef.set_scheduledSearch(false);
        thisRef.startHumanySearch();
    }
    else if (typeof searchComplete != 'undefined')
    {
        // TODO: No! This should be sent via events instead
        searchComplete(remainingSearchesCounter);
    }
}



if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();
