function toggleBrowse(id)
{
	id = id.toLowerCase();
	if(toggleObj)
	{
		Element.hide(toggleObj);
	}
	Element.show(id);
    document.forms[0].action = '/browse/'+id;
	toggleObj = id;
}

function enableField(id)
{
	$(id).disabled = false;
}

/**{{{Array BBTagSettings
 *
 * Setup object which controls the BBCode object
 */
var lasttag = false;
//}}}
//{{{Browser Detection
// Check for Browser & Platform for PC & IE specific bits
// More details from: http://www.mozilla.org/docs/web-developer/sniffer/browser_type.html
var clientPC = navigator.userAgent.toLowerCase(); // Get client info
var clientVer = parseInt(navigator.appVersion); // Get browser version

var is_ie = ((clientPC.indexOf("msie") != -1) && (clientPC.indexOf("opera") == -1));
var is_nav = ((clientPC.indexOf('mozilla')!=-1) && (clientPC.indexOf('spoofer')==-1)
                && (clientPC.indexOf('compatible') == -1) && (clientPC.indexOf('opera')==-1)
                && (clientPC.indexOf('webtv')==-1) && (clientPC.indexOf('hotjava')==-1));
var is_moz = 0;
var is_saf = clientPC.indexOf("safari") != -1;

var is_win = ((clientPC.indexOf("win")!=-1) || (clientPC.indexOf("16bit") != -1));
var is_mac = (clientPC.indexOf("mac")!=-1);
//}}}

/**{{{function in_array
 *
 * Clone of the php function by the same name
 *
 * @param	mixed	needle		The array element you're looking for
 * @param	Array	haystack	The array to search through
 */
function in_array(needle, haystack) {
    for(val in haystack) {
        if(needle == haystack[val]) return true;
    }
    return false;
}//}}}

/**{{{function key_exists
 *
 * Clone of the php function array_key_exists
 *
 * @param	mixed	needle		The key you're looking for
 * @param	Array	haystack	The associative array (or object, depending how you look at it) to search through
 */
function key_exists(needle, haystack) {
    for(val in haystack) {
        if(needle == val) return true;
    }
    return false;
}//}}}

/**Singleton::BBCode
 *
 * This object is used to manage a BB input form like that used with forums and blog posts ect.
 */
