var IE = document.all?true:false
var viewing, adultviewing, viewingvar, toggletype, lastpost;
var typevars = '';

// Return a boolean value telling whether the first argument is an Array object. 
function isArray(test) {
	if (typeof test == 'object') {
		var	criterion = test.constructor.toString().match(/array/i);
		return (criterion != null);
	}
	return false;
}

function doMenu(item) {
	obj=$(item);
	if (obj.style.display=="block") {
		obj.style.display="none";
	}
	else {
		obj.style.display="block";
	}
}

function OpenMenu(item) {
	obj=$(item);
	obj.style.display="block";
}

function CloseMenu(item) {
	obj=$(item);
	obj.style.display="none";
}

function expandComments(item) {
	$('commentlink'+item).href = 'javascript:showPost(\''+item+'\')';
	new Effect.BlindDown('comloading'+item, {duration: .3});
	ajax_do('/dragdrop/sqlconnect.php?comment=view&post='+item);
}

function showPost(post) {
  new Effect.BlindUp('comments'+post, {duration: .3});
  $('commentlink'+post).href = 'javascript:expandComments(\''+post+'\')';
  $('commentlink'+post).innerHTML = $('commentlink'+post).innerHTML.replace(/Hide/, "Show");
}


function voteUp(item, tag) {
  ajax_do('/dragdrop/sqlconnect.php?meta=voteup&item='+item+'&tag='+tag);
}

function voteDown(item, tag) {
  ajax_do('/dragdrop/sqlconnect.php?meta=votedown&item='+item+'&tag='+tag);
}

function delTag(item, tag) {
  ajax_do('/dragdrop/sqlconnect.php?meta=delete&item='+item+'&tag='+tag);
}

function openMetaAdd(id) {
	div = $('metatags'+id);
	if (!$('metabox'+id)) {
		inputbox = document.createElement("b");
		inputbox.id = 'metabox'+id;
		inputbox.innerHTML = '<input type="text" size="20" id="metatag'+id+'" maxlength="15" />&nbsp;<input type="button" id="metabutton'+id+'" value="Add" class="formInputButton" onclick="addMetaTag(\''+id+'\');" style="padding: 0px 3px 0px 3px;">&nbsp;<input type="button" value="X" class="formInputButton" onclick="this.parentNode.hide();" style="padding: 0px 3px 0px 3px;">';
		inputbox.style.display = 'none';
		div.appendChild(inputbox);
		Event.observe($('metatag'+id), "keydown", function(event){if(event.keyCode == 13) addMetaTag(id);});
	  new Effect.Appear(inputbox, {afterFinish:function(obj){obj.element.firstChild.focus();}});
	}
	else new Effect.Appear('metabox'+id, {afterFinish:function(obj){obj.element.firstChild.focus();}});
}

function addMetaTag(id) {
  item2='metatag'+id;
  obj=$(item2);
  tag=obj.value;
  ajax_do('/dragdrop/sqlconnect.php?meta=metaadd&item='+id+'&tag='+tag);
}

function ratePost(event) {
	rating = event.memo.rated;
	post = event.memo.identity.substr(9);
	$(event.memo.identity).innerHTML = '<img src="/images/loading.gif" alt="" />';
	ajax_do('/dragdrop/sqlconnect.php?rate&post='+post+'&rating='+rating);
}

function findMovie(address, method, number) {
	address = address.replace(/&/g,"%26");
  ajax_do('/dragdrop/sqlconnect.php?movie&method='+method+'&address='+address+'&number='+number);
}

function getSubCat(cat, type) {
  if (undefined === type) {
		div = $('category');
	  div.innerHTML = '<select tabindex=\"2\" style=\"width: 144px;\"><option value=\"999\">Loading...</option></select>';
	  ajax_do('/dragdrop/sqlconnect.php?subcat='+cat);
  }
  else {
		ajax_do('/dragdrop/sqlconnect.php?type='+type);
	}
}

