﻿Ext.namespace('BYB.UI.Signup');
Ext.namespace('BYB.Store');
Ext.namespace('BYB.User');
Ext.namespace('BYB.Widget');
Ext.namespace('BYB.Data');

Ext.state.Manager.setProvider(new Ext.state.CookieProvider({
    expires: new Date(new Date().getTime() + (1000 * 60 * 60 * 24 * 365))
}));

$("img").lazyload();
$(document).ready(function () {
    addTips();
    addCorners();
    checkSec();
    buildMenu();
    notifications();
    checkNots();

    initFb();
    if (BYB.Util.isDefined('newUser')) {
        BYB.UI.Signup.app.init('modalDiv');
        $("#modalDiv").dialog();
    }
/*
    $("#footerFloatBar").show();
    $("#footerFloatBar").jixedbar({
        showOnTop: false,
        transparent: false,
       slideSpeed: "slow",
        roundedCorners: false,
        roundedButtons: false,
        menuFadeSpeed: "slow",
        tooltipFadeSpeed: "fast",
        tooltipFadeOpacity: 0.5
    });*/

    $(".recentUpdateDiv").each(function () {
        $(this).hover(function () {
            $(this).removeClass('recentUpdateDiv');
            $(this).addClass('recentUpdateDiv_over');
        }, function () {
            $(this).removeClass('recentUpdateDiv_over');
            $(this).addClass('recentUpdateDiv');
        });
        $(this).click(function () {
            window.location = "/stats/matchup/" + $(this).attr("id").substring(3);
        });
    });

});
$(function() {
		$("#tags").autocomplete({
			source: '/user/searchall/'
		});
	});
	
function notifications(){
	if ($('#notificationDiv') != null) {
		if (BYB.Util.isDefined('not_auto')) {
			$('#notificationDiv').bxSlider({
				alignment: 'horizontal', // 'horizontal', 'vertical' - direction in which slides will move
				controls: not_auto, // determines if default 'next'/'prev' controls are displayed
				speed: 1000, // amount of time slide transition lasts (in milliseconds)
				pager: false, // determines if a numeric pager is displayed (1 2 3 4...)
				pager_short: false, // determines if a 'short' numeric pager is displayed (1/4)
				pager_short_separator: ' / ', // text to be used to separate the short pager
				margin: 0,
				next_text: '', // text to be displayed for the 'next' control
				next_image: '/images/spacer.gif', // image to be used for the 'next' control
				prev_text: '', // text to be displayed for the 'prev' control
				prev_image: '/images/spacer.gif', // image to be used for the 'prev' control
				auto: not_auto, // determines if slides will move automatically
				pause: 5000, // time between each slide transition (auto mode only) 
				auto_direction: 'next', // order in which slides will transition (auto mode only)
				auto_hover: true, // determines if slideshow will pause while mouse is hovering over slideshow
				auto_controls: false, // determines if 'start'/'stop' controls are displayed (auto mode only)
				ticker: false, // determines if slideshow will behave as a constant ticker
				stop_text: 'stop', // text to be displayed for the 'stop' control
				start_text: 'start', // text to be displayed for the 'start' control
				wrapper_class: 'bxslider_wrap' // class name to be used for the outer wrapper of the slideshow
			});
		}
	//	$('#notificationDiv').css('display', 'block');
	}
}

function buildMenu(){
    jQuery('ul.sf-menu').superfish();
}

function checkSec() {
    return true;
    if (BYB.Util.isDefined("page_lock")) {
        var pwTxt = new Ext.form.TextField({
            fieldLabel: 'Password'
        });
        var win = new Ext.Window({
            layout: 'form',
            width: 300,
            autoHeight: true,
            modal: true,
            closable: false,
            buttons: [new Ext.Button({
                text: 'Submit',
                handler: function(){
                    if (pwTxt.getValue() == 'gozooka') {
                        BYB.Util.ajax('/user/checksec', {
                            id: pwTxt.getValue()
                        }, function(ret){
                            var res = Ext.decode(ret.responseText);
                            if (res) 
                                win.close();
                        });
                    }
                }
            })],
            items: [pwTxt],
            title: 'Please Enter Fanzooka Password'
        });
        win.show();
    }
}

function hideLoading(){
    $.unblockUI({
        fadeOut: 200
    });
}

function loading(caption) {
    $.blockUI({
        theme: true,
        title: 'Fanzooka',
        message: '<table><tr><td><img class="throbber" src="/images/throbber.gif" alt="Loading..." /></td><td style="font-weight:bold; color:#000; padding-left:7px;">' + caption + '</td></tr></table>',
        baseZ: 7000,
        width: 250,
        css: {
            border: '3px solid #cc0000',
            padding: '15px',
            backgroundColor: '#fff',
            '-webkit-border-radius': '10px',
            '-moz-border-radius': '10px',
            opacity: 0.8,
            color: '#cc0000'
        }
    });
}

function sendFbInvite(fbid){
    facebookPublish(fbid, 'Fanzooka.com Invite', 'Join me on Fanzooka.com!', [{
        text: 'Join!',
        href: 'http://www.fanzooka.com/account/signup/'
    }], 'Fanzooka.com Invite', function(){
    }, function(){
    });
}

function growl(notification, message){
    $.growlUI(notification, message);
}

function createMask(id, message, showImage){

    if (message == null) 
        message = 'loading...';
    
    var img = '';
    if (showImage == true || showImage == null) 
        img = '<div style="float:left;"><img class="throbber" src="/images/throbber.gif" alt="Loading..." /></div>';
    
    var msg = img + '<div style="float:left; padding-left:5px;">' + message + '</div>';
    
    $("#" + id).block({
        message: '<div style="padding:2px">' + msg + "</div>",
        css: {
            padding: '10px',
            border: '3px solid #cc0000'
        }
    });
}

function hideMask(id){
    $("#" + id).unblock();
}

function fbfpage(start, ct){
    createMask('fbFriendList', null, false);
    $('#fbFriendList').load('/facebook/FbFriendList/', {
        start: start,
        count: ct
    }, function(){
        hideMask('fbFriendList');
        addCorners();
    });
}

function facebookPublish(targetId, title, desc, actionLinks, sCallback, fCallback){
	if (BYB.Util.isDefined('fbusr')) {
	
		FB.ui({
			method: 'stream.publish',
			message: desc,
			target_id: targetId,
			action_links: actionLinks,
			user_message_prompt: title
			//,
			//attachments:[{'type': 'image', 'src': image}] 
		}, function(response){
			if (response && response.post_id) {
				sCallback();
			}
			else {
				fCallback();
			}
		});
			return true;
	}
	return false;
}

function logout(){
    loading('logging out...');
    
   // if (BYB.Util.isDefined('fbusr')) {
   //     FB.logout(function(response){
            // user is now logged out
   //         window.location.href = "/user/logout/";
   //     });
   // }
   // else {
        window.location.href = "/user/logout/";
   // }
}

function login(){
    document.location.href = '/user/login/';
}

function initFb(){
	if (BYB.Util.isDefined('FB')) {
		FB.init({
			appId: fbapi,
			status: true, // check login status
			cookie: true, // enable cookies to allow the server to access the session
			xfbml: true // parse XFBML
		}, baseUrl + 'xd_receiver.htm');
		
		FB.Event.subscribe('auth.sessionChange', function(response){
			if (response.session) {
			
			}
			else {
			//	loading('logging out of Facebook...');
				
				// The user has logged out, and the cookie has been cleared
				// location.reload(true);
			}
		});
	}
}

function fbloginSuccess(){
    loading('checking Facebook Connect status...');
    
    BYB.Util.ajax(baseUrl + 'facebook/updatemyfbid/', {}, function(result){
        var result = Ext.util.JSON.decode(result.responseText);
        
        if (result.Error) {
            // need to associate or create account
            Ext.Msg.hide();
            showCreateAssocWin(result.ReturnObject);
        }
        else {
            window.location.reload();
        }
    });
}

function addBud(id){
    loading('adding bud...');
    BYB.Util.ajax(baseUrl + 'user/addbud', {
        userId: id
    }, function(val){
        hideLoading();
        val = Ext.util.JSON.decode(val.responseText);
        if (val.Error == false) {
            fzalert('Success', 'We\'ve sent this user a request to become your Bud!');
        }
        else {
            fzalert('Ooops', val.Message);
        }
    });
}

function confirm(msg, ycall, ncall, ccall){
    $("#confirmMsg").html(msg);
    
    $("#confirmYes").button();
    $("#confirmYes").show();
    $("#confirmNo").button();
    $("#confirmNo").show();
    $("#confirmCancel").button();
    $("#confirmCancel").show();
    
    $("#confirmYes").click(function(){
        $.unblockUI();
        
        if (ycall != null) 
            ycall();
    });
    
    $("#confirmNo").click(function(){
        $.unblockUI();
        
        if (ncall != null) 
            ncall();
    });
    
    $("#confirmCancel").click(function(){
        $.unblockUI();
        
        if (ccall != null) 
            ccall();
    });

    $.blockUI({
    baseZ:5000,
        theme: true,
        title: 'Confirm',
        message: $("#confirmDialog")
    });
}

var confirmDiv;
function fzalert(title, msg, okcall) {
    if (confirmDiv == null)
        confirmDiv = $("#confirmDialog");

    $("#confirmMsg").html(msg);
    $("#confirmYes").hide();
    $("#confirmNo").button({
        label: 'OK'
    });
    $("#confirmCancel").hide();

    $("#confirmNo").click(function () {
        $.unblockUI();

        if (okcall != null) {
            okcall();
        }
    });

    Ext.Msg.hide();
    Ext.WindowMgr.hideAll();

    $.blockUI({
        theme: true,
        title: title,
        message: confirmDiv
    });
}
function archiveCustomBet(betId){
	loading('adding to archive...');
	BYB.Util.ajax('/challenge/archivecustom/', {
		betId: betId
	}, function(ret){
		BYB.Util.forceReload();
	});
}
function archiveBet(betId){
	loading('adding to archive...');
	BYB.Util.ajax('/challenge/archive/', {
		betId: betId
	}, function(ret){
		BYB.Util.forceReload();
	});
}

var _prefsPanel;
var _ln;
var _fn;
var _em;
var _country;
var _newHandle;
var _zip;
var _timeZone;
var _pw1;
var _pw2;
var _pw3;
var _emailNot;
function openPrefs(){
		loading('1 second...');
		BYB.Util.ajax('/user/LoadMyPrefs/', {
}, function (ret) {
    hideLoading();
    if (_prefsPanel == null) {

        var user = Ext.decode(ret.responseText);

        _fn = BYB.Util.createTextField({
            fieldLabel: 'First Name',
            width: 250,
            maskRe: /^[a-zA-Z0-9]{0,}$/,
            value: user.FirstName,
            validators: ['BYB.Validators.character50Max', 'BYB.Validators.required']
        });
        _ln = BYB.Util.createTextField({
            fieldLabel: 'Last Name',
            width: 250,
            maskRe: /^[a-zA-Z0-9]{0,}$/,
            value: user.LastName,
            validators: ['BYB.Validators.character50Max', 'BYB.Validators.required']
        });
        _em = BYB.Util.createTextField({
            fieldLabel: 'Email',
            width: 250,
            value: user.Email,
            validators: ['BYB.Validators.emailAddress', 'BYB.Validators.required']
        });

        var selCon = 'United States';
        if (user.Country != null) {
            selCon = user.Country;
        }
        var cData = [];
        for (var x = 0; x < countries.length; x++) {
            cData[cData.length] = [countries[x], countries[x]];
        }
        _country = BYB.Util.createCombo({
            typeAhead: false,
            triggerAction: 'all',
            lazyRender: true,
            mode: 'local',
            editable: false,
            store: new Ext.data.ArrayStore({
                id: 0,
                fields: ['myId', 'displayText'],
                data: cData
            }),
            fieldLabel: 'Country',
            value: selCon,
            valueField: 'myId',
            displayField: 'displayText'
        });

        _country.on('select', function () {
            if (_country.getValue() != 'United States') {
                _zip.setValue('');
                _zip.setVisible(false);
                _zip.getEl().up('.x-form-item').setDisplayed(false);
            }
            else {
                _zip.setVisible(true);
                _zip.getEl().up('.x-form-item').setDisplayed(true);
            }
        });
        _zip = BYB.Util.createTextField({
            fieldLabel: 'Zip Code',
            width: 65,
            value: user.ZipCode,
            maskRe: /^[0-9_-]{1,5}$/
        });
        _pw1 = BYB.Util.createTextField({
            inputType: 'password',
            width: 250,
            fieldLabel: 'Old Password'
        });
        _pw2 = BYB.Util.createTextField({
            inputType: 'password',
            width: 250,
            fieldLabel: 'New Password',
            validators: ['BYB.Validators.character50Max']
        });
        _pw3 = BYB.Util.createTextField({
            inputType: 'password',
            width: 250,
            fieldLabel: 'New Password (again)',
            validators: ['BYB.Validators.character50Max']
        });
        _newHandle = BYB.Util.createTextField({
            width: 250,
            fieldLabel: 'Handle',
            value: user.Handle,
            maskRe: /^[a-zA-Z0-9]{0,}$/,
            validators: ['BYB.Validators.character50Max', 'BYB.Validators.required']
        });

        _emailNot = new Ext.form.Checkbox({
            fieldLabel: 'Send me Weekly Challenge email updates'
        });
        _emailNot.setValue(user.SendWeeklyChalNot);

        var timeStore = [];
        timeStore[0] = ['-5', 'Eastern Standard Time (EST)'];
        timeStore[1] = ['-6', 'Central Standard Time (CST)'];
        timeStore[2] = ['-7', 'Mountain Standard Time (MST)'];
        timeStore[3] = ['-8', 'Pacific Standard Time (PST)'];

        _timeZone = BYB.Util.createCombo({
            fieldLabel: 'Time Zone',
            store: timeStore,
            valueField: 'ID',
            labelWidth: 250,
            mode: 'local',
            displayField: 'Title',
            editable: false,
            forceSelection: true,
            triggerAction: 'all',
            width: 250,
            listWidth: 225,
            value: user.TimeZone
        });
        _changePwPanel = BYB.Util.createPanel({
            border: false,
            layout: 'form',
            labelWidth: 200,
            items: [_newHandle, _fn, _ln, _em, _country, _zip, _timeZone, _pw1, _pw2, _pw3, _emailNot/*, txtNot, cellNumber, textProvider*/],
            autoHeight: true
        });

        _prefsPanel = new Ext.Panel({
            items: [_changePwPanel],
            autoHeight: true,
            border: false
        });

        _prefsPanel.render('prefsForm');
    }

    $('#prefsDiv').dialog({ width: 490, title: 'Edit Prefs' });
    $('#prefsBtn').button({ label: 'Submit' });
    $('#prefsBtn').click(function () {
        if (_pw2.getValue() == _pw3.getValue()) {
            if (BYB.Util.validatePanel(_changePwPanel)) {
                Ext.Msg.wait('loading...');
                BYB.Util.ajax('/User/ChangeUserInfo/', {
                    oldpw: _pw1.getValue(),
                    newpw: _pw2.getValue(),
                    timeZone: _timeZone.getValue(),
                    firstName: _fn.getValue(),
                    lastName: _ln.getValue(),
                    email: _em.getValue(),
                    handle: _newHandle.getValue(),
                    zip: _zip.getValue(),
                    country: _country.getValue(),
                    sendText: false,
                    sendWeeklyChalMail: _emailNot.getValue()
                }, function (ret) {
                    var val = Ext.util.JSON.decode(ret.responseText);
                    if (val.Error == false) {
                        if (val.Message == "NewHandle") {
                            document.location.href = '/franchise/' + _newHandle.getValue() + '/';
                        }
                        else {
                            Ext.Msg.hide();
                            $('#prefsDiv').dialog('close');
                        }
                    }
                    else {
                        hideLoading();
                        Ext.Msg.alert('Woops', val.Message);
                    }
                });
            }
        }
        else {
            Ext.Msg.alert('Error', 'Passwords were not the same');
        }
    });
});
}

