﻿/// <reference path="/Scripts/jstorage.js"/>
/// <reference path="/Scripts/Services.js"/>

String.prototype.format12 = function () {
    var formatted = this, i;
    for (i = 0; i < arguments.length; i++) {
        formatted = formatted.replace("{" + i + "}", arguments[i]);
    }
    return formatted;
};

String.format = String.prototype.format = function () {
    var formatted = arguments[0], i;
    for (i = 1; i < arguments.length; i++) {
        formatted = formatted.replace(new RegExp("\\{"+(i-1)+"\\}","g") , arguments[i]);
    }
    return formatted;
};

$.fixDate = function (data) {
    if (data) {
        $.each(data, function (id, value) {
            if (typeof (value) === 'string' && value.substring(0, 6) === '/Date(') {
                data[id] = new Date(parseInt(value.substr(6)));
            } else if (typeof (value) === 'object') $.fixDate(value);
        });
    }
};

function Service(path, func, d, onSuccess, onFailure, context) {
    $.ajax({
        type: "POST",
        url: (path ? path : "/Services.asmx") + "/" + func,
        cache: false,
        contentType: "application/json; charset=utf-8",
        data: $.toJSON(d),
        dataType: "json",
        success: function (r) {
            $.fixDate(r); if (onSuccess) onSuccess(r, context);
        },
        error: function (r) {
            if (onFailure) onFailure(r, context);
        }
    });

}

function MSService(path, func, d, onSuccess, onFailure, context) {
    Service(path, func, d,
        function (r, ctx) {
            onSuccess(r?r.d:null, ctx);
        },
        function (r, ctx) {
            onFailure(r, ctx);
        }, context);
}

if (top && top.location && top.location != document.location) {
    top.location = document.location;
}
String.prototype.trim = function() { return $.trim(this); };
Date.__c_p = Date.parse; Date.parse = function (s) { try { return Date.__c_p(s); } catch (e) { var d = Date._jsParse(s); if (d) { return d; } else { throw e; } } };
Date.parseLocale = function(d) { return new Date(Date.parse(d)); };
__doPostBack = function (eventTarget, eventArgument) {
    if (!window.theForm.onsubmit || (window.theForm.onsubmit() != false)) {
        window.theForm.__EVENTTARGET.value = eventTarget;
        window.theForm.__EVENTARGUMENT.value = eventArgument;
        $("form").trigger("submit");
    }
};
var translDict = {};
$.fn.translate = function (lan) {
    var o = { t: $(this), l: [] };
    var f = function (o1) {
        $('.translatable', o1.t).each(function () {
            var a = $(this).attr('tid');
            var t = translDict[a];
            if (t) $(this).text(t);
        });
    };
    $('.translatable', o.t).each(function () { var a = $(this).attr('tid'); if (!translDict[a]) o.l.push(a); });
    if (o.l.length) {
        Service('', 'GetTranslations', { lang: lan || window.pageLanguage || '', tids: o.l },
			function (r, o1) {
			    for (var i = 0; i < o1.l.length; i++) translDict[o1.l[i]] = r.d[i];
			    f(o1);
			},
			function () {
			    alert('Translation failed');
			}, o);
    }
    else f(o);
};

var IE6 = false;///*@cc_on || @_jscript_version < 5.7@*/;

if (!$(window).data('events')) $(window).data('events', []);

// Initialize all calendar inputs
$(function () {
    var el = $('.datepicker');
    el.each(function () {
        $(this).data('orgDate', $(this).val());
    }).datepicker({
        changeMonth: true,
        //        changeYear: true,
        showAnim: 'fadeIn',
        yearRange: '-110:+5',
        dateFormat: 'd M yy'
    });
    el.datepicker('option', $.datepicker.regional[window.pageLanguage || ''])
	.datepicker('option', { changeYear: true, dateFormat: 'd M yy' }).each(
		function () {
		    var od = $(this).data('orgDate').replace(/-/g, ' ');
		    if (od)
		        $(this).datepicker('setDate', od);
		});
});

