﻿function NewSite() {
    $('#newsite').slideDown(
        'slow', function() { $(this).css('border', 'solid 2px #e0e0e0'); }
    );
    setTimeout("CloseNewSite();", 10000);
}

function CloseNewSite() {
    $('#newsite').slideUp();
}

jQuery.fn.maxLength = function(max) {
    this.each(function() {
        var box; var pos; var actualWidth; var actualHeight;
        $(this).focus(function() {
            box = $('<div style="background-color: black;color:white;padding:4px;font-weight:bold;"><div><span id="ct"></span>&nbsp;chars left</div></div>');
            pos = $.extend({}, $(this).offset(), { width: $(this).width(), height: $(this).height() + 20 });
            box.remove().css({ top: -200, left: -200, display: 'block' }).appendTo(document.body);
            box.css({ position: 'absolute', zIndex: 100000, opacity: 0.8 });
            actualWidth = box[0].offsetWidth, actualHeight = box[0].offsetHeight;
            box.css({ top: pos.top - 8, left: pos.left + pos.width + 4 });
            if ($(this).val() != "") { $('#ct').html((max - $(this).val().length).toString()); }
            else $('#ct').html(max.toString());
        }).blur(function() {
            box.remove();
        });

        var type = this.tagName.toLowerCase();
        var inputType = this.type ? this.type.toLowerCase() : null;
        if (type == "input" && (inputType == "text" || inputType == "password")) {
            //this.maxLength = max;
            this.onkeypress = function(e) {
                var ob = e || event; var keyCode = ob.keyCode;
                var hasSelection = document.selection ? document.selection.createRange().text.length > 0 : this.selectionStart != this.selectionEnd;
                return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection);
            };
            this.onkeyup = function() {
                if ($(this).val().length >= max) $('#ct').text("0");
                else $('#ct').text((max - $(this).val().length).toString());
                if (this.value.length > max) { this.value = this.value.substring(0, max); }
            };

        }
        else if (type == "textarea") {
            this.onkeypress = function(e) {
                var ob = e || event; var keyCode = ob.keyCode; var hasSelection = document.selection ? document.selection.createRange().text.length > 0 : this.selectionStart != this.selectionEnd;
                return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection);
            };
            this.onkeyup = function() {
                if ($(this).val().length >= max)
                { $("#ct").text("0"); }
                else
                { $("#ct").text((max - $(this).val().length).toString()); }
                if (this.value.length > max) { this.value = this.value.substring(0, max); }
            };
        }
    });
};


$.fn.clearForm = function() {
    return this.each(function() {
        $(':input', this).each(function() {
            var type = this.type, tag = this.tagName.toLowerCase();
            if (type == 'text' || type == 'password' || tag == 'textarea') this.value = '';
            else if (type == 'checkbox' || type == 'radio') this.checked = false;
            else if (tag == 'select') this.selectedIndex = -1;
        });
    });
};

jQuery.fn.maxLengthOld = function(max) {
    this.each(function() {
        var type = this.tagName.toLowerCase();
        var inputType = this.type ? this.type.toLowerCase() : null;
        if (type == "input" && inputType == "text" || inputType == "password") {
            this.maxLength = max;
        }
        else if (type == "textarea") {
            this.onkeypress = function(e) {
                var ob = e || event;
                var keyCode = ob.keyCode;
                var hasSelection = document.selection ? document.selection.createRange().text.length > 0 : this.selectionStart != this.selectionEnd;
                return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection);
            };
            this.onkeyup = function() {
                if (this.value.length > max) {
                    this.value = this.value.substring(0, max);
                }
            };
        }
    });
};

/**********************************************************************
    Error!
**********************************************************************/
function ExtensionOkayForType(extension, type) {
    var e = extension.toString().toLowerCase();
    var t = type.toLowerCase();

    if (t == "image" || t == "gift" || t == "picture") {
        if (e != "jpg" && e != "gif" && e != "png") { return false; }
    } else if (t == "video") {
        if (e != "mpg" && e != "wmv" && e != "avi" &&
            e != "mov" && e != "mp4" && e != "flv") { return false; }
    } else if (t == "audio") {
        if (e != "wav" && e != "mp3" && e != "aiff" ) { return false; }
    }
    
    return true;
}