function getPostForm(type) {
  div = $('category');
  div.innerHTML = '<select tabindex=\"2\" style=\"width: 144px;\"><option value=\"999\">Loading...</option></select>';
  ajax_do('/dragdrop/sqlconnect.php?subcat='+cat);
}

function addFriend(id) {
	ajax_do('/dragdrop/sqlconnect.php?addfriend='+id);
}

function removeFriend(id) {
	ajax_do('/dragdrop/sqlconnect.php?removefriend='+id);
}

function chooseFriend(id, method) {
  new Effect.Fade($('request'+id));
  $('requests').innerHTML = parseInt($('requests').innerHTML) - 1;
	ajax_do('/dragdrop/sqlconnect.php?'+method+'='+id);
}

// Get base url
var base_url = document.location.pathname;

function ajax_do (url) {
  // Does URL begin with http?
  /*if (url.substring(0, 4) != 'http') {
          url = base_url + url;
  }*/
  
  // Create new JS element
  var jsel = document.createElement('SCRIPT');
  jsel.type = 'text/javascript';
  jsel.src = url;
  
  // Append JS element (therefore executing the 'AJAX' call)
  document.body.appendChild(jsel);
}

function dhtmlLoadScript(url) {
   if (!$(url)) {
		 var e = document.createElement("script");
	   e.src = e.id = url;
	   e.type="text/javascript";
	   document.getElementsByTagName("head")[0].appendChild(e);
   }
}

function checkLinkBox() {
	obj=$('linkbox');
	if (obj.checked == true) doMenu('urldiv');
}

function openAlphaMenu(id) {
  OpenMenu(id);
  div = $('fixform');
  div.style.top = '-3px';
}

function closeAlphaMenu(id) {
  CloseMenu(id);
  div = $('fixform');
  div.style.top = '0px';
}

function submitFilterForm(sort, method) {
	showLoading();
	if (method == 'filter') {
		if (sort != '') {
			$('filter').value = sort;
			$('filter').addClassName('highlightfield');
		}
		else $('filter').removeClassName('highlightfield');
	}
	Element.scrollTo('title');
	ajax_do('/index.php?echoposts=1&'+method+'='+sort+'&justIDs=1');
}

function changeCat(url, subcat, select) {
  showLoading();
  Element.scrollTo('title');
  if (url == 'community' || url == 'sitenews' || url == 'classifieds' || (undefined !== select && (select.substr(3,1) == '0' || select.substr(3,1) == '5'))) {
		if ($('typebardisable').style.display != 'block') $('typebardisable').style.display = 'block';
		if (Element.visible('adulttypebar')) new Effect.Fade($('adulttypebar'));
	}
	else $('typebardisable').style.display = 'none';
  if (url.indexOf("adult") != -1) {
		if (!Element.visible('adulttypebar')) new Effect.Appear($('adulttypebar'));
	}
	else if (Element.visible('adulttypebar')) new Effect.Fade($('adulttypebar'));
	ajax_do('/index.php?echoposts=1&category='+url+'&justIDs=1');
	if (undefined !== select && select != '') {
		if (select.substr(0,3) != 'cat') selectCat(select.substr(0,1), select);
		else selectSubCat(select);
	}
}

function selectCat(maincat, subcat) {
	if (subcat == '' || subcat.length == 1) subcat = 'catall'+maincat;
	else subcat = 'cat'+subcat;
	if (maincat == '') maincat = '0';
	else if (maincat == '0') maincat = '5';
	else if (maincat == '5') maincat = '6';
	Accordion.activate($$('#accordion .accordion_toggle')[maincat]);
	selectSubCat(subcat);
}

function selectSubCat(id) {
	if ($$('#accordion .accordion_content a.selected')[0]) $$('#accordion .accordion_content a.selected')[0].className = '';
	if ($(id)) $(id).className = 'selected';
}

