// ---------------------------------------------------------------------------
// index.js
// 
// Copyright (c) 2007 Amber-Lace Technologies. 
// All rights reserved.
// 
// No part of this document may be copied or duplicated without the express
// written permission of Amber-Lace Entertainment and Amber-Lace Technologies
//---------------------------------------------------------------------------

var dis = '';
var type = '';
var searchQuery = '';
var pobj = null;
var SearchControl;
var lastPath = '';
var firstPath = '';
var O="";
var ie = false;
var to = null;

// Tooltip functions

function T(text,me) 
{
	O=me;
	O.onmousemove=U;
	document.getElementById('toolTipBox').innerHTML=text;
	document.getElementById('toolTipBox').style.display="block";
	window.onscroll=U;
}

function U() 
{
	var ev = arguments[0] ? arguments[0] : window.event;

	var x = ev.clientX;
	var y = ev.clientY;

  	var diffX = 24;
	var diffY = 24;

	var ttb = document.getElementById('toolTipBox');
	
	var st = body().scrollTop ? body().scrollTop : body().parentNode.scrollTop;
	var sl = body().scrollLeft ? body.scrollLeft : body().parentNode.scrollLeft;

 	var top  = y - 2 + diffY + st;
	var left = x - 2 + diffX + sl;

	if((left + 224) >= body().scrollWidth) {
		left = body.scrollWidth - 224;
	//	top = top + 20;
	}
  	ttb.style.left = left + "px";
	ttb.style.top = top + "px";

	ttb.style.width = '200px';
	ttb.style.height = '32px';

  	O.onmouseout=H;
}

function H() 
{
	document.getElementById('toolTipBox').style.display="none";
}

// ------------------------
// Mouse over functions
// ------------------------

function LB(me)
{
	pobj = me;

	var r = /^a$/i;

	for(i = 0; i < me.childNodes.length; i++) {
		if(me.childNodes[i].nodeName.match(r)) {
			me.childNodes[i].style.color = '#48487A';
		}
	}

	me.style.background = '#F3F3FF';
	me.style.border = 'solid 1px #000';

	me.onmouseout=LU;
}

function LU()
{
	pobj.style.background = '#fff';
	pobj.style.border = 'solid 1px #fff';

	var r = /^a$/i;

	for(j = 0; j < pobj.childNodes.length; j++) {
		if(pobj.childNodes[j].nodeName.match(r)) {
			pobj.childNodes[j].style.color = '#FEFEFF';
		}
	}
}

// ---------------------
// Utility functions
// ---------------------

function body()
{
	var tmp = document.getElementsByTagName('body');
	return tmp[0];
}

