// Cookie routines copyright Stephen Chapman, Felgall Pty Ltd, http://www.felgall.com/

var dbug = 0; 
function d_a(ary) {var beg = next_entry(ary) - 1; for (var i = beg ; i > -1; i--) {ary[i] = null;}} 
function init_array() {if (dbug) alert('init_cookie');  var ary = new Array(null); return ary;} 
//function set_cookie(name,value,expires) {if (dbug) alert('set_cookie'); if (!expires) expires = new Date(); document.cookie = name + '=' + escape(value) + '; expires=' + expires.toGMTString() + '; path=/';} 
function set_cookie(name,value,expires) {if (dbug) alert('set:'+name+'='+value); if (expires) document.cookie = name + '=' + escape(value) + '; expires=' + expires.toGMTString() + '; path=/'; else document.cookie = name + '=' + escape(value) + '; path=/';} 
function get_cookie(name) {if (dbug) alert('get_cookie'); var dcookie = document.cookie; var cname = name + "="; var clen = dcookie.length; var cbegin = 0; while (cbegin < clen) {var vbegin = cbegin + cname.length; if (dcookie.substring(cbegin, vbegin) == cname) {var vend = dcookie.indexOf (";", vbegin); if (vend == -1) vend = clen; return unescape(dcookie.substring(vbegin, vend));} cbegin = dcookie.indexOf(" ", cbegin) + 1; if (cbegin == 0) break;} return null;} 
function del_cookie(name) {if (dbug) alert('del_cookie'); document.cookie = name + '=' + '; expires=Thu, 01-Jan-70 00:00:01 GMT; path=/';} 
function get_array(name, ary) {if (dbug) alert('get_array'); d_a(ary); var ent = get_cookie(name); if (ent) {i = 1; while (ent.indexOf('^') != '-1') {ary[i] = ent.substring(0,ent.indexOf('^')); i++; ent = ent.substring(ent.indexOf('^')+1, ent.length);}}} 
function set_array(name, ary, expires) {if (dbug) alert('set_array'); var value = ''; for (var i = 1; ary[i]; i++) {value += ary[i] + '^';} set_cookie(name, value, expires);} 
function del_entry(name, ary, pos, expires) {if (dbug) alert('del_entry'); var value = ''; get_array(name, ary); for (var i = 1; i < pos; i++) {value += ary[i] + '^';} for (var j = pos + 1; ary[j]; j++) {value += ary[j] + '^';} set_cookie(name, value, expires);} 
function next_entry(ary) {if (dbug) alert('next_entry'); var j = 0; for (var i = 1; ary[i]; i++) {j = i} return j + 1;}
function debug_on() {dbug = 1;} 
function debug_off() {dbug = 0;} 
function dump_cookies() {if (document.cookie == '') document.write('No Cookies Found'); else {thisCookie = document.cookie.split('; '); for (i=0; i<thisCookie.length; i++) {document.write(thisCookie[i] + '<br \/>');}}}


function swapDivs(oldDiv, newDiv) {
	document.getElementById(oldDiv).style.display = 'none';
	document.getElementById(newDiv).style.display = 'block';
}

function clk(lid) {
	(new Image()).src="/go?t=L&id="+escape(lid);
	return false;
}

function clka(aid) {
	(new Image()).src="/go?t=A&id="+escape(aid);
	return false;
}

function view(url) {
	set_cookie("lc",url);
	return true;
}


function rollOver(imgName)
 {
   if (document.images)
    {
      imgOn=eval(imgName + "Over.src");
      document[imgName].src= imgOn;
    }
 }

function rollOff(imgName)
 {
   if (document.images)
    {
      imgOff=eval(imgName + "Normal.src");
      document[imgName].src= imgOff;
    }
 }



var http_request = false;

function makeRequest(url, parameters, readyContents) {
	http_request = false;
	if (window.XMLHttpRequest) { // Mozilla...
		http_request = new XMLHttpRequest();
		//if (http_request.overrideMimeType) {
		//	http_request.overrideMimeType('text/xml');
		//}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if (!http_request) {
		alert('Unable to rate link from this browser. Perhaps try another?');
		return false;
	}
	http_request.onreadystatechange = readyContents;
	http_request.open('GET', url + parameters, true);
	http_request.send(null);
}

