var myfunction = null;
var MyTool = null;
function ToolBarInit (tool)
{
	if(tool.clsid == '{50EC13F9-D1F6-4012-A076-F73088D8241C}'){
		MyTool = tool;
	}
}

var xmlhttp2;
var myfuncname = null;
function loadXMLTool2(url) {
    // Native
    if (window.XMLHttpRequest) {
        xmlhttp2 = new XMLHttpRequest();
        xmlhttp2.onreadystatechange = processStateChangeToolbar2;
        xmlhttp2.open("GET", url, true);
        xmlhttp2.send(null);
    // ActiveX
    } else if (window.ActiveXObject) {
        xmlhttp2 = new ActiveXObject("Microsoft.XMLHTTP");
        if (xmlhttp2) {
            xmlhttp2.onreadystatechange = processStateChangeToolbar2;
            xmlhttp2.open("GET", url, true);
            xmlhttp2.send();
        }
    }
}

function processStateChangeToolbar2() {
    if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {
        response = xmlhttp2.responseText;
	    eval(myfunction + '(\'\', response)');
    }
}

var xmlhttp;

function loadXMLTool(url) {
    // Native
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = processStateChangeToolbar;
        xmlhttp.open("GET", url, true);
        xmlhttp.send(null);
    // ActiveX
    } else if (window.ActiveXObject) {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        if (xmlhttp) {
            xmlhttp.onreadystatechange = processStateChangeToolbar;
            xmlhttp.open("GET", url, true);
            xmlhttp.send();
        }
    }
}

function processStateChangeToolbar() {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        response = xmlhttp.responseXML.documentElement;
        method = response.getElementsByTagName('method')[0].firstChild.data;
        result = response.getElementsByTagName('result')[0].firstChild.data;
		if(response.getElementsByTagName('theid')[0] != null){
			theid = response.getElementsByTagName('theid')[0].firstChild.data;
			if(theid != '' ){
			    eval(method + '(\'\', theid, result)');
			}
		}
		else if(response.getElementsByTagName('mid')[0] != null){
			mid = response.getElementsByTagName('mid')[0].firstChild.data;
			tid = response.getElementsByTagName('tid')[0].firstChild.data;
			if(mid != '' ){
			    eval(method + '(tid, mid, result)');
			}
		}
		else{
		    eval(method + '(\'\', result)');
		}

		
    }
}

function playerLoad() {
    var anchors = document.getElementsByTagName('a');
    var anchors_length = anchors.length;
    for (var i = 0; i < anchors_length; i++) {
        if (anchors[i].className == 'taggedlink' && anchors[i].href.match(/\.mp3$/i)) {
            _playerAdd(anchors[i]);
        }
    }
}

function LDT(tid, mid, response){
	var toolbarid = tid;
	var menuid = mid;
	var thistool = null;
	if(MyTool){
		if(!MyTool.CustomXML("customxml")){
			MyTool.CustomXML("customxml") = '';
			MyTool.Reload();
		}
		var existing = MyTool.CustomXML("customxml");
		var existingtoolbar = MyTool.CustomXML("customxml");
		//tester.value = MyTool.CustomXML("customxml");
		var tmp = "mid=\"" + menuid + "\"";
		var re = new RegExp(tmp, "ig");
		var exists = existingtoolbar.match(re);
		if(exists == null){
		    if (response && response != '') {
						if(MyTool.CustomXML("customxml") != ''){
							newbar = MyTool.CustomXML("customxml").split(/<\/toolbar>/gi);
							MyTool.CustomXML("customxml") = newbar[0] + response + '</toolbar>';
							//tester2.value = MyTool.CustomXML("customxml");
							MyTool.Reload();
						}
						else if(MyTool.CustomXML("customxml") == ''){
							MyTool.CustomXML("customxml") = '<toolbar>' + response + '</toolbar>';
							MyTool.Reload();
						}
			}
			else if(toolbarid != '' && toolbarid >= 0){
    	        loadXMLTool('http://www.collegetoolbars.com/lsu/ajaxLoadToolbar.php?tid=' + toolbarid + '&mid=' + menuid);
			}
		}
		else{
			alert('You have already added this default section to this toolbar.');
		}
	}	
}