var BBCode = {
    withPanel: false,
    /**{{{BBCode::load
     *
     * Method to be attached to window.onload. Handles everything which needs to be loaded before the show can begin. DOM objects, even listeners etc.
     *
     */
    load: function(id) {
        BBCode.txtarea  = $(id);
        BBCode.selection = "";
        var buttondiv   = $('bbbuttons');
        var uls = document.getElementsByClassName('bbbuttons');
        for(var j=0; j<uls.length; j++) {
          var children = uls[j].childNodes;
          for(var i=0; i<children.length; i++) {
              if(children[i].nodeType == 1 && children[i].tagName.toLowerCase()=="li") {
                  if(children[i].getAttribute('ID') == 'bbrescan') {
                      children[i].onclick = function() { BBCode.scanText(); };
                  } else {
                      children[i].onclick = function() { BBCode.handleClick(this); };
                  }
              }
          }
        }
        BBCode.withPanel = ($('bbpanel')?true:false);
        if(BBCode.withPanel) {
            try {
                BBCode.txtarea.onchange   = function() { 
                    BBCode.scanText(); 
                };
                BBCode.txtarea.onkeypress = function() { 
                    window.clearTimeout(); 
                    window.setTimeout(function() { 
                        BBCode.scanText(); }, 
                    3000); 
                };
            } catch(e) {
                alert("NO BBCode 2");
            }
            BBCode.panel = new Panel($('bbpanel'));
        }
    },//}}}
    /**{{{BBCode::getTag
     *
     * Extract the tag name from it's id
     *
     */
    getTag: function (id) {
        if (id == '')
            return false;
        id.match(/^bb(.*)$/);
        var bbtag = RegExp.$1;
        if(!key_exists(bbtag, bbtagsettings)) return false; //no such tag available
        return bbtag;
    },//}}}
    /**{{{BBCode::handleClick
     *
     * The function which is added to the click event listener for each of the action buttons
     */
    handleClick: function(element) {
        if ($('sorrymsg') && $('sorrymsg').firstChild) {
            $('sorrymsg').removeChild($('sorrymsg').firstChild);
        }
        var bbtag = BBCode.getTag(element.id)
        if(!bbtag) { 
            return false; 
        }
        if(!key_exists(bbtag, bbtagsettings)) {
            alert("Failed two ["+bbtag+"]"); 
            return false;
        }
        BBCode.currentTag = bbtag;
        txtarea = BBCode.txtarea;
        if(clientVer >= 4 && is_ie && is_win && document.selection.createRange().text) {
            theSelection = document.selection.createRange().text;
            txtarea = BBCode.txtarea;
            if(theSelection) {
                
                document.selection.createRange().text = "["+bbtag+"]" + theSelection + "[/"+bbtag+"]"; 
            } 
        } else if(txtarea.selectionEnd && txtarea.selectionEnd - txtarea.selectionStart >0) {
            if (bbtag == 'track' || bbtag == 'album') {
                var attrval = prompt(bbtagsettings[bbtag][2], "");
                if (!attrval) return false;
                var opentag = "["+bbtag+" "+bbtagsettings[bbtag]['attr']+"="+attrval+"]";
            } else if(bbtag=='event') {
                var attrval = prompt(bbtagsettings[bbtag][1], "");
                if (!attrval) return false;
                attrval.match(/^http:\/\/(.*)\/(\d+)(\/|)$/);
                var eventid = RegExp.$2;
                var opentag = "["+bbtag+"="+eventid+"]";
            }
            else 
                var opentag = "["+bbtag+"]";
            txtarea.value = txtarea.value.substring(0, txtarea.selectionStart) + 
                            opentag + txtarea.value.substring(txtarea.selectionStart, txtarea.selectionEnd) + 
                            "[/"+bbtag+"]" + txtarea.value.substring(txtarea.selectionEnd, txtarea.value.length)
        } else {
            /* no selection */
            var promptCount = 0;
            var b = bbtagsettings[bbtag];
            var responses = new Array();
            while (b['prompts'] > promptCount) {
                promptCount++;
                if (!b['prefill']) 
                    b['prefill'] = "";
                    var resp = prompt(b[promptCount], b['prefill']);
                    if (resp) responses.push(resp);
                    else return false;
             }
         
         // handle responses
         if (responses.length <= 1) {
             txtarea.value += "["+bbtag+"]" + responses[0];
         }
         else { // second param is presumed to be final param for now
            if (bbtag == 'url')
                txtarea.value += "[url="+responses[0]+"]" + responses[1];
            else if(bbtag=='event') {
                responses[0].match(/^http:\/\/(.*)\/(\d+)(\/|)$/);
                var eventid = RegExp.$2;
                txtarea.value += "["+bbtag+"="+eventid+"]" + responses[1];
            } else
                txtarea.value += "["+bbtag+" "+b['attr']+"="+responses[1]+"]" + responses[0];   
         }
          txtarea.value += "[/"+bbtag+"]";
        }

    if (bbtagsettings[bbtag]['ajaxian']) {
        lasttag = bbtag;
        BBCode.scanText();  
        }
        
        // try to focus at end of text, well, better than nothing for now
        txtarea.focus();
    
    },//}}}
    /**{{{BBCode::ajaxCatch
     *
     * Method passed to the ajax object to handle the response
     */
    ajaxCatch: function(response, params, manual) {
        if(response) {
            if(!manual) {
                BBCode.addToTxtarea();
            }
            var i = null;
            var resname = getElementText(response, 'resname');
            //if(resname=='event') {
            //  i=BBCode.panel.checkForItem(resname, 
            //    getElementText(response, 'id'), getElementText(response, 'id'));
            //} else {
              i=BBCode.panel.checkForItem(resname, 
                getElementText(response, 'name'), getElementText(response, 'artist'));
            //}
            switch(i) {
                case 3:
                    BBCode.panel.addItem(response, true);
                    break;
                case 1:
                    this.panel.list.appendChild(panelRemovedItems[this.panel.panel.id][this.panel.lastItemCheck].element);
                    break;
                default:
            }
        } else {
          if (lasttag) {
            $('sorrymsg').appendChild(document.createTextNode('Sorry, we couldn\'t find that '+lasttag+'. Try again?'));
            lasttag = false;
          }
        }

    },//}}}
    /**{{{BBCode::scanText
     *
     *Do a pass over the text extracting tags and checking them against the lists.
     *
     */
    scanText: function() {
        if ($('sorrymsg') && $('sorrymsg').firstChild) {
            $('sorrymsg').removeChild($('sorrymsg').firstChild);
        }
        var txtarea = BBCode.txtarea;
        var otheritems1 = this.panel.listItems('other');
        var otheritems = new Array(otheritems1.length);
        for(var i=0; i<otheritems1.length; i++) {
            otheritems[i] = otheritems1[i];
        }
        //use regular expressions to check the text
        var regex = /\[([^ ^\=]+)([^\]]*)\]([^\[]+)\[\/\1\]/g;
        var result;
        while ((result = regex.exec(txtarea.value)) != null) {
            //check to see if it's in any of the lists
            if(in_array(result[1], ['artist', 'album', 'track', 'event'])) {
                    if(result[1]=='event') {
                        result[2] = result[2].substr(1);
                        result[3] = result[2];
                    }
                switch(this.panel.checkForItem(result[1], result[3], result[2])) {
                    case 0://default list
                        break;
                    case 1://removed list, re-add it from the cache
                        this.panel.list.appendChild(panelRemovedItems[this.panel.panel.id][this.panel.lastItemCheck].element);
                        break;
                    case 2://other list
                        //don't splice or you'll lose the keys
                        otheritems[this.panel.lastItemCheck] = false;
                        break;
                    case 3://not found, add it
                        var resget = new ResourceGet();
                        for(key in bbtagsettings[result[1]].ajaxian) {
                            if(key == "artist") {
                                try {
                                    var artist = result[2].match(/artist=([^\]]*)/)[1];
                                    resget.setParam(key, artist);
                                } catch(e) {
                                    //alert(e.message+"\n"+result[2]);
                                }
                            } else {
                                resget.setParam(key, bbtagsettings[result[1]].ajaxian[key]);
                            }
                        }
                        resget.setParam('name', result[3]);
                        resget.setCallback(function(response, params) { 
                            BBCode.ajaxCatch(response, params, true); 
                        }, false);
                        resget.send();
                        break;
                }
            }
        }//end while
        //now we need to remove all items which are in the list but not in the textarea
        for(var i=0; i<otheritems.length; i++) {
            if(otheritems[i]) {
                this.panel.removeItem(otheritems[i].element.id);
            }
        }
    }//}}}
}

