/*************************************************************
* Misc utility scripts used by the Microgroove platform.
* This file is grouped into several sections and should be
* obsfucated before deployment.
*************************************************************/

function UrlEncode(plaintext) {
    // The Javascript escape and unescape functions do not correspond
    // with what browsers actually do...
    var SAFECHARS = "0123456789" + 				// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" + // Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()"; 				// RFC2396 Mark characters
    var HEX = "0123456789ABCDEF";

    var encoded = "";
    for (var i = 0; i < plaintext.length; i++) {
        var ch = plaintext.charAt(i);
        if (ch == " ") {
            encoded += "+"; 			// x-www-urlencoded, rather than %20
        } else if (SAFECHARS.indexOf(ch) != -1) {
            encoded += ch;
        } else {
            var charCode = ch.charCodeAt(0);
            if (charCode > 255) {
                alert("Unicode Character '"
                        + ch
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted.");
                encoded += "+";
            } else {
                encoded += "%";
                encoded += HEX.charAt((charCode >> 4) & 0xF);
                encoded += HEX.charAt(charCode & 0xF);
            }
        }
    } // for

    return encoded;
}

function trackClick(url, name) {
    //backwards compatibility
}

function setCookie(name, value, expire, path) {
    document.cookie = name + "=" + escape(value) + ((expire == null) ? "" : ("; expires=" + expire.toGMTString())) + ((path) ? "; path=" + path : "");
}

function getCookie(name) {
    var search = name + "=";
    if (document.cookie.length > 0) {
        offset = document.cookie.indexOf(search);
        if (offset != -1) {
            offset += search.length;
            end = document.cookie.indexOf(";", offset);
            if (end == -1)
                end = document.cookie.length;

            return unescape(document.cookie.substring(offset, end));
        }
    }
}

function killCookie(name, path) {
    theValue = getCookie(name);
    if (theValue)
        document.cookie = name + '=' + theValue + '; expires=Fri, 13-Apr-1970 00:00:00 GMT' + ((path) ? '; path=' + path : '');
}

function paramaterFrom(param, argument) {
    argument = '=' + argument + '&';
    if (argument.indexOf(param) != -1) {
        locStart = argument.indexOf(param) + param.length + 1;
        locEnd = argument.indexOf('&', locStart);
        if (locEnd < locStart)
            locEnd = argument.length;

        return argument.substring(locStart, locEnd);
    }
    else
        return null;
}

function replaceString(fullS, oldS, newS) {
    for (var i = 0; i < fullS.length; i++) {
        if (fullS.substring(i, i + oldS.length) == oldS)
            fullS = fullS.substring(0, i) + newS + fullS.substring(i + oldS.length, fullS.length);
    }
    return fullS;
}

function unPackUrl(url) {
    return replaceString(replaceString(replaceString(replaceString(url, "!", "?"), "^", "&"), "|", "="), "$", "/");
}

function ChangeSortOrder(cookieName, sortOrder, reloadUrl) {
    setCookie(cookieName, sortOrder, null, "/");
    RedirectLocation(reloadUrl);
}

function RedirectLocation(redirectUrl) {
    window.location.href = redirectUrl;
}

/*************************************************************
* Content view tracking and server posting scripts.
*************************************************************/

function TrackView(contentTypeID, contentID, currentViewCount, timeToLive, hash, isReadOnly) {
    function GetCookie(cookieName) {
        var cookies = document.cookie.split(";");

        for (var i = 0; i < cookies.length; i++) {
            var nameValue = cookies[i].split("=");

            if (nameValue.length == 2 && nameValue[0].replace(" ", "") == cookieName) {
                return nameValue[1];
            }
        }

        return null;
    }

    function SetCookie(cookieName, cookieValue) {
        document.cookie = cookieName + "=" + cookieValue + ";path=/;";
    }

    function GetViewCount(text, contentTypeID, contentID) {
        var countName = contentTypeID + "_" + contentID;
        var pairs = text.split("|");

        for (var i = 0; i < pairs.length; i++) {
            var nameValue = pairs[i].split(":");

            if (nameValue.length == 2 && nameValue[0] == countName) {
                return nameValue[1];
            }
        }

        return 0;
    }

    function SetViewCount(text, contentTypeID, contentID, value) {
        var countName = contentTypeID + "_" + contentID;
        var pairs = text.split("|");
        var found = false;
        text = "";

        for (var i = 0; i < pairs.length; i++) {
            var nameValue = pairs[i].split(":");

            if (nameValue.length == 2) {
                if (nameValue[0] == countName) {
                    text += countName + ":" + value + "|";
                    found = true;
                }
                else {
                    text += nameValue[0] + ":" + nameValue[1] + "|";
                }
            }
        }

        if (!found) {
            text += countName + ":" + value + "|";
        }

        return text;
    }

    if (!isReadOnly) {
        // Call server procedure.
        var image = new Image();
        image.src = "/aspnet_client/microgroove/tracking/tracking.ashx?contentTypeID=" + contentTypeID
			+ "&contentID=" + contentID
			+ "&ttl=" + timeToLive
			+ "&h=" + hash
			+ "&t=" + (new Date()).getTime();
    }

    // Save current view count to cookie.
    var cookie = GetCookie("TrackViewCount");
    if (cookie == null) {
        cookie = SetViewCount("", contentTypeID, contentID, currentViewCount);
    }

    var value = GetViewCount(cookie, contentTypeID, contentID);
    if (value != 0) {
        currentViewCount = value;
    }

    if (!isReadOnly) {
        currentViewCount++;
    }

    cookie = SetViewCount(cookie, contentTypeID, contentID, currentViewCount);
    SetCookie("TrackViewCount", cookie);

    return currentViewCount;
}

/*************************************************************
* AJAX-based author tooltips.
*************************************************************/

var _mouseX;
var _mouseY;
var _isTooltipActive = false;

function GetMember(memberID) {
    CallMemberService(memberID);
    return "<div style='margin:10px;'>Loading...</div>";
}

function CallMemberService(memberID) {
    if (memberID != 0) {
        $.getJSON("/webservices/v4.0/int/memberservice.aspx/GetMember", { memberID: memberID },
			function(item) {
			    if (item) {
			        SetTooltipContent("<div style='margin:10px;'><img src='" + item.ImageUrl + "'></div><div style='margin-top:10px;margin-left:10px;'><strong>User: </strong>" + item.Username + "</div><div style='margin-left:10px;'><strong>Location: </strong>" + item.Location + "</div><div style='margin-left:10px;margin-bottom:10px;'><strong>Joined: </strong>" + item.ConfirmedDate + "</div>");
			    };
			});
    }
}

function GetBrowserHeight() {
    if ($.browser.msie) {
        return document.body.offsetHeight;
    }
    else {
        return window.innerHeight;
    }
}

function GetBrowserWidth() {
    if ($.browser.msie) {
        return document.body.offsetWidth;
    }
    else {
        return window.innerWidth;
    }
}

function ActivateMouseMoveEvents() {
    if (!$.browser.msie) {
        document.captureEvents(Event.MOUSEMOVE)
    }
    document.onmousemove = GetMouseXY;
}

function UpdateTooltipPos() {
    if (!document.getElementById || !document.getElementById('ToolTip') || !_mouseX || !_mouseY) {
        return;
    }

    var toolTipLeft = (_mouseX + 20) + "px";
    if ((_mouseX + 270) > GetBrowserWidth()) {
        toolTipLeft = (_mouseX - 240) + "px";
    }

    document.getElementById('ToolTip').style.left = toolTipLeft;
    document.getElementById('ToolTip').style.top = (_mouseY) + "px";
}

function GetMouseXY(e) {
    if (!document.getElementById || !document.getElementById('ToolTip')) {
        return;
    }

    if ($.browser.msie) {
				var top = (document.documentElement && document.documentElement.scrollTop) ? document.documentElement.scrollTop : document.body.scrollTop;
        // grab the x-y pos.s if browser is IE
        _mouseX = event.clientX + document.body.scrollLeft;
        _mouseY = event.clientY + top;
    }
    else {
        // grab the x-y pos.s if browser is NS
        _mouseX = e.pageX;
        _mouseY = e.pageY;
    }

    if (_mouseX < 0) {
        _mouseX = 0;
    }
    if (_mouseY < 0) {
        _mouseY = 0;
    }
    if (_isTooltipActive) {
        UpdateTooltipPos();
    }
}

function ShowHideTooltip(which, content) {
    if (!document.getElementById || !document.getElementById('ToolTip')) {
        return;
    }
    if (which) {
        UpdateTooltipPos();
        _isTooltipActive = true;
        document.getElementById('ToolTip').style.visibility = "visible";
        SetTooltipContent(content);
    }
    else {
        _isTooltipActive = false;
        document.getElementById('ToolTip').style.visibility = "hidden";
        SetTooltipContent('');
    }
}

function SetTooltipContent(content) {
    if (!document.getElementById || !document.getElementById('ToolTip')) {
        return;
    }
    document.getElementById('ToolTip').innerHTML = "<div style='width:220px;border:1px solid black;background-color:white;font-family:verdana, arial, sans-serif;font-size:8pt;color:black;'>" + content + "</div>";
}

/*************************************************************
* Form validation and show / hide scripts.
*************************************************************/

function ValidateDropdowns(source, arguments) {
    if (arguments.Value == "null")
        arguments.IsValid = false;
    else
        arguments.IsValid = true;
}

function ValidateUsername(source, arguments) {
    if (arguments.Value.match(/^[A-Za-z0-9]{5,20}?$/))
        arguments.IsValid = true;
    else
        arguments.IsValid = false;
}

function ValidatePassword(source, arguments) {
    if (arguments.Value.match(/^(.){5,20}?$/))
        arguments.IsValid = true;
    else
        arguments.IsValid = false;
}

function ValidateEmail(source, arguments) {
    var re = /^[a-zA-Z-_0-9]+(\.[a-zA-Z-_0-9]+)*@[a-zA-Z-_0-9]+(\.\w+)+$/;
    if (re.test(arguments.Value))
        arguments.IsValid = true;
    else
        arguments.IsValid = false;
}

function GetMail(elementName, joinFormUrl) {
    window.document.location.href = joinFormUrl + $("#" + elementName).val();
}

function GetRef(elementName) {
    if (!document.getElementById)
        return document[elementName];
    else
        return document.getElementById(elementName);
}

function clearMemberImage(memberImageClearedTracker, memberImage, memberImageContainer) {
    $("#" + memberImageClearedTracker).val('true');
    $("#" + memberImage).hide();
    $("#" + memberImageContainer).hide();
}

/*************************************************************
* The onloadsOn() function will set the window.onload function to
* be onloadsOn() which will run all of your window.onload
* functions.
*************************************************************/
function onloadsOn() {
    window.onload = onloadsGo;
}

/*************************************************************
* The onloadsGo() function loops through the onloads array and
* runs each function in the array.
*************************************************************/
function onloadsGo() {
    for (var i = 0; i < _onloads.length; i++)
        eval(_onloads[i]);
}

/*************************************************************
* The onloadsAdd() function will add another function to the onloads
* array to be run when the page loads.
*************************************************************/
function onloadsAdd(func) {
    _onloads[_onloads.length] = func;
}

/*************************************************************
* The onloads array holds all of the functions you wish to run
* when the page loads.
*************************************************************/
var _onloads = new Array();

//install the onload handlers
onloadsOn();



/*************************************************************
* WebIM scripts for opening windows and checking for new
* messages on a schedule.
*************************************************************/

var _INTERVAL = 5000;
var _timerID = 0;
var _memberID = 0;

function InitMessaging(fromMemberID) {
    if (fromMemberID != 0) {
        _memberID = fromMemberID;
        onloadsAdd("StartTimer();");
    }
}

function CallService() {
    if (!IsChattingDisabled()) {
        $.getJSON("/webservices/v4.0/int/messagingservice.aspx/IsMessageWaiting", { memberID: _memberID },
			function(item) {
			    if (_memberID != 0 && !IsChattingDisabled() && item && item.SenderID && item.SenderID != 0 && !GetChatting(item.SenderID)) {
			        OpenModalWindow("/aspnet_client/microgroove/windows/chat/intro.aspx?t=" + item.SenderID + "&ta=" + UrlEncode(item.Author) + "&tl=" + UrlEncode(item.AuthorLocation) + "&ti=" + UrlEncode(item.ImageUrl) + "&m=" + UrlEncode(item.MessageBody), "IntroWindow");
			        SetChatting(item.SenderID, true);
			    };

			    StartTimer();
			});
    }
    else {
        StartTimer();
    }
}

function StartTimer() {
    _timerID = setTimeout("CallService()", _INTERVAL);
}

function OpenNoChatWindow() {
    alert("You need to be a logged in member to WebIM other members. Please log in or register.");
}

function OpenLogInToChatWindow() {
    alert("You need to be a logged in member to WebIM other members. Please log in or register.");
}

function OpenAuthorOfflineChatWindow() {
    alert("The person you are trying to WebIM is currently offline.");
}

function OpenChatWindow(recipientID) {
    if (_memberID == recipientID) {
        alert("When you click this icon next to another member that is currently online, \ryou can start an Instant Messaging conversation with that member, \rfrom right within this site.");
        return;
    }

    if (recipientID == 0) {
        return;
    }

    var url = "/aspnet_client/microgroove/windows/chat/default.aspx?t=" + recipientID;

    var chasm = screen.availWidth;
    var mount = screen.availHeight;

    var w = 327;
    var h = 390;

    wHandle = null;
    wHandle = window.open(url, 'ChatWindow_' + recipientID, 'width=' + w + ',height=' + h + ',left=' + ((chasm - w - 10) * .5) + ',top=' + ((mount - h - 30) * .5) + ',scrollbars=no');
    if (wHandle.blur) wHandle.focus();
}

function SetChatting(recipientID, isChatting) {
    var chattingCookie = "";

    if (getCookie("ChattingRecipients") != null) {
        chattingCookie = getCookie("ChattingRecipients");
    }

    var recipients = chattingCookie.split("|");
    var found = false;
    chattingCookie = ""; //reset as we're about to rebuild this

    for (var i = 0; i < recipients.length; i++) {
        if (recipients[i] == recipientID && isChatting) {
            //recipientID already in the cookie, keep them there
            chattingCookie += recipientID + "|";
            found = true;
            continue;
        }

        if (recipients[i] == recipientID && !isChatting) {
            //recipientID already in the cookie, so skipping adding it back in
            found = true;
            continue;
        }

        chattingCookie += recipients[i] + "|";
    }

    if (!found && isChatting) {
        chattingCookie += recipientID + "|";
    }

    setCookie('ChattingRecipients', chattingCookie, null, '/');
}

function GetChatting(recipientID) {
    var chattingCookie = "";

    if (getCookie("ChattingRecipients") != null) {
        chattingCookie = getCookie("ChattingRecipients");
    }
    else {
        return false;
    }

    var recipients = chattingCookie.split("|");

    for (var i = 0; i < recipients.length; i++) {
        if (recipients[i] == recipientID) {
            return true;
        }
    }

    return false;
}

function EnableChatting() {
    setCookie('Chatting', 'Enabled', null, '/');
}

function DisableChatting() {
    setCookie('Chatting', 'Disabled', null, '/');
}

function IsChattingDisabled() {
    return (getCookie('Chatting') != null && getCookie('Chatting') == "Disabled");
}

/*************************************************************
* Windowing scripts to support RadWindow client side
* behaviour.
*************************************************************/

var _isWindowReloading = false;

function OpenModalWindow(url, id) {
    var oManager = GetRadWindowManager();
    if (oManager) {
        HeightCheck(oManager.Open(url, id));
        RemovePageEmbeds();
    }
}

function OpenDeleteWindow(url, id) {
    var oManager = GetRadWindowManager();
    if (oManager) {
        HeightCheck(oManager.Open(url, id));
        RemovePageEmbeds();
    }
}

function WindowCallback(radWindow, returnValue) {
    if (arguments.length > 2) {
        if (returnValue) {
            _isWindowReloading = true;
            var url = RemoveVisibleOnPageLoad(returnValue);
            RedirectLocation(url);
        }
        return;
    }

    if ((typeof Microgroove != 'undefined') && (typeof Microgroove.onModalWindowComplete == 'function')) {
        Microgroove.onModalWindowComplete(function() {
            WindowCallback(radWindow, returnValue, false);
        });
        return;
     }

     WindowCallback(radWindow, returnValue, false);
}

function WindowClosed(radWindow) {
    if (arguments.length > 1) {
        if (!_isWindowReloading) {
            var url = RemoveVisibleOnPageLoad(document.location.href);
            RedirectLocation(url);
        }
        return;
    }

    if ((typeof Microgroove != 'undefined') && (typeof Microgroove.onModalWindowComplete == 'function')) {
        Microgroove.onModalWindowComplete(function() {
            WindowClosed(radWindow, false);
        });
        return;
    }

    WindowClosed(radWindow, false);
}

function RemovePageEmbeds() {
    $("span.ad").empty();
}

function RemoveVisibleOnPageLoad(url) {
    var param = paramaterFrom("vpl", url);
    return url.replace(param, "false");
}

function HeightCheck(radWindow) {
    if (radWindow) {
        var h = $(window).height();

        if (radWindow.GetHeight() > h) {
            radWindow.SetHeight(h);
            radWindow.Center();
        }
    }
}

function Resize(radWindow, width, height) {
    if (radWindow) {
        radWindow.SetWidth(width);
        radWindow.SetHeight(height);
        radWindow.Center();
    }
}

function AttachJavaScriptProtocal(url) {
    return "javascript:" + url;
}

function BindWindowMethods() {

    var bindings = "*[href^='OpenModalWindow'], *[href^='RedirectLocation']";

    $(bindings).each(function() {

        var href = $(this).attr("href");
        $(this).attr("href", AttachJavaScriptProtocal(href));

    });
}

$(document).ready(function() {
    BindWindowMethods();
});

/*************************************************************
* Member Playlists allow site members to build their own
* streaming audio playlists from tracks in the CMS authored
* playlists.
*************************************************************/

function initMemberPlaylistSortables() {
    if ($("#MemberPlaylist").sortable) {
        $("#MemberPlaylist").sortable({
            handle: $(".positioner"),
            stop: function(e, ui) {
                $.get("/webservices/v4.0/pub/memberplaylistservice.aspx/UpdateMemberPlaylist",
					{ trackIDs: $('#MemberPlaylist').sortable('toArray').toString(),
					    memberID: $('#MemberPlaylist').attr('MemberID'),
					    affinityID: $('#MemberPlaylist').attr('AffinityID')
					});
            }
        });
    }
}

function deleteMemberTrack(trackid, memberid, affinityid) {
    $.get("/webservices/v4.0/pub/memberplaylistservice.aspx/DeleteTrackFromMemberPlaylist",
				{ trackID: trackid,
				    memberID: memberid,
				    affinityID: affinityid
				});
    $("#" + trackid).slideUp("slow", function() {
        $("#" + trackid).remove();
    });
}

function addMemberTrack(trackid, memberid, affinityid) {
    $.get("/webservices/v4.0/pub/memberplaylistservice.aspx/AddTrackToMemberPlaylist",
				{ trackID: trackid,
				    memberID: memberid,
				    affinityID: affinityid
				});
}

function onAjaxResponseEnd(ajaxPanel, eventArgs) {
    initMemberPlaylistSortables();
}

$(document).ready(function() {
    initMemberPlaylistSortables();
});