function CheckValidUrl(strUrl) {
    var regexUrl = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/ ;
    return regexUrl.test(strUrl);
}


Controtex = {};
Controtex.AuthManager = {};
Controtex.Lib = {};

DSInfo = {};
Controtex.ModalManager = {
    initialized: false,

    background: null,
    dialog: null,

    ShowDialog: function () {
        if (!this.dialog) {
            this.dialog = $('#logInPanel');
            this.dialog.dialog({ dialogClass: 'modalDialog', modal: true, title: 'Locked feature', width: 400, autoOpen: false });
            this.dialog.parent().css('position', 'fixed');
            if (IE6) {
                $(window).scroll(function () { $('#logInPanel').dialog("option", "position", "center"); });
            }
            $('#_logCancel').click(function () { return Controtex.ModalManager.HideDialog(); });
            this.dialog.keypress(function (event) {
                if (event.keyCode == 13 || event.charCode == 13) { $('#_logButton').click(); return false; }
                else return true;
            });
        }
        this.dialog.dialog('open');

        return false;
    },
    HideDialog: function () {
        if (this.dialog) this.dialog.dialog('close');
        return false;
    }
};
Controtex.AuthManager.Current = {

    LoadRoles: function () {
    },

    IsInRoles: function (levels) {
        var lvls = levels.split(',');
        for (var i = 0; i < lvls.length; i++) {
            for (var j = 0; j < this._roles.length; j++)
                if (this._roles[j] == lvls[i])
                    return true;
        }
        return false;
    },

    Levels: {
        'U': { val: 1, name: 'User', msg1: 'You must be a user to access this feature.', msg2: 'If you are a user, please log in below' },
        'S': { val: 2, name: 'Silver Member', msg2: 'You must be a member to access this feature.' },
        'G': { val: 3, name: 'Gold Member' },
        'P': { val: 4, name: 'Platinum Member' },
        'H': { val: 5, name: 'Honorary Member' },
        'M': { val: 2, name: 'Member' },
        'A': { val: 100, name: 'Administrator' },
        msg1: '<p>You must be a {0} to access this feature.</p>',
        msg2: '<p>If you are a {0}, please log in below</p>',
        umsg: "<p>If you are not a user, you can <a href='/CreateUser.aspx'>create a <strong>free</strong> user account</a>. If you want to get more out of dancesportinfo, you can also <a href='/Membership_Details.aspx'>become a member</a>.</p>",
        mmsg: "<p>If you are not a member you must <a href='/Membership_Details.aspx'>become a member</a> to continue.</p>",
        notsuf: 'Your access level is not sufficient. Try another user name, if possible.'
    },

    CheckLevel: function (level, onSufficientLevel, onInsufficientLevel) {
        if (!level) {
            return onSufficientLevel();
        }

        if (!this._roles) {
            var ctx = this;
            Service('', 'GetLoginDetails', {},
                function (result) {
                    ctx._roles = result.d.Roles || [];
                    ctx._member = result.d.Member;
                    ctx.CheckLevel(level, onSufficientLevel, onInsufficientLevel);
                },
                function (error) {
                    alert(error.get_message());
                });
            return false;
        }
        var levels = this.Levels[level.charAt(0)].val || 0;
        levels--;

        if (levels == -1 || (levels == 1 && this.IsInRoles("Everyone")) || (levels == 99 && this.IsInRoles("Administrators")) || (levels < 99 && this._member && this._member.Level >= levels))
            onSufficientLevel();
        else {
            if (this._member && this._member.Level >= 1) // already logged in
                alert(this.Levels.notsuf);
            onInsufficientLevel();
        }
        return false;
    },

    DisplayPanel: function (level, delegate) {
        var panel = $('#logInPanel');
        var l = this.Levels;
        var name = l[level].name;
        panel.find('#_logDesc').html(l.msg1.format12(name) + l.msg2.format12(name));
        panel.find('#_logReg').html((level == 'U' || level == 'H') ? l.umsg : l.mmsg);
        $('#fb-root').data('fb', { scope: this, level: level, delegate: delegate });
        $('#_logButton').unbind('click').click(function () { return Controtex.AuthManager.Current.LogIn(level, delegate); });


        //        $(panel).keypress(function (event) {
        //            if (event.keyCode == 13 || event.charCode == 13) {
        //                event.cancelBubble = true;
        //                if (event.stopPropagation) event.stopPropagation();
        //                if (event.preventDefault) event.preventDefault();
        //                $('#_logButton').click(); return false;
        //            }
        //            else if (event.keyCode == 27 || event.charCode == 27) {
        //                event.cancelBubble = true; if (event.stopPropagation) event.stopPropagation();
        //                Controtex.ModalManager.HideDialog(); return false;
        //            }
        //            else return true;
        //        });


        Controtex.ModalManager.ShowDialog();
        $('#userName').focus();
    },

    AttemptAccess: function (level, delegate) {
        this.CheckLevel(level, delegate, function () { return Controtex.AuthManager.Current.DisplayPanel(level, delegate); });
        return false;
    },

    LogIn: function (level, delegate) {
        var ctx = { scope: this, level: level, delegate: delegate };
        $('#_logChecking').show();
        DSInfo.Client.Web.Services.Login($('#userName').val().trim(), $('#password').val(), false,
            function (validCredentials) {
                $('#_logChecking').hide();
                if (!ctx || !ctx.scope) return;
                var wrong = !validCredentials;
                $('#_logWrong').toggle(wrong);
                if (wrong) return;
                Controtex.ModalManager.HideDialog();
                if(ctx && ctx.scope) ctx.scope._roles = null;
                Controtex.AuthManager.Current.AttemptAccess(ctx.level, ctx.delegate);
            },
            function (error) {
                $('#_logChecking').hide();
                alert(error.get_message());
            }, ctx);
    }

};
var Images = [];