function changePage(page) {
	$('page'+currentpage).className = '';
	$('page'+page).className = 'selected';
	if (page > 1) {
		$('lastpage').style.display = 'inline';
		$('lastpage').href = 'javascript:changePage(\''+(page-1)+'\');';
	}
	else if ($('lastpage')) $('lastpage').style.display = 'none';
	numpages = parseInt(numpages);
	if (page < numpages) {
		$('nextpage').style.display = 'inline';
		$('nextpage').href = 'javascript:changePage(\''+(parseInt(page)+1)+'\');';
	}
	else if ($('nextpage')) $('nextpage').style.display = 'none';
	currentpage = page;
	showLoading();
	$$('.wholepost').invoke('remove');
	Element.scrollTo('title');
	ajax_do('/index.php?echoposts=1&page='+page+'&viewing=loadingTop');
}

function countdown(seconds) {
  if ($('countdown')) {
		seconds = seconds - 1;
	  $('countdown').innerHTML = seconds;
	  if (seconds > 0) window.setTimeout("countdown("+seconds+")",1000);
	  else CloseMenu('countdownfield');
  }
}

function viewPost(id) {
	showLoading();
	ajax_do('/index.php?echoposts=1&viewpost='+id+'&justIDs=1');
}

function viewPosts(user) {
	showLoading();
	Element.scrollTo('title');
	ajax_do('/index.php?echoposts=1&viewposts='+user+'&justIDs=1');
}

function toggleType(type, adult, only) {
	if (adult == '1') {
		spans = $('adulttypebar').getElementsByTagName('span');
		toggletype = 'adulttype';
		types = new Array('straight','lesbian','gay');
		imgtypes = types;
		tempviewing = adultviewing;
	}
	else {
		spans = $('typebar').getElementsByTagName('span');
		toggletype = 'type';
		types = new Array('link','camera','film','blog','ipod');
		if (only == '1') tempviewing = new Array('0','0','0','0','0');
		else tempviewing = viewing;
	}
	if (undefined === tempviewing) {
		tempviewing = new Array();
		for (var i=0;i<spans.length;i++) {
			if ($(spans[i]).hasClassName('typedisable')) tempviewing[i] = '0';
			else tempviewing[i] = '1';
		}
	}
	for(var x=0;x<tempviewing.length;x++) {
		if (types[x] == type) {
			if (tempviewing[x] != '1') {
				tempviewing[x] = '1';
				$(spans[x]).removeClassName('typedisable');
			}
			else {
				tempviewing[x] = '0';
				$(spans[x]).addClassName('typedisable');
			}
		}
		else if (only == '1') $(spans[i]).addClassName('typedisable');
	}
	viewingvar = tempviewing;
	viewingvar.join(',');
  if (adult == '1') adultviewing = tempviewing;
  else viewing = tempviewing;
	showLoading();
	ajax_do('/index.php?echoposts=1&'+toggletype+'='+viewingvar+typevars+'&justIDs=1');
}

function makeNew(arrange) {
	var removePosts = [];
	var postEffects = [];
	newpostsA = newposts.split(",");
	posts = '';	
	div = $("postwrapper");
	div.cleanWhitespace();
	if (undefined === arrange) {
		for(x=0;x<div.childNodes.length;x++) {
			if ((!newpostsA.inArray(div.childNodes[x].id) && div.childNodes[x].id != 'loadingTop' && div.childNodes[x].id != 'pagebar')) {
				if (postEffects.length < 4) postEffects.push(new Effect.BlindUp(div.childNodes[x]));
				removePosts.push(div.childNodes[x]);
			}
			else posts = posts+div.childNodes[x].id+',';
		}
	}
	else {
		newpostsA.unshift("loadingTop");
		newpostsA.push("pagebar");
		for(x=0;x<div.childNodes.length;x++) {
			if (newpostsA[x] != div.childNodes[x].id && div.childNodes[x].id != 'pagebar') {
				if (postEffects.length < 4) postEffects.push(new Effect.BlindUp(div.childNodes[x]));
				removePosts.push(div.childNodes[x]);
			}
			else if (div.childNodes[x].id != 'pages') posts = posts+div.childNodes[x].id+',';
		}
	}
	new Effect.Parallel(postEffects, {
		queue: {
			position: 'start', 
			scope: 'postKill'
		},
		afterFinish: function(){
			removePosts.invoke('remove');
		}
	});
	ajax_do('/index.php?echoposts=1&viewing='+posts);
}

