﻿    /** String Functions **/

String.prototype.trim = function() {
    a = this.replace(/^\s+/, '');
    return a.replace(/\s+$/, '');
};

String.prototype.startsWith = function(pattern){
    if(pattern != null && typeof(pattern) == String && this.length >= pattern.length){
        var subString = this.substring(0, pattern.length);
        return (pattern.toLowerCase() == subString.toLowerCase());
    }
    
    return false;
}

/** DIALOG FUNCTIONS START **/
var dialogDimensions = {};
function OpenDialogWindow(windowName, onClose) {
    try {
        var dialog = jQuery('#' + windowName);
        if (!dialogDimensions[windowName]) {
            dialogDimensions[windowName] = { height: jQuery(dialog).height(), width: jQuery(dialog).width() };
        }
        var height = dialogDimensions[windowName].height;
        var width = dialogDimensions[windowName].width;
        if (dialog) {
            jQuery(dialog).dialog({
                autoOpen: true,
                close: function(e, ui) { if (onClose) { onClose(e, ui); } jQuery(this).dialog('destroy'); },
                closeOnEscape: false,
                closeText: '',
                dialogClass: '',
                draggable: false,
                height: height,
                modal: true,
                open: function(e, ui) { jQuery(this).css('display', 'block'); },
                resizable: false,
                width: width,
                bgiframe: true
            });

            if (jQuery(dialog).find('div[hideIcon=\'false\']').length > 0) {
                jQuery('.ui-icon').addClass('ui-dialog-icon');
            }      
            jQuery('.ui-dialog-body')
                .height(height - 47)
                .width(width - 7);
            jQuery('.ui-dialog-header-center').width(width - 22);
            jQuery('.ui-dialog-footer-center').width(width - 22);
            jQuery('.ui-dialog-titlebar-close').attr('href', 'javascript:{}');
            jQuery('.ui-dialog').height(jQuery('.ui-dialog').height() + 47);            
        }
    }
    catch (ex) {
        //alert(ex);
    }
}

function CreateWindow(url, name, width, height) {
    if (!url) return null;
    if (!name) name = "";
    if (!width) width = screen.width;
    if (!height) height = screen.height;

    var w = window.open(url, name, "width=" + width + ", height=" + height + ", scrollbars=yes,resizable=1", true);
    if (w == null){
        alert("Please turn off your pop-up blocker to view this popup window!");
    }
    
    return w;
}

function OpenGameWindow(gameUrl){
    var win = CreateWindow(gameUrl, "GamePlay", 1013, 690);
    if(win != null){
        win.focus();
    }
}

function OpenPrizeWindow(prizeUrl){
    var win = CreateWindow(prizeUrl, "PrizeView", 442, 448);
    if(win != null){
        win.focus();
    }
}

function OpenVideoWindow(videoUrl) {
	var win = CreateWindow(videoUrl, "VideoView", 656, 376);
	if (win != null) {
		win.focus();
	}
}

/** DIALOG FUNCTIONS END **/

function BookmarkSite(openInNewWindow){
    var url = "http://" + window.location.host;
    var title = "Club Bing";
    
    if ((navigator.appName == "Microsoft Internet Explorer") && (parseInt(navigator.appVersion) >= 4)) {
        window.external.AddFavorite(url, title);
    } else if (navigator.appName == "Netscape" && window.sidebar && window.sidebar.addPanel) {
        window.sidebar.addPanel(title, url, "");
    } else {
        alert("Sorry, we are unable to bookmark this site for you.  Please do this manually.");
    }
}

function ShowStatus(msg){
    window.status = msg;
    return true;
}

function ShowDefaultSettingsPage(openInNewWindow){
    var instructionsUrl = "/Pages/About/DefaultSettings.aspx?ns=1";

    if(openInNewWindow){
            window.open(instructionsUrl, "defaultsearchsettings");
        }
        else{
            window.location.href = instructionsUrl;
        }
}


function SetSearchDefault(openInNewWindow) {
    if ((typeof window.sidebar == "object") && (typeof window.sidebar.addSearchEngine == "function"))  {
        window.sidebar.addSearchEngine(
            "http://www.bing.com/s/osd3.xml",         /* engine URL */
            "http://www.bing.com/favicon.ico",        /* icon URL */          
            "Bing",                                   /* engine name */          
            "Web" );                                  /* category name */  
    } 
    else if( window.external ){     
        try{
            window.external.AddSearchProvider('http://www.bing.com/s/osd3.xml');
        }
        catch(e){
            ShowDefaultSettingsPage(openInNewWindow);
        }
    }
    else{
        ShowDefaultSettingsPage(openInNewWindow);
    }
}

function SetHomePage() {
    if (document.all) {
        document.body.style.behavior = 'url(#default#homepage)';
        document.body.setHomePage('http://www.bing.com');
    }
    else if (navigator && navigator.userAgent && navigator.userAgent.toLowerCase().indexOf('firefox') > -1) {
        alert('Click on the Set Bing as Your Hompage link and drag it to the Home toolbar button.');
    }
    else {
        alert('Your browser requires that you set Bing as your homepage manually.');
    }

    return false;
}


function DDLTextBox_OnFocus(src, e){
    var listBox = document.getElementById(src.getAttribute("ListControlId"));
    listBox.style.display = "block"; 
}

function DDLTextBox_OnBlur(src, e){
    
}