function ShowHint(name) {
    $('embed,object').hide(); // Hide any flash which will peak through our popup
    $.facebox({ ajax: "/AjaxCommands/Hint.aspx?name=" + name });
    return false;
}

function ReportAbuse() {
    $('embed').hide(); // Hide any flash which will peak through our popup
    $.facebox({ ajax: "/AjaxCommands/ReportAbuse.aspx?url=" + window.location.href });
    return false;
}

function HideTipsy() {
    $('.tipsy').each(function() { $(this).remove(); });
 }

function PopupError(msg) {
    jQuery.facebox({ ajax: '/AjaxViews/AjaxError.aspx?m=' + msg });
}


function showError(element, dir, msg) {
    $("'" + element + "'").tipsy({gravity:"'" + dir + "'", title: "'" + msg + "'"} );
}

function showErrorIfEmpty(element, dir, msg) {
    if ( $(element).val() == "" ) {
        $(element).tipsy({ gravity: dir, title: msg });
        return false;
    }
    return true; // was okay
}


function Notification(msg) {
    jQuery.facebox(msg);
    return false;
}

/**********************************************************************
   Game Library
**********************************************************************/

function ShowGameInfo(id) {
    jQuery.facebox({ ajax: '/AjaxViews/GameInfo.aspx?id=' + id });
    return false;
}

function DownloadGame(id) {

}


/**********************************************************************
  Invite codes
**********************************************************************/
function ViewOnlineRequest(id) {
    jQuery.facebox({ ajax: '/Online/ViewRequest.aspx?id=' + id});
    return false;
}

function ShowInviteInfo(iid, id) {
    jQuery.facebox({ ajax: '/AjaxViews/InviteInfo.aspx?iid=' + iid + '&id=' + id });
    return false;
}



function PlayGame(id, inviteId) {
    $.ajax({
        url: '/AjaxCommands/UserPlayGame.aspx?g=' + id + '&i=' + inviteId,
        cache: false,
        dataType: "html",
        success: function(data) {
            window.location = "/Game/View.aspx?g=" + id;
        },
        error: function(e, txt, data) {
            window.location = "/Tokens/Buy.aspx?r=true";
        }
    });
}

function RefuseGame(id,inviteId) {
    $.ajax({
        url: '/AjaxCommands/UserRefuseGame.aspx?g=' + id + '&i=' + inviteId,
        cache: false,
        dataType: "html",
        success: function(data) {
            window.location = "/User/View.aspx";
        },
        error: function(e, txt, data) {
            window.location = "/Tokens/Buy.aspx?r=true";
        }
    });
}

function DeleteGame(id) {
    $.facebox({ajax: '/AjaxViews/GameDelete.aspx?g=' + id});
    return false;
}

function ShowSendInvite(fid, gid) {
    if (gid == "" || fid == "") return false;
    jQuery.facebox({ ajax: '/AjaxViews/InviteToGame.aspx?fid=' + fid + '&gid=' + gid });
    return false;
}

function SendInvite() {
    var fid = $('._friendId').val();
    var gid = $('._ddlGames').val();
    if (gid == "") return;
    return SendInviteInternal(fid, gid, false);
}

function SendInviteInternal(fid, gid, gift) {
    $.ajax({
        type: "POST",
        url: "/AjaxCommands/SendInvite.aspx",
        data: "fid=" + fid + "&gid=" + gid + "&gift=" + gift.toString(),
        beforeSend: function() {
        },
        success: function(msg) {
            $.facebox(msg);
        },
        error: function(XMLHttpRequest, textStatus, errorThrow) {
            PopupError("Failed to send the invite");
        }
    });
    return false;
}


function SimpleBlock(fid) {
    $.ajax({
        type: "POST",
        url: "/AjaxCommands/CreateBlock.aspx",
        data: "t=" + fid,
        success: function(msg) {
            window.location.href = "/User/View.aspx";
        },
        error: function(XMLHttpRequest, textStatus, errorThrow) {
            PopupError("Failed to block that user, please try later.");
        }
    });
    return false;
}