function showLoading(hide) {
	if (hide == 1) new Effect.BlindUp('loadingTop', {duration: .35, queue: 'end'});
	else new Effect.BlindDown('loadingTop', {duration: .35, queue: 'start'});
}

Effect.ResizeToContent = function(element) {
  element.cleanWhitespace();
	var newHeight = element.scrollHeight+'px';
  return new Effect.Morph(element, { style: { height: newHeight }, duration: 0.3 });
};

function morphResize(element, height) {
	if (element.getHeight()+'px' != height) {
		new Effect.Morph(element, {
		  style: {
		    height: height
		  },
		  duration: 0.5,
		  afterFinish: function(obj) {
				$(obj.element.id+'arrow').src = '/images/down.png';
			}
		});
	}
	else {
		var newHeight = element.scrollHeight+'px';
		new Effect.Morph(element, {
		  style: {
		    height: newHeight
		  },
		  duration: 0.5,
		  afterFinish: function(obj) {
				$(obj.element.id+'arrow').src = '/images/up.png';
			}
		});
	}
}


function newPost() {
	Modalbox.show('/dragdrop/sqlconnect.php?newpost=1', {title: "New Post", width: 700});
}

function editPost(post) {
	Tips.hideAll();
	Modalbox.show('/dragdrop/sqlconnect.php?newpost=1&edit='+post, {title: "Edit Post", width: 700});
}

function updatePost(post) {
	if (undefined === post) post = lastpost;
	ajax_do('/index.php?echoposts=1&justIDs=1');
	ajax_do('/index.php?echoposts=1&update='+post);
}

function readMore(post) {
	$('post'+post).style.height = Element.getDimensions($('post'+post)).height + 'px';
	ajax_do('/index.php?echoposts=1&readmore='+post);
}

function readLess(post) {
	ajax_do('/index.php?echoposts=1&readless='+post);
}

function showNew() {
	$('postform').parentNode.removeChild($('postform'));
	Modalbox.show('/index.php?echoposts=1', {title: "Viewing Post", width: $('postwrapper').offsetWidth, afterHide: function() { updatePost();} });
}

function viewProfile(user) {
	Tips.hideAll();
	Modalbox.show('/index.php?echoposts=1&viewprofile='+user, {title: user+"'s Profile", width: 700});
}

function showPrefs(prefs) {
	if (undefined === prefs) prefs = '';
	Modalbox.show('/index.php?echoposts=1&prefs='+prefs, {title: 'Preferences', width: 700, afterHide: function() { window.location = "/"}});
}

function sendPrefs(prefs) {
	if (undefined === prefs) prefs = '';
	$('prefsformsubmit').value = 'Submitting...';
	$('prefsformsubmit').disabled = true; 
	Modalbox.show('/index.php?echoposts=1&prefs='+prefs+'&'+Form.serialize($('prefsform')), {title: "Preferences", width: 700, afterHide: function() { window.location = "/"}});
}

function newsletter() {
	Modalbox.show('/index.php?echoposts=1&newsletter=1', {title: "Beta Alert Sign-Up", width: 700});
}

function sendMail() {
	$('send').value = 'Sending...';
	$('send').disabled = true;
	$('content').value = FCKeditorAPI.GetInstance('FCKeditor1').GetHTML(true);
	ajax_do('/owpm/index.php?request=sendmail&'+Form.serialize($('mailform')));
}

