var theDomain = 'http://' + document.domain;

function keepAlive() {	
	
	$.getJSON(theDomain + "/ajax/keepAlive.php", { }, function(json){
		
		if ( json.a != "undefined" && json.a == "1") {
			//still alive
		} else {
			theInt = window.clearInterval(theInt);
		}
		 
	});
	
}

function cellBind(funcCall) {

	if ($("#cell_1").length != 0) {
	
		$("#cell_1").bind("focus", function(e) { goGreen("#cell_1"); });
		$("#cell_2").bind("focus", function(e) { goGreen("#cell_2"); });
		$("#cell_3").bind("focus", function(e) { goGreen("#cell_3"); });
	
		//do number traversing
		$("#cell_1").bind("keyup", function(e) { cellFull(e, "cell_", "1"); });
		$("#cell_2").bind("keyup", function(e) { cellFull(e, "cell_", "2"); });
	
		if (funcCall) {
			//return submit
			$("#cell_3").bind("keydown", function(e) { checkRet(e, ""); });		
			$("#cell_3").bind("keyup", function(e) { checkRet(e, funcCall); });
		}
	}	
	
}

function checkCell() {

	var cell = $("#cell_1").val().trim() + $("#cell_2").val().trim() + $("#cell_3").val().trim();	
	return errorCheck(cell, "cell_", "Cell Number", "phone", 10, 10, 1, 1, "");	

}

function cellFull (e, idBase, idNum) {
		
	var valLength = $("#" + idBase + idNum).val().length;
	
	var idNumNext = parseInt(idNum) + 1;
	
	if (valLength > 2 && e.keyCode != 9 && e.keyCode != 37 && e.keyCode != 38 && e.keyCode != 39 && e.keyCode != 40 && e.keyCode != 16) {
				
		$("#" + idBase + idNumNext).focus();
		
	}
	
}

function breakout_of_frame() {
	if (top.location != location) {
		top.location.href = document.location.href;
	}
}

function shareFocus(id) {
	$("#" + id).css("background-color", "#67a54b");
}
function shareBlur(id) {
	$("#" + id).css("background-color", "white");
}

function resetTimer() {
	alert("TIME EXPIRED!  YOUR SOCIAL DATA WILL BE DELETED\n\nDo you want to know who is viewing your profile and searching for you?  \n\nClick 'Ok' below to save your Social Data for " + (timerInterval / 1000) + " more seconds so that you can find out.");
	
	//pull new timer via ajax
	$.get("ajax/timer.php", {}, function(data){
			
		$("#timerCont").replaceWith(data);
		
	});
	
	setTimeout("resetTimer()", timerInterval);
	
}

function updatePurchase(id) {
	
	var offer = $("#amountOpt" + id).val();
	var given = $("#amountGiven" + id).html();
	
	$("#amount").val(offer + '.00');
	$("#item_name").val(given);
	
	if (id == 1) {
		//termType
		$("#t3").val("Y");
		//termLength
		$("#p3").val("1");
	} 
	else if (id == 2) {
		//termType
		$("#t3").val("M");
		//termLength
		$("#p3").val("3");
	} 	
	else if (id == 3) {
		//termType
		$("#t3").val("D");
		//termLength
		$("#p3").val("1");
	} 	
	
}

function feedSubmit() {
	
	//get vars
	var err = "";
	var email = $("#email").val();
	var subject = $("#subject").val();
	var message = $("#message").val();
	
	//check errors
	err += errorCheck(email, "email", "Email", "email", 5, 150, 1, 1, "");
	err += errorCheck(subject, "subject", "Subject", "string", 5, 250, 1, 1, "");
	err += errorCheck(message, "message", "Message", "string", 15, 20000, 0, 1, "");
	
	if (!err) {
		//if good submit
		doSubmit("feedForm");	
	} else {
		//if bad output errors
		doError(err);
	}
	
	
}

function alertObj(obj) {
	
	var str="";
	
	for(prop in obj) {
		str+=prop + " value :"+ obj[prop]+"\n";
	}

	alert(str);
    	
}	

function keepHolder() {
	keepBubble = 1;
}

function getTheType(theId) {
	
	var shortType = theId.substring(0, 2);
	
	if (shortType == "pi") {
		return 'picture';
	}
	else if (shortType == "ci") {
		return 'city';
	}
	else if (shortType == "sc") {
		return 'school';
	}
	else if (shortType == "wo") {
		return 'work';
	}
	else if (shortType == "te") {
		return 'testimonial';
	}
	else if (shortType == "he") {
		return 'headline';
	}
	else if (shortType == "ab") {
		return 'about';
	}
	else if (shortType == "co") {
		return 'comment';
	}
	
}

function showExtra(theId) {
	
	//if a vote is submitted keep alive bubble
	if (freezePop != 1) {
	
		//make sure to keep alive
		keepBubble = 1;
		
		//get values
		realId = theId.substring(2);
		theType = getTheType(theId); 
		votes_for = $("#" + theId + "_f").val();
		votes_against = $("#" + theId + "_a").val();
		
		//set values in ui
		$("#votesFor").html(votes_for);
		$("#votesAgainst").html(votes_against);
		$("#commentBubble").attr({href: "content.php?type=" + theType + "&id=" + realId});
		$("#addBubble").attr({href: "add.php?id=" + theSid + "&type=" + theType});			
		$("#viewBubble").attr({href: "view.php?id=" + theSid + "&type=" + theType});
		$("#shareBubble").bind("click", function(e) { doShare(theType, realId); });		
		
		//unbind previous
		$("#plusVote").unbind("click");	
		$("#minusVote").unbind("click");
		
		//bind the votes
		$("#plusVote").bind("click", function(e) { doVote(theType, realId, 1, theId); pausePop(1); });	
		$("#minusVote").bind("click", function(e) { doVote(theType, realId, 0, theId);  pausePop(1); });		
	
		if (theType == "headline") {
			place(theId, 'voteHolder', 'right', 0, 88);
		}
		else if (theType == "picture") {
			place(theId, 'voteHolder', 'right', 0, 75);		
		}
		else if (theType == "testimonial" || theType == "comment") {
			place(theId, 'voteHolder', 'right', 5, 75);		
		}		
		else {
			place(theId, 'voteHolder', 'right', 0, 93);		
		}		
	
		//hide message
		$("#voteMessage").css("display", "none");
		//show vote row
		$("#voteRow").css("display", "block");
	
		//show bubble
		$("#voteHolder").css("display", "block");
		
	}

}

function startFade() {
	
	if (freezePop != 1) {
		keepBubble = 0;	
		setTimeout("closeBubble()", 500);
	}
		
}

function closeBubble() {
	
	if (keepBubble != 1) {
		$('#voteHolder').css('display', 'none');	
	}
	
}

function pausePop(theOn) {
	
	if (theOn == 1) {
		freezePop = 1;
	} else {		
		$('#voteHolder').css('display', 'none');	
		freezePop = 0;		
	}
}