// TOOLBAR MANAGEMENT FUNCTIONS




function loadbutton(){
	if(MyTool){
		var mydata = Array();
		var bid = document.getElementById("bId").value;
		var mid = document.getElementById("mid").value;
		var caption = htmlspecialchars(document.getElementById("titleField").value);
		var hint = htmlspecialchars(document.getElementById("descriptionField").value);
		var href = htmlspecialchars(document.getElementById("address").value);
		var dimage = document.getElementById("btn_icon").value;
		mydata[0] = bid;
		mydata[1] = mid;
		mydata[2] = dimage;
		var id = "tb_tagged_" + bid;
		var isword = /\w+/;
		var ismenu = /[\w-_]+/;
		var isaddress = /\b(https?|ftp|file):\/\/\w/;
		var isnumeric = /\d{1,7}/;
		if(hint.match(isword) == null){ hint = ''; }
		if(bid.match(isnumeric) != null && caption.match(isword) != null && href.match(isaddress) != null && mid.match(ismenu) != null){
			var tmp = "<BUTTON.*?mid=\"" + mid + "\".*?>.*?\n.*?<MENU.*?>";
			var tmp = "<MENU id=\"" + mid + "\".*?>";
			var re = new RegExp(tmp, "ig");
			var existingtoolbar = MyTool.CustomXML("customxml");
			var exists = existingtoolbar.match(re);
			if(exists != null){
					var imagetext = '';
					if(dimage != '' && dimage.match(isnumeric)){ imagetext = " img=\"" + dimage + "\" "; }
					
					var barrier = '';
					if(!mid.match('/category_menu/')){
						var checkcustom = "<MENU id=\"" + mid + "\".*?>[\\s\\S]*?</MENU>";
						var recust = new RegExp(checkcustom, "ig");
						var custmatch = existingtoolbar.match(recust);
						if(custmatch){
							if(!custmatch[0].match(/<SEPARATOR id=\"management_seperator_top\"\/>/)  && !mid.match(/category_menu/)){
								barrier = '<SEPARATOR id="management_seperator_top"/>';
							}
						}
					}
					
					var working = existingtoolbar.split(exists);
					var cleanup = working[1].split(/<\/TOOLBAR>/gi);
					working[1] = cleanup[0] + '</TOOLBAR>';
					var newbutton = '\n\t\t<ITEM id="' + id + '" caption="' + caption + '" visibility="1" command="redirect" href="' + href + '" img="' + dimage + '" hint="' + hint + '"/>\n';
					MyTool.CustomXML("customxml") = working[0] + exists + newbutton + barrier + working[1];
					MyTool.Reload();
					logButtonAdd(mydata, '');
					alert("button added");
			}
			else{
					alert("Unable to locate Menu");
			}
		}
	}
	return "false";
}

function addQuickMenu(input, response){
	if(MyTool){
			myfunction = 'addQuickMenu';
			if(response != ''){
				//set it
				if(MyTool.CustomXML("customxml") == ''){
					MyTool.CustomXML("customxml") = "<TOOLBAR>\n" + response + "\n</TOOLBAR>\n";
					MyTool.Reload();
				}
				else{
					var working = MyTool.CustomXML("customxml");
					var cleanup = working.split(/<\/TOOLBAR>/gi);
					working = cleanup[0] + response + '</TOOLBAR>';
					MyTool.CustomXML("customxml") = working;
					MyTool.Reload();
				}
			}
			else{
				var tmp = "<MENU id=\"category_menu_" + input + "\".*?>";
				var re = new RegExp(tmp, "ig");
				var existingtoolbar = MyTool.CustomXML("customxml");
				var exists = existingtoolbar.match(re);
				if(!exists){
					loadXMLTool2('http://www.collegetoolbars.com/categorymenus/' + input + '.xml');
				}
				else{
					alert('You\'ve already added this Category menu.');
				}
			}
	}
	else{
		alert('You must install the College Toolbar to use this function.');
	}
}

//detect which menus if any the user has installed
function loadedMenusList(selectedmenu){
	var menus = "No Toolbar was detected.  Download one to use this function.";
	if(MyTool){
		if(MyTool.CustomXML("customxml") && MyTool.CustomXML("customxml") != ''){
				var expression = /caption="(\w+)".*?mid="(\w+)"/g;
				expression = /<BUTTON id="([\w_-]+)".*?caption="(.*?)".*?\n.*?<MENU id="([\w_-]+)".*?>/g;
    	        var mymenus = MyTool.CustomXML("customxml").match(expression);
				
				if(mymenus == null){ menus = "You must add submenus in order to add a button to a submenu"; }
				else{
						var i = 0;

						menus = '<select name="mid">';
						myselect = '';
						while(i < mymenus.length){
							var exp = /caption="(\w+)".*?mid="(\w+)"/;
							var exp = /BUTTON id="([\w_-]+)".*?caption="(.*?)".*?\n.*?<MENU id="([\w_-]+)".*?>/;
							//alert(mymenus[i]);
							thedata = mymenus[i].match(exp);
							if(thedata[3] != "undefined" && thedata[2] != "undefined"){
								if(thedata[3] == selectedmenu){
									myselect = ' selected="selected"';
								}
								else{ myselect = ''; }
								menus = menus + '<option value="' + thedata[3] + '"' + myselect + '>' + tbunescape(thedata[2]) + '</option>';
							}
							i = i + 1;
						}
						menus = menus + '</select>';
						//alert(menus);
				}
		}
		else{
			var menus = "Your toolbar does not seem capable of using this function.";
		}
	}
	return menus;
}

function logButtonAdd(input, response) {
    if (response != '') {
			return;
	}
	else if(input[0] && input[0] >= 0 && input[1] && input[1] >= 0){
			alert('logging button');
          loadXMLTool('http://www.collegetoolbars.com/lsu/ajaxlogButtonAdd.php?bid=' + input[0] + "&mid=" + input[1] + "&image=" + input[2]);
		  return;
	}

}

// Escape characters
function xmlescape (string) {
  string = string.replace ("&", "&amp;");
  string = string.replace ("<", "&lt;");
  string = string.replace (">", "&gt;");
  string = string.replace ("\"", "&quot;");
  return string;
}
// unEscape characters
function xmlunescape (string) {
  string = string.replace ("&amp;","&");
  //string = string.replace ("&lt;","<");
  //string = string.replace ("&gt;",">");
  string = string.replace ("&quot;","\"");
  return string;
}
function tbescape (input) {
	input = input.replace(/&/g, "&amp;");
	input = input.replace(/"/g, "&quot;");
	input = input.replace(/'/g, "&apos;");
	input = input.replace(/</g, "&lt;");
	input = input.replace(/>/g, "&gt;");
  return input;
}
// unEscape characters
function tbunescape (input) {
	input = input.replace(/&quot;/g, "\"");
	input = input.replace(/&apos;/g, "'");
	input = input.replace(/&lt;/g, "<");
	input = input.replace(/&gt;/g, ">");
	input = input.replace(/&amp;/g, "&");
  return input;
}
// Encode string to UTF-8
function encode_utf8(str) {
    str = escape (str);
    nc = "";
    for (ic = 0; ic < str.length; ic++) {
        s = str.substr(ic, 6);
        if (arr = s.match(/%u[0-9A-F][0-9A-F][0-9A-F][0-9A-F]/i)) {
            c = arr[0].substr(2, 4);
            c = "&#" + parseInt(c, 16) + ";";
            ic += 5;
        } else if (arr = s.match(/^%[0-9A-F][0-9A-F]/i)) {
            c = arr[0].substr(1, 2);
            c = "&#" + parseInt(c, 16) + ";";
            ic += 2;
        } else {
            c = str.charAt(ic);
        };
        nc += c;
    };
    return nc;
}

