﻿/// <reference name="MicrosoftAjax.js"/>
/// <reference path="~/Scripts/Services.js" />
/// <reference path="/Scripts/Services.js" />

function DSInfoSearchComp(sc) {
    var searchComp = sc;

    function moreLessToggle() {
        sh('#line2');
        sh('#line3');
        sh('#line4');
        sh('#line5');
    }

    function sh(e) {
        var el = $(e, searchComp.mainPanel);
        if (el) {
            if (el.hasClass('hidden'))
                el.removeClass('hidden');
            else
                el.addClass('hidden');
        }
    }

    function loadCountries() {
        var p = searchComp.mainPanel;
        searchComp.tl = $('#Towns', p)[0];
        searchComp.tl.options.length = 0;
        searchComp.tl.disabled = true;
        searchComp.pageNo = 0;
        var cl = $('#Countries', p)[0];
        cl.options.length = 0;
        $.each(window.countryData, function(i, v) {
            var oOption = document.createElement("OPTION");
            cl.options.add(oOption);
            oOption.innerHTML = v;
            oOption.value = i;
        });
        $('#Countries', p).gentleSelect({
            columns: 3,
            itemWidth: 100
        });
    }

    function loadTowns() {
        var p = searchComp.mainPanel;
        searchComp.pageNo = 0;
        var cl = $('#Countries', p)[0];
        if (cl.value.length > 0) {
            DSInfo.Client.Web.Services.GetPlaces(cl.value, function(r) { fillTowns(r); }, townsFailed);
        }
        searchComp.tl = $('#Towns', p)[0];
        searchComp.tl.options.length = 0;
        searchComp.tl.disabled = true;
        updateComps();
    }

    function townsFailed() {
        var p = searchComp.mainPanel;
        $('#Towns', p).attr('disabled', true);
        alert('Error in connection');
    }

    function compsFailed() {
        var p = searchComp.mainPanel;
        $('#comps', p).html("<strong>Error</strong>");
        alert('Error in connection');
    }

    function fillTowns(s1) {
        var p = searchComp.mainPanel;
        var s = [' All'];
        for (var j = 0; j < s1.length; j++)
            if (s1[j]) s.push(s1[j]);
        searchComp.tl = $('#Towns', p)[0];
        searchComp.tl.options.length = 0;
        if (s.length == 0)
            searchComp.tl.disabled = true;
        else {
            searchComp.tl.disabled = false;
            for (var i = 0; i < s.length; i++) {
                var oOption = document.createElement("OPTION");
                searchComp.tl.options.add(oOption);
                oOption.innerHTML = s[i];
                oOption.value = s[i];
            }
        }
        $('#Towns', p).gentleSelect({
            columns: 3,
            itemWidth: 100,
            left: -100,
            top: -100,
            title: 'Select town from the list below'
        }).on('change', function() { updateComps(); });

    }

    function updateComps() {
        searchComp.pageNo = 0;
        updateComps2();
    }

    function updateComps2() {
        var p = searchComp.mainPanel;
        searchComp.onSearchStarts();
        var cl = $('#Countries', p)[0];
        searchComp.tl = $('#Towns', p)[0];
        var town = '';
        if (searchComp.tl.selectedIndex >= 0)
            town = searchComp.tl.value;
        if (town === ' All') town = '';
        var cn = $('#compName', p)[0];
        var sd = '';
        if (typeof(searchComp.txtStartedTillId) != 'undefined')
            sd = $(searchComp.txtStartedTillId, p).val();
        var photos = $(searchComp.cbPhotosId, p).prop('checked');
        var videos = $(searchComp.cbVideosId, p).prop('checked');
        var style = $('#styleList', p).val();
        var status = $('#statusList', p).val();
        var ccountry = $('#CCountries', p).val();
        DSInfo.Client.Web.Services.GetCompetitionList3(cl.value, town, sd, cn.value, searchComp.language, searchComp.pageNo, searchComp.pageSize, photos, videos, style, status, ccountry, searchComp.coupleId, compsLoaded, compsFailed, ++searchComp.tickets.comps);
        $('#comps', p).html('Loading ...<img src="/Pictures/loading3.gif" />');
    }

    function stringBuffer() {
        this.buffer = [];
    }

    stringBuffer.prototype.append = function (string) {
        this.buffer[this.buffer.length] = string;
        return this;
    };

    stringBuffer.prototype.toString = function () {
        return this.buffer.join("");
    };


    function compsLoaded(r, ticket) {
        var p = searchComp.mainPanel;
        if (ticket != searchComp.tickets.comps)
            return;
        var eventTime = 0;

        var ahrefComp = "<a href='/Competition/";
        var aend = "</a>";
        var clinkpage = searchComp.linkToPhotos ? "/Photos.aspx'>" : "/EventList.aspx'>";
        var elinkpage = searchComp.linkToPhotos ? "/Photos.aspx'>" : "/Results.aspx'>";


        var buf = new stringBuffer();

        
        buf.append('<table><tbody>');
        for (var i = 0, rlen = r.length; i < rlen; i++) {
            var c = r[i].Comp;
            var encodedComp = (c.CodedName.length == 0 ? c.Name : c.CodedName) + "_" + c.ID;
            var cPath = ahrefComp + encodedComp;
            buf.append("<tr valign='top'><td >");
            buf.append("<span class='currentCompName'>");
            buf.append(cPath);
            buf.append(clinkpage);
            buf.append(c.Name);
            buf.append(aend);
            buf.append("</span>");

            if (c.Photo > 0 || c.Video > 0) {
                buf.append("<span style='font-weight:normal;padding-left:10px; line-height:18px; font-size: 90%'>");
                if (c.Photo > 0) {
                    buf.append(cPath);
                    buf.append("/Photos.aspx'>");
                    buf.append(searchComp.PhotoWord);
                    buf.append(" (");
                    buf.append(c.Photo);
                    buf.append(")");
                    buf.append(aend);
                    if (c.Video > 0)
                        buf.append(" | ");
                }
                if (c.Video > 0) {
                    buf.append(cPath);
                    buf.append("/Videos.aspx'>");
                    buf.append(searchComp.VideoWord);
                    buf.append(" (");
                    buf.append(c.Video);
                    buf.append(")");
                    buf.append(aend);
                }
                buf.append("</span>");
            }
            buf.append("</td>");
            buf.append("<td style='margin-bottom: 0.2em; color:#900'>" + c.Place + "</td>");
            buf.append("<td style='margin-bottom: 0.2em;'>" + c.Date + "</td>");

            var starfdfsd = new Date();
            if (!searchComp.doNotDisplayEvents) {
                buf.append("</tr><tr><td colspan='3' style='padding-bottom: 20px;'>");
                //var img = c.Sponsors.length == 0 ? "" : "<img src='/Pictures/Sponsors/dsi_logo_small.jpg' style='float:left;padding-right:10px;padding-bottom:3px'>";

                var sponsors = [];
                sponsors[21] = {
                    texts: [
                    'Shoes, accessories, fabrics, dancewear, rhinestones. All your dancing needs.<br /><a href="http://www.dsi-london.com" target="_blank">Visit us on-line</a>',
                    'Couture dresses, DSI Designer Collection, which include the BBC Strictly Come Dancing dresses and practice wear. <a href="http://www.dsi-london.com/site/?action=cat&cat_id=2" target="_blank">Click to browse our collection</a>',
                    'View our comprehensive range of fabrics, including basic, stretch and Austrian laces, sequined, metallic foiled, shirt & trouser fabrics and more... <a href="http://www.dsi-london.com/site/?action=cat&cat_id=6" target="_blank">Browse the selection</a>'
                ],
                    url: "http://www.dsi-london.com",
                    img: "/Pictures/Sponsors/dsi_logo_small.jpg"
                };

                sponsors[11] = {
                    texts: [
                    'Our shoes benefit from two years development with an internationally respected physiotherapist.<br /><a href="http://www.rayrose.com" target="_blank">Visit us on-line</a>',
                    'The shoes in our collection always look great and the action on the foot is exactly what you\'d expect from a high-performance dance shoe. <a href="http://www.rayrose.com" target="_blank">Click to browse our collection</a>',
                    'Our collection is in constant redevelopment, refinement and improvement <a href="http://www.rayrose.com" target="_blank">Browse the selection</a>'
                ],
                    url: "http://www.rayrose.com",
                    img: "/Pictures/Sponsors/Ray-Rose-Logo-small.png"
                };
                var img = "";
                for (var ind = 0; ind < c.Sponsors.length; ind++) {
                    var si = c.Sponsors[ind];
                    var sp = sponsors[si];
                    if(!sp) continue;
                    var randVal = Math.random() * sp.texts.length;
                    var dsiSel = Math.floor(randVal);

                    img += '<p style="font-size:11px" sponsorId="'+si+'"><a href="'+sp.url+'" target="_blank"><img src="'+sp.img+'" style="float:left;padding-right:10px;padding-bottom:3px" /></a>' + sp.texts[dsiSel] + '</p><br />';
                }
                buf.append("<div style='font-size:90%;'>");
                buf.append(img);
                for (var j = 0; j < c.EventDates.length; j++) {
                    var eventDate = c.EventDates[j];
                    if (c.EventDates.length > 1) {
                        buf.append("<div style='color:#333;float:left;'>");
                        buf.append(eventDate.Dow);
                        buf.append("</div> :");
                    }
                    buf.append("<div class='compEventsSubtitles' style='margin-left: 10px'>");
                    for (var k = 0; k < eventDate.Events.length; k++) {
                        var ev = eventDate.Events[k];
                        if (k > 0)
                            buf.append("&nbsp;<b>&middot;</b>&nbsp;");
                        buf.append(cPath);
                        buf.append("/");
                        buf.append(ev.CodedName.length == 0 ? ev.Name : ev.CodedName);
                        buf.append("_");
                        buf.append(ev.ID);
                        buf.append(elinkpage);
                        buf.append(ev.Name);
                        buf.append(aend);
                    }
                    buf.append("</div>");
                }
                buf.append("</td>");
            }
            eventTime += (new Date() - starfdfsd);
            buf.append("</tr>");
        }
        buf.append("</tbody></table>");

        $('#comps', p).html(buf.toString());

        var getidname = function(e) {
            var id = e.attr('href').replace( /^.*_/ , '').replace( /\/.*/ , '');
            var n = e.text();
            return { id: id, name: n };
        };
        $('span.currentCompName a', p).click(
            function() {
                var comp = getidname($(this));
                searchComp.CompId = comp.id;
                searchComp.CompName = comp.name;
                $(searchComp.CompIdId, p).val(comp.id);
                $(searchComp.CompNameId, p).val(comp.name);
                searchComp.EventId = 0;
                searchComp.EventName = '';
                $(searchComp.EventIdId, p).val(0);
                $(searchComp.EventNameId, p).val('');
                return searchComp.onCompSelected(comp.id, comp.name, $(this), comp);
            });
        $('.compEventsSubtitles a', p).click(
            function() {
                var comp = getidname($(this).parents('tr:first').prev().find('a:first'));
                searchComp.CompId = comp.id;
                searchComp.CompName = comp.name;
                $(searchComp.CompIdId, p).val(comp.id);
                $(searchComp.CompNameId, p).val(comp.name);
                var e = getidname($(this));
                searchComp.EventId = e.id;
                searchComp.EventName = e.name;
                $(searchComp.EventIdId, p).val(e.id);
                $(searchComp.EventNameId, p).val(e.name);
                return searchComp.onEventSelected(e.id, e.name, $(this), comp, e);
            });

        searchComp.onUpdated();
    }

    function nextPage() {
        searchComp.pageNo++;
        updateComps2();
        return false;
    }

    function prevPage() {
        if (searchComp.pageNo)
            searchComp.pageNo--;
        updateComps2();
        return false;
    }

    this.initCompSearch = function (btnSearch) {
        var p = searchComp.mainPanel;
        $('#data', p).data('sc', searchComp);
        $('#data', p).data('t', this);
        loadCountries();
        $('.prevPage', p).click(function () {
            prevPage();
            return false;
        });
        $('.nextPage', p).click(function () {
            nextPage();
            return false;
        });
        $('#moreless', p).click(function () {
            moreLessToggle();
            return false;
        });
        $('#Countries', p).gentleSelect({
            columns: 4,
            itemWidth: 100,
            left: -220,
            top: -100
        }).on('change', function () { loadTowns(this); });
        $('#CCountries', p).gentleSelect({
            columns: 4,
            itemWidth: 100,
            left: -220,
            top: -100
        });
        $('#Towns', p).gentleSelect({
            columns: 3,
            itemWidth: 100,
            left: -100,
            top: -100
        }).on('change', function () { updateComps(); });

        $('#styleList', p).gentleSelect({
            columns: 3,
            itemWidth: 100,
            left: -150
        });
        $('#statusList', p).gentleSelect({
            columns: 3,
            itemWidth: 100,
            left: -150
        });
        $(btnSearch, p).click(function () {
            updateComps();
            return false;
        });
        $(searchComp.cbPhotosId, p).change(function () { updateComps(); });
        $(searchComp.cbVideosId, p).change(function () { updateComps(); });
        searchComp.CompId = $(searchComp.CompIdId, p).val();
        searchComp.CompName = $(searchComp.CompNameId, p).val();
        searchComp.EventId = $(searchComp.EventIdId, p).val();
        searchComp.EventName = $(searchComp.EventNameId, p).val();
        this.Refresh = updateComps;
        //updateComps();
    };
}