function alertContents() {
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			//alert(http_request.responseText);
			response = http_request.responseText;
			if(response.indexOf('|') != -1) 
				update = response.split('|');
			else
				return;
			id='rate-'+update[0];
			idcur='current-'+update[0];
			if (update[1] == 'dupe') {
				document.getElementById(id).innerHTML = "Thanks, but one vote per " + update[2] + ".";
				return;
			}
			widthOffset = update[1] * 15;
			document.getElementById(id).innerHTML = "Thanks! The new average is " + update[1];
			document.getElementById(idcur).style.width = widthOffset + 'px';
		} else {
			alert('There was a problem with the request.');
		}
	}
}
function rate(rating, ratetype, id) {
  //var getstr = "?";
  var getstr = "?rating="+rating+"&type="+ratetype+"&id="+id;
  //alert('Voting is temporarily disabled. Will be back on Tues 4/11. Thanks');
  //var getstr = "?rating=3";
  makeRequest('/rate', getstr, alertContents);
}

var favetype1;
var substype1;

function fave(favetype, id, logged_in) {
	favetype1 = favetype;
	if(logged_in) {
		var getstr = "?type="+favetype+"&id="+id;
		makeRequest('/fave', getstr, faveReturn);
	}
	else {
		// Tell them to login politely.
		pleaseLogin(favetype, id, 'fave', '');
	}
	return false;
}

function subscribe(substype, id, logged_in) {
	substype1 = substype;
	if(logged_in) {
		var getstr = "?type="+substype+"&id="+id;
		makeRequest('/subscribe', getstr, subscribeReturn);
	}
	else {
		// Tell them to login politely.
		pleaseLogin(substype, id, 'subscribe', '');
	}
	return false;
}

function remove_fave(id) {
	if(confirm("Are you sure you want to remove this favorite?") == 0)
		return false;
	var getstr = "?action=remove&id="+id;
	makeRequest('/fave', getstr, faveReturn);
	return false;
}

function remove_sub(id, olink) {
	if(confirm("Are you sure you want to remove this PW Alert?") == 0)
		return false;
	var getstr = "?action=remove&id="+id;
	makeRequest('/subscribe', getstr, subscribeReturn);
	remove_row(olink);
	return false;
}

function faveReturn() {
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			//alert(http_request.responseText);
			response = http_request.responseText;
			if(response.indexOf('|') != -1) 
					update = response.split('|');
			else
				return;
			if(update[0] == 'fave' && update[1] == 'success') {
				var add_fave1 = document.getElementById('add_fave');
				if(add_fave1) {
					if (favetype1 == 'profile') {
						add_fave1.parentNode.innerHTML = '<a name=""><img src="/images/icon_friend.png" title="Friend" />&nbsp;Is a Friend</a>'; //update[2];
					} else {
						add_fave1.parentNode.innerHTML = '<img src="/images/icon_fav.png" title="Favorite" />'; //update[2];
					}
				}
				return;
			}
			if(update[0] == 'fave' && update[1] == 'deleted') {
				window.location.reload();
				return;
			}
		}
	}
}

function subscribeReturn() {
	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			//alert(http_request.responseText);
			response = http_request.responseText;
			if(response.indexOf('|') != -1) 
					update = response.split('|');
			else
				return;
			if(update[0] == 'subscribe' && update[1] == 'success') {
				var add_subs1 = document.getElementById('add_subs_' + update[3]);
				if(add_subs1) {
					add_subs1.parentNode.innerHTML = '<a href=\"/profile/\" class=\"subscribed\">Subscribed</a>'; //update[2];
				}
				return;
			}
			if(update[0] == 'subscribe' && update[1] == 'deleted') {
				// TODO: ajaxy row delete?
				//window.location.reload();
				return;
			}
		}
	}
}

function displayMessage(user, msgid, p, box) {
	//alert('displayMessage(' + '/profile/' + user + '/messaging?id=' + msgid + '&p=1&box=0&lb=1' + ')');
	tb_show('Message', '/profile/' + user + '/messaging?height=500&width=400&id=' + msgid + '&p=' + p + '&box=' + box + '&lb=1', null);
	return false;
}

function sendMessage(user, to, msgid, p, box, replytype, reply) {
	var qs = '?height=500&width=400&lb=1&id=' + msgid + '&p=' + p + '&box=' + box;
	if (replytype != null && replytype != '') {
		qs += '&' + replytype + '=' + reply;
	} else {
		qs += '&to=' + to;
	}
	tb_show('Compose Message', '/profile/' + user + '/messaging/send' + qs, null);
	return false;
}

function sendMsg(user, to, logged_in) {
	if(logged_in) {
		sendMessage(user, to, 0, 1, 0);
	}
	else {
		// Tell them to login politely.
		pleaseLogin('','','','');
	}
	return false;
}

function pleaseLogin(favetype, id, actiontype, addpg) {
//	var login_dialog1 = document.getElementById('login_dialog');
//	if(login_dialog1) {
//		login_dialog1.style.display = 'block';
//	}
	// temporary add 3
	var addp = '';
	if (actiontype == 'subscribe') {
		addp = '3';
	}
	if (addpg == null) {
		addpg = '';
	}
	tb_show('Please Login to PW','/lblogin' + addp + '?height=235&width=420&action='+actiontype+'&favetype='+favetype+'&id='+id+'&pg='+location.href+escape(addpg), null);
}