function createSubmit(step) {
	
	//local scope
	var err = '';
	
	//clear all errors		
	$("textarea").removeClass("wrong");
	$("input").removeClass("wrong");
	$("select").removeClass("wrong");
	
	if (step == 1) {
	
		$("#genderCont").removeClass("wrong");
		
		//error check values
		err += errorCheck($("#fName").val(), "fName", "First Name", "string", 2, 50, 1, 1, "");
		err += errorCheck($("#lName").val(), "lName", "Last Name", "string", 2, 50, 1, 1, "");
		err += errorCheck($("#city").val(), "city", "City", "string", 2, 100, 1, 1, "");		
		err += errorCheck($("input[@name='gender']:checked").val(), "gender", "Gender", "gender", 0, 0, 0, 1, "");	
						
		//if any part of birthday is supplied, make sure all is supplied
		if ($("#bMonth").val() != "" || $("#bDay").val() != "" || $("#bYear").val() != "") {
			
			if ($("#bMonth").val() == "" || $("#bDay").val() == "" || $("#bYear").val() == "") {
				err += "Cannot only enter part of birthday.<br/>";
				$("#bMonth").addClass("wrong");
				$("#bDay").addClass("wrong");
				$("#bYear").addClass("wrong");
			}
			
		} 
				
	}
	else if (step == 2) {
		err = checkPic();
	}
	else if (step == 3) {
		
		if ($("#headline").val()) {
			err += errorCheck($("#headline").val(), "headline", "Headline", "string", 2, 100, 1, 1, "");
		}		
		if ($("#about").val()) {		
			err += errorCheck($("#about").val(), "about", "About", "string", 2, 40000, 1, 1, "");
		}
		
	}
	else if (step == 4) {
		
		//remove testimonial containter issue
		$("#testimonialCont").removeClass("wrong");
		
		if ($("#school").val()) {
			err += errorCheck($("#school").val(), "school", "School", "string", 2, 50, 1, 1, "");		
		}
		
		if ($("#work").val()) {
			err += errorCheck($("#work").val(), "work", "Work Section", "string", 2, 50, 1, 1, "");			
		}
		
		if ($("#testimonial").val() || $("#rating").val()) {
			err += errorCheck($("#testimonial").val(), "testimonial", "Testimonial", "testimonial", 1, 7000, 1, 1, $("#rating").val());					
		}
		
	}
	else if (step == 5) {
		
		if ($("#email").val()) {
			err += errorCheck($("#email").val(), "email", "Email", "email", 0, 150, 0, 1, "");			
		}
		
	}
	
	//if no error, then show image verification step	
	if (err == '' && step == 1) {
		
		//see if cap is needed
		$.getJSON("ajax/captchaNeeded.php", { submitType: 'create' }, function(needed){
	
			//require captcha 
			if (needed.r == 'y') {
		
				//send function to string
				theFunc = "createSubmit('" + step + "');";		
				getCaptchaCredit();
				return false;
			} else {
				doSubmit('formCreate');
			}
		
		});
	
		
	}
	else if (err == '') {
		doSubmit('formCreate');
	} 
	else {
		doError(err);
	}
	
}

function tryLogin() {
	
	//clear all wrong listings from CSS
	$("input").removeClass("wrong");
	
	//get data
	var email = $("#email").val();
	var pass = $("#pass").val();
	
	//standard data check
	var err = "";
	err += errorCheck(email, "email", "Email", "email", 2, 100, 1, 1, "");
	err += errorCheck(pass, "pass", "Password", "password", 2, 100, 1, 1, "");
	
	
	if (!err) {		
		doSubmit('loginForm');				
	} else {		
		doError(err);
	}
	
}

function goGreen(id) {
	
	$("textarea").removeClass("greenOut");
	$("input").removeClass("greenOut");
	$("select").removeClass("greenOut");
	$("#genderCont").removeClass("greenOut");
	
	$(id).addClass("greenOut");
	
}

function checkRet(e, theFunc) {
	if (e.keyCode == 13) {
		e.preventDefault();				
		eval(theFunc);
	}
}

function openWin(loc, width, height) {
	
	var configStr = 'toolbar=0,status=0,width=' + width + ',height=' + height;
	
	openedWin = window.open(loc,'winOpened',configStr);
}

//fix for trim function
if(typeof String.prototype.trim !== 'function') {
  String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g, ''); 
  }
}

function submitLanding() {
	
	//clear all wrong listings from CSS
	$("textarea").removeClass("wrong greenOut");
	$("input").removeClass("wrong greenOut");
	$("select").removeClass("wrong greenOut");
	$("#cell_Cont").removeClass("wrong");
	
	//check data
	var err = "";
	if ($("#fullName").length != 0) {
		
		var fullName = $("#fullName").val().trim();	
		
		//make sure there is a space in there between names for first and last (trim used already)
		if (/\s/.test(fullName) == false) {
			err = "Please enter your <u>First</u> and <u>Last</u> names. <br/>";
			$("#fullName").addClass("wrong");		
		} else {
			err += errorCheck(fullName, "fullName", "Full Name", "string", 5, 100, 1, 1, "");				
		}
		
	}
	if ($("#fName").length != 0) {
		var fName = $("#fName").val().trim();
		err += errorCheck(fName, "fName", "First Name", "string", 2, 100, 1, 1, "");
	}
	if ($("#lName").length != 0) {
		var lName = $("#lName").val().trim();
		err += errorCheck(lName, "lName", "Last Name", "string", 2, 100, 1, 1, "");	
	}
	if ($("#email").length != 0) {
		var email = $("#email").val().trim();	
		err += errorCheck(email, "email", "Email", "email", 5, 50, 1, 1, "");
	}
	if ($("#cell_1").length != 0) {
		var cell = $("#cell_1").val().trim() + $("#cell_2").val().trim() + $("#cell_3").val().trim();	
		err += errorCheck(cell, "cell_", "Cell Number", "phone", 10, 10, 1, 1, "");
	}
	
	if (!err) {
		
		//if good submit
		doSubmit("landingForm");	
	} else {
		//if bad output errors
		doError(err);
	}
	
}

function shareEmail() {
	
	//get emails
	var emails = $("#emails").val();
	//get msg
	var msg = encodeURIComponent($("#shareMessage").val());	
	//get fromEmail
	var fromEmail = $("#fromEmail").val();
	
	$.getJSON("ajax/share_email.php", { type: shareType, id: targetId, emails: emails, fromEmail: fromEmail, msg: msg}, function(json){
	
		if (json.r) {									
			alert("Success - Content Shared");
			$('#shareHolder').dialog('close');
			
			//clear both fields
			$("#emails").val("");
			$("#shareMessage").val("");					
			
		} else {
			alert(json.e);
		}
			
	});
	
}

function configShare() {
	// Dialog			
	$('#shareHolder').dialog({
		autoOpen: false,
		hide: 'blind',
		resizable: false,
		draggable: false,
		modal: false,
		width: 395
	});
}