function BlockUserBeingViewed() {
    var fid = $('._friendId').val();
    $.ajax({
        type: "POST",
        url: "/AjaxCommands/CreateBlock.aspx",
        data: "t=" + fid,
        success: function(msg) {
            jQuery.facebox("<h1>User has been blocked</h1>");
            window.location.href = "/User/View.aspx";
        },
        error: function(XMLHttpRequest, textStatus, errorThrow) {
            PopupError("Failed to block that user, please try later.");
        }
    });
    return false;
}

function ShowChallengeMessage(guid) {
    $.facebox({ajax: '/AjaxViews/ShowGUIDMessage.aspx?guid=' + guid});
    return false;
}

function DeleteAllMessages() {
    $.ajax({
        type: "POST",
        url: "/AjaxCommands/DeleteMessage.aspx",
        data: "id=" + escape('*'),
        success: function(msg) {
            if (msg == "OK") {
                    $(document).trigger('close.facebox');
            }

            return false;
        },
        error: function(XMLHttpRequest, textStatus, errorThrow) {
            PopupError("The system failed to delete your messages");
        }
    });

    return false;
}

function DeleteMessage(elem, id) {
    $.ajax({
        type: "POST",
        url: "/AjaxCommands/DeleteMessage.aspx",
        data: "id=" + id,
        success: function(msg) {
            if (msg == "OK") {
                $('.h' + elem).remove();
                $('.' + elem).fadeOut(function() {
                    $(this).remove();
                    var i = parseInt($('._inmsgCount').html());
                    i = i - 1;
                    if (i == 0) {
                        $('._inmsgLink').hide();
                    }
                    if (i > 0)
                        $('._inmsgCount').html(i.toString());

                    i = parseInt($('._count').html());
                    i = i - 1;
                    $('._count').html(i.toString())

                    if ($('._msgList table').size() == 0) {
                        $(document).trigger('close.facebox');
                    }
                });
            }

            return false;
        },
        error: function(XMLHttpRequest, textStatus, errorThrow) {
            PopupError("The system failed to delete the message ");
        }
    });

    return false;
}


/**********************************************************************
    Asset management 
 **********************************************************************/
function DeleteAsset(aid) {
    var parent = $('.d' + aid);
    $.ajax({
        type: "POST",
        url: "/AjaxCommands/AssetMgmt.aspx",
        data: "action=delete&id=" + aid,
        success: function(msg) {
            $(parent).fadeOut("normal", function() {
                $(parent).remove();
            });
        },
        error: function(XMLHttpRequest, textStatus, errorThrow) {
            PopupError("Failed to delete the asset.");
        }
    });

    return false;
}


/**********************************************************************
    Previews
**********************************************************************/

function ShowAsset(id) {
    jQuery.facebox({ ajax: '/AjaxViews/ShowAsset.aspx?id=' + id });
    return false;
}

function ShowAssetBrowser(id) {
    var w = window.open('/AjaxViews/ShowAsset.aspx?t=b&id=' + id);
    w.focus();
    return false;
}


/**********************************************************************
    Messaging
**********************************************************************/

function ShowMessage(id) {
    HideTipsy();
    jQuery.facebox({ ajax: '/AjaxViews/ViewMessage.aspx?id=' + id });
   
    $("p[rel='" + id + "']").fadeOut(function() { $("p[rel='" + id + "']").remove(); });
    return false;
}

function ShowSendMessage(to) {
    $(document).trigger('close.facebox');
    jQuery.facebox({ ajax: '/AjaxViews/ShowSendMessage.aspx?to=' + to });
    return false;    
}


function SendMessage(target, msgCtrl, showResult) {
    if ($(msgCtrl).val() == "") {
        return;
    }

    $('._send').attr("disabled", "true");
    $.ajax({
        type: "POST",
        url: "/AjaxCommands/SendMessage.aspx",
        data: "target=" + target + "&msg=" + escape($(msgCtrl).val()),
        success: function(msg) {
            $(msgCtrl).val("");
            $('._send').attr('disabled', '');
            if (showResult)
                jQuery.facebox('<h1>Message sent to ' + target + '</h1>');
            else {
               // $(document).trigger('close.facebox');
            }

            $('._sendComplete').hide();
            $('._sendComplete').html("Message sent");
            $('._sendComplete').fadeIn(function() {
            setTimeout("$('._sendComplete').fadeOut(function(){$(document).trigger('close.facebox');});", 1500);
            });
        },
        error: function(XMLHttpRequest, textStatus, errorThrow) {
            PopupError("The system failed to send the message to the specified user.");
        }
    });

    return false;
}