function registerPopup(addpg) {
	tb_show('Register with PW','/lbregister?height=235&width=420&pg='+location.href+escape(addpg), null);
}

function mailAdd(address, type, extra) {
	tb_show('Send An Email','/lbmail?to=' + escape(address) + '&height=435&width=525&type='+type+'&page='+escape(window.location.href)+extra, null);
	return false;
}

function showDiv(s) {
	var oHide = document.getElementById(s);
	if(oHide) {
		if (oHide.style.display == 'none') {
			oHide.style.display = 'block';
		} else {
			oHide.style.display = 'none';
		}
	}
}

function hide(s) {
	var oHide = document.getElementById(s);
	if(oHide) {
		oHide.style.display = 'none';
	}
}

function searchq(q_mashups, q_apis)
{
	if (q_apis.value != '' && q_apis.value != 'Search APIs') {
		window.location.href = '/apitag/?q=' + q_apis.value;
		return false;
	}

	window.location.href = '/mashups/directory/1?q=' + q_mashups.value;
	return false;

}


function showTabById(id, cont)
{
        var dname = id.substr(id.indexOf('#')+1);
        var obj = document.getElementById(dname);
        return showTab(obj, cont);
}

function showTabByPos(cont, pos)
{
        var lis = cont.find('a');
        if(pos < lis.length && pos >= 0) {
                return showTabById(lis[pos].href, cont);
        }
}

function showTab(obj, cont)
{
        //alert(cont);
        if (cont.selected_tab) {
                cont.selected_tab.style.display = "none";
	}
        if (obj) {
                obj.style.display = "block";
                cont.selected_tab = obj;
        }
	showMap(cont, obj);
        updateSelected(cont, obj.id);
        return false;
}

function updateSelected(cont, id)
{
        var lis = cont.find('a');
        for(i = 0; i < lis.length; i++) {
                if (lis[i].href.match('#' + id + '$')) {
                        lis[i].className = lis[i].className.replace(/ ?selected/, '');
                        lis[i].className += ' selected';
                } else {
                        lis[i].className = lis[i].className.replace(/ ?selected/, '');
                }
        }
}

function setupTabs(cont)
{
        var lis = cont.find('a');
	var j = 0;
        for (i = 0; i < lis.length; i++) {
		if (lis[i].href.indexOf('#') < 0) {
			continue;
		}
                var dname = lis[i].href.substr(lis[i].href.indexOf('#')+1);
                var d = document.getElementById(dname);
                if (d) {
                        lis[i].cont = cont;
                        lis[i].onclick = function() { return showTabById(this.href, this.cont); };
                        if (j > 0) {
                                d.style.display = 'none';
                        } else {
                                cont.selected_tab = d;
                        }
			j++;
                }
        }
}

function showMap(cont, item) {
        var imch = $(item).children('div').children('img');
	//alert('by golly: ' + imch.length);
	if (imch.length == 0) {
        	/*imch = $(item).children('dl > dd > a > img');
		//alert('hoo nelly: ' + imch.length);
		if (imch.length == 0) {
			return;
		}*/
		return;
	}
        var imgname = imch.next().html();
	//alert(item.id + ',' + imch.src + ',' + imgname);
        if (imch.attr('src') != 'about:blank') return;
	var mappath = imgname.replace('.png', '.map');
	var mapname = imgname.replace('.png', '').replace('/images/charts/', '');
	var loadimg = new Image();
	loadimg.src = '/images/loading.gif';
	//alert(imch[0]);
	/*var ib = 0;
	jQuery.each(imch.item(0), function(key, value) {
		alert("key: " + key + "; value: " + value);
	});*/

	//var pos = $(imch[0]).offset();
	//$(loadimg).css({ position: "absolute", top:pos.top+74, left:pos.left});
	loadimg.id = 'loadimg';
	var loadp = $(imch.parent());
	loadp.append(loadimg);
	//$(item).append(loadp);
        $.ajax({
                url: mappath,
                dataType: 'html',
                image1:imch,
                div1:item,
                success:
                    function (html) {
			// JPGraph bug fixed.
			html = html.replace('/>', '>');
                        $(this.div1).append(html);
                        this.image1.attr('useMap', '#' + mapname);
                        this.image1.attr('ismap', 'ismap');
                    }
                });
        imch.attr('src', imgname);
	imch.css('display', 'none');
	imch.load(function () {
		this.style.display = 'inline';
		$('#loadimg').css('display', 'none'); 
	});
}
