/////////// GENERAL OBJECT /////////////////////////////
xMousePos = 0; // Horizontal position of the mouse on the screen
yMousePos = 0; // Vertical position of the mouse on the screen
xMousePosMax = 0; // Width of the page
yMousePosMax = 0; // Height of the page
if (document.layers) { // Netscape
	document.captureEvents(Event.MOUSEMOVE);
	document.onmousemove = captureMousePosition;
} else if (document.all) { // Internet Explorer
	document.onmousemove = captureMousePosition;
} else if (document.getElementById) { // Netcsape 6
	document.onmousemove = captureMousePosition;
}
function CloneObject(what) {
    for (i in what) {
        if (typeof what[i] == 'object') {
            this[i] = new CloneObject(what[i]);
		} else {
            this[i] = what[i];
		}
	}
}
function captureMousePosition(e) {
	var dc; //DRAG CONTAINER
	var ddiv; //DRAG HELPER DIV
	var activeCont = undefined; //STORES THE ACTIVE CONTAINER DIV
	
	ev = e || window.event;

	if (ev.pageX || ev.pageY) {
		xMousePos = ev.pageX;
		yMousePos = ev.pageY;
		xMousePosMax = window.innerWidth+window.pageXOffset;
		yMousePosMax = window.innerHeight+window.pageYOffset;		
	
	} else {
		xMousePos = ev.x+document.body.scrollLeft;
		yMousePos = ev.y+document.body.scrollTop;
		xMousePosMax = document.body.clientWidth+document.body.scrollLeft;
		yMousePosMax = document.body.clientHeight+document.body.scrollTop;		
	}

	return false;
	
}
function g(obj) {
	var temp;
	temp = eval("document.all." + obj)
	if (temp == undefined) {
		temp = eval("document." + obj)
		if (temp == undefined) {
			temp = eval("document.getElementById('" + obj + "')")
		}
	}	
	return temp;
}	
function getBrowser () {

	var browser = navigator.userAgent.toLowerCase();
	
	if (browser.indexOf('msie') != -1) {browser = 'ie'};
	if (browser.indexOf('firefox') != -1) {browser = 'ff'};
	if (browser.indexOf('safari') != -1) {browser = 'sa'};
	if (browser.indexOf('opera') != -1) {browser = 'op'};
	
	return browser;
}	
function getClientSize () {
	var c = new Object();
	if (typeof(window.innerWidth) == 'number') {
		c.width = window.innerWidth+window.pageXOffset;
		c.height = window.innerHeight+window.pageYOffset;
	} else {
		c.width = document.body.clientWidth+document.body.scrollLeft;
		c.height = document.body.clientHeight+document.body.scrollTop;		
	}
	return c;
}
function decodeEmailText (str) {
var out = '';
var ccode;
	for (var i=0;i<str.length;i++) {
		ccode = str.charCodeAt(i) - 1
		out += String.fromCharCode(ccode);
	}	
	out = '<a href="mailto:' + out + '" class="slink" >' + out + '</a>';		
	document.write(out);
}
function brief (str, l) {
var temp = '';

	if (str.length > l) {
		temp = str.slice(0,l-3) + '...';
	} else {
		temp = str.slice(0,l);
	}

	return temp;
}
function centerDiv (dWidth) {
	var c = getClientSize();
	var l = (c.width / 2) - (dWidth / 2);					
	return l;
}	
function showFInfo(str) {
	if (str.length > 0 ) {
		var posx =(parseInt(xMousePos) + 50);		
		if ((posx+tr.references.get('finfo').offsetWidth) >= xMousePosMax) {
			posx = (xMousePosMax - tr.references.get('finfo').offsetWidth);				
		}	
		tr.references.get('finfo').style.top = (parseInt(yMousePos) + 10) + 'px';
		tr.references.get('finfo').style.left = posx + 'px';
		tr.references.get('finfo').innerHTML = str;
		tr.references.get('finfo').style.display = 'block';
	} else {
		tr.references.get('finfo').style.display = 'none';
	}
}
function hideFInfo () {
	tr.references.get('finfo').style.display = 'none';
}	
function showInfo(str) {
	if (str.length > 0 ) {
		g('hinfo').innerHTML = str;
		g('hinfo').style.top = (parseInt(yMousePos) + 25) + 'px';
		g('hinfo').style.left = (parseInt(xMousePos) - 50) + 'px';
		g('hinfo').style.display = 'block';		
	} else {
		g('hinfo').style.display = 'none';
	}
}
function hideInfo () {
	g('hinfo').style.display = 'none';
}	
function removeRow(id) {
  var tr = g(id);
	if (tr) {
		if (tr.nodeName == 'TR') {
			var tbl = tr; // Look up the hierarchy for TABLE
			while (tbl != document && tbl.nodeName != 'TABLE') {
				tbl = tbl.parentNode;
			}
			if (tbl && tbl.nodeName == 'TABLE') {
				while (tr.hasChildNodes()) {
					tr.removeChild( tr.lastChild );
				}
				tr.parentNode.removeChild( tr );
			}
		} else {
			alert( 'Specified document element is not a TR. id=' + id );
		}
	} else {
		alert( 'Specified document element is not found. id=' + id );
	}
}		
function captureKeypress (e, callback) {
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;

	if (keycode == 13) {
		eval(callback);
		return false;			
	}		
		
}
///////////  AJAX FUNCTIONS /////////////////////////////
var req;
var ajaxQ = Array(); // THE AJAX QUEUE
var ajaxStatus = 'ready'; // THE STATUS OF THE AJAX CALLER#
var targetDiv = '';
function initCom () {
	req = false;
	if(window.XMLHttpRequest) {
		try {
			req = new XMLHttpRequest();
		} catch(e) {
			req = false;
		}
	} else if(window.ActiveXObject) {
		try {
			req = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try {
				req = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {
				req = false;
			}
		}
	}
}
function com (strURL, callback, frm, tDiv, s) {

	if (req == undefined) {initCom()};

	if (ajaxStatus != 'busy') {		
		ajaxStatus = 'busy';
		document.body.style.cursor='wait';
				
		var refresh = Math.random();
		var str = "";
		
		if (strURL.lastIndexOf('?') != -1) {
			temp = "&";
		} else {
			temp = "?";
		}

		if (tDiv != undefined) {targetDiv = tDiv};
		
		if (frm != undefined || s != undefined) {
			
			if (s != undefined) {
				str = s;
			} else {
				str = getForm(frm);
			}
			req.open('POST',strURL+temp+'r='+refresh);
		} else {
			req.open('GET',strURL + temp + 'r=' + refresh);
		}
		
		req.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		
		if (callback != undefined) {req.onreadystatechange = callback};
		req.send(str);	
		
	} else {	
		str = "com('" + strURL + "'";
		if (callback != undefined) {str += "," + callback};
		if (frm != undefined) {str += ",g('" + frm.name + "')"} else {str += ",undefined"};
		if (tDiv != undefined) {str += ",'" + tDiv + "'"} else {str += ",undefined"};
		if (s != undefined) {str += ",'" + s + "'"} else {str += ",undefined"};
		str += ")";
		ajaxQ.push(str);
	
	}
	return false;
}
function comProcessNext () {
	ajaxStatus = 'ready';
	if (ajaxQ.length > 0) {
		eval(ajaxQ[0]);
		ajaxQ.splice(0,1);
	}
}
function parseDoc (response) {
var doc;
	try {//Internet Explorer
		doc=new ActiveXObject("Microsoft.XMLDOM");
		doc.async="false";
		doc.loadXML(response);
	} catch(e) {
		var parser=new DOMParser();
		doc=parser.parseFromString(response,"text/xml");
	}	
	return doc;
}
function getFirstNode (doc) {
	switch (browser) {
		case 'ie':
			var f = doc.firstChild.nextSibling;
			break;
		case 'ff':
		case 'sa':
		case 'op':		
			var f = doc.firstChild;
			break;
	}
	return f;
}
function parseXML () {
	document.body.style.cursor='default';
	
	if (req.readyState == 4) {		
		if (req.status == 200) {
			var response = req.responseText;
			comProcessNext();
			var doc = parseDoc(response);				
			var fnode = getFirstNode(doc);
			switch (fnode.nodeName) {
				case "pls":
					//PLAYLISTS			
					pls = doc.getElementsByTagName("p");											
					for (i=0;i<pls.length;i++) {					
						var node = pls[i];
						var res = new Playlist;
						//READ INT0 THE ARRAY
						res.id = node.getAttribute("c1");
						res.name = node.getAttribute("c2");
						res.shared = node.getAttribute("c3");
						res.rating = node.getAttribute("c4");	
						res.ttlvids = node.getAttribute("c5");	
						res.username = node.getAttribute("c6");							
						res.userrating = node.getAttribute("c7");	

						if (tr.curPl == undefined && i == 0) {
							tr.curPl = res;
							tr.pl = res.id;
							tr.setSearchMode('youtube');
						}						
						tr.playlists.add(res);
					}					
					tr.playlists.display();
					break;
					
				case 'pl':
					//TUNES
					tr.references.get('sloader').style.display = 'none';					
					//HIDE THE LOADING ICON
					if (g('plload' + tr.pl) != null) {g('plload' + tr.pl).style.display = "none"};
					//CLEAR DOWN THE CURRENT PL
					tr.curPl.clear();
					tu = doc.getElementsByTagName("t");
					var toggle = 0;
					
					for (i=0;i<tu.length;i++) {						
						var node = tu[i];
						var res = new Video;
						//READ INT0 THE ARRAY
						res.id = node.getAttribute("c1");
						res.videoid = node.getAttribute("c2");
						res.name = unescape(node.getAttribute("c3"));
						res.artist = unescape(node.getAttribute("c4"));
						res.album = unescape(node.getAttribute("c5"));
						res.duration = node.getAttribute("c6");			
						res.played = node.getAttribute("c7");
						res.seq = i;
						res.disabled = node.getAttribute("c8");
						tr.curPl.add(res);
					}				
					tr.curPl.cached = true;
					tr.curPl.display();
					break;	

				case 'pubpl':				
					//TUNES
					tr.references.get('sloader').style.display = 'none';
					//CLEAR DOWN THE CURRENT PL
					tr.curPubPl.clear();
					tu = doc.getElementsByTagName("t");
					var toggle = 0;

					for (i=0;i<tu.length;i++) {						
						var node = tu[i];
						var res = new Video;
						//READ INT0 THE ARRAY
						res.id = node.getAttribute("c1");
						res.videoid = node.getAttribute("c2");
						res.name = unescape(node.getAttribute("c3"));
						res.artist = unescape(node.getAttribute("c4"));
						res.album = unescape(node.getAttribute("c5"));
						res.duration = node.getAttribute("c6");			
						res.played = node.getAttribute("c7");
						res.seq = i;
						res.disabled = node.getAttribute("c8");
						
						tr.curPubPl.add(res);
					}
					tr.curPubPl.cached = true;
					tr.curPubPl.publicpl = true;
					tr.curPubPl.display();	
					break;

				case 'pladd':
					//NEW TRACK ADDED TO PLAYLIST
					var tu = doc.getElementsByTagName("t");
					
					var toggle = 0
					var str = tr.templates.get('plrowtemplate');
					
					//THERE'S ONLY 1 RESULT TO LOOP THROUGH
					for (i=0;i<tu.length;i++) {						
						var node = tu[i];
						var res = new Video;

						//READ INT0 THE ARRAY
						res.id = node.getAttribute("c1")	
						res.videoid = node.getAttribute("c2")
						res.name = node.getAttribute("c3")
						res.artist = node.getAttribute("c4")
						res.album = node.getAttribute("c5")
						res.duration = node.getAttribute("c6")						
						res.played = node.getAttribute("c7")
						
						var seq = 0;
						if (tr.curPl.count > 0) {
							seq = tr.curPl.count
						}
						res.seq = seq;
						
						tr.curPl.add(res);
						
						//APPEND THE ROW TO THE PLAYLIST
						//THIS IS IN CASE THE XML RETURNS AFTER THE BACK TO PLAYLIST BUTTON IS CLICKED
						toggle = 1;

						if (toggle == 2) {
							tclass = 'tuneentry2'
							trclass = 'tunerow2'
							txtclass = 'tuneentryi'
							timg = 'white'
							tcolor = 'ffffff'
							toggle = 0
						} else {
							tclass = 'tuneentry1'
							trclass = 'tunerow1'
							txtclass = 'tuneentryi'
							timg = 'ltblue'
							tcolor = 'eff4fa'
						}
						
						if (res.played == '0') {txtclass = 'tuneentryibold'};						
						
						var t = str;
						t = t.replace(/-i-/g, i);
						t = t.replace(/-id-/g, res.id);
						t = t.replace(/-name-/g, res.name);
						t = t.replace(/-artist-/g, res.artist);
						t = t.replace(/-album-/g, res.album);
						t = t.replace(/-duration-/g, res.duration);
						t = t.replace(/-tclass-/g, tclass);
						t = t.replace(/-trclass-/g, trclass);
						t = t.replace(/-txtclass-/g, txtclass);
						t = t.replace(/-timg-/g, timg);
						t = t.replace(/-tcolor-/g, tcolor);
						t = t.replace(/<tbody>/gi, '');
						t = t.replace(/<\/tbody>/gi, '');

						//REDISPLAY THE PLAYLIST					
						tr.curPl.display();

					}					
					break;
				case 'npls':
					//NEW PLAYLIST
					pls = doc.getElementsByTagName("p");						
					
					for (i=0;i<pls.length;i++) {						
						var node = pls[i];
						var res = new Playlist;
						//READ INT0 THE ARRAY
						res.id = node.getAttribute("c1");
						res.name = node.getAttribute("c2");
						res.shared = node.getAttribute("c3");
						res.rating = node.getAttribute("c4");	
						res.ttlvids = node.getAttribute("c5");	
						res.username = node.getAttribute("c6");							
						res.userrating = node.getAttribute("c7");	

						tr.playlists.add(res);
					}
					
					tr.playlists.display();
					
					if (fnode.getAttribute("m") == 'adddisc') {
						tr.doAddDiscs(res.id);
					}					
					break;
				case 'plsaddalbum':
					var desc = '';
					if (fnode.getAttribute("notfound") == 0) {
						desc = 'All songs were found!';
					} else {
						desc = fnode.getAttribute("notfound") + ' songs were not found';
					}
					updateAddAlbumStatus ((parseInt(fnode.getAttribute("ttl")) - parseInt(fnode.getAttribute("notfound"))) + " songs have been added to your playlist", desc, 100);
					g('aaclose').style.display = 'block';
					g('aacancel').style.display = 'none';
					tr.playlists.get(fnode.getAttribute("pl")).cached = false;
					tr.playlists.load(parseInt(fnode.getAttribute("pl")));
					break;	
				case 'pub':
					//PUBLIC PLAYLISTS
					tr.references.get('sloader').style.display = 'none';
					
					var pub = doc.getElementsByTagName("p");
					var toggle = 0									
					var str = tr.templates.get('pubrowtemplate');
					var outArr = new Array();
					
					for (i=0;i<pub.length;i++) {	
						var node = pub[i];
						var res = new Playlist;
						//READ INT0 THE ARRAY
						res.id = node.getAttribute("c1");
						res.name = node.getAttribute("c2");
						res.shared = node.getAttribute("c3");						
						res.rating = node.getAttribute("c4");	
						res.ttlvids = node.getAttribute("c5");	
						res.username = node.getAttribute("c6");	
						res.uid = node.getAttribute("c8");	
						tr.publicplaylists.add(res);
						
						toggle += 1;
						if (toggle == 2) {
							tclass = 'tuneentry2'
							trclass = 'tunerow2'
							txtclass = 'tuneentryi'
							timg = 'white'
							tcolor = 'ffffff'
							toggle = 0
						} else {
							tclass = 'tuneentry1'
							trclass = 'tunerow1'
							txtclass = 'tuneentryi'
							timg = 'ltblue'
							tcolor = 'eff4fa'
						}																
						if (tr.playlists.inPlaylists(res.id)) {icolor = 'btn_unsubscribe'} else {icolor='btn_subscribe'};
						
						var rstr = '';
						for (var j=1;j<=5;j++) {
							if (j <= res.rating) {
								rstr += '<img src="' + imagePath + 'icon_star_over.gif" border=0>';
							} else {
								rstr += '<img src="' + imagePath + 'icon_star.gif" border=0>';
							}
						}
						var t = str;
						t = t.replace(/-i-/g, i);
						t = t.replace(/-id-/g, res.id);
						t = t.replace(/-name-/g, res.name);
						t = t.replace(/-ttlvids-/g, res.ttlvids);
						t = t.replace(/-rating-/g, rstr);
						t = t.replace(/-user-/g, res.username);
						t = t.replace(/-uid-/g, res.uid);
						t = t.replace(/-icolor-/g, icolor);
						t = t.replace(/<tbody>/g, '');
						t = t.replace(/<\/tbody>/g, '');

						outArr.push(t);						
					}

					tr.references.get('publicdiv').innerHTML = '<table cellpadding=0 cellspacing=0 border=0 style="background-image:url(' + imagePath + 'alternating_blue_white.gif)" width="100%" height="100%" >' + outArr.join('') + tr.templates.get('pubrowformat') + '</table>';	
					resizeClient();
										
					//SET THE NEXT AND PREV BUTTONS
					var ttl = fnode.getAttribute("ttl")
					
					if (ttl > (tr.pubStartIndex + tr.pubMaxResults)) {
						if (tr.references.get('optpubnext').src.indexOf('_over') != -1) {
							tr.references.get('optpubnext').src = imagePath + 'opt_next_over.png';
						} else {
							tr.references.get('optpubnext').src = imagePath + 'opt_next.png';
						}
					} else {
						tr.references.get('optpubnext').src = imagePath +'opt_next_grey.png';
					}
					
					if (tr.pubStartIndex > 1) {
						if (tr.references.get('optpubprev').src.indexOf('_over') != -1) {
							tr.references.get('optpubprev').src = imagePath + 'opt_prev_over.png';
						} else {
							tr.references.get('optpubprev').src = imagePath + 'opt_prev.png';
						}
					} else {
						tr.references.get('optpubprev').src = imagePath + 'opt_prev_grey.png';	
					}
					break;
			}
		}

	}

}
function handleResponse () {
	document.body.style.cursor='default';
	if (req.readyState == 4) {		
		if (req.status == 200) {		
			var response = req.responseText;
			g(targetDiv).innerHTML = response;
			//RUN ANY CODE IN SCRIPT TAGS
			parseScript(response);	
			comProcessNext();					
		}		
	}
}	
function parseScript(_source) {
	//RUNS JAVASCRIPT IN AJAX PAGE AFTER IT'S LOADED 
	var source = _source;
	var scripts = new Array();
	while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
		var s = source.indexOf("<script");
		var s_e = source.indexOf(">", s);
		var e = source.indexOf("</script", s);
		var e_e = source.indexOf(">", e);		
		// Add to scripts array
		scripts.push(source.substring(s_e+1, e));
		// Strip from source
		source = source.substring(0, s) + source.substring(e_e+1);
	}
	// Loop through every script collected and eval it
	for(var i=0; i<scripts.length; i++) {
		try {			
			eval(scripts[i]);
		}
		catch(ex) {
			// do what you want here when a script fails
		}
	}
	// Return the cleaned source
	return source;
}	
function noCallback () {
	document.body.style.cursor='default';
	if (req.readyState == 4) {		
		if (req.status == 200) {
			var response = req.responseText;
			comProcessNext();
		}
	}
}
function getForm(fObj) {
	var str = "";
	var ft = "";
	var fv = "";
	var fn = "";
	var els = "";
	for (var i=0;i<fObj.elements.length;i++) {
		els = fObj.elements[i];
		ft = els.title;
		fv = els.value;
		fn = els.name;			
		
		switch (els.type) {
			case "text":
			case "hidden":
			case "password":
			case "textarea":
				str += fn + "=" + encode(fv) + "&";
				break;
			
			case "checkbox":
			case "radio":
				if (els.checked) {str += fn + "=" + encode(fv) + "&"};
				break;
				
			case "select-one":
				str += fn + "=" + els.options[els.selectedIndex].value + "&";
				break;
		
		}		
	}
	str = str.substr(0,(str.length - 1));
	return str;
}
function encode(string) {
	return escape(string);
}	
///////////  COOKIE FUNCTIONS /////////////////////////////
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function eraseCookie(name) {
	createCookie(name,"",-1);
}	