function isTelephone(s) {
    return false;
}

function isEmail(s) {
    var v = new RegExp();
    v.compile(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return v.test(s);
}

function isUrl(s) {
    var v = new RegExp();
    var v2 = new RegExp();
    v.compile("^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$");
    v2.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$");
    return v.test(s) || v2.test(s);
}

function UpdateAssetProps(aid) {
    var nm = $("._anm").val();
    $.post('/Assets/AssetPropertiesView.aspx', { name: nm, id: aid }, function(data) {
        $(".c" + aid).animate({ opacity: 0 }, 500, function() {
            $(".c" + aid).html(data);
        }).animate({ opacity: 1 }, 500);
        HideTipsy();
    });
    return false;    
}

function ShowAssetProperties(cid, id) {
    HideTipsy();
    $.get("/Assets/AssetPropertiesView.aspx?id=" + id, {}, function(data) {
   
        $(cid).tipsy({ gravity: 't', title: data, ignoreclick: true });
        $("._anm").maxLength(50);
        $("._ade").maxLength(200);
    });
    return false;
}

function ShowFriendProperties(fid, elem) {
    HideTipsy();
    $.get("/AjaxViews/FriendLinks.aspx?f=" + fid, {}, function(data) {
        $(elem).tipsy({ gravity: 't', title: data, ignoreclick: true });
    });
    return false;    
}


var lastUrl;
function ShowAssetsOfType(type) {
    lastUrl = "/AjaxViews/AssetSelector.aspx?type=" + type;
    $('#assets').load(lastUrl);
    return false;
}

function AddNewAssetOfType(type) {
    lastUrl = "/AjaxViews/AddAsset.aspx?type=" + type;
    $('#add').load(lastUrl);
    return false;
}


/* Library funcs */
function LibrarySelect(id, elem) {
    selLibElement = id;
    $('.libItem_' + theType + '_Sel').removeClass('libItem_' + theType + '_Sel');
    $(elem).addClass("libItem_" + theType+ '_Sel');
    $("#libraryView").load("/AjaxViews/LibraryPreview.aspx?id=" + id + "&type=" + $('._typeId').val());
    return false;
}

function SubmitNewChallenge() {
    var id = $("._cid").val();
    var json = "";
    var ty = $("._typeId").val();
    var extra = "";
    if (selected == 0) {
        if (selLibElement == -1) {
            $(".libcontainer").tipsy({ gravity: 'w', title: 'You must select a challenge from the library' });
            return;
        }

        id = selLibElement;
        if ($("#retryYes").length > 0) {
            extra = "&retry=" + $("#retryYes").is(":checked");
            extra = extra + "&howmany=" + $("#howmany").val();
        }
    } else {
        json = GetJSONForChallenge();
        if (json == "") {
            $('._tbName').tipsy({ gravity: 'w', title: 'Both a name and description are required for challenge' });
            return;
        }
        var err = false;
        if ($("._tbName").size() > 0 && $("._tbName").val() == "") {
            $('._tbName').tipsy({ gravity: 'w', title: 'Please give your challenge a name' });
            err = true;
        }
        if ($("._tbDesc").size() > 0 && $("._tbDesc").val() == "") {
            $('._tbDesc').tipsy({ gravity: 'w', title: 'Please describe your challenge' });
            err = true;
        }
        if ($("._challengeName").size() > 0 && $("._challengeName").val() == "") {
            $('._challengeName').tipsy({ gravity: 'w', title: 'Please give your challenge a name' });
            err = true;
        }
        if ($("._challengeDescription").size() > 0 && $("._challengeDescription").val() == "") {
            $('._challengeDescription').tipsy({ gravity: 'w', title: 'Please describe your challenge' });
            err = true;
        }
        if (err) return false;
    }

    if ($("._addToLib input")) {
        extra = "&add=" + $("._addToLib input").is(":checked");
    }

    $.ajax({
        type: "POST",
        url: "/AjaxCommands/SaveChallenge.aspx",
        data: "id=" + id + "&json=" + json + "&type=" + ty + extra,
        success: function(msg) {
            window.location.href = "/Challenge/CreateStep3.aspx?cid=" + $('._cid').val();
        },
        error: function(XMLHttpRequest, textStatus, errorThrow) {
            PopupError("Failed to save the challenge");
        }
    });
}


function ShowMore(tableElem, type, rowGuid) {
    var count = 0;
    var r = $('.' + rowGuid);
    var a = $('.' + rowGuid + " a");

    if (a.html() == "More") {
        $.cookie(a.attr("rel"), 'open');
        a.html("Less");
        a.removeClass("morelink").addClass("lesslink");
    } else {
        $.cookie(a.attr("rel"), 'closed');
        a.html("More");
        a.removeClass("lesslink").addClass("morelink");
        count = 3;
    }
    r.remove();

    $(tableElem).append("<tr id='temp'><td colspan='3' align='center'><img width='32' src='/Content/Images/facebox/loading.gif'/></td></tr>");


    $.ajax({
        url: '/AjaxViews/GameTableView.aspx?t=' + type + "&c=" + count,
        cache: false,
        dataType: "html",
        success: function(data) {
            $('#temp').remove();
            $(tableElem + " tr:gt(0)").remove();
            $(tableElem).append(data);
            $(tableElem).append(r);
        },
        error: function(e, txt, data) {
            PopupError("The system failed to retrieve the list of games");
        }
    });
}



/**
* Cookie plugin
* Copyright (c) 2006 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

; (function($) { var m = $.scrollTo = function(b, h, f) { $(window).scrollTo(b, h, f) }; m.defaults = { axis: 'xy', duration: parseFloat($.fn.jquery) >= 1.3 ? 0 : 1 }; m.window = function(b) { return $(window).scrollable() }; $.fn.scrollable = function() { return this.map(function() { var b = this, h = !b.nodeName || $.inArray(b.nodeName.toLowerCase(), ['iframe', '#document', 'html', 'body']) != -1; if (!h) return b; var f = (b.contentWindow || b).document || b.ownerDocument || b; return $.browser.safari || f.compatMode == 'BackCompat' ? f.body : f.documentElement }) }; $.fn.scrollTo = function(l, j, a) { if (typeof j == 'object') { a = j; j = 0 } if (typeof a == 'function') a = { onAfter: a }; if (l == 'max') l = 9e9; a = $.extend({}, m.defaults, a); j = j || a.speed || a.duration; a.queue = a.queue && a.axis.length > 1; if (a.queue) j /= 2; a.offset = n(a.offset); a.over = n(a.over); return this.scrollable().each(function() { var k = this, o = $(k), d = l, p, g = {}, q = o.is('html,body'); switch (typeof d) { case 'number': case 'string': if (/^([+-]=)?\d+(\.\d+)?(px)?$/.test(d)) { d = n(d); break } d = $(d, this); case 'object': if (d.is || d.style) p = (d = $(d)).offset() } $.each(a.axis.split(''), function(b, h) { var f = h == 'x' ? 'Left' : 'Top', i = f.toLowerCase(), c = 'scroll' + f, r = k[c], s = h == 'x' ? 'Width' : 'Height'; if (p) { g[c] = p[i] + (q ? 0 : r - o.offset()[i]); if (a.margin) { g[c] -= parseInt(d.css('margin' + f)) || 0; g[c] -= parseInt(d.css('border' + f + 'Width')) || 0 } g[c] += a.offset[i] || 0; if (a.over[i]) g[c] += d[s.toLowerCase()]() * a.over[i] } else g[c] = d[i]; if (/^\d+$/.test(g[c])) g[c] = g[c] <= 0 ? 0 : Math.min(g[c], u(s)); if (!b && a.queue) { if (r != g[c]) t(a.onAfterFirst); delete g[c] } }); t(a.onAfter); function t(b) { o.animate(g, j, a.easing, b && function() { b.call(this, l, a) }) }; function u(b) { var h = 'scroll' + b; if (!q) return k[h]; var f = 'client' + b, i = k.ownerDocument.documentElement, c = k.ownerDocument.body; return Math.max(i[h], c[h]) - Math.min(i[f], c[f]) } }).end() }; function n(b) { return typeof b == 'object' ? b : { top: b, left: b} } })(jQuery);