function DDLTextBox_OnKeyPress(src, e){
    var evt = e || window.event;
    var charCode = evt.keyCode || evt.which;
    var key = String.fromCharCode(charCode);
    
    var text = src.value;
    var searchTerm = text + key;
    var match = "";
    
    var listBox = document.getElementById(src.getAttribute("ListControlId"));
    if(listBox){
        for(var i = 0; i < listBox.options.length; i++){
            var optionVal = listBox.options[i].value;
            if ( optionVal.substring(0, searchTerm.length).toUpperCase() == searchTerm.toUpperCase() ) {
				// Found match.		
				match = optionVal;
				
				break;
			}
        }
    }
    
    if(match != ""){
       
        listBox.value = match;
    }
    else{
        src.value = text;
        CancelEvent(evt);
    }
    
    return true;
}

function DDLListBox_OnChange(src, e){
    var selectedValue = src.value;
    
    var textBox = document.getElementById(src.getAttribute("TextControlId"));
    if(textBox != null){
        textBox.value = selectedValue;
    }
    
    src.style.display = "none";
}


function CancelEvent(e) {
  e = e ? e : window.event;
  if(e.stopPropagation)
    e.stopPropagation();
    
  if(e.preventDefault)
    e.preventDefault();
    
  e.cancelBubble = true;
  e.cancel = true;
  e.returnValue = false;
  
  return false;
}

/** Cookie Functions **/
function createCookie(name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		var expires = "; expires=" + date.toGMTString();
	}
	else var expires = "";
	document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for (var i = 0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ') c = c.substring(1, c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
	}
	return null;
}

function eraseCookie(name) { createCookie(name, "", -1); }

function parseUrl(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
}

function disableImageButton(id) {
    var button = $("input:image[id$='"+id+"']");
    
    if (button.length > 0) {
        button.attr("disabled", "disabled");
        button.data("EnabledImageUrl", button.attr("src"));
        button.attr("src", button.attr("DisabledImageUrl"));
    }    
}

function enableImageButton(id) {
    var button = $("input:image[id$='"+id+"']");
    
    if (button.length > 0) {
        button.removeAttr("disabled");
        button.attr("src", button.data("EnabledImageUrl"));
    }
}

/* Friend Search functions*/
GetCacheBurst = function() {
    var d = new Date();
    return "dt" + d.getFullYear() + d.getMonth() + d.getDate() + d.getHours() + d.getMinutes() + d.getSeconds() + d.getMilliseconds();
}

function SearchForFriend(searchTextBox, errorLabel, searchResults, handleLabel, avatarImage, overlayImage, handleHyperlink, addFriendImage, instructions, errorContainer, waitingDiv) {
    errorLabel.text("");
    if (!errorContainer) { errorContainer = errorLabel; }

    if (searchTextBox.attr("value").length > 0) {

        errorContainer.show();
        searchResults.hide();
        if (instructions) { instructions.hide(); }

        if (waitingDiv != null) {
            waitingDiv.show();
        }

        $.getJSON("/PendingFriends.ashx",
            { command: "search", username: searchTextBox.attr("value"), dt: GetCacheBurst() },
            function(result) {
                if (result.accountFound) {
                    searchTextBox.attr("value", "");
                    handleLabel.text(result.username);
                    avatarImage.attr("src", result.avatarImageUrl);
                    overlayImage.css("display", result.isVip ? "inline" : "none");

                    if (result.id2) {
                        handleHyperlink.attr("href", "javascript:{}");
                        handleHyperlink.click(function() {
                            var handle = window.open("/Pages/Community/ViewProfile.aspx?ppid=" + result.id2, "PublicProfile", "width=800,height=800,scrollbars=yes,resizable=1", true);
                            handle.focus();
                        });

                        avatarImage.css("cursor", "pointer");
                        avatarImage.click(function() {
                            var handle = window.open("/Pages/Community/ViewProfile.aspx?ppid=" + result.id2, "PublicProfile", "width=800,height=800,scrollbars=yes,resizable=1", true);
                            handle.focus();
                        });

                        handleLabel.removeClass("DarkGrayBold");
                    }
                    else {
                        handleHyperlink.removeAttr("href");
                        handleHyperlink.unbind("click");
                        avatarImage.unbind("click");
                        avatarImage.css("cursor", "auto");
                        handleLabel.addClass("DarkGrayBold");
                    }

                    if (result.isFriendRequest) {
                        addFriendImage.attr("src", "/Pages/Community/Images/AcceptButton.gif");
                    }
                    else {
                        addFriendImage.attr("src", "/Pages/Community/Images/Invite/AddFriend.png");
                    }

                    searchResults.show();
                    errorContainer.hide();

                    omnitureScriptManager.resetEvents();
                }

                if (result.isPrivate) {
                    OpenDialogWindow("communityPrivateProfileReminderDialogName");
                }

                if (result.self) {
                    errorLabel.text("You cannot invite yourself.");
                    errorContainer.show();
                }

                if (result.friend) {
                    errorLabel.text("This user is already on your friend list.");
                    errorContainer.show();
                }

                if (result.pending) {
                    errorLabel.text("This user is already on your pending list.");
                    errorContainer.show();
                }

                if (result.maxFriends) {
                    errorLabel.text("You have reached your 50 friend limit.");
                    errorContainer.show();
                }

                if (result.noMatch) {
                    errorLabel.text("No matches found.");
                    errorContainer.show();
                }

                if (waitingDiv != null) {
                    waitingDiv.hide();
                }
            });
    }
    else {
        if (instructions) { instructions.show(); }
        errorContainer.hide();
        searchResults.hide();
    }
}
/* END Friend Search function*/