function openShareDialog(special) {
	
	//config the dialog	
	configShare();
	
	//make modal if special
	if (special) {
		$('#shareHolder').dialog('option', 'modal', true);		
	} else {
		$('#shareHolder').dialog('option', 'modal', false);		
	}
	
	//open dialog
	$('#shareHolder').dialog('open');
}
	

var shareSpecial = "";
var shareType = "";
function doShare(myShareType, myTargetId, special) {

	//make special global
	shareSpecial = special;
	
	//set view window
	shareScreen("init");
	
	//set to global for shareIt function
	shareType = myShareType;
	targetId = myTargetId;
	
	//open share
	openShareDialog(special);
}

function shareIt(network, directTarget, directId) {
	
	//if the direct targets are set, then use them
	if (directTarget) {
		shareType = directTarget;
		targetId = directId;
	}
	
	//open popup before ajax (otherwise will be blocked)
	if (network == 'facebook') {
		winShare = window.open('','socialSharer','toolbar=0,status=0,width=980,height=436');
	} 
	else if (network != "email") {
		winShare = window.open('','socialSharer','');
	}
	
	$.getJSON("ajax/shareInfo.php", { type: shareType, id: targetId, network: network }, function(json){
	
		if (json.l) {
						
			//create events and pageviews in ga
			doEvent('share', network, shareType, '');
							
			if (network != "email") {
				
				//close window
				if (!directTarget) {
					$('#shareHolder').dialog('close');
				}
				
				//direct winShare to right location
				winShare.location = unescape(json.l);
								
			} else {
								
				shareScreen("email");
				
				//if direct to email, open window
				if (directTarget) {
					openShareDialog();
				}
				
			}
			
		}
			
	});
}

function shareScreen(fLocation) {

	if (!fLocation || fLocation == "init") {
		//init stage
		$('#shareHolder').dialog('option', 'width', 395);				
		$("#emailCont").css("display", "none");
		$("#importCont").css("display", "none");		
		$("#networkCont").css("display", "block");
			
		//turn on special section
		if (shareSpecial) {
			$('#' + shareSpecial + 'Share').css('display', 'block');
		} else {
			$('#postShare').css('display', 'none');
			$('#viewShare').css('display', 'none');
		}
		
	} 
	else if (fLocation == "email") {
		//email
		$('#shareHolder').dialog('option', 'width', 325);
		$("#networkCont").css("display", "none");
		$("#importCont").css("display", "none");
		$("#emailCont").css("display", "block");
		$("#emails").focus();
	}
	else if (fLocation == "import") {
		//import
		$('#shareHolder').dialog('option', 'width', 325);
		$("#networkCont").css("display", "none");
		$("#emailCont").css("display", "none");
		$("#importCont").css("display", "block");
		$("#email").focus();
	}
	
}


function changePass() {
	
	//clear all wrong listings from CSS
	$("input").removeClass("wrong");
	
	//get values
	var nPass = $("#pass1").val();
	var cPass = $("#pass2").val();
	var err = "";
	
	//make sure passwords are there
	err += errorCheck(nPass, "pass1", "New Password", "password", 0, 0, 0, 1, "");
	err += errorCheck(cPass, "pass2", "Confirm Password", "password", 0, 0, 0, 1, "");
	
	if (cPass != nPass) {
		err += "Passwords do not match.";
	}
	
	if (!err) {
		doSubmit('newPassForm');
	} else {
		doError(err);
	}
}

function noticePop(type) {

	if (type == "own") {
		theWidth = 410;
		theHeight = 300;
	} else {
		theWidth = 370;
		theHeight = 200;	
	}
	
	
	$('#noticeDialog').dialog({
		autoOpen: false,
		hide: 'blind',
		resizable: false,
		draggable: false,
		modal: false,
		width: theWidth,
		height: theHeight,		
		buttons: {
			"Cancel": function() { 
				$(this).dialog("close");
			},
			"Ok": function() { 
				updateNotice();
			}
		}
	});
			
}

function noticeConfig(id, type) {
	
	//open popup
	noticePop(type);		
	$('#noticeDialog').dialog('open');
	$('button').blur();		
	
	//set spinner
	doWait('noticeCont');
		
	//show content in popup
	$.get("ajax/noticeOptions.php", {id: id, type: type}, function(data){
		
		//clear wait
		clearWait('noticeCont');
		
		//replace content
		if (data != 0) {
			$("#noticeCont").html(data);									
		} 
				
	});	
	
}

function updateNotice() {
	//get vars
	var sType = $("#sType").val();
	var sId = $("#sId").val();
	var opt = new Array();
	
	if (sType == "track") {
		var rate_limit = $("input[@name='rate_limit']:checked").val();
		
		//add waiting
		doWait("submitStatus");
	
	} else {
		
		var trackerAdd = $("input[name='trackerAdd']:checked").val();
		var aboutAdd = $("input[name='aboutAdd']:checked").val();
		var birthdayAdd = $("input[name='birthdayAdd']:checked").val();
		var cityAdd = $("input[name='cityAdd']:checked").val();
		var pictureAdd = $("input[name='pictureAdd']:checked").val();
		var headlineAdd = $("input[name='headlineAdd']:checked").val();
		var schoolAdd = $("input[name='schoolAdd']:checked").val();
		var secretAdd = $("input[name='secretAdd']:checked").val();
		var testimonialAdd = $("input@name='testimonialAdd']:checked").val();
		var workAdd = $("input[name='workAdd']:checked").val();
		var commentAdd = $("input[name='commentAdd']:checked").val();
		var subCommentAdd = $("input[name='subCommentAdd']:checked").val();
		
		//create total to pass
		var opt = "trackerAdd:" + trackerAdd + ",aboutAdd:" + aboutAdd + ",birthdayAdd:" + birthdayAdd + ",cityAdd:" + cityAdd + ",pictureAdd:" + pictureAdd + ",headlineAdd:" + headlineAdd + ",schoolAdd:" + schoolAdd + ",secretAdd:" + secretAdd + ",testimonialAdd:" + testimonialAdd + ",workAdd:" + workAdd + ",commentAdd:" + commentAdd + ",subCommentAdd:" + subCommentAdd;

		//add waiting
		doWait("submitCont");
		
	}
			
	//see if cap is needed
	$.getJSON("ajax/noticeReport.php", {id: sId, type: sType, rate_limit: rate_limit, opt: opt}, function(json){

		clearWait("submitCont");
	
		//require captcha 
		if (json.r == 1) {
			
			//make green text
			$("#submitCont").addClass("goodUpdate");
			$("#submitCont").html(json.n);
						
			
		} else {
			
			//make red text
			$("#submitCont").addClass("badUpdate");			
			$("#submitCont").html(json.e);
			
		}
		
		//close window
		setTimeout("$('#noticeDialog').dialog('close')", 500);
		;
	
	});

}