var countries = new Array("United States", "Afghanistan", "Albania", "Algeria", "Andorra", "Angola", "Antarctica", "Antigua and Barbuda", "Argentina", "Armenia", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegovina", "Botswana", "Brazil", "Brunei", "Bulgaria", "Burkina Faso", "Burma", "Burundi", "Cambodia", "Cameroon", "Canada", "Cape Verde", "Central African Republic", "Chad", "Chile", "China", "Colombia", "Comoros", "Congo, Democratic Republic", "Congo, Republic of the", "Costa Rica", "Cote d'Ivoire", "Croatia", "Cuba", "Cyprus", "Czech Republic", "Denmark", "Djibouti", "Dominica", "Dominican Republic", "East Timor", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Ethiopia", "Fiji", "Finland", "France", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Greece", "Greenland", "Grenada", "Guatemala", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Honduras", "Hong Kong", "Hungary", "Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Italy", "Jamaica", "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Korea, North", "Korea, South", "Kuwait", "Kyrgyzstan", "Laos", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg", "Macedonia", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Mauritania", "Mauritius", "Mexico", "Micronesia", "Moldova", "Mongolia", "Morocco", "Monaco", "Mozambique", "Namibia", "Nauru", "Nepal", "Netherlands", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Norway", "Oman", "Pakistan", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Poland", "Portugal", "Qatar", "Romania", "Russia", "Rwanda", "Samoa", "San Marino", " Sao Tome", "Saudi Arabia", "Senegal", "Serbia and Montenegro", "Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "Spain", "Sri Lanka", "Sudan", "Suriname", "Swaziland", "Sweden", "Switzerland", "Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "Togo", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "Uruguay", "Uzbekistan", "Vanuatu", "Venezuela", "Vietnam", "Yemen", "Zambia", "Zimbabwe");

BYB.UI.Signup.app = function(){
    var _email1;
    var _email2;
    var _pw;
    var _pw2;
    function createAcctWin(renderDiv, usr){
    
        var fn = new Ext.form.TextField({
            fieldLabel: 'First Name',
            allowBlank: false,
            width: 200,
            validators: ['BYB.Validators.required']
        });
        
        var ln = new Ext.form.TextField({
            fieldLabel: 'Last Name',
            allowBlank: false,
            width: 200,
            validators: ['BYB.Validators.required']
        });
        var handle = new Ext.form.TextField({
            fieldLabel: 'Desired Username<br />(5-13 Characters)',
            allowBlank: false,
            width: 200,
            //maskRe:'^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{4,8}$'
            maskRe: /^[a-zA-Z0-9_-]{1,13}$/,
            autoCreate: {
                tag: "input",
                type: "text",
                size: "20",
                autocomplete: "off",
                maxlength: "13"
            },
            validators: ['BYB.Validators.required', 'BYB.UI.Signup.app.unVal']
        });
        
        if (usr != null) {
            if (usr.first_name.length > 0 && usr.last_name.length > 0) {
                fn.setValue(usr.first_name);
                ln.setValue(usr.last_name);
                
                handle.setValue(usr.first_name.substring(0, 1) + usr.last_name);
                
                if (handle.getValue().length > 13) {
                    handle.setValue(handle.getValue().substring(0, 12));
                }
            }
        }
        
        var promo = new Ext.form.TextField({
            fieldLabel: 'Promo Code',
            width: 100
        });
        
        if (BYB.Util.isDefined('newUser')) {
            fn.setValue(newUser.FirstName);
            ln.setValue(newUser.LastName);
            handle.setValue(newUser.Handle);
        }
        _email1 = new Ext.form.TextField({
            fieldLabel: 'Email',
            allowBlank: false,
            width: 200,
            vtype: 'email',
            validators: ['BYB.Validators.required', 'BYB.UI.Signup.app.email1Val']
        });
        
        _email2 = new Ext.form.TextField({
            fieldLabel: 'Email (again)',
            allowBlank: false,
            width: 200,
            vtype: 'email',
            validators: ['BYB.Validators.required', 'BYB.UI.Signup.app.email1Val']
        });
        
        _pw = new Ext.form.TextField({
            inputType: 'password',
            fieldLabel: 'Password',
            allowBlank: false,
            width: 200,
            validators: ['BYB.Validators.required', 'BYB.UI.Signup.app.validatePWs']
        });
        _pw2 = new Ext.form.TextField({
            inputType: 'password',
            fieldLabel: 'Password (again)',
            allowBlank: false,
            width: 200,
            validators: ['BYB.Validators.required', 'BYB.UI.Signup.app.validatePWs']
        });
        
        var zip = BYB.Util.createTextField({
            fieldLabel: 'Zipcode',
            allowBlank: false,
            width: 100,
            maskRe: /^[0-9_-]{1,5}$/
        });
        
        var cData = [];
        for (var x = 0; x < countries.length; x++) {
            cData[cData.length] = [countries[x], countries[x]];
        }
        var country = BYB.Util.createCombo({
            typeAhead: false,
            triggerAction: 'all',
            lazyRender: true,
            mode: 'local',
            editable: false,
            store: new Ext.data.ArrayStore({
                id: 0,
                fields: ['myId', 'displayText'],
                data: cData
            }),
            fieldLabel: 'Country',
            value: 'United States',
            valueField: 'myId',
            displayField: 'displayText'
        });
        
        country.on('select', function(){
            if (country.getValue() != 'United States') {
                zip.setValue('');
                zip.setVisible(false);
                zip.getEl().up('.x-form-item').setDisplayed(false);
            }
            else {
                zip.setVisible(true);
                zip.getEl().up('.x-form-item').setDisplayed(true);
            }
        });
        
        var existUserId = null;
        if (BYB.Util.isDefined('newUser')) {
            existUserId = newUser.ID;
        }
        
        var is21 = new Ext.form.Checkbox({
            boxLabel: 'I VERIFY THAT I AM 18 YEARS OF AGE',
            checked: false,
            width: 300
        });
        
        var emailNot = new Ext.form.Checkbox({
            boxLabel: 'Send me periodic email updates',
            checked: false,
            width: 300
        });
        
        var terms = new Ext.form.Checkbox({
            style: 'padding-top:5px; padding-bottom:5px',
            boxLabel: 'I agree to the <a href="javascript:showTerms()">Terms and Conditions</a>',
            checked: false,
            width: 300
        });
        
        is21.on('check', allowBut);
        terms.on('check', allowBut);
        
        function allowBut(cb, checked){
            if (terms.getValue() && is21.getValue()) {
                submit.setDisabled(false);
            }
            else {
                submit.setDisabled(true);
            }
        }
        
        var submit = new Ext.Button({
            text: 'Submit',
            disabled: true
        });
        submit.on('click', function(){
        
            if (fn.getValue() == '') {
                fzalert('Ooops', 'You must enter a first name');
            }
            else {
                if (ln.getValue() == '') {
                    fzalert('Ooops', 'You must enter a last name');
                }
                else {
                    if (handle.getValue().length > 13) {
                        fzalert('Ooops', 'Your handle must be between 5-13 characters');
                    }
                }
            }
            if (BYB.Util.validatePanel(pnl)) {
                if (is21.getValue() != true) {
                    fzalert('Ooops', 'You MUST be 18 years old to register for Fanzooka.com');
                }
                else {
                    loading('creating account...');
                    BYB.Util.ajax('/Account/CreateAccount/', {
                        firstName: fn.getValue(),
                        lastName: ln.getValue(),
                        email: _email1.getValue(),
                        sendEmail: emailNot.getValue(),
                        handle: handle.getValue(),
                        zip: zip.getValue(),
                        country: country.getValue(),
                        existUser: existUserId,
                        promo: promo.getValue(),
                        pw: _pw.getValue()//,
                        //  challenge: Recaptcha.get_challenge(),
                        //  capresponse: Recaptcha.get_response()
                    }, function(ret){
                        var response = Ext.decode(ret.responseText);
                        if (response.Error == false) {
                            if (BYB.Util.isDefined('newUser')) {
                                if (BYB.Util.isDefined('betredir')) {
                                    document.location.href = '/challenge/match/' + betredir + '/';
                                }
                                else {
                                    if (BYB.Util.isDefined('customredir')) {
                                        document.location.href = '/challenge/custom/' + customredir + '/';
                                    }
                                    else {
                                        document.location.href = '/franchise/' + handle.getValue() + '/';
                                    }
                                }
                            }
                            else {
                                //  fzalert('Success!', '<b>Account created successfully!</b><br /><br />Check your email for a verification message', function(){
                                loading('redirecting...');
                                document.location.href = '/franchise/' + handle.getValue();
                                //});
                            }
                        }
                        else {
                            // Recaptcha.reload();
                            fzalert('Small Problem...', response.Message, function(){
                                if (response.Message.indexOf('pending invite') > -1) {
                                    loading('redirecting...');
                                    document.location.href = '/account/acceptinvite/?u=' + response.ReturnObject.ID;
                                }
                            });
                        }
                    });
                }
            }
        });
        
        var items = [fn, ln, handle, _email1, _email2, country, zip, promo, emailNot, terms, is21//, new Ext.Panel({
        // border: false,
        //  style: 'padding-left:200px;',
        //  items: [Ext.get('recaptcha_div')]
        // }) 
        ];
        if (BYB.Util.isDefined('newUser')) {
        
            if (newUser.Email.length == 0) {
                items = [new Ext.form.Label({
                    text: 'Complete your Fanzooka signup!',
                    style: 'font-weight:bold; color:#cc0000'
                }), fn, ln, handle, _email1, _email2, country, zip, _pw, _pw2, promo, emailNot, terms, is21];
            }
            else {
                items = [new Ext.form.Label({
                    text: 'Complete your Fanzooka signup!',
                    style: 'font-weight:bold; color:#cc0000'
                }), fn, ln, handle, country, zip, _pw, _pw2, promo, emailNot, terms, is21];
            }
        }
        
        var pnl = BYB.Util.createFormPanel({
            layout: 'form',
            labelWidth: 135,
            items: items,
            border: false,
            buttons: [submit]
        });
        
        pnl.render(renderDiv);
        
        $("#" + renderDiv).dialog({
            height: 400,
            width: 500,
            modal: true
        });
        
        
    }
    return {
        init: function(div, usr){
            createAcctWin(div, usr);
        },
        unVal: function(val){
            if (val.length < 5 || val.length > 13) {
                return 'Username must be between 5-13 characters';
            }
            else {
                return true;
            }
        },
        email1Val: function(val){
            if (_email1.getValue().toLowerCase() != _email2.getValue().toLowerCase()) {
                return 'Emails must match';
            }
            else 
                return true;
        },
        validatePWs: function(val){
            if (_pw.getValue() != _pw2.getValue()) 
                return "Passwords must match";
            else {
                if (_pw.getValue().length < 6) 
                    return "Passwords must be at least 6 characters";
                else 
                    return true;
            }
        }
    };
}();

function showContactUsWin(){
    var lbl = new Ext.form.Label({
        html: '<div style="font-size:12px; font-weight:bold; padding-bottom:10px;">Send a question or support request to Fanzooka</div>'
    });
    
    var msg = new Ext.form.TextArea({
        width: 200,
        fieldLabel: 'Message'
    });
    
    var pnl = new Ext.form.FormPanel({
        items: [lbl, msg],
        border: false,
        bodyStyle: 'padding:5px'
    });
    
    var submit = new Ext.Button({
        text: 'Submit'
    });
    submit.on('click', function(){
        loading('loading...');
        BYB.Util.ajax('/support/submitrequest/', {
            request: msg.getValue()
        }, function(res){
            hideLoading();
            if (res.responseText == 'true') {
                win.close();
                fzalert('Thank you!', 'Thanks for contacting us. We will be respond to your request ASAP!');
            }
            else {
                win.close();
            }
        });
    });
    var win = new Ext.Window({
        title: 'Contact / Support',
        modal: true,
        width: 350,
        height: 180,
        items: [pnl],
        buttons: [submit]
    });
    win.show();
    win.center();
}

function showCreateAssocWin(usr){
    hideLoading();
    $("#loginAssoc").dialog({
        height: 160,
        width: 350,
        modal: true
    });
    $("#login3").hide();
    $("#yesBtn").button();
    $("#noBtn").button();
    
    $("#noBtn").click(function(){
        BYB.UI.Signup.app.init('createAcct', usr);
    });
    
    $("#yesBtn").click(function(){
        $("#q1").hide();
        
        var un = new Ext.form.TextField({
            fieldLabel: 'Username<br />(or email)'
        });
        var pw = new Ext.form.TextField({
            inputType: 'password',
            fieldLabel: 'Password'
        });
        
        var pnl = new Ext.Panel({
            layout: 'form',
            items: [un, pw],
            border: false
        });
        pnl.render('login2');
        $("#login3").show();
        $("#loginBtn").button();
        $("#loginBtn").click(function(){
            loading('loading...');
            BYB.Util.ajax(baseUrl + 'facebook/assocfbid/', {
                un: un.getValue(),
                pw: pw.getValue()
            }, function(result){
                var result = Ext.util.JSON.decode(result.responseText);
                
                if (result) {
                    location.reload(true);
                }
                else {
                    Ext.Msg.hide();
                    fzalert('Woops', 'The username / password you\'ve specified is invalid.');
                }
            });
        });
    });
}

function challengeUser(uid)
{
	loading('1 second...');
	document.location.href = "/user/challenge/?against=" + uid;
}

function ignoreFbUser(fbid){
    loading('1 second...');
    BYB.Util.ajax(baseUrl + 'user/ignorefbuser', {
        friendID: fbid
    }, function(){
        location.reload(true);
    });
}

function addCorners(){
    // Use the each() method to gain access to each elements attributes
    $('#mainBody div[class=corner]').each(function(){
        $(this).corner("round 8px").parent().css('padding', '4px').corner("round 10px");
    });
}

function addTip(element, tip){
    $(element).qtip({
        content: tip,
        position: {
            corner: {
                target: 'bottomMiddle', // Position the tooltip above the link
                tooltip: 'topMiddle'
            },
            adjust: {
                screen: true // Keep the tooltip on-screen at all times
            }
        },
        show: {
            when: 'mouseover',
            solo: true // Only show one tooltip at a time
        },
        hide: 'mouseout',
        style: {
            tip: true, // Apply a speech bubble tip to the tooltip at the designated tooltip corner
            border: {
                width: 0,
                radius: 4
            },
            name: 'light', // Use the default light style
            width: 350 // Set the tooltip width
        }
    });
}

function addTips(){
    // Use the each() method to gain access to each elements attributes
    $('#mainBody a[rel]').each(function(){
        $(this).qtip({
            content: {
                // Set the text to an image HTML string with the correct src URL to the loading image you want to use
                text: '<img class="throbber" src="/images/throbber.gif" alt="Loading..." />',
                url: $(this).attr('rel'), // Use the rel attribute of each element for the url to load
                title: {
                    text: 'Fanzooka - ' + $(this).attr('name') // Give the tooltip a title using each elements text
                    //button: 'Close' // Show a close link in the title
                }
            },
            position: {
                corner: {
                    target: 'bottomMiddle', // Position the tooltip above the link
                    tooltip: 'topMiddle'
                },
                adjust: {
                    screen: true // Keep the tooltip on-screen at all times
                }
            },
            show: {
                when: 'mouseover',
                solo: true // Only show one tooltip at a time
            },
            hide: 'mouseout',
            style: {
                tip: true, // Apply a speech bubble tip to the tooltip at the designated tooltip corner
                border: {
                    width: 0,
                    radius: 4
                },
                name: 'light', // Use the default light style
                width: 350 // Set the tooltip width
            }
        });
    });
}

function setupTagLine(){
    $("#tagLineDiv").show();
    $("#tagLineEdit").hide();
    
    $("#tagLineBtn").click(function(){
        createMask('tagLineEdit', 'Updating', false);
        BYB.Util.ajax('/user/UpdateStatus/', {
            status: $("#tagLineArea").val()
        }, function(ret){
            var res = Ext.decode(ret.responseText);
            hideMask('tagLineEdit');
            if (res) {
                $("#tagLineDiv").show();
                $("#tagLineDiv").html($("#tagLineArea").val());
                $("#tagLineEdit").hide();
            }
            else {
                fzalert('Woops', 'There was an issue updating your status', function(){
                });
            }
        });
    });
    $("#tagLineCancel").click(function(){
        $("#tagLineEdit").hide();
        $("#tagLineDiv").show();
    });
    
    $("#tagLineSpan").click(function(){
        $("#tagLineDiv").hide();
        $("#tagLineEdit").show();
    });
}

BYB.Util = function () {
    function ajaxFailure() {
        fzalert('Error', 'An error has been encountered - please try again or <a href="javascript:showContactUsWin()">Submit a support request</a>');
    }

    return {
        openInNewWindow: function (url) {
            var newWindow = window.open(url, '_blank');
            newWindow.focus();
            return false;
        },
        roll: function (img_name, img_src) {
            document[img_name].src = img_src;
        },
        decodeHTML: function (str) {
            var ret = str;
            ret = ret.replaceAll('&lt;', '<');
            ret = ret.replaceAll('&gt;', '>');
            ret = ret.replaceAll('\\x22', '"');
            ret = ret.replaceAll("\\x27", "'");
            return ret;
        },
        newUserSignup: function () {
            fzalert('Signup for a Franchise!', 'You need to be signed in to a Fanzooka Franchise to post. <br /><br /><a href="/user/login/">Click here to log in or create a free account</a>');
        },
        showUpdateTimer: function (div, seconds) {

            function calcage(secs, num1, num2, unit) {
                var s = ((Math.floor(secs / num1)) % num2).toString();
                if (s.length < 2) {
                    s = "0" + s;
                }
                /*if (s == '00) 
                return '';
                else*/
                return s + unit;
            }

            var ret = calcage(seconds, 86400, 100000, "D, ");
            ret += calcage(seconds, 3600, 24, "H, ");
            ret += calcage(seconds, 60, 60, "M, ");
            ret += calcage(seconds, 1, 60, "S");

            //Ext.get(div).dom.innerHTML = ret;
            $('#' + div).html(ret);
            seconds -= 1;

            if (seconds > 0) {
                setTimeout('BYB.Util.showUpdateTimer("' + div + '",' + seconds + ')', 1000);
            }
        },
        isDefined: function (variable) {
            return (typeof (window[variable]) == "undefined") ? false : true;
        },
        forceReload: function () {
            window.location.reload(true);
        },
        createDataViewPanel: function (dvParams, pnlParams, store, tplHeight, inner, minHeight, pageSize) {
            var vwPrms = {
                loadingText: 'Loading...',
                store: store
            };
            Ext.apply(vwPrms, dvParams);
            var vw = new Ext.DataView(vwPrms);

            var mh = true;
            if (minHeight != null) {
                mh = minHeight;
            }

            var bbar = null;
            if (pageSize != null) {
                bbar = BYB.Util.createPagingToolbar(pageSize, store);
            }
            var pnlPrms = {
                items: [vw],
                autoHeight: true,
                width: 346,
                collapsible: true,
                border: false,
                autoScroll: true
            };
            Ext.apply(pnlPrms, pnlParams);

            if (bbar != null) {
                pnlPrms.bbar = bbar;
            }

            var pnl = BYB.Util.createPanel(pnlPrms, inner);

            pnl.on('render', function () {
                pnl.getEl().setStyle('height', '250px');
                pnl.getEl().mask('Loading...');
            });

            store.on('load', function (records) {
                if ((records.data.length * tplHeight) < 275) {
                    var nh = records.data.length * tplHeight + 63;
                    pnl.setHeight(nh);
                }
                else {
                    if (mh) {
                        pnl.setHeight(275);
                    }
                    else {
                        pnl.setHeight(records.data.length * tplHeight);
                    }
                }

                if (pnl.getEl() != null) {
                    pnl.getEl().setStyle('height', 'auto');
                    pnl.getEl().unmask();
                }
                pnl.doLayout();
            });

            return pnl;
        },
        createGrid: function (params, store, pageSize) {

            var addpaging = false;
            if (pageSize != null) {
                if (store != null) {
                    addpaging = true;
                }
            }

            var bbar;
            if (addpaging) {
                bbar = BYB.Util.createPagingToolbar(pageSize, store);
            }

            var prms = {
                cls: 'inner',
                disableSelection: false,
                enableColumnHide: false,
                enableColumnResize: false,
                loadMask: true,
                stripeRows: true,
                trackMouseOver: false,
                width: 348,
                enableHdMenu: false,
                maxHeight: 275,
                autoHeight: true,
                autoScroll: true,
                defaultSortable: false,
                viewConfig: {
                    forceFit: true,
                    enableRowBody: false,
                    autoFill: false,
                    emptyText: 'No current records'
                }
            };

            if (addpaging)
                prms.bbar = bbar;

            if (store != null)
                prms.store = store;

            Ext.apply(prms, params);
            return new Ext.grid.GridPanel(prms);
        },
        createTemplateFromControl: function (control) {
            var tmp = BYB.Util.decodeHtml(control);

            return new Ext.XTemplate(tmp);
        },
        createPagingToolbar: function (pageSize, store) {
            var pagingBar = new Ext.PagingToolbar({
                pageSize: pageSize,
                store: store,
                displayInfo: true,
                displayMsg: 'Displaying {0} - {1} of {2}',
                emptyMsg: ""
            });

            return pagingBar;
        },
        createTextArea: function (params) {
            var tf = new Ext.form.TextArea(params);
            return tf;
        },
        createButton: function (params) {
            return new Ext.Button(params);
        },
        createCombo: function (params) {
            var prms = {
                mode: 'remote',
                typeAhead: false,
                forceSelection: true,
                triggerAction: 'all',
                loadingText: 'Loading...'
            };
            Ext.apply(prms, params);
            return new Ext.ux.DefaultingComboBox(prms);
            // return new Ext.form.ComboBox(prms);
        },
        createPasswordField: function (params) {
            var np = {
                inputType: 'password'
            };
            Ext.apply(np, params)
            var tf = new Ext.form.TextField(np);
            return tf;
        },
        createTextField: function (params) {
            var tf = new Ext.form.TextField(params);
            return tf;
        },
        createLabel: function (params) {
            var tf = new Ext.ux.form.StaticTextField(params);
            return tf;
        },
        createDatePicker: function (params) {
            var dp = new Ext.form.DateField(params);
            return dp;
        },
        createTimePicker: function (params) {
            var dp = new Ext.form.TimeField(params);
            return dp;
        },
        createFormPanel: function (params) {
            var prms = {
                bodyStyle: 'padding:5px'
            };
            Ext.apply(prms, params);
            var frm = new Ext.form.FormPanel(prms);
            return frm;
        },
        createPanel: function (params, inner) {
            var innerCls = true;
            if (inner != null) {
                innerCls = inner;
            }

            var prms;
            if (innerCls) {
                prms = {
                    bodyStyle: 'padding:5px',
                    style: 'padding-bottom:10px',
                    cls: 'inner'
                }
            }
            else {
                prms = {
                    bodyStyle: 'padding:5px'
                }
            }
            Ext.apply(prms, params);
            var frm = new Ext.Panel(prms);
            return frm;
        },
        createRemoteStore: function (url, columns, idCol, params) {
            var colList = [];
            for (var x = 0; x < columns.length; x++) {
                colList[x] = {
                    name: columns[x]
                };
            }

            var urlStr = baseUrl + url;

            var pxy = new Ext.data.HttpProxy({
                url: urlStr,
                method: 'POST'
            });

            var prms = {
                proxy: pxy,
                remoteSort: true,
                root: 'Values',
                reader: new Ext.data.JsonReader({
                    root: 'Values',
                    totalProperty: 'TotalCount',
                    id: idCol
                }, colList)
            };
            Ext.apply(prms, params);

            if (prms.baseParams != null) {
                prms.baseParams.__extjs = true;
            }
            else {
                prms.baseParams = {
                    __extjs: true
                };
            }

            var store = new Ext.data.Store(prms);

            return store;
        },
        validatePanel: function (panel) {
            var ret = true;
            for (var x = 0; x < panel.items.items.length; x++) {
                if (panel.items.items[x].validators != null) {
                    for (var y = 0; y < panel.items.items[x].validators.length; y++) {
                        var result = eval(panel.items.items[x].validators[y] + '(\'' + panel.items.items[x].getValue() + '\')');
                        if (result != true) {
                            panel.items.items[x].markInvalid(result);
                            ret = false;
                        }
                    }
                }
            }
            return ret;
        },
        showMessage: function (msg, title, callback) {
            if (title == null) {
                title = 'Info';
            }
            fzalert(title, msg, callback);
        },
        evalDateStr: function (dateStr) {
            var dt = eval(dateStr.replace(/\/Date\((\d+)\)\//gi, "new Date($1)"));
            return dt;
        },
        ajax: function (url, params, success, failure) {
            if (failure == null) {
                failure = ajaxFailure;
            }
            var tmpParams = {
                __extjs: true
            };
            Ext.apply(tmpParams, params);
            Ext.Ajax.request({
                url: url,
                //  disableCaching :true,
                method: 'POST',
                success: success,
                failure: failure,
                params: tmpParams,
                timeout: 100000
            });
        },
        refreshPage: function () {
            window.location.reload();
        },
        sideNavSelect: function (index) {
            for (var x = 0; x < 10; x++) {
                var tmp = Ext.get('profNav' + x);
                if (tmp != null) {
                    if (index == x) {
                        tmp.replaceClass('profileNavItem', 'profileNavItemSel');
                    }
                    else {
                        tmp.replaceClass('profileNavItemSel', 'profileNavItem');
                    }
                }
            }
        }
    };
} ();
Ext.ux.DefaultingComboBox = function(config){
    Ext.ux.DefaultingComboBox.superclass.constructor.call(this, config);
};

Ext.extend(Ext.ux.DefaultingComboBox, Ext.form.ComboBox, {
    setValue: function(v){
        // If the ComboBox hasn't been loaded yet, load it asynchronously
        // before setting the value.
        if (this.mode == 'remote' && this.store.getCount() == 0) {
            this.store.on("load", function(){
                Ext.ux.DefaultingComboBox.superclass.setValue.call(this, v);
            }, this, {
                single: true
            });
            this.doQuery(this.allQuery, true);
        }
        else {
            Ext.ux.DefaultingComboBox.superclass.setValue.call(this, v);
        }
    }
});

BYB.Validators = function(){
    return {
        required: function(value){
            if (value == null) {
                return "Required";
            }
            else {
                if (value.length > 0) {
                    return true;
                }
                else {
                    return "Required";
                }
            }
        },
        emailAddress: function(value){
            var emailregex = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
            if (emailregex.test(value) == false) {
                return "Invalid email format.";
            }
            else {
                return true;
            }
        },
        character50Max: function(value){
            if (value == null) {
                return "Must be less that 50 characters";
            }
            else {
                if (value.length > 50) {
                    return 'Must be less that 50 characters';
                }
                else {
                    return true;
                }
            }
        },
        character100Max: function(value){
            if (value == null) {
                return "Must be less that 100 characters";
            }
            else {
                if (value.length > 50) {
                    return 'Must be less that 100 characters';
                }
                else {
                    return true;
                }
            }
        },
        passwordMinMax: function(value){
            if (value == null || value.length == 0) {
                return true;
            }
            else {
                if (value.length < 5 || value.length > 50) {
                    return 'Password must be between 6-100 characters';
                }
                else {
                    return true;
                }
            }
        }
    };
}();

BYB.UI.Common = function () {

    var _suggStore;

    function createLinkWin(id, title, desc, link, isPublic, isDraft, teamTags, playerTags){
	
	$('#postRow').hide();
		$('#titleInput').val(title);
		$('#shortInput').val(desc);
		
		var draftVal = false;
		if (isDraft == true) {
			draftVal = true;
		}
		var tagWidget = new BYB.Widget.tagSelector();
		var tagPanel = tagWidget.getPanel();
		tagWidget.setSelected(teamTags, playerTags);
		
		$('#publicInput').attr('checked', isPublic);
		$('#linkInput').val(link);
		$('#newArticleSave').button().click(function(){
			var ok = true;
			if ($('#shortInput').val().length > 500) {
				fzalert('Oooops', 'The description must be less than 500 characters');
				ok = false;
			}
			else {
				if ($('#titleInput').val().length > 150) {
					fzalert('Oooops', 'The title must be less than 150 characters');
					ok = false;
				}
				else {
					if ($('#titleInput').val().length == 0) {
						fzalert('Oooops', 'You must supply a title');
						ok = false;
					}
					else {
						if ($('#linkInput').val().length == 0) {
							fzalert('Oooops', 'You must supply a link');
							ok = false;
						}
					}
				}
			}
			
			if (ok) {
				loading('Submitting...');
				
				var draft = false;
				draft = $('#draftInput').is(':checked');
				
				var addit = '';
				if (id != null) 
					addit += '?articleId=' + id;
				
				var tt = tagWidget.getSelectedTeams();
				var pt = tagWidget.getSelectedPlayers();
				
				BYB.Util.ajax('/user/postlink/' + addit, {
					title: $('#titleInput').val(),
					blurb: $('#shortInput').val(),
					isPublic: $('#publicInput').is(':checked'),
					link: $('#linkInput').val(),
					isDraft: draft,
					teamTags: tt,
					playerTags: pt
				}, function(res){
					var artNum = Ext.decode(res.responseText);
					var fbDesc = curUserHandle + ' has posted a new article';
					fbDesc += ' titled "' + $('#titleInput').val() + '"';
					fbDesc += ' on Fanzooka.com';
					
					var actionLinks = [{
						"text": "View this Article!",
						"href": baseUrl + "/franchise/column/" + artNum + "/"
					}];
					
					var callback = function(){
						document.location.href = "/franchise/column/" + artNum + "/";
					};
					
					if (!facebookPublish(null, 'Want to publish this Article to your wall?', fbDesc, actionLinks, callback, callback)) {
						callback();
					}
					
				});
			}
		});
		
		$('#newArticle').dialog({
			title: 'Sports Column Article',
			modal: true,
			width: 480,
			height: 200
		});
	}

    function createPostWin(id, title, isPublic, isDraft, body, teamTags, playerTags, youTubeVal) {
        var title = new Ext.form.TextField({
            fieldLabel: 'Title',
            width: 400,
            required: true,
            autoCreate: {
                tag: 'input',
                type: 'text',
                autocomplete: 'off',
                maxlength: '150'
            },
            value: title
        });

        var draftVal = false;
        if (isDraft == true)
            draftVal = true;

        var tagWidget = new BYB.Widget.tagSelector();
        var tagPanel = tagWidget.getPanel();
        tagWidget.setSelected(teamTags, playerTags);

        var youTube = new Ext.form.TextField({
            fieldLabel: 'YouTube URL<br />(optional)',
            width: 400
        });

        if (youTubeVal != null) {
            youTube.setValue(youTubeVal);
        }

        var rd1 = new Ext.form.Radio({
            boxLabel: 'Save as Draft',
            name: 'draftRadio',
            checked: draftVal
        });
        var rd2 = new Ext.form.Radio({
            boxLabel: 'Publish',
            name: 'draftRadio',
            checked: !draftVal
        });
        var rg = new Ext.form.RadioGroup({
            items: [rd2, rd1],
            fieldLabel: 'Status'
        });

        var story = new Ext.form.TextArea({
            fieldLabel: 'Story',
            width: 400,
            value: body,
            height: 200
        });

        var publicStory = new Ext.form.Checkbox({
            fieldLabel: 'Public',
            checked: isPublic
        });
        var btn = new Ext.Button({
            text: 'Submit'
        });
        btn.on('click', function () {
            var ok = true;
            if (title.getValue().length > 150) {
                Ext.Msg.alert('Oooops', 'The title must be less than 150 characters');
                ok = false;
            }
            else {
                if (title.getValue().length == 0) {
                    Ext.Msg.alert('Oooops', 'You must enter a title');
                    ok = false;
                }
            }

            if (story.getValue().length == 0) {
                Ext.Msg.alert('Oooops', 'You must enter a story');
                ok = false;
            }

            if (ok) {
                Ext.Msg.wait('Submitting...');

                var draft = false;
                if (rd1.getValue() == true) {
                    draft = true;
                }

                var addition = '';
                if (id != null)
                    addition += '?articleID=' + id
                BYB.Util.ajax('/user/postarticle/' + addition, {
                    title: title.getValue(),
                    story: story.getValue(),
                    isPublic: publicStory.getValue(),
                    isDraft: draft,
                    youTube: youTube.getValue(),
                    teamTags: tagWidget.getSelectedTeams(),
                    playerTags: tagWidget.getSelectedPlayers()
                }, function (res) {
                    var artNum = Ext.decode(res.responseText);
                    var fbDesc = curUserHandle + ' has posted a new article';
                    fbDesc += ' titled "' + title.getValue() + '"';
                    fbDesc += ' on Fanzooka.com';

                    var actionLinks = [{
                        "text": "View this Article!",
                        "href": baseUrl + "/franchise/column/" + artNum + "/"
                    }];

                    var retFct = function () {
                        document.location.href = "/franchise/column/" + artNum + "/";
                    }
                    if (!BYB.Facebook.post('Want to publish this Article to your wall?', fbDesc, actionLinks, retFct)) {
                        retFct();
                    }
                });
            }
        });
        var pnl = BYB.Util.createPanel({
            layout: 'form',
            border: false,
            items: [title, youTube, story, publicStory, tagPanel, rg]
        });
        var win = new Ext.Window({
            items: pnl,
            buttons: [btn],
            title: 'Post an Article!',
            modal: true,
            autoScroll: true,
            height: 480,
            width: 550
        });
        win.show();
        win.center();
    }

    return {
        showInviteUserWin: function () {
            var email = new Ext.form.TextField({
                fieldLabel: 'Email',
                allowBlank: false,
                width: 200,
                vtype: 'email',
                validators: ['BYB.Validators.required']
            });

            var lbl = new Ext.form.Label({
                html: '<div style="padding-bottom:10px;"><span style="font-size:12px; font-weight:bold;">Enter your bud\'s information to invite to Fanzooka!</span><br />(Seperate emails with commas for multiple invites)</div>'
            });

            var msg = new Ext.form.TextArea({
                width: 200,
                fieldLabel: 'Message'
            });

            var pnl = BYB.Util.createFormPanel({
                items: [lbl, email, msg],
                border: false,
                bodyStyle: 'padding:5px'
            });

            var submit = new Ext.Button({
                text: 'Submit'
            });
            submit.on('click', function () {
                if (BYB.Util.validatePanel(pnl)) {
                    loading('loading...');
                    BYB.Util.ajax('/user/InviteUser/', {
                        email: email.getValue(),
                        msg: msg.getValue()
                    }, function (res) {
                        hideLoading();
                        if (res.responseText == 'true') {
                            win.close();
                            Ext.Msg.alert('Success', 'An invite has been successfully sent!');
                        }
                        else {
                            win.close();
                            Ext.Msg.alert('Wooops', 'A user with this email address is already registered. Use the Bud Search to find them!');
                        }
                    });
                }
            });
            var win = new Ext.Window({
                title: 'Invite a Bud to Fanzooka!',
                modal: true,
                width: 350,
                height: 200,
                items: [pnl],
                buttons: [submit]
            });
            win.show();
            win.center();
        },
        showContactUsWin: function () {
            var lbl = new Ext.form.Label({
                html: '<div style="font-size:12px; font-weight:bold; padding-bottom:10px;">Send a question or support request to Fanzooka</div>'
            });

            var msg = new Ext.form.TextArea({
                width: 200,
                fieldLabel: 'Message'
            });

            var pnl = new Ext.form.FormPanel({
                items: [lbl, msg],
                border: false,
                bodyStyle: 'padding:5px'
            });

            var submit = new Ext.Button({
                text: 'Submit'
            });
            submit.on('click', function () {
                Ext.Msg.wait('loading...');
                BYB.Util.ajax('/support/submitrequest/', {
                    request: msg.getValue()
                }, function (res) {
                    if (res.responseText == 'true') {
                        win.close();
                        Ext.Msg.alert('Success', 'Thanks for contacting us. We will be respond to your request ASAP!');
                    }
                    else {
                        win.close();
                    }
                });
            });
            var win = new Ext.Window({
                title: 'Contact / Support',
                modal: true,
                width: 350,
                height: 180,
                items: [pnl],
                buttons: [submit]
            });
            win.show();
            win.center();
        },
        showImportantMessages: function () {
            var store = BYB.Util.createRemoteStore('/user/GetMyImportantMessages/', ['ID', 'Title', 'Message', 'Url'], 'ID');
            var msgGrid = BYB.Util.createGrid({
                header: false,
                columns: [{
                    width: 18,
                    header: '',
                    dataIndex: 'ID',
                    renderer: function () {
                        return '<img src="/images/icons/excl16.jpg" />';
                    }
                }, {
                    header: 'Message',
                    width: 380,
                    dataIndex: 'Title',
                    renderer: function (val, meta, rec) {
                        var ret = '<a href="' + rec.get('Url') + '">' + val + '</a>';
                        if (rec.get('Message') != null) {
                            ret += '<br /><span color="#aaa">' + rec.get('Message') + '</span>';
                        }

                        return ret;
                    }
                }],
                store: store,
                autoHeight: true,
                maxHeight: 500,
                loadMask: true,
                width: 400,
                border: false
            });

            var win = new Ext.Window({
                items: [msgGrid],
                autoHeight: true,
                title: 'Important Messages',
                modal: true,
                width: 410
            });
            store.on('load', function () {
                win.center();
            });
            store.load();
            win.show();
            win.center();
        },
        attachUserTip: function (userID, elem) {
            new Ext.ToolTip({
                target: elem,
                shadow: 'drop',
                width: 300,
                dismissDelay: 0,
                autoLoad: {
                    url: '/quicktip/UserTip/?userid=' + userID
                },
                height: 50,
                trackMouse: false
            });
        },
        attachTeamTip: function (teamID, elem) {
            new Ext.ToolTip({
                target: elem,
                shadow: 'drop',
                width: 305,
                dismissDelay: 0,
                autoLoad: {
                    url: '/quicktip/TeamTip/?teamid=' + teamID
                },
                height: 50,
                trackMouse: false
            });
        },
        attachMatchTip: function (teamID, elem) {
            new Ext.ToolTip({
                target: elem,
                shadow: 'drop',
                dismissDelay: 0,
                width: 300,
                autoLoad: {
                    url: '/quicktip/MatchTip/?matchID=' + teamID
                },
                height: 50,
                trackMouse: false
            });
        },
        giveThumbsUp: function (banterID, storyID, thumb, thumbdone) {
            if (BYB.Util.isDefined('curUserId')) {
                Ext.get(thumb).setStyle('display', 'none');
                Ext.Msg.wait('Loading...');
                BYB.Util.ajax('/user/givethumbsup/', {
                    storyID: storyID,
                    banterID: banterID
                }, function () {
                    Ext.Msg.hide();
                    Ext.Msg.alert('Success', 'You\'ve given this story a thumbs up!');
                    Ext.get(thumbdone).setStyle('display', 'inline');
                });
            }
            else {
                Ext.Msg.alert('Ooops', "You're not current signed in to Fanzooka - you can either <a href='/user/login/'>log in</a> or <a href='/account/signup/'>sign up</a>");
            }
        },
        makePurchase: function (itemID, quantity) {
            Ext.Msg.wait('Loading...');
            BYB.Util.ajax('/store/MakePurchase/', {
                itemID: itemID,
                quantity: quantity
            }, function () {
                Ext.Msg.hide();
                Ext.Msg.alert('Complete', 'Purchase Complete!')
            });
        },
        showStoreItem: function (itemid) {
            var win = new Ext.Window({
                autoLoad: {
                    url: '/store/ItemDetail/?itemid=' + itemid,
                    callback: function () {
                        win.center();
                    }
                },
                width: 220,
                height: 250,
                autoHeight: true,
                modal: true
            });

            win.show();
        },
        ignoreSugg: function (match) {
            loading('1 second...');
            BYB.Util.ajax('/user/ignoresugg/?matchupid=' + match, {}, function (res) {
                //  Ext.Msg.hide();
                //  _suggStore.load();
                BYB.Util.forceReload();
            });
        },
        getSuggestedBetsPanel: function (hideIfNone) {

            var url = 'Bet/GetSuggestedBets/';

            _suggStore = BYB.Util.createRemoteStore(url, ['ID', 'MatchupID', 'AgainstID', 'AgainstHandle', 'MatchupName', 'EventDate'], 'ID');

            var tpl = new Ext.XTemplate('<tpl for=".">', '<div style="padding-top:3px; border-bottom:solid 1px #ccc; padding-bottom: 3px;">', '<div><div class="suggHeader">Matchup:</div><div class="suggItem"><a href="/stats/matchup/{MatchupID}/">{MatchupName}</a></div></div>', '<div><div class="suggHeader">Date:</div><div class="suggItem">{EventDate}</div></div>', '<div><div class="suggHeader">Versus:</div><div class="suggItem"><div style="float:left;"><a href="/franchise/{AgainstHandle}/">{AgainstHandle}</a></div></div></div>', '<div><div class="suggPlace"><a href="javascript:BYB.UI.Common.ignoreSugg({ID});">Ignore</a> | <a href="/user/challenge/?match={MatchupID}">Place the Challenge ></a></div></div>', '</div>', '</tpl>');
            // '<div class="sugBetsDiv"><div class="anonymatchup"><table cellpadding="0" cellspacing="0"><tr><td style="width:91px; text-align:center; vertical-align:top; padding-top:7px; padding-left:7px;"><table cellpadding="0" cellspacing="0"><tr><td><img src="{User1TeamLargeLogo}" width="40" height="40" /></td><td style="padding-left:2px"><img class="imgBorder" width="40" height="40" src="{User1Pic}" style="solid 1px #666" alt="{User1Handle}" border="0"></td></tr><tr><td colspan="2"  style="padding-top:4px"><a class="handleLink" href="/franchise/{User1Handle}">{User1Handle}</a><br /><a class="teamLink" href="/Stats/Team/{User1TeamID}/{User1TeamName}"><b>{User1ShortTeamName}</b></a></td></tr></table></td><td style="width:100px; height:75px; text-align:center; vertical-align:bottom;"><a href="/user/placematchup/?match={MatchupID}"  style="color:white">Place Bet!</a></td><td style="width:95px; text-align:center; padding-top:7px; padding-right:5px;"><table cellpadding="0" cellspacing="0"><tr><td><img src="{User2TeamLargeLogo}" width="40" height="40" /></td><td style="padding-left:2px"><img class="imgBorder" width="40" height="40" src="{User2Pic}" style="solid 1px #666" alt="{User2Handle}" border="0"></td></tr><tr><td colspan="2"  style="padding-top:4px"><a class="handleLink" href="/franchise/{User2Handle}">{AgainstHandle}</a><br /><a class="teamLink" href="/Stats/Team/{User2TeamID}/{User2TeamName}"><b>{User2ShortTeamName}</b></a></td></tr></table></td></tr></table></div></div>', '</tpl>');

            var panel = new Ext.Panel({
                id: 'suggBets',
                frame: false,
                width: 253,
                hidden: true,
                border: false,
                autoHeight: true,
                collapsible: true,
                layout: 'fit',
                collapsed: true,
                title: 'Suggestions',
                style: 'padding:2px; background-color:#fff;',
                items: new Ext.DataView({
                    store: _suggStore,
                    tpl: tpl,
                    autoHeight: true,
                    itemSelector: 'recentBetsDiv',
                    emptyText: '<a href="/user/challenge/"><img src="/images/nobets.jpg" border="0"></a>'
                })
            }, false);
            _suggStore.on('load', function (store, records) {
                if (records.length > 0) {
                    panel.show();
                    panel.expand(true);
                }
                else {
                    panel.hide();
                }
            });

            _suggStore.load();
            return panel;
        },
        getAnonymousBetsPanel: function (hideIfNone) {

            var url = 'Bet/GetAvailableAnonyousBets/';

            var betStore = BYB.Util.createRemoteStore(url, ['Description', 'VsUser', 'Url', 'ID', 'SportID', 'CustomID'], 'ID');

            var tpl = new Ext.XTemplate('<tpl for=".">', '<div class="recentBetsDiv"><div class="anonymatchup" style="padding-bottom:3px; border-bottom:solid 1px #666; padding-top:3px; padding-left:3px;"><table cellpadding="0" cellspacing="0" width="100%"><tr><tpl for="VsUser"><td width="60">{SmallDetails}</td></tpl><td style="padding-left:4px; vertical-align:top; text-align:left;"><b>Challenge:</b><br /><i>{Description}</i></td></tr><tr><td colspan="2" style="padding-top:4px; text-align:right;"><a href="/bet/IgnoreAnonyBet/?sportsBetID={SportID}&customBetID={CustomID}">Ignore</a>&nbsp;|&nbsp;<a href="{Url}">View Challenge &gt;</a></td></tr></table></div></div>', '</tpl>');

            var panel = new Ext.Panel({
                id: 'anonyBets',
                frame: false,
                width: 253,
                border: false,
                autoHeight: true,
                hidden: true,
                collapsed: true,
                collapsible: true,
                layout: 'fit',
                title: 'Available Challenges',
                style: 'padding:2px; background-color:#fff;',
                items: new Ext.DataView({
                    store: betStore,
                    tpl: tpl,
                    autoHeight: true,
                    itemSelector: 'recentBetsDiv',
                    emptyText: '<a href="/user/challenge/"><img src="/images/nobets.jpg" border="0"></a>'
                })
            }, false);
            betStore.on('load', function (store, records) {
                if (records.length > 0) {
                    var pnl = Ext.getCmp('anonyBets');
                    pnl.show();
                    pnl.expand(true);
                    addTips();
                }
            });
            betStore.load();
            return panel;
        },
        forgotPwWin: function () {
            var subBtn = new Ext.Button({
                text: 'Submit'
            });

            subBtn.on('click', function () {
                if (pnl.getForm().isValid()) {
                    Ext.Msg.wait('Sending...');

                    var url = baseUrl + 'user/forgotpw';
                    if (url.indexOf('www') > -1) {
                        url = 'http://www.fanzooka.com/user/forgotpw/';
                    }
                    BYB.Util.ajax(url, {
                        email: em.getValue()
                    }, function (res) {
                        var worked = Ext.decode(res.responseText);
                        if (worked == true) {
                            Ext.Msg.alert('Success', 'An email has been sent containing your new password.', function () {
                                Ext.Msg.wait('Redirecting to login...');
                                document.location.href = '/user/login/';
                            });
                        }
                        else {
                            Ext.Msg.alert('Failure', 'A user account was not found for that email address');
                        }
                    });
                }
            });

            var em = new Ext.form.TextField({
                fieldLabel: 'Email',
                allowBlank: false,
                width: 200
            });
            var txt = new Ext.form.Label({
                html: '<div style="font-size:13px; font-weight:bold; padding-bottom:10px;">Enter your email address to reset your password</div>'
            });
            var pnl = new Ext.form.FormPanel({
                items: [txt, em],
                bodyStyle: 'padding:6px'
            });

            var win = new Ext.Window({
                items: [pnl],
                title: 'Forgot Password',
                modal: true,
                buttons: [subBtn],
                width: 350,
                autoHeight: true
            });

            win.show();
            win.center();
        },
        editLinkWin: function (articleId) {
            if (articleId != null) {
                Ext.Msg.wait('Loading...')
                // loading
                BYB.Util.ajax('/user/loadarticle/', {
                    id: articleId
                }, function (ret) {
                    var res = Ext.decode(ret.responseText);
                    Ext.Msg.hide();
                    createLinkWin(articleId, res.Title, res.Blurb, res.Link, res.Public, res.Draft, res.TeamTags, res.PlayerTags);
                });
            }
            else {
                createLinkWin(null, '', '', '', true, false, [], []);
            }
        },
        postLinkWin: function () {
            createLinkWin(null, '', '', 'http://', true, false, [], []);
        },
        deleteArticle: function (articleID) {
            Ext.Msg.confirm('Confirm Delete', 'Are you sure you\'d like to delete this article?', function (btn) {
                if (btn == 'yes') {
                    Ext.Msg.wait('Deleting article...')
                    BYB.Util.ajax('/user/deletearticle/', {
                        articleID: articleID
                    }, function (ret) {
                        document.location.href = '/franchise/' + curUserHandle + '#tb:fran-column';
                    });
                }
            });
        },
        postArticleWin: function (articleId) {
            if (articleId != null) {
                Ext.Msg.wait('Loading...')
                // loading
                BYB.Util.ajax('/user/loadarticle/', {
                    id: articleId
                }, function (ret) {
                    var res = Ext.decode(ret.responseText);
                    Ext.Msg.hide();
                    createPostWin(articleId, res.Title, res.Public, res.Draft, res.Content, res.TeamTags, res.PlayerTags, res.YouTubeLink);
                });
            }
            else {
                createPostWin(null, '', true, false, '', [], [], '');
            }
        },
        printSchedWin: function () {
            var startDate = new Ext.form.DateField({
                fieldLabel: 'Start Date',
                value: new Date()
            });

            var nextDate = new Date();
            var unixDate = new Date(nextDate.getTime() + 30 * 24 * 60 * 60 * 1000);
            nextDate.setFullYear(unixDate.getFullYear());
            nextDate.setMonth(unixDate.getMonth());
            nextDate.setDate(unixDate.getDate());

            var endDate = new Ext.form.DateField({
                fieldLabel: 'End Date',
                value: nextDate
            });

            var sportBoxes = [];
            for (var x = 0; x < sportList.length; x++) {
                sportBoxes[x] = new Ext.form.Checkbox({
                    boxLabel: sportList[x].Name,
                    sportID: sportList[x].ID,
                    name: 'sportBox' + x,
                    checked: sportList[x].Active
                });
            }
            var sports = new Ext.form.CheckboxGroup({
                id: 'myGroup',
                xtype: 'checkboxgroup',
                fieldLabel: 'Include Sports',
                itemCls: 'x-check-group-alt',
                // Put all controls in a single column with width 100%
                columns: 2,
                items: sportBoxes
            });
            var bets = new Ext.form.Checkbox({
                fieldLabel: 'Optional',
                boxLabel: 'Show games that I have bets on'
            });
            var pnl = new Ext.Panel({
                bodyStyle: 'padding:8px;',
                layout: 'form',
                width: 350,
                items: [startDate, endDate, sports, bets]
            });
            var btn = new Ext.Button({
                text: 'Go!'
            });
            btn.on('click', function () {
                var sportStr = '';
                for (var x = 0; x < sportBoxes.length; x++) {
                    if (sportBoxes[x].getValue() == true)
                        sportStr += sportBoxes[x].sportID + ',';
                }
                var loc = '/user/printmyschedule/?start=' + getDateStr(startDate.getValue()) + '&end=' + getDateStr(endDate.getValue()) + '&sports=' + sportStr + '&showbets=' + bets.getValue()
                window.open(loc, '', 'scrollbars=yes,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');

            });
            function getDateStr(theDate) {
                return theDate.getMonth() + 1 + '/' + theDate.getDate() + '/' + theDate.getFullYear();
            }
            var win = new Ext.Window({
                items: pnl,
                modal: true,
                title: 'Choose which games to show in your schedule',
                buttons: [btn],
                width: 365,
                height: 255
            });
            win.show();
            win.center();
        },
        showPendingBets: function () {
            var betsStore = BYB.Util.createRemoteStore('User/GetMyBets/', ['SportName', 'Winner', 'WaitingForUserID', 'WaitingForUserHandle', 'DatePlaced', 'BetID', 'MatchupID', 'AgainstUserHandle', 'Team1Name', 'Team2Name', 'MyPicTeam', 'AgainstUserID', 'AgainstUserPic', 'EventDate', 'EventName', 'Status'], 'ID');

            if (curUserId != null) {
                betsStore.baseParams.userID = curUserId;
                betsStore.baseParams.myPending = true;
            }

            var betGrid = BYB.Util.createGrid({

                columns: [{
                    header: 'Against',
                    width: 80,
                    dataIndex: 'AgainstUserHandle',
                    renderer: BYB.Renderers.againstRenderer
                }, {
                    header: 'Game',
                    width: 250,
                    dataIndex: 'EventName',
                    renderer: BYB.Renderers.eventRenderer
                }, {
                    header: 'Status',
                    width: 100,
                    dataIndex: 'Status',
                    renderer: BYB.Renderers.statusRenderer
                }, {
                    header: 'Placed',
                    width: 130,
                    dataIndex: 'DatePlaced'
                }, {
                    header: 'View',
                    width: 60,
                    dataIndex: 'BetID',
                    renderer: BYB.Renderers.gotoRenderer
                }],
                store: betsStore,
                autoHeight: true,
                maxHeight: 500,
                width: 592,
                border: false
            });

            betsStore.load({
                params: {
                    myPending: true,
                    start: 0,
                    limit: 100
                }
            });
            var win = new Ext.Window({
                title: 'Pending Bets',
                items: [betGrid],
                width: 600,
                autoHeight: true
            });
            win.show();
        },
        showFindBud: function () {
            var pnl = BYB.User.Common.getFindBudPanel();
            var win = new Ext.Window({
                modal: true,
                title: 'Find a Bud',
                items: [{
                    html: '<div style=\'padding-bottom:10px; padding-left:10px; font-weight:bold; padding-top:10px;\'>Enter your bud\'s Name, E-mail, or Franchise Name to search!</div>'
                }, pnl],
                style: 'background-color:white',
                autoScroll: true,
                width: 440,
                height: 350
            });
            win.show();
            win.center();
        },
        getRecentBetsPanel: function (userID, storeUrl, inner) {

            if (storeUrl == null) {
                var url;
                if (userID == null) {
                    url = 'Bet/GetRecentBets/';
                }
                else {
                    url = 'User/GetMyRecentBets/?userID=' + userID
                }
            }
            else {
                url = storeUrl;
            }

            var betStore = BYB.Util.createRemoteStore(url, ['Winner', 'MatchupID', 'BetID', 'User1TeamName', 'User1ShortTeamName', 'User2ShortTeamName', 'EventDate', 'User1Rank', 'SportClass', 'User1TeamID', 'User2TeamID', 'SportName', 'User2TeamName', 'User1Handle', 'User2Rank', 'User2Handle', 'User1Pic', 'User2Pic', 'DatePlaced'], 'BetID');

            //'<tr><td colspan="3" style="text-align:center; font-size:10px; padding-top:3px; font-color:#aaa;">', '<i>Match: {EventDate}<br/>Bet Placed: {DatePlaced}</i></td></tr>
            var tpl = new Ext.XTemplate('<tpl for="."><div class="recentBetsDiv"><div class="<tpl if="this.isNoWinner(Winner)">anonymatchup</tpl><tpl if="this.isu2Winner(Winner)">matchupwinner2</tpl><tpl if="this.isu1Winner(Winner)">matchupwinner1</tpl>">', '<table cellpadding="0"><tr><td style="width:95px; text-align:center;padding-top:7px;', '">', '<a class="handleLink" href="/franchise/{User1Handle}">{User1Handle}<br>', '<img class="imgBorder" width="40" height="40" src="{User1Pic}" style="solid 1px #666" alt="{User1Handle}" border="0">', '</a><br /><a class="teamLink" href="/Stats/Team/{User1TeamID}/{User1TeamName}"><b>{User1ShortTeamName}</b></a></td>', '<td style="width:100px; height:75px; text-align:center; vertical-align:bottom;">', '<a href="/challenge/match/{BetID}/" style="color:white">View</a></td><td style="width:95px; text-align:center;padding-top:7px;', '"><a class="handleLink" href="/franchise/{User2Handle}">', '{User2Handle}<br><img class="imgBorder" width="40" height="40" src="{User2Pic}" style="solid 1px #666" title="{User2Handle}" border="0"></a><br />', '<a class="teamLink" href="/Stats/Team/{User2TeamID}"><b>{User2ShortTeamName}</b></a></td></tr>', '</table></div></div></tpl>', {
                isNoWinner: function (winner) {
                    return winner == null;
                },
                isu1Winner: function (winner) {
                    return winner == 1;
                },
                isu2Winner: function (winner) {
                    return winner == 2;
                }
            });

            var pms = {
                id: 'recent-bets-all',
                frame: false,
                width: 238,
                autoHeight: true,
                collapsible: true,
                layout: 'fit',
                bodyStyle: 'padding:0px',
                title: 'Recent Bets',
                style: 'padding:3px; background-color:white;',

                items: new Ext.DataView({
                    store: betStore,
                    tpl: tpl,
                    autoHeight: true,
                    itemSelector: 'recentBetsDiv',
                    emptyText: '<a href="/user/challenge/"><img src="/images/nobets.jpg" border="0"></a>'
                })
            };

            var panel = BYB.Util.createPanel(pms, inner);
            betStore.load();
            return panel;
        },
        getSportsNewsWindow: function (id, title) {
            var wnd = new Ext.Window({
                title: title,
                autoLoad: '/News/SportStory/' + id + '/',
                width: 450,
                height: 400,
                autoScroll: true
            });
            wnd.show();
        },
        getSportsCombo: function (params, onlyActive) {
            var sportTpl = new Ext.XTemplate('<tpl for="."><div class=\'x-combo-list-item\'><table cellpadding=\'4\' cellspacing=\'4\'><tr><td><img class=\'comboIcon\' src=\'' + liveAppPath + '{Logo}\' width=25 height=25></td><td>{Name}</td></tr></table></div></tpl>');

            var sportsStore = BYB.Data.Common.getSportsStore(onlyActive);

            if (params == null)
                params = {};
            var pms = {
                store: sportsStore,
                displayField: 'Name',
                valueField: 'ID',
                editable: false,
                fieldLabel: 'Sport',
                mode: 'remote',
                loadingText: 'Loading...',
                width: 200,
                forceSelection: true,
                triggerAction: 'all',
                tpl: sportTpl
            };

            Ext.apply(params, pms);

            var sport = new Ext.form.ComboBox(params);

            return sport;
        },
        getTeamCombo: function (sportId, params) {
            var sportsStore = BYB.Data.Common.getTeamStore(sportId);

            var prm = {
                store: sportsStore,
                displayField: 'Name',
                valueField: 'ID',
                fieldLabel: 'Team',
                mode: 'remote',
                loadingText: 'Loading...',
                width: 200,
                forceSelection: true,
                triggerAction: 'all'
            };

            Ext.apply(prm, params);

            var cmbo = BYB.Util.createCombo(prm);

            return cmbo;
        },
        getBudsPanel: function (userId) {
            var budStore = BYB.Util.createRemoteStore('User/GetMyBuds/?userId=' + userId, ['ID', 'Handle', 'Record', 'RequestedBy', 'ProfilePic'], 'ID');

            var tpl = new Ext.XTemplate('<tpl for=".">', '<div class="thumb-wrap" id="{ID}">', '<div class="thumb"><table cellpadding="2"><tr><td style="width:50px"><a href="/franchise/{Handle}"><img src="{ProfilePic}" width="40" height="40" class="imgBorder" title="{Handle}" border="0"></a></td><td style="width:100px"><a href="/franchise/{Handle}">{Handle}</a></td>{[this.getPending(values.RequestedBy)]}<td style="width:100px; text-align:center;">VS Record<br><b>{Record}</b></td></tr></table></div>', '</tpl>', '<div class="x-clear"></div>', {
                getPending: function (req) {
                    if (req == null) {
                        return "";
                    }
                    else {
                        if (req == curUserId) {
                            return '<td>Waiting for user\'s approval</td>';
                        }
                        else {
                            return "<td><a href='javascript:BYB.User.Common.approveBud(" + req + ")'>Approve</a></td>";
                        }
                    }
                }
            });

            var panel = BYB.Util.createPanel({
                id: 'images-view',
                frame: false,
                width: 300,
                autoHeight: true,
                collapsible: true,
                layout: 'fit',
                title: 'Bettin\' Buds',

                items: new Ext.DataView({
                    store: budStore,
                    loadingText: 'Loading...',
                    tpl: tpl,
                    autoHeight: true,
                    itemSelector: 'div.thumb-wrap',
                    emptyText: 'No buds.'
                })
            });

            budStore.load();
            return panel;
        },
        getRecentMatchupBetsPanel: function (matchupID) {
            var url = 'Bet/GetBetsOnMatchup/?matchupID=' + matchupID;
            return BYB.UI.Common.getRecentBetsPanel(null, url);
        },
        getFantasyBanterPanel: function (fantasyID, config) {
            return BYB.UI.Common.getBanterPanel(null, null, null, null, null, null, config, null, null, null, null, null, fantasyID);
        },
        getBanterPanel: function (betID, matchupID, teamID, budID, groupID, leagueID, config, custombetID, storyID, leagueBetID, asUser, pollID, fantasyID) {
            var url = 'Banter/GetBanter/';
            var subUrl = baseUrl + 'Banter/AddBanter/';
            if (matchupID != null) {
                url += '?matchupID=' + matchupID;
                subUrl += '?matchupID=' + matchupID;
            }
            if (teamID != null) {
                url += '?teamID=' + teamID;
                subUrl += '?teamID=' + teamID;
            }
            if (budID != null) {
                url += '?budID=' + budID;
                if (asUser != null)
                    url += '&uid=' + asUser;
                subUrl += '?budID=' + budID;
            }
            if (betID != null) {
                url += '?betID=' + betID;
                subUrl += '?betID=' + betID;
            }
            if (custombetID != null) {
                url += '?custombetID=' + custombetID;
                subUrl += '?custombetID=' + custombetID;
            }
            if (groupID != null) {
                url += '?groupID=' + groupID;
                subUrl += '?groupID=' + groupID;
            }
            if (leagueID != null) {
                url += '?leagueID=' + leagueID;
                subUrl += '?leagueID=' + leagueID;
            }
            if (leagueBetID != null) {
                url += '?leagueBetID=' + leagueBetID;
                subUrl += '?leagueBetID=' + leagueBetID;
            }
            if (storyID != null) {
                url += '?storyID=' + storyID;
                subUrl += '?storyID=' + storyID;
            } if (pollID != null) {
                url += '?pollID=' + pollID;
                subUrl += '?pollID=' + pollID;
            }
            if (fantasyID != null) {
                url += '?fantasyID=' + fantasyID;
                subUrl += '?fantasyID=' + fantasyID;
            }

            var banterStore = BYB.Util.createRemoteStore(url, ['ID', 'Message', 'PostDate', 'UserID', 'UserHandle', 'UserProfilePic'], 'ID');

            var pagingBar = new Ext.PagingToolbar({
                pageSize: 5,
                store: banterStore,
                displayInfo: true,
                displayMsg: 'Displaying message {0} - {1} of {2}',
                emptyMsg: "No messages to display"
            });

            var msgWidth = 580;
            try {
                msgWidth = config.width - 25;
            }
            catch (e) {
                // leave it 580
                msgWidth = 580;
            }

            var tpl = new Ext.XTemplate('<tpl for="."><div class="banterDiv"><div style="padding-bottom:0px; width:' + msgWidth + 'px; padding-top:5px;">', '<table cellpadding="0" width="100%" cellspacing="0">', '<tr><td style="text-align:left; padding-bottom:3px;padding-top:5px;" colspan="2">', '<a href="/franchise/{UserHandle}/" style="color:#666; text-decoration:none;">{UserHandle} at {PostDate}</a>:</td></tr>', '<tr style="background-color:#f6f6f6"><td style="vertical-align:top; width:45px;padding:3px; " width:"45"><img border="0" src="{UserProfilePic}" />', '</td><td style="vertical-align:top;padding:3px; text-align:left; width:610px;color:#000000;">{Message}</td></tr></table></div></div></tpl>');

            var title = 'Messageboard'

            //    var label = BYB.Util.createLabel({
            //      rawvalue: '<span style="color:black;font-weight:bold;">' + title + '</span>'
            // });
            var msgBox = BYB.Util.createTextArea({
                width: msgWidth,
                height: 50,
                emptyText: 'Enter your message here'
            });

            var subBtn = BYB.Util.createButton({
                text: 'Submit'
            });

            subBtn.on('click', function () {
                if (BYB.Util.isDefined('curUserId')) {
                    loading('submitting comment...');

                    BYB.Util.ajax(subUrl, {
                        message: msgBox.getValue()
                    }, function () {
                        hideLoading();
                        msgBox.setValue('');
                        banterStore.load();
                    });
                }
                else {
                    BYB.Util.newUserSignup();
                }
            });

            var itms = [msgBox, new Ext.Panel({
                buttonAlign: 'center',
                border: false,
                buttons: [subBtn]
            }), new Ext.DataView({
                store: banterStore,
                tpl: tpl,
                autoHeight: true,
                itemSelector: 'banterDiv',
                emptyText: ''
            })];

            if (asUser != null) {
                itms = [new Ext.DataView({
                    store: banterStore,
                    tpl: tpl,
                    autoHeight: true,
                    itemSelector: 'banterDiv',
                    emptyText: ''
                })];
            }

            var params = {
                border: false,
                frame: true,
                width: 600,
                loadMask: true,
                autoHeight: true,
                bodyStyle: 'background-color:#fff; padding-left:5px;padding-bottom:5px; padding-right:5px;',
                bbar: pagingBar,
                items: itms
            };
            Ext.apply(params, config);

            var panel = BYB.Util.createPanel(params, false);
            banterStore.load({
                params: {
                    start: 0,
                    limit: 5
                }
            });

            return panel;
        }
    }
} ();

BYB.User.Common = function(){
    var _newUserWindow;
    var _userLoginWindow;
    var _findBudWindow;
    var _onFavSuccess;
    var _favStore;
    var _favBtn;
    var _favFilterBox;
    
    function showNewUserWindow(){
        var firstName = new Ext.form.TextField({
            fieldLabel: 'First Name',
            validators: ['BYB.Validators.required']
        });
        var lastName = new Ext.form.TextField({
            fieldLabel: 'Last Name',
            validators: ['BYB.Validators.required']
        });
        var email = new Ext.form.TextField({
            fieldLabel: 'E-mail address',
            validators: ['BYB.Validators.required']
        });
        var username = new Ext.form.TextField({
            fieldLabel: 'Desired Username',
            validators: ['BYB.Validators.required']
        });
        /*  var pw = new Ext.form.TextField({
         fieldLabel: 'Password',
         validators: ['BYB.Validators.required']
         });
         var pw2 = new Ext.form.TextField({
         fieldLabel: 'Password Again',
         validators: ['BYB.Validators.required']
         }); */
        var submit = new Ext.Button({
            text: 'Submit'
        });
        submit.on('click', function(){
            if (BYB.Util.validatePanel(newUserPanel)) {
                Ext.Msg.wait('Loading...');
                BYB.Util.ajax(baseUrl + 'user/newuser', {
                    firstName: firstName.getValue(),
                    lastName: lastName.getValue(),
                    userName: username.getValue(),
                    email: email.getValue()
                }, newUserSuccess);
            }
        });
        var newUserPanel = new Ext.form.FormPanel({
            items: [firstName, lastName, username, email],
            layout: 'form',
            defaults: {
                msgTarget: 'side'
            },
            bodyStyle: 'padding:4px',
            labelWidth: 110,
            buttons: [submit]
        });
        _newUserWindow = new Ext.Window({
            items: newUserPanel,
            title: 'Create a New User Account',
            height: 180,
            width: 300,
            modal: true
        });
        
        _newUserWindow.show();
    }
    
    
    
    function showLoginUserWindow(){
    
        var loginPanel = createLoginPanel();
        
        _userLoginWindow = new Ext.Window({
            items: loginPanel,
            title: 'Login',
            height: 127,
            width: 300,
            modal: true
        });
        
        _userLoginWindow.show();
    }
    
    function getFindBudPnl(){
        var store = BYB.Util.createRemoteStore('User/FindBud/', ['ID', 'FullName', 'ProfilePic', 'Location', 'Handle'], 'ID')
        var search = BYB.Util.createTextField({
            fieldLabel: 'Search For',
            enableKeyEvents: true,
            width: 280
        });
        search.on('keyup', function(fld, e){
            var p = e.getCharCode() + '';
            if ((search.getValue().length > 1)) {
                doSearch();
            }
            else {
                store.filter('Name', 'AAAAAAANNNASDASD');
            }
        });
        
        function doSearch(){
            store.baseParams.query = search.getValue();
            grid.setVisible(true);
            store.clearFilter();
            store.load();
        }
        
        function profileRenderer(val){
            return '<img src=\'' + val + '\' />';
        }
        function selectRenderer(val){
            return '<a href=\'/franchise/' + val + '\'><img src="/images/icons/go32.gif" border="0" /></a>';
        }
        var grid = BYB.Util.createGrid({
            store: store,
            columns: [{
                header: '',
                width: 50,
                dataIndex: 'ProfilePic',
                renderer: profileRenderer
            }, {
                header: 'User',
                width: 200,
                dataIndex: 'Handle',
                renderer: function(val, meta, rec){
                    return "<b>" + val + "</b><br />" + rec.get('FullName');
                }
            }, {
                header: 'Location',
                dataIndex: 'Location',
                width: 100
            }, {
                header: '',
                dataIndex: 'Handle',
                width: 70,
                renderer: selectRenderer
            }],
            width: 400,
            autoHeight: true,
            hidden: true
        });
        
        var findBudPanel = BYB.Util.createPanel({
            autoWidth: true,
            autoHeight: true,
            autoScroll: true,
            layout: 'form',
            border: false,
            items: [search, grid]
        });
        
        search.focus();
        
        return findBudPanel;
    }
    
    function getFullSearchCombo(){
        var store = BYB.Util.createRemoteStore('User/SearchAll/', ['ID', 'Url', 'Title', 'Image', 'Description'], 'ID');
        
        var combo = new Ext.form.ComboBox({
            mode: 'remote',
            width: 150,
            emptyText: 'search for team, user, player',
            store: store,
            displayField: 'Title',
            emptyClass: 'emptyCombo',
            valueField: 'ID',
            hideTrigger: true,
            queryDelay: 770,
            forceSelection: true,
            enableKeyEvents: true,
            editable: true,
            tpl: '<tpl for="."><div class="x-combo-list-item" style="font-size:10px;"><table><tr><td><img width="20" height="20" src="{Image}" /></td><td><b>{Title}</b><br />{Description}</td></tr></table></div></tpl>'
        });
        
        combo.on('select', function(){
            var id = combo.getValue();
            var rec = store.getById(id);
            Ext.Msg.wait('Loading...');
            document.location.href = rec.get('Url');
        });
        
        return combo;
    }
    
    function getFindTeamPnl(){
    
        // var resultTpl = new Ext.XTemplate('<tpl for="."><div class=\'x-combo-list-item\'><h3><span>{FirstName} {LastName}</h3></div></tpl>');
        
        var needLoad = true;
        var favModel = TeamModel;
        favModel[favModel.length] = 'IsFavorite';
        favModel[favModel.length] = 'IsEnemy';
        
        
        _favStore = BYB.Util.createRemoteStore('User/FindTeam/', favModel, 'ID');
        _favStore.on('load', function(){
            if (!needsLoad) 
                _favStore.filter('Name', _favFilterBox.getValue(), true, false);
        });
        _favFilterBox = BYB.Util.createTextField({
            fieldLabel: 'Search For',
            enableKeyEvents: true,
            width: 350
        });
        _favFilterBox.on('keyup', function(fld, e){
            var p = e.getCharCode() + '';
            //if (p == '13') {
            if ((_favFilterBox.getValue().length > 2) && (needsLoad)) {
                needsLoad = false;
                doSearch();
            }
            else {
                if (_favFilterBox.getValue().length < 3) {
                    needsLoad = true;
                    _favStore.filter('Name', 'blahhh', true, true);
                }
                
                if (!needsLoad) 
                    _favStore.filter('Name', _favFilterBox.getValue(), true, false);
            }
            //}
        });
        
        function doSearch(){
            _favStore.baseParams.query = _favFilterBox.getValue();
            grid.setVisible(true);
            _favStore.clearFilter();
            _favStore.load();
        }
        
        function logoRenderer(val){
            return '<img src=\'' + val + '\' width="40" height="40" />';
        }
        
        function selectRenderer(val, meta, rec){
        
            if (rec.get('IsFavorite') == true) {
                return 'One of your Favorites!'
            }
            else {
                if (rec.get('IsEnemy') == true) 
                    return 'One of your Rivals!'
            }
            var tmp = '<a href=\'javascript:BYB.User.Common.addFavorite(' + val + ',true, BYB.User.Common.reloadFavsAndEnableBtn);\'>Add as Favorite</a><br />';
            tmp += '<a href=\'javascript:BYB.User.Common.addFavorite(' + val + ',false);\'>Add as Rival</a>';
            return tmp;
        }
        function nameRenderer(val, meta, rec){
            var ind = val.toLowerCase().indexOf(_favFilterBox.getValue().toLowerCase());
            if (ind > -1) {
                return val.substring(0, ind) + '<span style="color:red; font-weight:bold">' + val.substring(ind, ind + _favFilterBox.getValue().length) + '</span>' + val.substring(ind + _favFilterBox.getValue().length);
            }
            else 
                return val;
        }
        
        var grid = BYB.Util.createGrid({
            store: _favStore,
            columns: [{
                header: '',
                width: 50,
                dataIndex: 'SmallLogo',
                renderer: logoRenderer
            }, {
                header: 'Sport',
                width: 120,
                dataIndex: 'SportName'
            }, {
                header: 'Name',
                dataIndex: 'Name',
                width: 170,
                renderer: nameRenderer
            }, {
                header: '',
                dataIndex: 'ID',
                width: 100,
                renderer: selectRenderer
            }],
            width: 480,
            autoHeight: true,
            hidden: true
        });
        
        var findBudPanel = BYB.Util.createPanel({
            width: 500,
            layout: 'form',
            border: false,
            items: [_favFilterBox, grid]
        });
        
        return findBudPanel;
    }
    
    // event handlers
    function newUserSuccess(val){
        Ext.Msg.hide();
        val = Ext.util.JSON.decode(val.responseText);
        if (val.Error != false) {
            Ext.Msg.alert('Info', val.message);
        }
        else {
            Ext.Msg.alert('info', 'User created successfully. You will be receiving an e-mail shortly with a new BetYourBuds password.')
            _newUserWindow.close();
        }
    }
    
    function addFavoriteSuccess(val){
        Ext.Msg.hide();
        val = Ext.util.JSON.decode(val.responseText);
        
        //location.reload(true);
        //	if (val == true) {
        //	location.reload(true);
        //}
        //else {
        //	Ext.Msg.alert('Alert', 'This team is already one of your favorites.');
        //}
        
        if (_onFavSuccess != null) 
            _onFavSuccess();
        else {
            BYB.Util.forceReload();
        }
    }
    
    function addBudSuccess(val){
        Ext.Msg.hide();
        val = Ext.util.JSON.decode(val.responseText);
        if (val.Error == false) {
            Ext.Msg.alert('Success', 'We\'ve sent this user a request to become your Bud!');
        }
        else {
            Ext.Msg.alert('Ooops', val.Message);
        }
    }
    
    function approveBudSuccess(val){
        val = Ext.util.JSON.decode(val.responseText);
        if (val.Error == false) {
            window.location.reload();
        }
        else {
            Ext.Msg.hide();
            Ext.Msg.alert('Alert', 'There was an error adding this user to your Bud List');
        }
    }
    
    return {
        showFindAddTeam: function(ttlTxt){
            if (ttlTxt == null) 
                ttlTxt = 'Enter a team name or city';
            
            var pnl = BYB.User.Common.getFindTeamPanel();
            
            _favBtn = new Ext.Button({
                text: 'I\'m done',
                disabled: true
            });
            _favBtn.on('click', function(){
                // win.close();
                Ext.Msg.wait('refreshing...');
                clearLastNot(function(){
                    BYB.Util.forceReload();
                });
                
            });
            var win = new Ext.Window({
                title: 'Find a Team',
                bodyStyle: 'background-color:white',
                items: [{
                    html: '<div style=\'padding-bottom:10px; padding-left:10px; font-weight:bold; font-size:13px; padding-top:10px;\'>' + ttlTxt + '</div>'
                }, pnl],
                width: 535,
                modal: true,
                height: 350,
                autoScroll: true,
                buttons: [_favBtn]
            });
            win.on('close', function(){
                clearLastNot();
            });
            win.show();
            win.center();
        },
        reloadFavsAndEnableBtn: function(){
            _favBtn.setDisabled(false);
            BYB.User.Common.reloadFavs();
        },
        reloadFavs: function(){
            _favStore.baseParams.query = _favFilterBox.getValue();
            _favStore.load();
        },
        changeProfilePic: function(){
            var fibasic = new Ext.form.FileUploadField({
                width: 250,
                id: 'form-file',
                fieldLabel: 'Select Image'
            });
            var cb = new Ext.form.Checkbox({
                boxLabel: 'I certify that I have the right to distribute this photo and that it is not pornography.',
                height: 40
            });
            var btn = new Ext.Button({
                text: 'Submit',
                handler: function(){
                    if (pnl.getForm().isValid()) {
                        if (cb.getValue() == true) {
                            Ext.Msg.wait('Uploading...');
                            pnl.getForm().submit({
                                url: '/User/PicUpload',
                                success: function(fp, o){
                                    document.location.href = '/franchise/' + curUserHandle + '/';
                                },
                                failure: function(form, action){
                                    Ext.Msg.alert('Alert', 'Unable to upload your image.');
                                }
                            });
                        }
                        else {
                            Ext.Msg.alert('Wooops', 'Please acknowledge that you have rights to this image and that it is not pornography.');
                        }
                    }
                }
            });
            var pnl = BYB.Util.createFormPanel({
                items: [fibasic, cb],
                fileUpload: true,
                height: 130,
                buttons: [btn]
            });
            var win = new Ext.Window({
                width: 450,
                height: 160,
                items: [pnl],
                title: 'Change Franchise Image',
                modal: true
            });
            win.show();
        },
        newUser: function(){
            showNewUserWindow();
        },
        loginUser: function(){
            showLoginUserWindow();
        },
        getSearchCombo: function(){
            return getFullSearchCombo();
        },
        getFindBudPanel: function(){
            return getFindBudPnl();
        },
        getFindTeamPanel: function(){
            return getFindTeamPnl();
        },
        addBud: function(id){
            Ext.Msg.wait('Adding user...')
            BYB.Util.ajax(baseUrl + 'user/addbud', {
                userId: id
            }, addBudSuccess);
        },
        approveBud: function(id){
            Ext.Msg.wait('Approving user...')
            BYB.Util.ajax(baseUrl + 'user/approvebud/', {
                budId: id
            }, approveBudSuccess);
        },
        addFavorite: function(teamID, favorite, onSuccess){
            Ext.Msg.wait('Adding favorite...');
            _onFavSuccess = onSuccess;
            BYB.Util.ajax(baseUrl + 'user/addfavorite/', {
                teamID: teamID,
                favorite: favorite
            }, addFavoriteSuccess);
        },
        showTagWindow: function(onSelect){
        
            var sport = BYB.UI.Common.getSportsCombo({}, false);
            
            var path = 'Stats/GetTeams/';
            var teamStore = BYB.Util.createRemoteStore(path, ['ID', 'Name'], 'ID');
            sport.on('select', function(){
                teamStore.baseParams.sportID = sport.getValue();
                teamStore.load();
                tmCmbo.clearValue();
                done.setDisabled(true);
                tmCmbo.setDisabled(false);
                playerCombo.setDisabled(true);
            });
            
            // teams
            var prm = {
                store: teamStore,
                displayField: 'Name',
                valueField: 'ID',
                fieldLabel: 'Team',
                mode: 'remote',
                loadingText: 'Loading...',
                width: 200,
                disabled: true,
                editable: false,
                forceSelection: true,
                triggerAction: 'all'
            };
            
            var tmCmbo = BYB.Util.createCombo(prm);
            tmCmbo.on('select', function(){
                playerStore.baseParams.teamID = tmCmbo.getValue();
                playerCombo.clearValue();
                playerStore.load();
                playerCombo.setDisabled(false);
            });
            
            // players
            var path2 = 'Stats/GetTeamPlayers/';
            var playerStore = BYB.Util.createRemoteStore(path2, ['ID', 'Name'], 'ID');
            var prm2 = {
                store: playerStore,
                displayField: 'Name',
                valueField: 'ID',
                fieldLabel: 'Player (optional)',
                disabled: true,
                editable: false,
                mode: 'remote',
                loadingText: 'Loading...',
                width: 200,
                forceSelection: true,
                triggerAction: 'all'
            };
            
            var playerCombo = BYB.Util.createCombo(prm2);
            
            var pnl = new Ext.Panel({
                layout: 'form',
                bodyStyle: 'padding:6px',
                items: [sport, tmCmbo, playerCombo],
                autoHeight: true,
                editable: false,
                width: 320,
                border: false
            });
            
            tmCmbo.on('select', function(){
                done.setDisabled(false);
            });
            
            var done = new Ext.Button({
                disabled: true,
                text: 'Add tag'
            });
            done.on('click', function(){
                var param = {};
                if (playerCombo.getValue() != null && playerCombo.getValue() != '') {
                    var rec = playerStore.getById(playerCombo.getValue());
                    param = {
                        player: rec
                    };
                }
                else {
                    var rec = teamStore.getById(tmCmbo.getValue());
                    param = {
                        team: rec
                    };
                }
                onSelect(param);
                win.close();
            });
            var win = new Ext.Window({
                title: 'Add a Player or Team Tag',
                items: pnl,
                autoHeight: true,
                buttons: [done],
                width: 340
            });
            
            win.show();
            win.center();
        }
    };
}();

BYB.Store.util = function(){

    var storeItemStore;
    var existItemPanel;
    var myItemPanel;
    
    var myItemSel = null;
    var budItemSel = null;
    
    var storeWin;
    var meSel = true;
    var newItemWin;
    
    function getItemsPanel(store, width, dontaddsel){
        if (width == null) {
            width = 700;
        }
        
        var actTpl = new Ext.XTemplate('<tpl for="."><div style="padding-left:10px"><div style="background-color:#CCCCCC;font-weight:bold;padding:2px;">SET: {Name} ({PercentComplete}% Complete)</div><tpl for="Items">', '<div class="matchItem" id="item{ID}" style="float:left; padding:10px; width:100px;">', '{LargeDetails}', '</div></tpl></div><div style="clear:both;" /></tpl>');
        
        var prms = {
            tpl: actTpl,
            store: store,
            loadingText: 'Loading...',
            border: false,
            emptyText: '<div style="padding:10px">No ZookaGoods!</div>'
        };
        
        if (dontaddsel != false) {
            var selParams = {
                overClass: 'overMatch',
                itemSelector: 'div.matchItem',
                singleSelect: true,
                selectedClass: 'matchSelected'
            };
            Ext.apply(prms, selParams);
        }
        
        var pnl = new Ext.DataView(prms);
        
        return pnl;
    }
    function getStoreItemsPnl(){
    
        var width = 700;
        
        var actTpl = new Ext.XTemplate('<tpl for="."><tpl for="Items">', '<div class="storeItem" id="item{ID}" style="float:left; padding-right:10px; width:100px;">', '<img style="border:solid 1px #ccc" src="{MediumImage}" /><div style="font-size:8pt;"><span style="font-weight:bold">Item: </span>{Title}</div>', '<div style="font-size:8pt;"><span style="font-weight:bold">Price: </span>{Cost}</div>', '<div><input type="button" id="buy{ID}" value="Buy This!"></input></div></div></tpl></tpl>');
        
        var storeItemStore = BYB.Util.createRemoteStore('/store/GetAllStoreItems/', StoreCategory, 'ID');
        var pnl = new Ext.DataView({
            tpl: actTpl,
            overClass: 'overMatch',
            itemSelector: 'div.storeItem',
            selectedClass: 'matchSelected',
            store: storeItemStore,
            singleSelect: true,
            border: false,
            emptyText: 'No recent activity'
        });
        
        storeItemStore.load();
        
        return pnl;
    }
    
    function getStoreSetSelectionPanel(store){
        var width = 670;
        
        var actTpl = new Ext.XTemplate('<tpl for="."><div style="padding:2px; clear:both;"><div style="background-color:#ccc; padding:2px; font-weight:bold;">Set: {Name}</div><tpl for="Items">', '<div class="storeItem" id="item{ID}" style="float:left; padding:2px; border: solid 1px #f2f2f2; width:102px; height:150px;">', '<img style="border:solid 1px #ccc" src="{MediumImage}" /><div style="font-size:8pt;font-weight:bold">{Title}</div>', '<div style="font-size:8pt;"><span style="font-weight:bold; color:#666;">Price: </span>{Cost}</div>', '<div style="font-size:8pt;"><span style="font-weight:bold;color:#666;">You Own: </span>{Quantity}</div>', '</div></tpl></div></tpl>');
        
        var view = new Ext.DataView({
            tpl: actTpl,
            id: 'storeView',
            overClass: 'overMatch',
            itemSelector: 'div.storeItem',
            selectedClass: 'matchSelected',
            store: store,
            singleSelect: true,
            border: false,
            emptyText: 'No recent activity',
            height: 400,
            autoScroll: true,
            width: width
        });
        
        store.load();
        var pnl = new Ext.Panel({
            items: [view],
            border: false,
            autoHeight: true,
            autoScroll: true,
            width: width + 10
        });
        return pnl;
    }
    
    function getStoreSelPanel(store){
        var width = 670;
        
        var actTpl = new Ext.XTemplate('<tpl for="."><tpl for="Items">', '<div class="storeItem" id="item{ID}" style="float:left; padding:5px; border: solid 1px #f2f2f2; width:102px; height:150px;">', '<img style="border:solid 1px #ccc" src="{MediumImage}" /><div style="font-size:8pt;"><span style="font-weight:bold">Item: </span>{Title}</div>', '<div style="font-size:8pt;"><span style="font-weight:bold">Price: </span>{Cost}</div>', '</div></tpl></tpl>');
        
        var view = new Ext.DataView({
            tpl: actTpl,
            id: 'storeView',
            overClass: 'overMatch',
            itemSelector: 'div.storeItem',
            selectedClass: 'matchSelected',
            store: store,
            singleSelect: true,
            border: false,
            emptyText: 'No recent activity',
            autoHeight: true,
            width: width
        });
        
        store.load();
        var pnl = new Ext.Panel({
            items: [view],
            border: false,
            autoHeight: true,
            autoScroll: true,
            width: width + 10
        });
        return pnl;
    }
    
    var meBtn = new Ext.Button({
        text: 'Select an Item'
    });
    var budBtn = new Ext.Button({
        text: 'Select an Item'
    });
    var purchaseNewBtn = new Ext.Button({
        text: 'Go To Store'
    });
    
    function showItemSelWin(fromElem, showStore){
        if (showStore) {
            purchaseNewBtn.show();
        }
        else {
            purchaseNewBtn.hide();
        }
        storeItemStore.load();
        storeWin.show(fromElem);
        //  storeWin.center();
    }
    var meLbl = new Ext.form.Label({});
    var budLbl = new Ext.form.Label({});
    
    return {
        purchaseItem: function(itemID){
            Ext.Msg.wait('Loading...');
            BYB.Util.ajax('/store/MakePurchase/', {
                itemID: itemID,
                quantity: 1
            }, function(result){
                var ret = Ext.util.JSON.decode(result.responseText);
                if (ret.Error == true) {
                    Ext.Msg.alert('Woops', 'You don\'t have enough Zooka Bucks to make this purchase');
                }
                else {
                    BYB.Util.forceReload();
                }
            });
        },
        sellItemWin: function(item, q){
            var numStore = [];
            for (var x = 1; x <= q; x++) {
                numStore[x - 1] = [x, x + ''];
            }
            var qb = BYB.Util.createCombo({
                fieldLabel: 'Sell How Many?',
                store: numStore,
                width: 50,
                editable: false,
                valueField: 'ID',
                mode: 'local',
                displayField: 'Title',
                typeAhead: true,
                forceSelection: true,
                triggerAction: 'all',
                value: 1
            });
            var pnl = new Ext.Panel({
                labelWidth: 110,
                layout: 'form',
                items: [qb],
                bodyStyle: 'padding:8px'
            });
            
            var ok = new Ext.Button({
                text: 'OK',
                handler: function(){
                    win.close();
                    Ext.Msg.wait('Selling...');
                    BYB.Util.ajax(baseUrl + 'store/sellstoreitem', {
                        itemID: item,
                        quan: qb.getValue()
                    }, function(){
                        BYB.Util.forceReload();
                    });
                }
            });
            
            var cancel = new Ext.Button({
                text: 'Cancel',
                handler: function(){
                    win.close();
                }
            });
            
            var win = new Ext.Window({
                items: pnl,
                title: 'Sell an Item',
                buttons: [ok, cancel],
                width: 240
            });
            
            win.show();
            win.center();
        },
        getStoreSelItemPanel: function(store){
            return getStoreSelPanel(store);
        },
        getStoreSetSelectionPanl: function(store){
            return getStoreSetSelectionPanel(store);
        },
        getExistItemsObj: function(budCombo){
        
            storeItemStore = BYB.Util.createRemoteStore('user/getmyitems/', UserStoreItem, 'ID');
            myItemPanel = getItemsPanel(storeItemStore, 390);
            storeWin = new Ext.Window({
                tbar: [purchaseNewBtn],
                title: 'Items You Own',
                items: [myItemPanel],
                width: 400,
                height: 400,
                modal: true,
                closeAction: 'hide'
            });
            purchaseNewBtn.on('click', function(){
                if (newItemWin == null) {
                    var pnl = BYB.Store.util.getStoreItemsPanel();
                    newItemWin = new Ext.Window({
                        title: 'Store',
                        width: 400,
                        height: 400,
                        modal: true,
                        items: [pnl],
                        closeAction: 'hide'
                    });
                    
                    pnl.on('click', function(view, index, node, e){
                        if (e.target.id.indexOf('buy') > -1) {
                            var itemID = e.target.id.substring(3);
                            Ext.Msg.wait('Loading...');
                            BYB.Util.ajax('/store/MakePurchase/', {
                                itemID: itemID,
                                quantity: 1
                            }, function(){
                                Ext.Msg.hide();
                                newItemWin.hide();
                                storeItemStore.load();
                            });
                        }
                    });
                }
                newItemWin.show();
            });
            meBtn.on('click', function(){
                meSel = true;
                storeItemStore.baseParams.userID = curUserId;
                storeWin.setTitle('Items you currently own');
                showItemSelWin(meBtn, true);
            });
            
            existItemPanel = new Ext.Panel({
                disabled: true,
                layout: 'column',
                title: 'Existing Items',
                border: false,
                style: 'padding-left:200px; padding-top:20px; padding-bottom:20px;',
                items: [new Ext.Panel({
                    border: false,
                    items: [{
                        html: '<div style="width:100px"><div style="font-size:15px; font-weight:bold">MY WAGER:</div><img id="myWager" src="/images/store/question_100.gif" width="100" height="100" /></div>'
                    }, meLbl, meBtn]
                }), new Ext.Panel({
                    border: false,
                    style: 'padding-left:100px;',
                    items: [{
                        html: '<div style="width:100px"><div style="font-size:15px; font-weight:bold">BUD WAGER:</div><img id="budWager" src="/images/store/question_100.gif" width="100" height="100" /></div>'
                    }, budLbl, budBtn]
                })],
                height: 240
            });
            
            var curBudHandle;
            budCombo.on('select', function(combo, record, index){
                curBudHandle = record.get('Handle');
                existItemPanel.setDisabled(false);
            });
            budBtn.on('click', function(){
                meSel = false;
                storeItemStore.baseParams.userID = budCombo.getValue();
                storeWin.setTitle('Items ' + curBudHandle + ' currently owns');
                showItemSelWin(budBtn, false);
            });
            myItemPanel.on('selectionchange', function(pnl, items){
                var sel = myItemPanel.getSelectedRecords()[0];
                if (sel != null) {
                    if (meSel) {
                        Ext.get('myWager').set({
                            src: sel.get('MediumImage')
                        });
                        myItemSel = sel.get('ID');
                        meLbl.setText(sel.get('Title'));
                    }
                    else {
                        Ext.get('budWager').set({
                            src: sel.get('MediumImage')
                        });
                        budItemSel = sel.get('ID');
                        budLbl.setText(sel.get('Title'));
                    }
                    storeWin.hide();
                }
            });
            return {
                panel: existItemPanel,
                getMyItemSel: function(){
                    return myItemSel;
                },
                getBudItemSel: function(){
                    return budItemSel;
                }
            };
        },
        getMyItemsPanel: function(store, width, nosel){
            return getItemsPanel(store, width, nosel);
        },
        getStoreItemsPanel: function(){
            return getStoreItemsPnl();
        },
        showStoreItem: function(itemid){
            var win = new Ext.Window({
                autoLoad: {
                    url: '/store/ItemDetail/?itemid=' + itemid,
                    callback: function(){
                        win.center();
                    }
                },
                width: 220,
                height: 250,
                autoHeight: true,
                modal: true
            });
            
            win.show();
        }
    };
}();
BYB.Widget.tagSelector = function(){

    var _panel;
    var _tagPlayers;
    var tagTeams;
    
    function init(){
        var tagBtn = new Ext.Button({
            text: 'Add Tag',
            fieldLabel: 'Tags'
        });
        
        _tagPlayers = [];
        _tagTeams = [];
        function tagAdded(tag){
            if (tag.player != null) {
                var plyrId = tag.player.get('ID');
                var name = tag.player.get('Name')
                addPlayerToPanel(plyrId, name);
            }
            else {
                // team
                var tm = tag.team.get('ID');
                var name = tag.team.get('Name');
                
                addTeamToPanel(tm, name);
            }
        }
        
        tagBtn.on('click', function(){
            BYB.User.Common.showTagWindow(tagAdded);
        });
        _panel = new Ext.Panel({
            layout: 'form',
            style: 'padding-bottom:3px;',
            border: false,
            items: [tagBtn]
        });
        
    }
    
    function addTeamToPanel(id, name){
        if (_tagTeams.indexOf(id) == -1) {
            var np = new Ext.Panel({
                layout: 'column',
                id: 'teamTag' + id,
                border: false,
                items: [new Ext.form.Label({
                    columnWidth: 0.75,
                    html: '<div style="padding-top:3px;padding-left:110px;">Team: ' + name + '</div>'
                }), new Ext.Button({
                    columnWidth: 0.25,
                    text: 'remove',
                    myTeam: id,
                    handler: function(){
                        _panel.remove(np);
                        _tagTeams.remove(this.myTeam);
                    }
                })]
            });
            _tagTeams[_tagTeams.length] = id;
            _panel.add(np);
            _panel.doLayout();
        }
    }
    
    function addPlayerToPanel(id, name){
        if (_tagPlayers.indexOf(id) == -1) {
            var np = new Ext.Panel({
                layout: 'column',
                id: 'playerTag' + id,
                border: false,
                items: [new Ext.form.Label({
                    columnWidth: 0.75,
                    html: '<div style="padding-top:3px;padding-left:110px;">Player: ' + name + '</div>'
                }), new Ext.Button({
                    columnWidth: 0.25,
                    text: 'remove',
                    myPlayer: id,
                    handler: function(){
                        _panel.remove(np);
                        _tagPlayers.remove(this.myPlayer);
                    }
                })]
            });
            _tagPlayers[_tagPlayers.length] = id;
            _panel.add(np);
            _panel.doLayout();
        }
    }
    
    function reset(teamArray, playerArray){
        //	if (_panel!=null)
        //_panel.removeAll();
        _tagPlayers = [];
        _tagTeams = [];
        
        for (var x = 0; x < teamArray.length; x++) {
            var id = teamArray[x].ID;
            var name = teamArray[x].Name;
            addTeamToPanel(id, name);
        }
        
        for (var x = 0; x < playerArray.length; x++) {
            var id = playerArray[x].ID;
            var name = playerArray[x].Name;
            addPlayerToPanel(id, name);
        }
    }
    
    return {
        getPanel: function(){
            init();
            return _panel;
        },
        getSelectedTeams: function(){
            var tt = '';
            for (var x = 0; x < _tagTeams.length; x++) {
                tt += _tagTeams[x] + ",";
            }
            return tt;
        },
        getSelectedPlayers: function(){
            var pt = '';
            for (var x = 0; x < _tagPlayers.length; x++) {
                pt += _tagPlayers[x] + ",";
            }
            
            return pt;
        },
        setSelected: function(teamArray, playerArray){
            reset(teamArray, playerArray);
        }
    }
}
Ext.namespace('Ext.ux.form');

        Ext.ux.form.StaticTextField = function(config) {
            this.name = config.name || config.id;
            Ext.ux.form.StaticTextField.superclass.constructor.call(this, config);
        };

        Ext.extend(Ext.ux.form.StaticTextField, Ext.BoxComponent, {
            /**
            * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
            * {tag: "div"})
            */
            defaultAutoCreate: { tag: "div" },

            /**
            * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field")
            */
            fieldClass: "x-form-text",

            // private
            isFormField: true,

            /**
            * @cfg {Boolean} postValue True to create a hidden field that will post the field's value during a submit
            */
            submitValue: false,

            /**
            * @cfg {Mixed} value A value to initialize this field with.
            */
            value: undefined,

            /**
            * @cfg {Boolean} disableReset True to prevent this field from being reset when calling Ext.form.Form.reset()
            */
            disableReset: false,

            // private
            field: null,

            /**
            * Returns the name attribute of the field if available
            * @return {String} name The field name
            */
            getName: function() {
                return this.name;
            },

            // private
            onRender: function(ct, position) {
                Ext.ux.form.StaticTextField.superclass.onRender.call(this, ct, position);
                if (!this.el) {
                    var cfg = this.getAutoCreate();
                    this.el = ct.createChild(cfg, position);

                    if (this.submitValue) {
                        this.field = ct.createChild({ tag: 'input', type: 'hidden', name: this.getName(), id: '' }, position);
                    }
                }

                this.el.addClass([this.fieldClass, this.cls, 'ux-form-statictextfield']);
                this.initValue();
            },

            // private
            afterRender: function(ct, position) {
                Ext.ux.form.StaticTextField.superclass.afterRender.call(this);
                this.initEvents();
            },

            // private
            initValue: function() {
                if (this.value !== undefined) {
                    this.setValue(this.value);
                }
                else
                    if (this.el.dom.innerHTML.length > 0) {
                    this.setValue(this.el.dom.innerHTML);
                }
                if (this.rawvalue !== undefined) {
                    this.setRawValue(this.rawvalue);
                }
                else
                    if (this.el.dom.innerHTML.length > 0) {
                    this.setRawValue(this.el.dom.innerHTML);
                }
            },
            /* initValue : function(){
            if(this.value !== undefined){
            this.setValue(this.value);
            }else if(this.el.dom.innerHTML.length > 0){
            this.setValue(this.el.dom.innerHTML);
            }
            },*/

            /**
            * Returns true if this field has been changed since it was originally loaded.
            */
            isDirty: function() {
                return false;
            },

            /**
            * Resets the current field value to the originally-loaded value
            * @param {Boolean} force Force a reset even if the option disableReset is true
            */
            reset: function(force) {
                if (!this.disableReset || force === true) {
                    this.setValue(this.originalValue);
                }
            },

            // private
            initEvents: function() {
                // reference to original value for reset
                this.originalValue = this.getRawValue();
            },

            /**
            * Returns whether or not the field value is currently valid
            * Always returns true, not used in StaticTextField.
            * @return {Boolean} True
            */
            isValid: function() {
                return true;
            },

            /**
            * Validates the field value
            * Always returns true, not used in StaticTextField.  Required for Ext.form.Form.isValid()
            * @return {Boolean} True
            */
            validate: function() {
                return true;
            },

            processValue: function(value) {
                return value;
            },

            // private
            // Subclasses should provide the validation implementation by overriding this
            validateValue: function(value) {
                return true;
            },            /**
            * Mark this field as invalid
            * Not used in StaticTextField.   Required for Ext.form.Form.markInvalid()
            */
            markInvalid: function() {
                return;
            },

            /**
            * Clear any invalid styles/messages for this field
            * Not used in StaticTextField.   Required for Ext.form.Form.clearInvalid()
            */
            clearInvalid: function() {
                return;
            },

            /**
            * Returns the raw field value.
            * @return {Mixed} value The field value
            */
            getRawValue: function() {
                return (this.rendered) ? this.value : null;
            },

            /**
            * Returns the clean field value.
            * @return {String} value The field value
            */
            getValue: function() {
                return this.getRawValue();
            },

            /**
            * Sets the raw field value. The display text is <strong>not</strong> HTML encoded.
            * @param {Mixed} value The value to set
            */
            setRawValue: function(v) {
                this.value = v;
                if (this.rendered) {
                    this.el.dom.innerHTML = v;
                    if (this.field) {
                        this.field.dom.value = v;
                    }
                }
            },

            /**
            * Sets the field value. The display text is HTML encoded.
            * @param {Mixed} value The value to set
            */
            setValue: function(v) {
                this.value = v;
                if (this.rendered) {
                    this.el.dom.innerHTML = Ext.util.Format.htmlEncode(v);
                    if (this.field) {
                        this.field.dom.value = v;
                    }
                }
            }
        });

        Ext.reg('statictextfield', Ext.ux.form.StaticTextField);

        Ext.form.FileUploadField = Ext.extend(Ext.form.TextField, {
            /**
            * @cfg {String} buttonText The button text to display on the upload button (defaults to
            * 'Browse...').  Note that if you supply a value for {@link #buttonCfg}, the buttonCfg.text
            * value will be used instead if available.
            */
            buttonText: 'Browse...',
            /**
            * @cfg {Boolean} buttonOnly True to display the file upload field as a button with no visible
            * text field (defaults to false).  If true, all inherited TextField members will still be available.
            */
            buttonOnly: false,
            /**
            * @cfg {Number} buttonOffset The number of pixels of space reserved between the button and the text field
            * (defaults to 3).  Note that this only applies if {@link #buttonOnly} = false.
            */
            buttonOffset: 3,
            /**
            * @cfg {Object} buttonCfg A standard {@link Ext.Button} config object.
            */

            // private
            readOnly: true,

            /**
            * @hide 
            * @method autoSize
            */
            autoSize: Ext.emptyFn,

            // private
            initComponent: function() {
                Ext.form.FileUploadField.superclass.initComponent.call(this);

                this.addEvents(
                /**
                * @event fileselected
                * Fires when the underlying file input field's value has changed from the user
                * selecting a new file from the system file selection dialog.
                * @param {Ext.form.FileUploadField} this
                * @param {String} value The file value returned by the underlying file input field
                */
            'fileselected'
        );
            },

            // private
            onRender: function(ct, position) {
                Ext.form.FileUploadField.superclass.onRender.call(this, ct, position);

                this.wrap = this.el.wrap({ cls: 'x-form-field-wrap x-form-file-wrap' });
                this.el.addClass('x-form-file-text');
                this.el.dom.removeAttribute('name');

                this.fileInput = this.wrap.createChild({
                    id: this.getFileInputId(),
                    name: this.name || this.getId(),
                    cls: 'x-form-file',
                    tag: 'input',
                    type: 'file',
                    size: 1
                });

                var btnCfg = Ext.applyIf(this.buttonCfg || {}, {
                    text: this.buttonText
                });
                this.button = new Ext.Button(Ext.apply(btnCfg, {
                    renderTo: this.wrap,
                    cls: 'x-form-file-btn' + (btnCfg.iconCls ? ' x-btn-icon' : '')
                }));

                if (this.buttonOnly) {
                    this.el.hide();
                    this.wrap.setWidth(this.button.getEl().getWidth());
                }

                this.fileInput.on('change', function() {
                    var v = this.fileInput.dom.value;
                    this.setValue(v);
                    this.fireEvent('fileselected', this, v);
                }, this);
            },

            // private
            getFileInputId: function() {
                return this.id + '-file';
            },

            // private
            onResize: function(w, h) {
                Ext.form.FileUploadField.superclass.onResize.call(this, w, h);

                this.wrap.setWidth(w);

                if (!this.buttonOnly) {
                    var w = this.wrap.getWidth() - this.button.getEl().getWidth() - this.buttonOffset;
                    this.el.setWidth(w);
                }
            },

            // private
            preFocus: Ext.emptyFn,

            // private
            getResizeEl: function() {
                return this.wrap;
            },

            // private
            getPositionEl: function() {
                return this.wrap;
            },

            // private
            alignErrorIcon: function() {
                this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);
            }

        });
        Ext.reg('fileuploadfield', Ext.form.FileUploadField);

        BYB.Data.Common = function () {
            return {
                getTeamStore: function (sportId) {
                    var path = 'Stats/GetTeams/';
                    var store = BYB.Util.createRemoteStore(path, ['ID', 'Name'], 'ID');
                    store.baseParams.sportID = sportId;


                    return store;
                },
                getSportsStore: function (active) {
                    var path = 'Stats/GetSports/?active=1';
                    if (active == false) {
                        path = 'Stats/GetSports/?active=0';
                    }

                    var sportStore = BYB.Util.createRemoteStore(path, ['ID', 'Name', 'Logo', 'Teams'], 'ID');

                    return sportStore;
                }
            }
        } ();
        function clearLastNot(callback) {
            if (user_notifications.length > 0) {
                var theNot = user_notifications[0];
                BYB.Util.ajax('/user/acknowledgeNotification', {
                    id: theNot.ID
                }, function () {
                    if (callback != null)
                        callback();
                });
                user_notifications.remove(theNot);
                checkNots();
            }
            else {
                if (callback != null)
                    callback();

            }
        }
        function checkNots(){
			if (BYB.Util.isDefined('user_notifications')) {
				if (user_notifications.length > 0) {
					var theNot = user_notifications[0];
					if (theNot.JSFunc != null && theNot.JSFunc != '') {
						eval(Ext.util.Format.htmlDecode(theNot.JSFunc));
					}
					else {
						var wh = 200;
						var ww = 200;
						if (theNot.WindowWidth != null) 
							ww = theNot.WindowWidth;
						if (theNot.WindowHeight != null) 
							wh = theNot.WindowHeight;
						
						var w = createBlankDiv('<div>' + Ext.util.Format.htmlDecode(theNot.Notification) + '</div>');
						w.dialog({
							width: ww,
							height: wh,
							//modal:true,
							title:'Fanzooka Notification',
							buttons: {
								 "Close": function(){
								 	BYB.Util.ajax('/user/acknowledgeNotification', {
								 		id: theNot.ID
								 	}, function(){
								 	
								 	});
								 	user_notifications.remove(theNot);
								 	$(this).dialog('close');
								 	checkNots();
								 }
							}
						});
						w.dialog('open');
					}
				}
			}
		}

        function createBlankDiv(content){
			if (content == null) 
				content = '';
			var div = $('<div style="display:hidden">' + content + '</div>').appendTo('body');
			return div;
		}