function mail(request, mailid, method) {
	if (undefined === mailid) mailid = '';
	if (undefined === method) method = '';
	if (undefined !== request) {
		if (request == 'delete') mailid = '&mailid='+mailid;
		else if ((request == 'showmail' || method != '') && method != 'numpage' && method != 'sendto') mailid = '&mailid='+mailid;
		if (method == 'reply' || method == 'forward') method = '&option='+method;
		else if (method == 'numpage') {
			method = '&numpage='+mailid;
			mailid = '';
		}
		else if (method == 'sendto') {
			method = '&sendto='+mailid;
			mailid = '';
		}
		request = '?request='+request;
	}
	else request = '';
	Modalbox.show('/owpm/index.php'+request+mailid+method, {title: "Mail", width: 800, afterFinish:function(){Modalbox.resizeToContent();}});
}

function validateNewsletter() {
	$('newsletterformsubmit').value = 'Submitting...';
	$('newsletterformsubmit').disabled = true; 
	Modalbox.show('/index.php?echoposts=1&newsletter=post&'+Form.serialize($('newsletterform')), {title: "Beta Alert Sign-Up", width: 700});
}

function resetView() {
	showLoading();
	if ($('filter').hasClassName('highlightfield')) {
		$('filter').removeClassName('highlightfield');
		$('filter').value = '';
	}
	ajax_do('/index.php?echoposts=1&resetview=reset&justIDs=1');
}

function validatePost(movie) {
	$('postformSubmit').value = 'Submitting...';
	$('postformSubmit').disabled = true;
	if (movie != '1') $('content').value = FCKeditorAPI.GetInstance('content').GetHTML(true);
	if ($('type') && $('type').disabled) {
		var wasdisabled = true;
		$('type').disabled = false;
	}
	ajax_do('/index.php?post=1&'+Form.serialize($('postform')));
	if (wasdisabled == true) $('type').disabled = true;
}

function isMouseLeaveOrEnter(e, handler) {
	if (e.type != 'mouseout' && e.type != 'mouseover') return false;
	var reltg = e.relatedTarget ? e.relatedTarget :
	e.type == 'mouseout' ? e.toElement : e.fromElement;
	while (reltg && reltg != handler) reltg = reltg.parentNode;
	return (reltg != handler);
}

function closeMenu() {
	if ($('usermenu')) new Effect.BlindUp($('usermenu'), {afterFinish:function(){	$$('#user').invoke('removeClassName', 'hovered');lastitem='';}, duration: .2, queue: 'end'});
}

function checkAll() {
	form='delform';
	val = $('master').checked;
	dml=document.forms[form];
	len = dml.elements.length;
	for(i=0;i<len;i++) {
		dml.elements[i].checked=val;
	}
}

function setStars(ratestars, rateaverage, novote) {
	for (var i=0;i<ratestars.length;i++) {
		if (novote == '1') new Starbox('ratestars'+ratestars[i], rateaverage[i], {locked: true, rated: rateaverage[i]});
		else new Starbox('ratestars'+ratestars[i], rateaverage[i]);
	}
	// observing all starboxes
	document.observe('starbox:rated', ratePost);
}

function updateX(v, number) {
	$('rateHandle'+number).innerHTML = v;
}

function updateSort(type) {
  sortvalue = new Array('mostpop', 'newest', 'leastpop', 'oldest');
  for(x=0;x<sortvalue.length;x++) {
    if (type == sortvalue[x]) $('sort').selectedIndex = x;
  }
}

Array.prototype.inArray = function (value)
// Returns true if the passed value is found in the
// array.  Returns false if it is not.
{
    var i;
    for (i=0; i < this.length; i++) {
        if (this[i] == value) {
            return true;
        }
    }
    return false;
};

function fixMargin(IDs) {
	for(x=0;x<IDs.length;x++) {
		$(IDs[x]).style.marginTop = '';
	}
}

var content, tag1, tag2, tag3, url;
function saveValues() {
	if ($('content___Frame') && typeof(FCKeditorAPI) != 'undefined' && FCKeditorAPI.GetInstance('content').GetHTML(true) != '<p>Enter the content of your post</p>') content = FCKeditorAPI.GetInstance('content').GetHTML(true);
	else content = '';
	if ($('tag1')) tag1 = $('tag1').value;
	if ($('tag2')) tag2 = $('tag2').value;
	if ($('tag3')) tag3 = $('tag3').value;
	if ($('url')) url = $('url').value;
}