function checkDelete(id, type) {
	if (confirm("Deletions Are Permanent!!! \n\n All content, votes, and comments attached to this item will be deleted.  \n\nAre you sure you want to delete this item?\n\n") == true) {
		contentDelete(id, type);
	} 
}

function contentDelete(id, type) {
	
	//if no error, then show image verification step	
	if (id && type) {
	
		$.getJSON("ajax/captchaNeeded.php", { submitType: 'deleteContent' }, function(needed){
		
			//require captcha 
			if (needed.r == 'y') {
		
				//send function to string
				theFunc = "contentDelete(" + id + ", '" + type + "');";		
				getCaptchaCredit();
				return false;
				
			} else {				
				
				//do delete
				$.getJSON("ajax/content_delete.php", { type: type, id: id }, function(json){
					
					if (json.r == 1) {
						alert(json.n);
						$("#" + id + "Cont").slideUp();
						
						doEvent("content deleted", type, id, "");
						
					}
					else if (json.e) {
						alert(json.e);
						if (json.r == 2 && confirm("Would you like to become a Premium Member?") == true) {
							window.location = 'secure.php';
						}
							
						
					}
					 
								
				
				});
				
			}
		
		});
		
	} else {
		
		doError(err);
		
	}
}

function submitPaypal() {
	doSubmit("paypalForm");
}

var payLocked = 0;
var logged = 0;
function cardPayment() {
	var err = '';
	
	//clear all wrong listings from CSS
	$("textarea").removeClass("wrong");
	$("input").removeClass("wrong");
	$("select").removeClass("wrong");
	$("#termsCont").removeClass("wrong");
	$("#chargeErrorsCont").css("display", "none");
	
	/////////////////	
	//GET DATA
	var ccName = $("#ccName").val();
	var ccNumber = $("#ccNumber").val();
	var expMonth = $("#expMonth").val();
	var expYear = $("#expYear").val();
	var zip = $("#zip").val();
	var cvv2 = $("#cvv2").val();
	var amount = $("#amount").val();
	var trialAmount = $("#trialAmount").val();
	var chargeType = $("#chargeType").val();
	var loadedOpt = $("#loadedOpt").val();
	
	err += errorCheck(ccName, "ccName", "Name on Card", "string", 3, 250, 1, 1, "");
	err += errorCheck(ccNumber, "ccNumber", "Card Number", "string", 3, 35, 1, 1, "");
	err += errorCheck(expMonth, "expMonth", "Exp. Month", "string", 2, 2, 1, 1, "");
	err += errorCheck(expYear, "expYear", "Exp. Year", "string", 4, 4, 1, 1, "");
	err += errorCheck(cvv2, "cvv2", "Security Code", "string", 2, 10, 1, 1, "");
	err += errorCheck(zip, "zip", "Zip Code", "string", 2, 20, 1, 1, "");
	
	if ($('#terms').attr('checked') == false) {
		err += "Must agree to Terms.";
		$("#termsCont").addClass("wrong");
	}
	
	/////////////////
	//INPUT CHECKS
							
	//if no error, then show image verification step	
	if (err == '' && payLocked == 0) {
	
		//set form to locked
		payLocked = 1;
		
		//hide input box
			$("#ccSubmit").css("display", "none");
		//show timer
			$("#payProcess").css("display", "block");	 		
	 		
		$.getJSON("ajax/ccPayment.php", { ccName: ccName, ccNumber: ccNumber, expMonth: expMonth, expYear: expYear, zip: zip, cvv2: cvv2, amount: amount, trialAmount: trialAmount, chargeType: chargeType, loadedOpt: loadedOpt }, function(json){

			//unlock form
			payLocked = 0;
			
			//if success then refresh window			
			if (json.r == 1) {
								
				if ((chargeType == "membership" || chargeType == "trial") && logged == 1) {
					window.location = 'success.php?subscribe=success';
				}
				else if (chargeType == "trial" || chargeType == "membership") {
					window.location = 'register.php?verify=success';
				}
				 else {
					window.location = 'success.php?payment=success';
				}
				
			} 
			else {
				
				//redirect user if already paid
				if (json.re) {
					window.location = json.re;
				}
				
				//highlight bad fields for re-check				
				if (!json.b) {				
					payErrorRed();  //all possible
				} 
				else {
					
					//single pay error exists
					payRemoveGreen();
					$("#" + json.b).addClass("wrong");
					$("#" + json.b).unbind('focus');
					$("#" + json.b).focus();
	
				}
				
				//if failure, then show errors	
				chargeError(json.e);				
				
				//hide the timer
				$("#payProcess").css("display", "none");
				//show the submit button
				$("#ccSubmit").css("display", "block");
				
			}
			
		});
		
	} else {
		
		chargeError(err);
		
	}
	
}

function payRemoveGreen() {
	$("#ccNumber").removeClass("greenOut");
	$("#expMonth").removeClass("greenOut");
	$("#expYear").removeClass("greenOut");				
	$("#zip").removeClass("greenOut");
	$("#cvv2").removeClass("greenOut");		
}

function payUnbind() {
	$('#zip').unbind('focus');
	$('#cvv2').unbind('focus');
	$('#ccNumber').unbind('focus');
	$('#ccName').unbind('focus');
	$('#expMonth').unbind('focus');
	$('#expYear').unbind('focus');	
}

function payErrorRed() {
	
	//add errors
	$("#ccNumber").addClass("wrong");
	$("#expMonth").addClass("wrong");
	$("#expYear").addClass("wrong");				
	$("#zip").addClass("wrong");
	$("#cvv2").addClass("wrong");
	
	//remove green fields
	payRemoveGreen();
	
	//unbind the green highlighting
	payUnbind();	
}		

function chargeError(err) {
	$("#chargeErrorsCont").css("display", "block");				
	$("#chargeErrors").css("display", "block");
	$("#chargeErrors").html(err);				
}

function showCV2() {
	mywindow = window.open("cv2.html","mywindow","location=0,status=0,scrollbars=0,width=357,height=515");
	
	mywindow.moveTo(100,100); 
}