function findPos(obj)
{
	var curleft = curtop = 0;

	if(obj.offsetParent) {
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while(obj = obj.offsetParent) {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}

	return [curleft, curtop];
}

function getElementsByClass(searchClass, node, tag)
{
	var classElements = new Array();

	if(node == null) {
		node = document;
	}
	if(tag == null) {
		tag = '*';
	}

	var els = node.getElementsByTagName(tag);
	var len = els.length;
	var pat = new RegExp("(^|\\s)" + searchClass + "(\\s|$)");
	for(i = 0, j = 0; i < len; i++) {
		if(pat.test(els[i].className)) {
			classElements[j] = els[i];
			j++;
		}
	}

	return classElements;
}

// ----------------------------------
// Navigation functions 
// ----------------------------------

function selectNavItem(index)
{
	var elems = getElementsByClass("navItem");

	for(i = 0; i < elems.length; i++) {
		if(i == index) {
			elems[i].style.background = '#F3F3FF';
			elems[i].style.borderTop = 'solid 1px #000';
			elems[i].style.borderLeft = 'solid 1px #000';
			elems[i].style.borderRight = 'solid 1px #000';
		} else {
			elems[i].style.background = '#fff';
			elems[i].style.border = '0px';
		}
	}
}

function selectSubNavItem(index)
{
	var elems = getElementsByClass("subNavItem");

	for(i = 0; i < elems.length; i++) {
		if(i == index) {
			elems[i].style.background = '#F3F3FF';
		} else {
			elems[i].style.background = '#fff';
		}
	}
}

function deSelectNavItems()
{
	var elems = getElementsByClass("navItem");
	for(i = 0; i < elems.length; i++) {
		elems[i].style.background = '#fff';
		elems[i].style.border = '0px';
	}
}

function navClick(index, path)
{
	var nc = Math.round(1000000 * Math.random());

	var fields = path.split('dis=');
	if(fields.length) {
		dis = fields[1];
	}

	selectNavItem(index);	

	clearSearch();
	focusSearch();

	newpath = path + '&t=' + type + '&asdf=' + nc;

	loadContent(newpath);		
}

function subNavClick(index, t)
{
	type = t;

	selectSubNavItem(index);

	if(document.getElementById('NCSearchResults').style.display == 'block') {
		search(searchQuery);		
	} else {
		var nc = Math.round(1000000 * Math.random());

		newpath = lastPath.replace(/\?.*$/, '');
		
		newpath += '?t=' + type;
		if(dis != null) {
			newpath += '&dis=' + dis;
		}
		newpath += '&asdf=' + nc;

		loadContent(newpath);
	}
	focusSearch();
}

function pageClick(path)
{
	var nc = Math.round(1000000 * Math.random());

	newpath = path + '&dis=' + dis + '&t=' + type + '&asdf=' + nc;

	if(newpath.match(/a\.php/)) {
		selectNavItem(3);
	} else if(newpath.match(/g\.php/)) {
		selectNavItem(0);
	}

	loadContent(newpath);

	focusSearch();
}

// --------------------------
// Search Functions
// --------------------------

function clearSearch()
{
	searchQuery = '';
	document.getElementById("NCSearchControlForm").q.value = '';
}

function focusSearch()
{
	document.getElementById("NCSearchControlForm").q.focus();
}

function search(query)
{
	showSearchResults();

	SearchControl.setType(type);
	SearchControl.execute(query);

	searchQuery = query;
}

function showSearchResults()
{
	deSelectNavItems();

	document.getElementById("NCSearchResults").style.display = 'block';
	document.getElementById("content").style.display = 'none';
}

// --------------------------------
// Favorite and Tagging functions
// --------------------------------

function addToFavs(id)
{
	var tb = document.getElementById('g_' + id);

	var html = tb.innerHTML;

	var newhtml = html.replace(/<a[^>]+>Add To Favs<\/a>/i, '<a>Added To Favs!</a>');
	tb.innerHTML = newhtml;

	// Kind of a dirty hack for IE and Opera to ensure that the users can see
	// their change was made.

	var r = /^p$/i;

	for(i = 0; i < tb.childNodes.length; i++) {
		if(tb.childNodes[i].nodeName.match(r)) {
			LB(tb.childNodes[i]);
			break;
		}
	}

	var nc = Math.round(1000000 * Math.random());
	var content = new AJAX(null);
	var path = '/api/f.php?o=a&i=' + id + '&nc=' + nc;
	content.request(path);
}

function removeFromFavs(id)
{
	var tb = document.getElementById('g_' + id);

	var html = tb.innerHTML;

	var newhtml = html.replace(/<a[^>]+>Remove<\/a>/i, '<a>Item Removed!</a>');
	tb.innerHTML = newhtml;

	// Kind of a dirty hack for IE and Opera to ensure that the users can see
	// their change was made.

	var r = /^p$/i;

	for(i = 0; i < tb.childNodes.length; i++) {
		if(tb.childNodes[i].nodeName.match(r)) {
			LB(tb.childNodes[i]);
			break;
		}
	}

	var nc = Math.round(1000000 * Math.random());
	var content = new AJAX(null);
	var path = '/api/f.php?o=r&i=' + id + '&nc=' + nc;
	content.request(path);
}

function tagGallery(id)
{
	var block = document.getElementById('g_' + id);

	var tb = document.getElementById('tagBox');

	tb.innerHTML = '<form name="tagForm" action="javascript:performTag(' + id + ', document.tagForm.tags.value);"><p><input type="text" name="tags" size="20" />&nbsp;<a onClick="javascript:performTag(' + id + ', document.tagForm.tags.value);">+</a>&nbsp;<a onClick="javascript:hideTagBox();">x</a></p></form>';

	var ar = findPos(block);
	var left = ar[0] + "px";
	var top = ar[1] + 126 + "px";

	tb.style.left = left;
	tb.style.top = top;
	
	tb.style.display = 'block';

	document.tagForm.tags.value = 'retrieving...';

	var content = new AJAX(null);

	var cb = function(http_request) { 
		if(http_request != null) {
			if (http_request.readyState == 4) {
				if (http_request.status == 200) {
					document.tagForm.tags.value = http_request.responseText;
		       		} 
			}	
		}
	};

	content.setCallBack(cb);

	var nc = Math.round(1000000 * Math.random());
	var path = '/api/t.php?o=r&i=' + id + '&nc=' + nc;
	content.request(path);

	document.tagForm.tags.focus();
}

function performTag(id, tags)
{
	var tb = document.getElementById('g_' + id);
	var html = tb.innerHTML;

	var newhtml = html.replace(/<a[^>]+>Tag Gallery<\/a>/i, '<a>Gallery Tagged!</a>');
	tb.innerHTML = newhtml;

	var nc = Math.round(1000000 * Math.random());
	var content = new AJAX(null);
	var path = '/api/t.php?o=a&i=' + id + '&s=' + document.tagForm.tags.value + '&nc=' + nc;
	content.request(path);

	// Kind of a dirty hack for IE and Opera to ensure that the users can see
	// their change was made.

	var r = /^p$/i;

	for(i = 0; i < tb.childNodes.length; i++) {
		if(tb.childNodes[i].nodeName.match(r)) {
			LB(tb.childNodes[i]);
			break;
		}
	}

	document.getElementById('tagBox').innerHTML = '';
	document.getElementById('tagBox').style.display = 'none';
}

function hideTagBox()
{
	document.getElementById('tagBox').style.display = 'none';
}

// -------------------
// Content functions
// -------------------

// var sc = 0;

function loadContent(path)
{
	//sc++;
	//document.getElementById('debug').innerHTML += '<p>loadContent :)</p>';
//	alert(sc + ' ... ' + path);

	if(path == '') {
		path = firstPath;
	}

	// Clear the poll timer so anything we do here won't
	// trigger a new call to this function before we're done

	if(to) {
		clearTimeout(to);
	}

	// Update IFrame for IE

	if(ie) {
		document.frames[0].location.href = makeDummy(path);
	}

	// Hide search results

	document.getElementById("NCSearchResults").style.display = 'none';

	// Unhide content

	var c = document.getElementById("content");
	c.style.display = 'block';
	c.innerHTML = '<p>Loading...</p>';

	// Load new content

	var content = new AJAX(c);
	content.request(path);

// 	document.getElementById('debug').innerHTML = '<p>' + path + '</p>';

	// Update URL with new state

	var hash = makeHash(path);
	window.location.hash = hash;

	// Update lastPath, select items and set poll for state changes

	selectItems(path);

	lastPath = path;

	to = setTimeout('pollLocation()', 1000);
}

function makeDummy(p)
{
	var r = /\/api\/(\w{1}\.php)\?(.*)/;
	var a = r.exec(p);

	var script = a[1];
	var query = a[2];	

	var dummy = '/api/d.php?s=' + script + '&' + query;
	return dummy;
}

function unMakeDummy(p)
{
	var r = /\/api\/d\.php\?s=(\w{1}\.php)&(.*)/;
	var a = r.exec(p);
	
	var script = a[1];
	var query = a[2];

	var np = '/api/' + script + '?' + query;
	return np;
}

function makeHash(path)
{
	var newpath = path.replace(/[\/]+/g, '_');
	newpath = newpath.replace(/[\?]+/g, '_q_');
	newpath = newpath.replace(/[&]+/g, '_amp_');

	return newpath;
}

function decodeHash(hash)
{
	var decoded = hash.replace(/_q_/g, '?');
	decoded = decoded.replace(/_amp_/g, '&');
	decoded = decoded.replace(/_/g, '/');
	decoded = decoded.replace(/^#/, '');
	return decoded;
}

function pollLocation()
{
	var hash = makeHash(lastPath);

	if(window.location.hash != ('#' + hash)) {
		loadContent(decodeHash(window.location.hash));
	} else {

		if(ie) {
			var r = /http:\/\/[\w|-|\.|\d|:|@]+(\/.*)/;
			var lo_src = document.frames[0].location.href;
			var src = '';
		
			if(lo_src.match(/http/)) {
				var ar = r.exec(lo_src);
				src = ar[1];
			} else {
				src = lo_src;
			}
	
			src = unMakeDummy(src);
			if(src != lastPath) {
				// alert('src = ' + src + ' lastPath = ' + lastPath);
				loadContent(src);
			}
		} 
	}

	to = setTimeout('pollLocation()', 1000);
}

function selectItems(path)
{
	var page = null;

	var r = /dis=(\w+)/;
	var ar = r.exec(path);
	dis = ar ? ar[1] : '';

	if(dis == '') {

		r = /(f|a|c)\.php/;
		var ar = r.exec(path);
		if(ar) {
			page = ar[1];
		}
	}

	r = /t=(\w+)/;
	ar = r.exec(path);
	type = ar ? ar[1] : 'both';

	if(page) {
		switch(page) {
		case 'f': selectNavItem(2); break;
		case 'a': selectNavItem(3); break;
		case 'c': selectNavItem(4); break;
		}
	} else {
		switch(dis) {
		case 'fresh': selectNavItem(0); break;
		case 'pop': selectNavItem(1); break;
		}
	}

	switch(type) {
	case 'pics': selectSubNavItem(0); break;
	case 'vids': selectSubNavItem(1); break;
	case 'both': selectSubNavItem(2); break;
	}
}

function onLoad(d, t, p)
{
	var path = '';
	var page = null;
	
	// Flag for IE

	if(navigator.userAgent) {
		if(navigator.userAgent.indexOf('MSIE') !== -1) {
			ie = true;
		}
	}

	// First see if a fragment identifier was passed and if so process it

	if(window.location.hash.length != 0) {

		var path = decodeHash(window.location.hash);
		lastPath = firstPath = path;

	} else {
		dis = d;
		type = t;
		lastPath = path = firstPath = p;

		if(ie) {
			document.frames[0].location.href = makeDummy(path);
		}
	}


	loadContent(path);

	// Load the search control

	var searcher = new Searcher();
	SearchControl = new SearchControl('javascript:search(document.getElementById(\'NCSearchControlForm\').q.value);', true, 25);

	SearchControl.addSearcher(searcher);
	SearchControl.draw(document.getElementById('SearchControl'));

	document.getElementById('NCSearchResults').style.display = 'none';
}