function replaceValues() {
	if ($('tag1') && undefined !== tag1) $('tag1').value = tag1;
	if ($('tag2') && undefined !== tag2) $('tag2').value = tag2;
	if ($('tag3') && undefined !== tag3) $('tag3').value = tag3;
	if ($('url')) {
		if (url != '' && undefined !== url) {
			$('url').value = url;
			if ($('linkbox')) {
				$('linkbox').checked = true;
				doMenu('urldiv');
			}
		}
	}
}

function showLinkMenu(type, id, element) {
	if (type == 'post') {
		url = '/viewpost/'+id+'/';
		new Tip(element, 'Use the link below to create a bookmark,<br>send to a friend, or post on another site<br><br><strong><a href="http://www.mydropspot.com'+url+'">http://www.mydropspot.com'+url+'</a></strong>', {
		  style: 'balloon',
		  title: 'Direct Link',
		  showOn: 'click',
			hook: {
				target: 'topMiddle',
				tip: 'bottomMiddle'
			},
		  stem: {
				position: 'bottomMiddle'
			},
			hideOn: { element: 'closeButton', event: 'click' }
		});
	}
	else {
		url = id;
		element = $('linkbutton');
		new Tip(element, 'Use the link below to create a bookmark,<br>send to a friend, or post on another site<br><br><strong><a href="http://www.mydropspot.com'+url+'">http://www.mydropspot.com'+url+'</a></strong>', {
		  style: 'balloon',
		  title: 'Direct Link',
		  showOn: 'click',
			hook: {
			},
		  stem: {
			},
			offset: { x: -60, y: -80 },
			hideOn: { element: 'closeButton', event: 'click' }
		});
	}
	element.prototip.show();
}

function updateRSSLinks(title, link) {
	$('rssmetalink').title = title;
	$('rssmetalink').href = link+'/feed.xml';
	$('rssbutton').href = link+'/feed.xml';
	$('linkbutton').href = 'javascript:showLinkMenu(\'site\',\''+link+'\');';
	linkTipInit();
}

function tipInit() {
  $$('.tipinit').each(function(element) {
		new Tip(element, element.alt, {
		  style: 'balloon'
		});
  });
  $$('.buttontip').each(function(element) {
		new Tip(element, element.title, {
		  style: 'balloon'
		});
  });
  $$('.votetag').each(function(element) {
		new Tip(element, '<div class="friendbar" style="display: block;width: 60px;margin-bottom: 6px;"><a href="javascript:voteUp(\''+element.id+'\')"><img src="/images/voteup.png" alt="" /> Is Good</a></div><div class="friendbar" style="display: block;"><a href="javascript:voteDown(\''+element.id+'\')"><img src="/images/votedown.png" alt="" /> Is Bad</a></div>', {
		  style: 'balloon',
		  title: 'This tag:',
			hideOn: { element: 'tip', event: 'mouseout' },
			hideAfter: .6,
			delay: .16
		});
  });
  $$('.deltag').each(function(element) {
		new Tip(element, '<div class="friendbar" style="display: block;width: 70px;"><a href="javascript:delTag(\''+element.id+'\')"><img src="/images/delete.png" alt="" /> Delete Tag</a></div>', {
		  style: 'balloon',
			hideOn: { element: 'tip', event: 'mouseout' },
			hideAfter: .6,
			delay: .16
		});
  });
  Tips.hideAll();
}

function linkTipInit() {
  new Tip($('linkspan'), 'Click for a link to this exact page', {
		style: 'balloon',
		hook: {
			target: 'topMiddle',
			tip: 'bottomMiddle'
		},
		stem: {
			position: 'bottomMiddle'
		},
		offset: { x: 9, y: 0 }
	});
  new Tip($('rssbutton'), 'RSS Feed for '+document.title, {
		style: 'balloon'
	});
}

function doNothing() {}