function imageListLoad(t, imageList, domain, delay, startInd) {
    if (!t.ImgList) {
        t = $(t).wrap('<div style="position: relative"></div>').parent();

        t.Domain = domain;
        t.Delay = delay;
        if (!imageList || imageList == '') {
            t.ImgList = 'no';
            return;
        }
        t.ImgNameList = decodeHTML(unescape(imageList)).split(';');
        t.ImgList = [];
        t.maxHeight = 0;
        for (var i = 0; i < t.ImgNameList.length; i++) {
            t.ImgList[i] = new Image();
            t.ImgList[i].src = t.Domain + t.ImgNameList[i];
            t.maxHeight = Math.max(t.maxHeight, $(t.ImgList[i]).height());
            $(t.ImgList[i]).css({ position: "absolute", top: "0", left: "0" });
        }
        t.height(t.maxHeight);
        t.ImgIdx = startInd;
        ind = Images.length;
        Images[ind] = t;
        setInterval("switchImage(" + ind + ");", t.Delay);
    }
}

function switchImage(i) {
    var t = Images[i];
    if (t.ImgIdx >= t.ImgNameList.length) t.ImgIdx = 0;

    var parent = t;
    var curImg = $("img", t);
    var targetImg = $(t.ImgList[t.ImgIdx]).css("opacity", 0);
    parent.append(targetImg);

    parent.maxHeight = Math.max(t.maxHeight, targetImg.width());

    curImg.stop().animate({ opacity: 0 }, 2000, function () { curImg.remove(); });
    targetImg.stop().animate({ opacity: 1 }, 2000);
    parent.stop().animate({ width: targetImg.width(), height: parent.maxHeight }, 2000);

    t.ImgIdx++;
}