function handleFocus(id)
{
    var obj = $(id);
    if(Element.hasClassName(obj, 'nofocus'))
    {
        Element.removeClassName($('recipients'), 'nofocus');
        obj.value = '';
    }
}

function addTAFFriend(name)
{
		handleFocus('recipients');
		var obj = $('recipients');
		str = $F('recipients');
		
		if(obj.value != '' && str.charAt(str.length-1) != ',')
		{
				name = ', '+name;
		}
		if(name == '-1' || name == ', -1')
		{
				obj.value = all_friends;
		}
		else
		{
				obj.value += name;
		}
}

var bbtagsettings = {
		b: {
				prompts: 1,
				1: "Enter the text that you'd like to make bold:" },
		i: {
				prompts: 1,
				1: "Enter the text that you'd like to make italic:" },
		u: {
				prompts: 1,
				1: "Enter the text that you'd like to underline:" },
		quote: {
				prompts: 1,
				1: "Enter the text that you'd like to quote:" },
		img: {
				prompts: 1,
				1: "Enter the full URL of the image you'd like to display:"},
				prefill: "http://",
		url: {
				prompts: 2,
				1: "Enter the address of the webpage you'd like to link to:",
				2: "Enter the title for this link:"},
		artist: {
				prompts: 1,
				1: "Enter an artist name:"},
		track: {
				prompts: 2,
				1: "Enter a track name:",
				2: "Enter the artist for this track:",
				attr: "artist"},
		user: {
				prompts: 1,
				1: "Enter a user name:"},
		tag: {
				prompts: 1,
				1: "Enter a tag name:"},
		youtube: {
				prompts: 1,
				1: "Enter the web address of the YouTube page containing the video you want to embed:"},
		googlevideo: {
				prompts: 1,
				1: "Enter the web address of the Google Video page containing the video you want to embed:"}, 
		rescan: {
		}
}

function playerhome()
{
         var so = new SWFObject('flash/mp3player.swf', 'player', '400', '140', '7');
                so.addVariable('file', 'player_lists/latest');
                so.addVariable('displaywidth', '120');
                so.addVariable('callback', 'player_lists/update_home');
                so.write('player');

}