function errorCheck(data, dataId, dataName, dataType, smallest, largest, checkForBad, addLines, extraInfo) {

	//must intialize to give local scope
	var err = '';

	//take care of optional arguments
	if (typeof checkForBad == 'undefined') {
		checkForBad = 1;
	}
	if (typeof addLines == 'undefined') {
		addLines = 0;
	}
	if (typeof extraInfo == 'undefined') {
		extraInfo = "";
	}
	
	//make sure field is there
	if (!data) {
		err = dataName.charAt(0).toUpperCase() + dataName.substr(1) + " is empty.";
	}
	
	//check special types
	else if (dataType == "string" || dataType == "testimonial") {		
		
		//not too small
		if (data.length < smallest) {
			err = dataName + " is too short.  Must be at least " + smallest + " characters.";
		}
		
		//not too big
		else if (data.length > largest && largest != 0) {
			err = dataName + " is too long.  " + largest + " character limit.";
		}
		
		//no bad values				
		else if (checkForBad == 1 && isIllegal(data)) {
			err = "Illegal characters in " + dataName + ": " + isIllegal(data)[0];
		}
		
		//do testimonial related checking
		if (dataType == "testimonial" && err == '') {
			
			//rating types		
			if (extraInfo != 1 && extraInfo != 2 && extraInfo != 3 && extraInfo != 4 && extraInfo != 5) {
				err = "Rating needed for " + dataType + ".";				
			}
			else if(!data || !extraInfo) {
				err = "Both a " + dataType + " and rating are needed.";
			}			
		
		}
				
	}		
	//gender types are special
	else if (dataType == "gender") {
		
		if (data != "1" && data != "2" && data != "male" && data != "female") {
			err = "Invalid gender provided.";
		}
		
	}
	else if (dataType == "email") {
						
		if (/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(data) == false) {
			err = "Please enter your valid Email.";
		}
		//not too big
		else if (data.length > largest && largest != 0) {
			err = dataName + " is too long.  " + largest + " character limit.";
		}
		//not too small
		else if (data.length < 6) {
			err = dataName + " is too short.  Must be at least " + smallest + " characters.";
		}
		
	}
	else if (dataType == "phone") {
						
		//make sure it is an integer
		if (parseInt(data) >= 1000000000 && parseInt(data) <= 9999999999) {
			//ok
		} else {
			err = "Please enter your valid " + dataName + ".";
		}
		
	}
	else if (dataType == "password") {
		
		var passLarge = 20;
		var passSmall = 5;				
		var badMatch = data.match(/('|")/);
		
		//not too big
		if (data.length > passLarge) {
			err = dataName + " is too long.  " + passLarge + " character limit.";
		}
		//not too small
		else if (data.length < passSmall) {
			err = dataName + " is too short.  Must be at least " + passSmall + " characters.";
		}
		//bad characters
		else if (badMatch) {
			err = "Illegal characters in " + dataName + ": " + badMatch[0];
		}
		//no bad values				
		else if (isIllegal(data)) {
			err = "Illegal characters in " + dataName + ": " + isIllegal(data)[0];
		}
						
		
	}
		
	//highlight input
	if (err) {
		$("#" + dataId).removeClass("greenOut"); //remove the green
		$("#" + dataId + "Cont").removeClass("greenOut");
		
		$("#" + dataId).addClass("wrong");
		$("#" + dataId + "Cont").addClass("wrong");
	}
	
	//add lines if needed
	if (addLines == 1 && err) {
		err = err + "<br/>";
	}	
	
	return err;
	
}

function place(anchor, target, generalPos, moreLeft, moreTop) {
	
	//anchor position
	var pos = $("#" + anchor).offset();  

	//anchor size  
    var eWidth = $("#" + anchor).outerWidth();
    var eHeight = $("#" + anchor).outerHeight();
    
    //placed box size
    var mWidth = $("#" + target).outerWidth();
    
    //set alignment
	if (generalPos == "right") {
		var left = (pos.left + eWidth - moreLeft) + "px";
		var top = pos.top - moreTop + "px";
	}
	else if (generalPos == "overlay") {
		var left = pos.left - moreLeft + "px";
		var top = pos.top - moreTop + "px";
	} 
	else {
		var left = (pos.left - moreLeft) + "px";			
		var top = pos.top - moreTop + eHeight + "px";
		
	}
	
	//show the menu directly over the placeholder  
    $("#" + target).css( { 
    	display: 'block',
    	position: 'absolute',
    	zIndex: 5000,
        left: left, 
        top: top
    } );

	
}
var placeNum = 0;
function placeImg(anchor, target, imgSrc, generalPos, moreLeft, moreTop) {
	
	if (!target) {
		//create image
		target =  "place" + placeNum;
		$(".topDiv").append("<img class='placed' id='" + target + "' src='" + imgSrc + "' />");
		placeNum++;
	}
		
	//anchor position
	var pos = $("#" + anchor).offset();  
		
	//anchor size  
    var eWidth = $("#" + anchor).outerWidth();
    var eHeight = $("#" + anchor).outerHeight();
    
    //placed box size
    var mWidth = $("#" + target).outerWidth();
    var mHeight = $("#" + target).outerHeight();
    
    //set alignment
	if (generalPos == "right") {
		var left = (pos.left + eWidth - moreLeft) + "px";
		var top = pos.top - moreTop + "px";
	}
	else if (generalPos == "overlay") {
		var left = pos.left - moreLeft + "px";
		var top = pos.top - moreTop + "px";
	} 
	else if (generalPos == "center") {
		var left = pos.left + eWidth / 2 - mWidth / 2 - moreLeft + "px";
		var top = pos.top + eHeight / 2 - mHeight / 2 - moreTop + "px";
	} 
	else {
		var left = (pos.left - moreLeft) + "px";			
		var top = pos.top - moreTop + eHeight + "px";
		
	}
	
	$("#" + target).css( { 
    	display: 'block',
    	position: 'absolute',
    	zIndex: 5000,
        left: left, 
        top: top
    } );
		
}

var starDefault = 5;

function goDefault() {
	setStar(starDefault);
}

function setStar(num) {

	i = 0;
	while (i <= 5) {
		
		if (num >= i) {	
			
			$("#starOff" + i).css("display", "none");
			$("#starOn" + i).css("display", "block");			

		} else {
			
			$("#starOn" + i).css("display", "none");			
			$("#starOff" + i).css("display", "block");
			
		}
		
		i++;
		
	}
	
}

function chooseStar(num) {
	starDefault = num;
	$("#rating").val(num);
}

function addComment() {
	var err = '';
	
	//clear all wrong listings from CSS
	$("textarea").removeClass("wrong");
	
	/////////////////
	//INPUT CHECKS
	
	//check if illegal characters comment
	if (isIllegal($("#newComment").val())) {
		err = 'Illegal characters in Comment: ' + isIllegal($("#newComment").val())[0];
	}
	//check min length
	else if ($("#newComment").val() == "") {
		err = 'Cannot make an empty comment.';
	}
	//check max length
	else if ($("#newComment").val().length > 5000) {
		err = 'Comment cannot exceed 5000 characters.';
	}	
							
	//if no error, then show image verification step	
	if (err == '') {
	
		$.getJSON("ajax/captchaNeeded.php", { submitType: 'comment' }, function(needed){
		
			//require captcha 
			if (needed.r == 'y') {
		
				//send function to string
				theFunc = "addComment();";		
				getCaptchaCredit();
				return false;
			} else {				
				//submit form
				doSubmit("composeComment");
			}
		
		});
		
	} else {
		
		doError(err);
		$("#newComment").addClass("wrong");			
		
	}
	
}

function configDelete(id) {

	$('#removeDialog').dialog({
		autoOpen: false,
		resizable: false,
		draggable: false,
		modal: false,
		width: 370,
		buttons: {
			"Cancel": function() { 
				$(this).dialog("close");
			},
			"Delete": function() { 
		 		window.location = 'mail.php?type=inbox&delete=1&mid=' + id;						
			}
		}
	});
			
}

function confirmDelete(id) {
						
	//set title
	theTitle = "Delete message?";
	
	$("#ui-dialog-title-removeDialog").text(theTitle);		
	
	//config the dialog	
	configDelete(id);
		
	//show div
	$("#contentHolder").css({"display" : "block", "text-align" : "left"});
	
	//open dialog
	$('#removeDialog').dialog('open');
	
	//set title
	$("#ui-dialog-title-removeDialog").text(theTitle);
	
	//blur button	
	$('button').blur();
}


function mailSend() {
	var err = '';
	
	//clear all wrong listings from CSS
	$("textarea").removeClass("wrong");
	$("input").removeClass("wrong");


	//check if illegal characters about
	if (isIllegal($("#about").val())) {
		err = 'Illegal characters in About: ' + isIllegal($("#about").val())[0];
		$("#about").addClass("wrong");		
	}
	//check min length
	else if ($("#about").val() == "") {
		err = 'Cannot send empty message.';
		$("#about").addClass("wrong");
	}
	//check max length
	else if ($("#about").val().length > 20000) {
		err = 'Message cannot exceed 20,000 characters.';
		$("#about").addClass("wrong");
	}
	
	//check if illegal characters about
	if (isIllegal($("#subject").val())) {
		err = 'Illegal characters in Subject: ' + isIllegal($("#subject").val())[0];
		$("#subject").addClass("wrong");		
	}
	//check max length
	else if ($("#subject").val().length > 100) {
		err = 'Subject cannot exceed 100 characters.';
		$("#subject").addClass("wrong");
	}
						
	//if no error, then show image verification step	
	if (err == '') {
	
		$.getJSON("ajax/captchaNeeded.php", { submitType: 'mail' }, function(needed){
		
			//require captcha 
			if (needed.r == 'y') {
		
				//send function to string
				theFunc = "mailSend();";		
				getCaptchaCredit();
				return false;
			} else {				
				//submit form
				doSubmit("composeMessage");
			}
		
		});
		
	} else {
		
		doError(err);
		
	}
	
}

//page 1 loaded on init
var remPage = 2;
var remResults = 30;

function getNews(lastCheck) {
	 
	//set pager to spin
	doWait("newsStatus");
	$("#newsPage").remove();
	
		
	$.get("ajax/newsfeeder.php", {lastCheck: lastCheck, results: remResults, page: remPage}, function(data){
			
		//replace content
		if (data != 0) {
			$("#news").append(data);			
			$("#newsStatus").remove();
			
			doEvent('newsfeed', 'more', '', '');
						
		} else {
			
			$("#newsStatus").css("display", "none");
			$("#newsOut").css("display", "inline");
		
		}
		
		remPage = remPage + 1;
				
	});
	
}

function getMini(id, type, results, page) {
	
	//page id set
	pagerId = "miniPage" + id + type; 
	//change css a little
	$("#" + pagerId).css({"width" : "100%", "margin-top" : "3px", "background-position" : "top right"});
	//set pager to spin
	doWait(pagerId);
	
	//
	
	$.get("ajax/minifeeder.php", {id: id, type: type, results: results, page: page}, function(data){
			
		//replace content
		$("#mini" + id + type).replaceWith(data);
		
		doEvent('minifeed', 'new page', '', '');
		
	});
	
}

function reView(theCase) {
	if (theCase == 'more') {
		$("#aboutShort").css("display", "none");
		$("#aboutFull").css("display", "block");
	} else {
		$("#aboutShort").css("display", "block");
		$("#aboutFull").css("display", "none");				
	}
}
			
function doError(err) {
	$("#showInfo").css("display", "none");
	$("#showErrors").css("display", "block");
	$("#showErrors").html(err);				
}
 
function doSubmit(id) {
	
	submitOk = 1;
	
	if (typeof id == 'undefined') {
		$("form:first").submit();
	} else {
		$("#" + id).submit();
	}

}

var theMatch;
function isIllegal(theStr) {

	var theMatch = theStr.match(/(\\|\/|<|\/|=|>|;|\|)/);
	return theMatch;
		
}

function ucfirst(str) {
	return str.charAt(0).toUpperCase() + str.substr(1);
}

function getExt(str) {
	theExt = str.split("\.");
	theLast = theExt.length - 1;
	return theExt[theLast].toUpperCase();
}	

function checkPic(id) {
	
	if (!id) {
		id = "contentText";
	}
	
	var err = '';
		
	//make sure extension is valid	
	theExt = getExt($('#' + id).val());		

	if (theExt != 'JPG' && theExt != 'GIF') {
		err = "Image must be in JPG or GIF format.";
	}	
	
	//check if pic is too short 
	if ($('#' + id).val().length < 2) {
		err = 'Location of image needed.';
	}

return err;

}			

function preSubmit() {
	var err = '';
	var placedAlready = '';
	//check for type in order to identify error-checking routine
	var submitType = $('#theType').val();
	
	//clear all wrong listings from CSS
	$("select").removeClass("wrong");
	$("input").removeClass("wrong");
	$("textarea").removeClass("wrong");

	
	////////////////////////
	//check different types
	////////////////////////
	
	if (submitType == 'testimonial' || submitType == 'secret' || submitType == 'comment' || submitType == 'city' || submitType == 'headline' || submitType == 'school' || submitType == 'work' || submitType == 'about') {
		
		// make submitType err description nice
		showType = ucfirst(submitType);
		
		//assign text limits 
		if (submitType == 'comment' || submitType == 'secret') {
			theLimit = 7000;
		}
		else if (submitType == 'testimonial') {			
			theLimit = 7000;			
			//check if rating was given
			if ($('#rating').val() < 1 || $('#rating').val() > 5) {
				err = 'No rating selected.';
			}
			
		}
		else if (submitType == 'city' || submitType == 'headline') {
			theLimit = 100;
		}
		else if (submitType == 'school' || submitType == 'work') {
			theLimit = 50;
		}
		else if (submitType == 'about') {
			theLimit = 40000;
		}
		
		
		//check if too short comment
		if ($('#contentText').val().length < 2) {
			err = showType + ' is too short.';
		}
		//check if too long comment
		if ($('#contentText').val().length > theLimit) {
			err = showType + ' is too long.  ' + theLimit + ' characters is the max length.';
		}
		//check if illegal characters in comment
		if (isIllegal($("#contentText").val())) {
			err = 'Illegal characters in '+ submitType + ': ' + isIllegal($("#contentText").val())[0];
		}

		
	}
	else if (submitType == 'birthday') {
		
		//check if still says Month, Day, or Year
		if ($('#bMonth').val() == "") {
			err = 'Please enter the correct date.';
			$("#bMonth").addClass("wrong");
		}
		
		if ($('#bYear').val() == "") {
			err = 'Please enter the date.';
			$("#bYear").addClass("wrong");
		}
		
		if ($('#bDay').val() == "") {
			err = 'Please enter the date.';
			$("#bDay").addClass("wrong");
		}
		
		
		//remember that the error was placed for later
		if (err) {
			placedAlready = "yes";
		}
	}

	else if (submitType == 'picture') {
	
		err = checkPic();					
		
	}
		
	//if no error, then show image verification step	
	if (err == '') {
	
		//see if cap is needed
		$.getJSON("ajax/captchaNeeded.php", { submitType: 'content' }, function(needed){
	
			//require captcha 
			if (needed.r == 'y') {
		
				//send function to string
				theFunc = "preSubmit();";		
				getCaptchaCredit();
				return false;
			} else {
				doSubmit("addContent");
			}
		
		});
	
		
	} else {
		doError(err);
		if (placedAlready != "yes") {
			$("#"+submitType).addClass("wrong");
		}
	}
	
}


function newCaptcha() {
	
	//show wait
	$("#captcha").css("display", "none");
	$("#captchaWait").css("display", "block");	
	
	$("#captcha").load('ajax/captchaShow.php', function(){
   		$("#captchaWait").css("display", "none");
		$("#captcha").css("display", "block");	
 	});

	//clear css on captcha input
	$("#captchaValue").removeClass("wrong");
	//clear value
	$("#captchaValue").val("");
	//show not submitted info
	$("#captchaInfo").css("display", "block");
	//hide errors that were previously made
	$("#captchaErrors").css("display", "none");
	
	//hide other errors on site
	$("#showInfo").css("display", "none");
	$("#showErrors").css("display", "none");
	
	//focus
	$("#captchaValue").focus();	
		
}


function captchaError(err) {
	$("#captchaInfo").css("display", "none");
	$("#captchaErrors").css("display", "block");
	$("#captchaErrors").text(err);				
}

function configCaptcha() {
	// Dialog			
	$('#captchaHolder').dialog({
		autoOpen: false,
		resizable: false,
		draggable: false,
		modal: false,
		width: 395, 
		height: 280
	});
}


function getCaptchaCredit() {
	
	//get new capture
	newCaptcha();			
							
	//config the dialog	
	configCaptcha();
	
	//set title
	$("#ui-dialog-title-captcha").text("Validity Check >>>");
	
	 	
	$('#captchaHolder').dialog('open');
	
	//focus
	$("#captchaValue").focus();	
	
}

function captchaSubmit() {
      
	//make sure captcha is right length
      
	if ($("#captchaValue").val().length != 5) {
			
		captchaError("Please enter 5 letters total.");
			
		$("#captchaValue").addClass("wrong");

			
	} else {
			
		//do ajax check
		$.getJSON("ajax/captchaCheck.php", {captchaValue: $("#captchaValue").val()}, function(json){
  			
			//if json.g == 1 then submit form
	  		if (json.g != 1) {
							
				// must go before error or error will not be shown
				newCaptcha();
						
				//get a new captcha and send an error
				captchaError("Incorrect letters provided.  Please try again.");						
					
			} else {
				
				//close dialog
				$('#captchaHolder').dialog("close");
				
				//reset captcha credits (make sure these are global)
				captchaVote = json.v;
				captchaContent = json.c;
				captchaAccount = json.a;
				captchaTrack = json.t;
				captchaMail = json.m;
				captchaComment = json.co;
				
				//send functions you were going to send	
				eval(theFunc);						
				
			}
  			
		});
			
	}

}


function configDialog() {
	// Dialog			
	$('#dialog').dialog({
		autoOpen: false,
		resizable: false,
		draggable: false,
		modal: false,
		width: 650,
		maxHeight: 495, 
		buttons: {
			"Close": function() { 
				$(this).dialog("close");
				$("#contentHolder").html("<img id='imgTarget' src='img/wait.gif' />"); 
			}
		}
	});
}

function showPic(theImg) {
	
	//send sought after pic
	$('#imgTarget').attr({ src: theImg });
	
	//config the dialog	
	configDialog();
	
	//show div
	$("#contentHolder").css("display", "block");
	
	 	
	$('#dialog').dialog('open');
	
	//set title
	$("#ui-dialog-title-dialog").text("View Picture");	
	
	$('button').blur();					
	
}

function showAbout(id) {
	
	//set title
	$("#ui-dialog-title-dialog").text("View About Section");
	
	//config the dialog	
	configDialog();
	
	//show div
	$("#contentHolder").css({"display" : "block", "text-align" : "left"});
	
	//open dialog
	$('#dialog').dialog('open');
	
	//set title
	$("#ui-dialog-title-dialog").text("View About Section");
		
	$('button').blur();
				
	//do ajax
	aUrl = 'ajax/aboutShow.php?id=' + id;
	$("#contentHolder").load(aUrl);
	
}

function showView(id) {
	
	//set title
	$("#ui-dialog-title-dialog").text("View Times");
	
	//config the dialog	
	configDialog();
	
	//redo height & width
	$('#dialog').dialog('option', 'width', 400);
	
	//show div
	$("#contentHolder").css({"display" : "block", "text-align" : "left"});
	
	//open dialog
	$('#dialog').dialog('open');
	
	//set title
	$("#ui-dialog-title-dialog").text("View Times");
	
	//blur button	
	$('button').blur();
				
	//do ajax
	aUrl = 'ajax/viewTimes.php?id=' + id;
	$("#contentHolder").load(aUrl);
	
}

function doVote(theType, theId, theVote, interfaceId) {

	//see if cap is needed
	$.getJSON("ajax/captchaNeeded.php", { submitType: 'vote' }, function(needed){
	
		//require captcha 
		if (needed.r == 'y') {			
			
			//send doVote function to string
			if (interfaceId) {
				theFunc = "doVote('" + theType + "', " + theId + ", " + theVote + ", '" + interfaceId + "');";
			} else {
					theFunc = "doVote('" + theType + "', " + theId + ", " + theVote + ");";			
			}
			getCaptchaCredit();
			return false;
		
		} else {
		
		
			//get base id to manipulate
			if (interfaceId) {
				baseId = "#voteTable";
				forId = "#votesFor";
				againstId = "#votesAgainst";
				statusId = "#voteMessage";				
				
				$("#voteRow").css("display", "none");
				
			} else {
				baseId = "#" + theType + "-" + theId;
				forId = baseId + "-f";
				againstId = baseId + "-a";
				statusId = baseId;
			}
			
			//set wait image
			$(statusId).addClass("loading");
			$(statusId).html("");
			$(statusId).css("display", "block");	
			
		
			//do ajax
			$.getJSON("ajax/voteSend.php", { type: theType, id: theId, vote: theVote }, function(json){							
				
				//record in GA
				doEvent('vote', theVote, theType, '');
				
				//set message
				$(statusId).removeClass("loading");
				$(statusId).fadeIn("fast");
				$(statusId).html(json.m);
				
				//set votes_for cache
				//set votes_against cache				
				if (interfaceId) {
					
					$("#" + interfaceId + "_f").val(json.f);
					$("#" + interfaceId + "_a").val(json.a);
					
					//let bubble fade
					setTimeout("pausePop(0)", 1500);	
					
				} else {
					$(forId).text(json.f);
					$(againstId).text(json.a);				
				}
				
			});
			
		}
	});	
	
}

function checkPlural($num, $word) {
	
	if ($num != 1) {
		$word = $word + "s";
	}
	
	return $word;
	
}

//var to determine whether to show topline notice
var noShow = 0; 

function doTrack(id, code) {
	
	//unset error messages
	$("#showInfo").css("display", "none");
	$("#showErrors").css("display", "none");	
	
	$.getJSON("ajax/captchaNeeded.php", { submitType: 'track' }, function(needed){
	
		//require captcha 
		if (needed.r == 'y') {
	
			//send function to string
			theFunc = "doTrack(" + id + ", '" + code + "');";		
			getCaptchaCredit();
			return false;
		} else {
			
			//clear words so they cant do multiple submits			
			$("#track"+id).text("");
			doWait("trackStat"+id);
			
			$.getJSON("ajax/tracker.php", {id: id, code: code}, function(json){
				//show return
				if (noShow != 1) {
					showReturn(json.n, json.e);
				}	
				
				clearWait("trackStat"+id);	
				
				//set track message
				if (json.r == 1) {
					$("#track"+id).text("Track Profile");	
					
					doEvent("track profile", "untracked", id, "");
								
				}
				else if (json.r == 2) {
					$("#track"+id).text("Untrack Profile");	
					
					doEvent("track profile", "tracking", id, "");
					
					//ask them to update their preference
					noticeConfig(id, 'track');
								
				}
				
				//change track number (r means a change was made)
				if (json.r != 0) {
					$("#trackerNum"+id).text(json.t + ' ' + checkPlural(json.t, 'tracker'));									
				}				
				
			});
			
			
		}
	
	});

}

function showReturn (notice, error) {
	if (error != '' && error != 0) {
		$("#showErrors").html(error);
		$("#showErrors").css("display", "block");						
	}
	//set notice
	if (notice != '' && notice != 0) {
		$("#showInfo").html(notice);
		$("#showInfo").css("display", "block");						
	}
}

function configRemove(id, code, type) {
	
	if (type == "request") {
		$('#removeDialog').dialog({
			autoOpen: false,
			resizable: false,
			draggable: false,
			modal: false,
			width: 430,
			buttons: {
				"Cancel": function() { 
					$(this).dialog("close");
				},
				"Ignore": function() { 
			 		removeFriend(id, code, type);
					$(this).dialog("close");				
				}
			}
		});
	} else {
		$('#removeDialog').dialog({
			autoOpen: false,
			resizable: false,
			draggable: false,
			modal: false,
			width: 370,
			buttons: {
				"Cancel": function() { 
					$(this).dialog("close");
				},
				"Remove": function() { 
			 		removeFriend(id, code, type);
					$(this).dialog("close");				
				}
			}
		});
	}
	
	
}

function confirmRemove(id, code, theName, type) {
	
	//set friend name
	$("#removeName").text(theName);	
	
	//set title 	
	if (type == 'request') {
		theTitle = "Ignore Request?";		
	} else {
		theTitle = "Remove Friend?";
	}
		
	//set title
	$("#ui-dialog-title-removeDialog").text(theTitle);		
	
	//config the dialog	
	configRemove(id, code, type);
		
	//show div
	$("#contentHolder").css({"display" : "block", "text-align" : "left"});
	
	//open dialog
	$('#removeDialog').dialog('open');
	
	//set title
	$("#ui-dialog-title-removeDialog").text(theTitle);
	
	//blur button	
	$('button').blur();
}

function removeFriend(id, code, type) {
	
	//unset error messages
	$("#showInfo").css("display", "none");
	$("#showErrors").css("display", "none");	
	
	$.getJSON("ajax/captchaNeeded.php", { submitType: 'friendRemove' }, function(needed){
	
		//require captcha 
		if (needed.r == 'y') {
	
			//send function to string
			theFunc = "removeFriend(" + id + ", '" + code + "', '" + type + "');";		
			getCaptchaCredit();
			return false;
		} else {						
			
			$.getJSON("ajax/friendRemove.php", {id: id, code: code, type: type}, function(json){
				
				if (noShow != 1) {
					//set error
					
					showReturn(json.n, json.e);									
					
					//hide configs
					$("#config2").css("display", "none");
					$("#config3").css("display", "none");
					$("#config1").css("display", "block");
										
				} else {
					
					$("#friend" + id).text("Request Ignored");
					
					doEvent("friend request", "removed", id, "");
					
				}
					
			});
			
			
		}
	
	});
}

function doFriend(id, code, rType) {
			
	//unset error messages
	$("#showInfo").css("display", "none");
	$("#showErrors").css("display", "none");	
	
	$.getJSON("ajax/captchaNeeded.php", { submitType: 'friend' }, function(needed){
	
		//require captcha 
		if (needed.r == 'y') {
	
			//send function to string
			theFunc = "doFriend(" + id + ", '" + code + "');";		
			getCaptchaCredit();
			return false;
		} else {						
		
		//set wait
		doWait("friend" + id);
	
			
			$.getJSON("ajax/friender.php", {id: id, code: code, rType: rType}, function(json){
				
				//set error
				if (noShow != 1) {
					showReturn(json.n, json.e);				
				}
				
				//clear wait
				clearWait("friend" + id);
				
				$("#friend" + id).text(json.n);
				
				doEvent("friend request", "requested", id, "");
												
			});
						
		}
	
	});

}

function doWait(baseId) {
	$("#" + baseId).html("");
	$("#" + baseId).css("display", "none");
	$("#" + baseId).addClass("loading");
	$("#" + baseId).fadeIn("slow");			
}

function clearWait(baseId) {
	$("#" + baseId).removeClass("loading");		
}

var submitOk = 0;
function goForm() {
	submitOk = 1;
	setTimeout("noForm()", 200);
}

function noForm() {
	submitOk = 0;
}

function nextPage(service, search, start, count) {
	//set pager to spin
	doWait(service + 'Pager');
	$.get("ajax/content.php", {service: service, search: search, start: start, count: count}, function(data){
		//replace content
		$("#" + service + 'Cont').replaceWith(data);
	});	
}

//protect against browser differences in form handling
$(document).ready(function() {

	$("input[type='button']").bind("click", function(e) { goForm(); });
	$("input[type='submit']").bind("click", function(e) { goForm(); });
	
	$("form").submit(function() {
		
 		if (submitOk == 0) {
 			return false;
		}
		
    });
});		