function urlencode(str) {
    return escape(str).replace(/\+/g, '%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/@/g, '%40');
}
function decodeHTML(str) {
    return str.replace(/&amp;/g, '&').replace(/&quot;/g, '"').replace(/&lt;/g, '<').replace(/&gt;/g, '>');
}



function ClientHide(el) {
    $(el).hide();
}

function ClientShow(el) {
    $(el).show();
}
function ClientVisible(el, v) {
    $(el).toggle(v ? true : false);
}

function IsClientVisible(el) {
    return $(el).isvisible();
}

var specChars = new Array('&AElig;', 'Æ', '&Aacute;', 'Á', '&Acirc;', 'Â', ' &Agrave;', 'À', '&Aring;', 'Å', '&Atilde;', 'Ã', '&Auml; ', 'Ä', '&Ccedil;', 'Ç', '&ETH;', 'Ð', '&Eacute;', 'É', '& Ecirc;', 'Ê', '&Egrave;', 'È', '&Euml;', 'Ë', '&Iacute;', 'Í', '&Icirc;', 'Î', '&Igrave;', 'Ì', '&Iuml;', 'Ï', '&N tilde;', 'Ñ', '&Oacute;', 'Ó', '&Ocirc;', 'Ô', '&Ograve; ', 'Ò', '&Oslash;', 'Ø', '&Otilde;', 'Õ', '&Ouml;', 'Ö', ' &THORN;', 'Þ', '&Uacute;', 'Ú', '&Ucirc;', 'Û', '&Ugrave ;', 'Ù', '&Uuml;', 'Ü', '&Yacute;', 'Ý', '&aacute;', 'á', '&acirc;', 'â', '&aelig;', 'æ', '&agrave;', 'à', '&aring ;', 'å', '&atilde;', 'ã', '&auml;', 'ä', '&brvbar;', '¦', '&ccedil;', 'ç', '&cent;', '¢', '&copy;', '©', '&deg;', ' °', '&eacute;', 'é', '&ecirc;', 'ê', '&egrave;', 'è', '&e th;', 'ð', '&euml;', 'ë', '&frac12;', '½', '&frac14;', '¼ ', '&frac34;', '¾', '&gt;', '>', '&gt', '>', '&iacute;', ' í', '&icirc;', 'î', '&iexcl;', '¡', '&igrave;', 'ì', '&iq uest;', '¿', '&iuml;', 'ï', '&laquo;', '«', '&lt;', '<', ' &lt', '<', '&mdash;', '—', '&micro;', 'µ', '&middot;', '· ', '&ndash;', '–', '&not;', '¬', '&ntilde;', 'ñ', '&oacut e;', 'ó', '&ocirc;', 'ô', '&ograve;', 'ò', '&oslash;', 'ø', '&otilde;', 'õ', '&ouml;', 'ö', '&para;', '¶', '&plusmn;', '±', '&pound;', '£', '&quot;', '\"', '&r aquo;', '»', '&reg;', '®', '&sect;', '§', '­', '*', '&sup1 ;', '¹', '&sup2;', '²', '&sup3;', '³', '&szlig;', 'ß', '&t horn;', 'þ', '&tilde;', '˜', '&trade;', '™', '&uacute;', 'ú', '&ucirc;', 'û', '&ugrave;', 'ù', '&uuml;', 'ü', '&ya cute;', 'ý', '&yen;', '¥', '&yuml;', 'ÿ');
function htmlEncode(text) {
    text = text.replace(eval('/&/g'), '&amp;');
    text = text.replace(eval('/"/g'), '&quot;');
    return (text);
}
function htmlDecode(text) {
    text = text.replace(eval('/&amp;/g'), '&');
    text = text.replace('&quot;', eval('/"/g'));
    return (text);
}

function menuLoaded(r) {
    var m = eval('(' + r + ')');
    menuLoaded2(m);
}
function menuLoaded2(m) {
    var html = '<div class="AspNet-Menu-Horizontal"><ul class="AspNet-Menu">';
    html += buildLevel(m);
    html += '</ul></div>';
    $('#menubar').html(html);
}
function buildLevel(m) {
    var locHtml = '';
    for (var i = 0; i < m.Children.length; i++) {
        var c = m.Children[i];
        locHtml += String.format('<li class="AspNet-Menu-{0}">', (c.Children.length == 0) ? "Leaf" : "WithChildren");
        if (c.Url != '')
            locHtml += String.format('<a href="{0}" class="AspNet-Menu-Link" title="{1}">{2}</a>', c.Url, c.Description, c.Text);
        else
            locHtml += String.format('<span class="AspNet-Menu-NonLink">{0}</span>', c.Text);
        if (c.Children.length > 0) {
            locHtml += '<ul>';
            locHtml += buildLevel(c);
            locHtml += '</ul>';
        }
        locHtml += '</li>';
    }
    return locHtml;
}
function menuLoadedFailed(r) {
    alert("Error loading menu.\r\n" + r);
}

DSInfo.GetPointBalance = function (ok, fail) {
    DSInfo.Client.Web.Services.GetPointBalance(ok, fail);
};

String.prototype.startsWith = function (str) {
    return (this.match("^" + str) == str);
};

function restrictlinks() {
    var el = $('a.[roles]');
    el.each(function () {
        var $this = $(this);
        var lvl = $this.attr('roles');
        var href = $this.attr('href'); $this.attr('href', '#');
        $this.attr('onclick', null);
        $this.click(function () {
            var f;
            if (href.startsWith('javascript:'))
                f = function () { eval(href.replace('javascript:', '')); };
            else
                f = function () { document.location = href; };
            Controtex.AuthManager.Current.AttemptAccess(lvl, f);
            return false;
        });

    });
}

getSilverlight = function () {
    var slVersion;
    function version() {
        try {
            try {

                var control = new ActiveXObject('AgControl.AgControl');

                if (control.IsVersionSupported("4.0"))
                    slVersion = 4;
                else
                    if (control.IsVersionSupported("3.0"))
                        slVersion = 3;
                    else
                        if (control.IsVersionSupported("2.0"))
                            slVersion = 2;
                        else
                            slVersion = 1;
            }

            catch (e) {
                var plugin = navigator.plugins["Silverlight Plug-In"];

                if (plugin) {

                    if (plugin.description === "1.0.30226.2")
                        slVersion = 2;

                    else
                        slVersion = parseInt(plugin.description[0]);
                }
                else
                    slVersion = 0;
            }
        }

        catch (e) {
            slVersion = 0;
        }
        return slVersion;
    }
    return {
        Version: version
    };
} ();

// read and report Silverlight version
$(function () {
    return;
// ReSharper disable JsUnreachableCode
// ReSharper disable AssignedValueIsNeverUsed
    var x = getSilverlight.Version();
// ReSharper restore AssignedValueIsNeverUsed
    DSInfo.Client.Web.Services.LogSL(x);
// ReSharper restore JsUnreachableCode
});


var TopMenu = { cache: {} };
$(function () {
    var tmp = '.edtSearch';
    TopMenu.el = $(tmp);
    TopMenu.el.autocomplete({
        source: function (request, response) {
            TopMenu.zIndex = TopMenu.el.css('zIndex');
            TopMenu.el.css('zIndex', 35000);
            if (TopMenu.cache.term == request.term && TopMenu.cache.content) {
                response(TopMenu.cache.content);
                return;
            }
            if (new RegExp(TopMenu.cache.term).test(request.term) && TopMenu.cache.content && TopMenu.cache.content.length < 13) {
                response($.ui.autocomplete.filter(TopMenu.cache.content, request.term));
                return;
            }
            Service('', 'GetSearchSuggestions', { q: request.term },
			function (data) {
			    TopMenu.cache.term = request.term;
			    TopMenu.cache.content = data.d;
			    response(data.d);
			}
		);
        },
        minLength: 3,
        close: function () { TopMenu.el.css('zIndex', TopMenu.zIndex); }

    });
}
);


// Like button
function LikeControl_setDisp(t) {
    var tn = t.siblings('.likeList');
    var ts = t.siblings('.likeSeparator');
    var l = t.attr('likes');
    if (!l) {
        tn.hide(); ts.hide();
        return;
    }
    var tid = t.attr('likeType');
    var id = t.attr('likeId');
    if (!tn.attr('fmt')) tn.attr('fmt', tn.text());
    tn.text(tn.attr('fmt').format12(l));
    tn.show(); ts.show();
    tn.unbind('handlerIn handlerOut')
				.mouseenter(function () {
				    Service('', 'GetLikeList', { likeType: tid, likeId: id },
						function (r) {
						    var el = $('<div class="popmsg"></div>');
						    if (r.d.length == 0) el.text('');
						    else {
						        var txt = r.d[0].UserName;
						        for (var i = 1; i < r.d.length; i++)
						            txt = txt + '<br/>' + r.d[i].UserName;
						        el.html(txt);
						        LikeControl_setpopup(el, tn.offset());
						        $.doTimeout(3000, function () { el.fadeOut(3000, function () { el.remove(); }); });
						    }
						},
						function () {
						}
						);
				})
				.mouseleave(function () {
				    LikeControl_clearpopups();
				});
}
var LikeControl_clearpopups = function () {
    $('.popmsg').remove();
};

function LikeControl_setpopup(el, pos, c) {
    LikeControl_clearpopups();
    $('body').append(el);
    pos.left += 50;
    pos.top += 20;
    if (c) el.css(c);
    el.css(pos);
    el.topZIndex();
}

function Init_Likes(sel) {
    var setpopup = function (el, pos, c) {
        LikeControl_setpopup(el, pos, c);
    };
    var showRes = function (t, txt) {
        var el = $('<div class="popmsg">' + txt + '</div>');
        setpopup(el, t.offset(), { width: 'auto' });
        $.doTimeout(2000, function () { el.fadeOut(1500, function () { el.remove(); }); });
    };

    var setDisp = function (t) {
        LikeControl_setDisp(t);
    };
    var clickLike = function (t) {
        setDisp(t);
        Service('', 'SetLike', { likeType: t.attr('likeType'), likeId: t.attr('likeId') },
            function (r) {
                if (r.d < 0) {

                }
                var txt = 'You have already marked it';
                if (r.d) {
                    t.attr('likes', r.d);
                    setDisp(t);
                    txt = 'Thank you';
                }
                showRes(t, txt);
            },
            function () {
            }
        );  // end Service call
    };
    $(sel).each(function () {
        setDisp($(this));
    });
    $(sel).click(function () {
        var t = $(this);
        Controtex.AuthManager.Current.AttemptAccess('U', function () { clickLike(t); return false; });
        return false;
    }).unbind('handlerIn handlerOut').
	  mouseenter(function () {
	      var t = $(this);
	      var el = $('<div class="popmsg"></div>');
	      var txt = 'Click here to like this';
	      el.text(txt);
	      setpopup(el, t.offset());
	      el.css('background-color', '#fff');
	  }).
	   mouseleave(function () {
	       $('.popmsg').fadeOut(1000, function () { LikeControl_clearpopups(); });
	   });

    return false;
}

$(function () { Init_Likes('.likeButton'); });


$.fn.bannerAdvert = function (opts) {
    function getAd(ad) {
        function showAd(res) {
            if (!res.data.length) {
                //adv.hide();
                ad.html('');
                return;
            }
            opts1.cache.ind = (opts1.cache.ind + 1) % opts1.maxCnt;
            var t = [$("<script><a href='/recordBannerStat.aspx?advId={{=id}}' refid={{=id}} adType=0><img src='/li.aspx?Path={{=bannerLocation}}' /></a></script>"),
                $("<script><td class='textadvert'><div class='textAd'><img id='imgImage' style='width:80px; imagealign:middle' src='{{=Image}}'><span>{{=Text}}</span><br><a id='lnkAdvert' href='{{=Link}}' refid={{=id}} adType=1>{{=LinkText}}</a></div></td></script>"),
                $("<script><div class='textadvert'><div class='textAd'><img id='imgImage' style='width:80px; imagealign:middle' src='{{=Image}}'><span>{{=Text}}</span><br><a id='lnkAdvert' href='{{=Link}}' refid={{=id}} adType=2>{{=LinkText}}</a></div></div></script>")
            ];
            window.gotopage = null;
            if (res.type === 1) { // if those are exhibits in middle box
                ad.html($("<table><tr/></table>")); // create surrounding table
                ad.find('tr').html(t[res.type].tmpl(res.data)); // and fill it with one row, several td's
            } else {
                if (res.data[0].flashLocation) {
                    var tmpl = $('#pnFlash').tmpl(res.data);
                    ad.html(tmpl);
                    window.gotopage = function () {
                        document.location = '/recordBannerStat.aspx?advId=' + res.data[0].id;
                    };
                }
                else
                    ad.html(t[res.type].tmpl(res.data)); // just fill-in standard advert
            }
            if (res.data[0].flashLocation)
                opts1.delay = 0;
            if (opts1.delay) {
                $.doTimeout(opts1.delay > 1000 ? opts1.delay : (1000 * opts1.delay), function () { getAd(ad); });
            }
        }
        var opts1 = ad.data('boptions');
        if (!opts1.cache) opts1.cache = { ind: 0 };
        if (opts1.cache[opts1.cache.ind]) {
            showAd(opts1.cache[opts1.cache.ind]);
        }
        else {
            var rt = Math.floor(Math.random() * 100);
            // if this is a middle box with some probability choose list of text adverts (shop exhibits)
            if (rt < opts1.tprop && (opts1.shape == 4) || opts1.type === 2) {
                Service('', 'GetTextAdvertSet', { cnt: opts1.tcnt || 3 },
                    function (r) {
                        var res = opts1.cache[opts1.cache.ind] = { type: opts1.type || 1, data: r.d };
                        showAd(res);
                    },
                    function (r) {
                        var err = r;
                        //alert('');
                    });
            } else {
                Service('', 'GetAdvertSet', { shape: opts1.shape, language: window.pageLanguage||'', countryCode: window.currentCountryId, cnt: opts1.cnt },
                    function (r) {
                        var res = opts1.cache[opts1.cache.ind] = { type: 0, data: r.d };
                        showAd(res);
                    },
                    function (r) {
                        var err = r;
                        //alert('');
                    });
            }
        }
    };
    var defaults = { shape: 2, cnt: 1, delay: 0, maxCnt: 1, tprob: 50 };
    var o = $.extend({}, defaults, opts);
    var adv = $(this);
    adv.data('boptions', o);
    if (o.disableHeader) adv.find('.bannerheader').hide();
    getAd(adv);
};

DSInfo.ShowCoupleSearch = function (opt) {
    var gcs = '#globalCoupleSearch';
    var el = $(gcs + ' .searchCouple');
    var ok = 0;
    el.coupleSearch({
        onSelected: function (ctx, scpl) {
            ok = 1;
            if (opt.onSelected)
                opt.onSelected(scpl);
            if (!opt.keepOpen)
                $(gcs).dialog('close');
            return false;
        }
    });
    $(gcs).dialog('open');
    $(gcs).dialog({ close: function () {
        if (!ok && opt.onCancel) opt.onCancel();
    }
    });
};
DSInfo.ShowCompSearch = function (opt) {
    var gcs = '#globalCompSearch';
    var sc = $('#data', gcs).data('sc');
    var t = $('#data', gcs).data('t');
    var ok = 0;
    sc.onCompSelected = function (id, name, t, c) {
        ok = 1;
        if (opt.onCompSelected)
            opt.onCompSelected(id, name, t, c);
        if (!opt.keepOpen)
            $(gcs).dialog('close');
        return false;
    };
    sc.onEventSelected = function (id, name, t, c, e) {
        ok = 1;
        if (opt.onEventSelected)
            opt.onEventSelected(id, name, t, c, e);
        if (!opt.keepOpen)
            $('#globalCompSearch').dialog('close');
        return false;
    };
    $(gcs).dialog('open').dialog({ close: function () {
        if (!ok && opt.onCancel) opt.onCancel();
    }
    });
    t.Refresh();
};


