// pop-up window
var fullpath = "http://www.heavendating.co.uk/";

function checkEmail(type, xmldata){
	var theSpan = document.getElementById("emailspan");
	theSpan.innerHTML = "";
	
	if(type == 1){
		var theEmail = document.getElementById("email").value;
		if(email = "") theSpan.innerHTML = "<strong>Please enter a valid email address</strong><br /><br />";
		else getData("ajax/checkemail.php?email=" + theEmail, 10);
	}
	else if(type == 2){
		var rootElement = xmldata.documentElement;
		var validEmail = rootElement.attributes[0].nodeValue;
		if(validEmail == 0) theSpan.innerHTML = "<strong>Please enter a valid email address</strong><br /><br />";
	}
}

function setOpacity(id, value)
{
	var testObj = document.getElementById(id);
	testObj.style.opacity = value/10;
	testObj.style.filter = 'alpha(opacity=' + value*10 + ')';
}

function setAvatar(photoid, filename){
	theInput = document.getElementById("avatarid");
	theImage = document.getElementById("avatarholder");
	
	theInput.value = photoid;
	theImage.src = "member-photos/thumbs/" + filename;
}

function hideUnhide(theDiv){
	var theDiv = document.getElementbyId(theDiv);
	
	if(theDiv.style.display == 'block') theDiv.style.display = 'none';
	else theDiv.style.display = 'block';
}

function changeImage(theImage, image1, image2){
	var theImage = document.getElementById(theImage);
	if(theImage.src == fullpath + "images/" + image1) theImage.src = 'images/' + image2;
	else theImage.src = 'images/' + image1;
}

function NewWindow(mypage,myname,w,h,scroll, status, menubar){
	var win = null;
	LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
	TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
	settings = 'width='+w+', height='+h+', top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+', status=' + status + ', resizable=1, menubar=' + menubar; 
	win = window.open(mypage, myname, settings);
	win.focus();
}

function unhidemails(){
	elementVar = document.getElementById('hiddenmailfield');
	elementVar.style.display = 'block';
}

function addToTextBox(textbox, text){
	var eleTextarea = document.getElementById(textbox);

	 eleTextarea.focus();
	 if( eleTextarea.createTextRange ) {
	   document.selection.createRange().text += text;
	 }
	 else if(eleTextarea.setSelectionRange){
	   var len = eleTextarea.selectionEnd;
	   eleTextarea.value = eleTextarea.value.substr( 0, len ) + text + eleTextarea.value.substr( len );
	   eleTextarea.setSelectionRange(len+text.length,len+text.length);
	 }
	 else{ 
		eleTextarea.value += text;
	 }
}

function getData(dataSource, type, alternative){
	//var this_div = document.getElementById(this_div);
	var XMLHttpRequestObject = false;
	if (window.XMLHttpRequest) {
		XMLHttpRequestObject = new XMLHttpRequest();
	} 
	else if (window.ActiveXObject){
		XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
	}
	if(XMLHttpRequestObject) {
		XMLHttpRequestObject.open("GET", dataSource, true);
		XMLHttpRequestObject.onreadystatechange = function()
		{
			if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200){
					switch(type){
						case 1: outputSearhResults(XMLHttpRequestObject.responseXML); break;
						case 2: outputUsernameAvail(XMLHttpRequestObject.responseXML); break;
						case 3: addTowns(XMLHttpRequestObject.responseXML); break;
						case 4: savedmail(XMLHttpRequestObject.responseXML); break;
						case 5: addPhotoMsg(XMLHttpRequestObject.responseXML); break;
						case 6: getPhotoInMsg(XMLHttpRequestObject.responseXML); break;
						case 7: outputInterested(XMLHttpRequestObject.responseXML); break;
						case 8: outputLookedat(XMLHttpRequestObject.responseXML); break;
						case 9: viewImageDetails(XMLHttpRequestObject.responseXML); break;
						case 10: checkEmail(2, XMLHttpRequestObject.responseXML); break;
					}
			}
		}
	XMLHttpRequestObject.send(null);
	}
	else{
		//cant do ajax do whatever	
		window.location = alternative;
	}
}

function makePOSTRequest(url, parameters, type) {
      http_request = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         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('Cannot create XMLHTTP instance');
         return false;
      }
      
      http_request.onreadystatechange = function(){
			if (http_request.readyState == 4 && http_request.status == 200){
				switch(type){
					case 1: updateDraft(http_request.responseXML); break;
					case 2: handleSpellingResults(http_request.responseXML); break;
					case 3: outputArticles(http_request.responseXML); break;
				}
			}
	  }
      http_request.open('POST', url, true);
      http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      http_request.setRequestHeader("Content-length", parameters.length);
      http_request.setRequestHeader("Connection", "close");
      http_request.send(parameters);
}

function outputArticles(xmlData){	
	var rootElement = xmlData.documentElement;
	var articles = rootElement.childNodes;
	var theDiv = document.getElementById("suggestHolder");
	var theContainer = document.getElementById("suggestContainer");
	var html = new String();
	var results = parseInt(rootElement.attributes[0].nodeValue);

	for(x=0; x < articles.length; x++){
		
		id = articles[x].attributes[0].nodeValue;
		title = articles[x].attributes[1].nodeValue;
		topicid = articles[x].attributes[2].nodeValue;
		topic = articles[x].attributes[3].nodeValue;
		
		html = html + "<a target='_blank' href=" + fullpath + "help/article-" + id + ".html title='" + title + "'>" + title + "</a><br />";
	}
	
	if(results > 0){
		theContainer.style.display='block';
		theDiv.innerHTML = html;
	}
}

function readKey(e){
	var key = window.event ? e.keyCode : e.which;
	var keychar = String.fromCharCode(key);
	var theTextarea = document.getElementById("ticket");

	if(parseInt(key) == 32){
		//send text off to be searched for relevant articles
		var theText = theTextarea.value;
		theText = encodeURI(theText);
		makePOSTRequest(fullpath + "ajax/getArticles.php", "text=" + theText, 3);
	}
}

function outputLookedat(xmlData){
	var theDiv = document.getElementById("lookedContent");
	var theSpan = document.getElementById("lookedtitle");
	var rootElement = xmlData.documentElement;
	var children = rootElement.childNodes;
	var theNum = rootElement.attributes[0].nodeValue;
	var theLevel = parseInt(rootElement.attributes[1].nodeValue);
	var html = "<br />";
	var titletext = new String();

	if((theLevel == 1 || theLevel == 2) && theNum == 0) titletext = "For more information about finding out about who has looked at your profile <a href='heavenextras.html' title='More info on Heaven Extras'>click here</a>";
	else{
		if(theNum == 20) titletext = "Over 20 members have checked out your profile, here's the lastest";
		else if(theNum == 1) titletext = "1 member has checked out your profile";
		else titletext = theNum + " members have checked out your profile!";
	}
	for(x=0; x < children.length; x++){
		username = children[x].attributes[1].nodeValue;
		userid = children[x].attributes[0].nodeValue;
		
		if(theLevel == 1 || theLevel == 2) html = html + "<a href='heavenextras.html' title='click here to find out who it is!'>Click here to find out who it is!</a><br />";
		else html = html + "<a href='" + username + "-profile.html' title='View " + username + "s profile'>" + username + "</a><br />";
	}
	
	theSpan.innerHTML = titletext;
	theDiv.innerHTML = html;
}
	
	

function outputInterested(xmlData){
	var rootElement = xmlData.documentElement;
	var msgid = parseInt(rootElement.attributes[0].nodeValue);
	var theDiv = document.getElementById("interestedDiv");
	var theSpan = document.getElementById("interestTitle");
	var theChildren = rootElement.childNodes;
	var html = new String();

	if(msgid == 1){
		//no matches
		titleHtml = "We couldnt find an ideal partner for you so we have come up with these matches that may be of interest";
	}
	else if(msgid == 2){
		//not set up ideal partner
		titleHtml = "You have not set up your ideal partner so for now we have come up with these matches that may be of interest";
	
	}
	else{
		//Found matches
		titleHtml = "Based on your ideal partner settings we have come up with these matches for you";
	}
	
	for(x=0; x < theChildren.length; x++){
		userid = theChildren[x].attributes[0].nodeValue;
		username = theChildren[x].attributes[1].nodeValue;
		
		html = html + "<div style='float: left; width: 20%; text-align: center;'><a href='" + username + "-profile.html' title='view " + username + "s profile'><img src='images/user-profile-photo.gif' alt='view " + username + "s profile' /><br />" + username + "</div>";
	}
	html = html + "<br class='clear' />";
	theDiv.innerHTML = html;
	theSpan.innerHTML = titleHtml;
}

function startDraftInterval(userid, msgid){
	var draftInterval = window.setInterval("startDraftSave(" + userid + ", '" + msgid + "')", 300000);
}

function startDraftSave(userid, msgid){

	var textBox =  document.getElementById("message");
	var subjectBox = document.getElementById("subject");
	var messagetoBox = document.getElementById("messageto");
	var text = encodeURI(textBox.value);
	var subject = encodeURI(subjectBox.value);
	var messageto = encodeURI(messagetoBox.value);

	if(text.length > 0){
		//save the text
		makePOSTRequest("ajax/saveDraft.php", "userid=" + userid + "&text=" + text + "&msgid=" + msgid + "&subject=" + subject + "&messageto=" + messageto, 1);
	}
}

function changeProfileImage(id, filename){
	var theImage = document.getElementById(id);
	var mainImage = document.getElementById("mainimage");
	var oldFilename = mainImage.src;
	
	//set the new image as main
	mainImage.src = "member-photos/thumbs/" + filename;
	mainImage.alt = comment;
}

function updateDraft(xmlData){
	var theSpan = document.getElementById("draftCount");
	var theDiv = document.getElementById("draftContainer");
	var rootElement = xmlData.documentElement;
	var children = rootElement.childNodes;
	var theCount = rootElement.attributes[0].nodeValue;
	var html = new String();

	if(children.length > 0){
		for(x=0; x < children.length; x++){
			
			dateadded = children[x].attributes[0].nodeValue;
			id = children[x].attributes[1].nodeValue;
			
			html = html + "&nbsp;- <a style='font-size: 7px; font-style: italic;' href='" + fullpath + "newmessage.html?msgid=" + id + "' title='use this draft'>" + dateadded + "</a><br />";
		}
	}
	
	theDiv.innerHTML = html;
	theSpan.innerHTML = theCount;
}

function addPhotoMsg(xmlData){
	var theDiv = document.getElementById("photos");
	var theErrorDiv = document.getElementById("photoError");
	var rootElement = xmlData.documentElement;
	var userid = rootElement.attributes[2].nodeValue;
	var errorCode = rootElement.attributes[0].nodeValue;
	var msgid = rootElement.attributes[1].nodeValue;
	errorCode = parseInt(errorCode);
		
	if(errorCode == 1){
		theErrorDiv.innerHTML = "<p>Sorry you can only add 3 photos per message<p>";
	}
	else if(errorCode == 0){
		theErrorDiv.innerHTML = "<p>Photo has been added to message<p>";
		getData('ajax/addphototomsg.php?msgid=' + msgid + '&type=2&userid=' + userid, 6);
		//document.write('ajax/addphototomsg.php?msgid=' + msgid + '&type=2&userid=' + userid);
	}
}

function getPhotoInMsg(xmlData){
	var rootElement = xmlData.documentElement;
	var children = rootElement.childNodes;
	var theDiv = document.getElementById("photos");
	var theDiv2 = document.getElementById("thephotos");
	var msgid = rootElement.attributes[1].nodeValue;
	var userid = rootElement.attributes[2].nodeValue;
	var counter = 0;
	var fade_array = new Array();
	

	html = "<p>";
	for(x = 0; x < children.length; x++){
		id = children[x].attributes[0].nodeValue;
		filename = children[x].attributes[1].nodeValue;
		comment = children[x].attributes[2].nodeValue;
		fade = parseInt(children[x].attributes[3].nodeValue);

		if(fade == 1){
			fade_array.push(id);
			type = 3;
		}
		else type = 1;

		html = html + "<img id='" + id + "' src='member-photos/small/" + filename + "' alt='" + comment + "' onclick=\"getData('ajax/addphototomsg.php?id=" + id + "&msgid=" + msgid + "&type=" + type + "&userid=" + userid + "', 5);\" /> &nbsp;";
		//document.write("onclick=\"getData('ajax/addphototomsg.php?id=" + id + "&msgid=" + msgid + "&type=" + type + "&userid=" + userid + "', 5);");
		counter++;
		if(counter == 8){
			html = html + "<br />";
			counter = 0;
		}
	}
	html = html + "</p>";
	theDiv2.innerHTML = html;

	//do the fades
	for(x = 0; x < fade_array.length; x++){
		setOpacity(fade_array[x], 5);
	}

}

function findPosX(obj)
{
var curleft = 0;
if(obj.offsetParent)
	while(1) 
	{
	  curleft += obj.offsetLeft;
	  if(!obj.offsetParent)
		break;
	  obj = obj.offsetParent;
	}
else if(obj.x)
	curleft += obj.x;
return curleft;
}

function findPosY(obj)
{
var curtop = 0;
if(obj.offsetParent)
	while(1)
	{
	  curtop += obj.offsetTop;
	  if(!obj.offsetParent)
		break;
	  obj = obj.offsetParent;
	}
else if(obj.y)
	curtop += obj.y;
return curtop;
}


function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

function stripHTML(value){
	var re = /<\S[^><]*>/g
	return value.replace(re, "");
}

function swapWord(id, oldWord, theword){
	var theTextarea = document.getElementById("message");
	var theDiv = document.getElementById(id);
	var newWord = document.getElementById(theword).innerHTML;
	var text = document.getElementById("message").value;
	
	//replace word in div
	theDiv.innerHTML = newWord;
	
	//replace word in textarea
	text = text.replace(oldWord, newWord)
	theTextarea.value = text;
}

function savedmail(xmlData){
	if(xmlData){
		var rootElement = xmlData.documentElement;
		var errorCode = rootElement.attributes[0].nodeValue;
		var theDiv = document.getElementById("maildiv");
		errorCode = parseInt(errorCode);
		
		if(errorCode == 1){
			theDiv.innerHTML = "<p>Sorry you can only save 10 items, please un-saved some before trying again<p>" + theDiv.innerHTML;
		}
	}
}

function addTowns(xmlData){
	var documentNode = xmlData.documentElement;
	var children = documentNode.childNodes;

	for(x = 0; x < children.length; x++){
		
		townid = children[x].attributes[0].nodeValue;
		town = children[x].attributes[1].nodeValue;
		
		//add the option to the box
		addOption("town", town, townid);
	}
}

function getTowns(selectname, postcodename){	
	var theSelect = document.getElementById(selectname);
	var theInput = document.getElementById(postcodename);
	var thepostcode = theInput.value;

	//test if they can do dynamic select boxes
	var test = testAddOption(theSelect);

	if(!test) window.location = "?loadtowns=" + thepostcode;
	else{
		//clear the select box
		theSelect.options.length = 0;
		getData("ajax/getTowns.php?postcode=" + thepostcode, 3);
	}
}

function testAddOption(selectBox){
	var theSelect = selectBox;
	
	optionTest = true;
	lgth = theSelect.options.length = 1;
	theSelect.options[lgth] = null;
	if (theSelect.options[lgth]) optionTest = false;
	
	return optionTest;
}
	

function addOption(selectbox,text,value ){
	var optn = document.createElement("OPTION");
	var selectbox = document.getElementById(selectbox);
	
	optn.text = text;
	optn.value = value;
	selectbox.options.add(optn);
}

function checkNameAvail(){	
	var username = document.getElementById("username").value;
	var theDiv = document.getElementById("suggestDiv");
	var error = false;

	//check username
	if(username.length < 4 || username.length > 12){
		theDiv.innerHTML = "<strong>Usernames must be longer than 3 letters and shorter than 12</strong><br /><br />";
		error = true;
	}

	if(username == "") error = true;
	if(!error) getData("ajax/check-username.php?username=" + username, 2);
}

function outputUsernameAvail(xmlData){
	var documentNode = xmlData.documentElement;
	var containerDiv  = document.getElementById("suggestDiv");
	var status = documentNode.attributes[0].nodeValue;
	var children = documentNode.childNodes;
	
	if(status == 1) html = "";
	else{
		html = "<strong>Sorry that username is taken, below are some suggestions (click to use)</strong><ul>";
		
		for(x = 0; x < children.length; x++){
			username = children[x].attributes[0].nodeValue;
			
			html = html + "<li><a href='' onclick='document.getElementById(\"username\").value=\"" + username + "\"; return false;'>" + username + "</a></li>";
		}
		
		html = html + "</ul>";
	}
	containerDiv.innerHTML = html;
}

function gofreesearch(){
	
	var gender1 = document.getElementById('gender1').value;
	var gender2 = document.getElementById('gender2').value;
	var postcode = document.getElementById('postcode').value;
	var age1 = document.getElementById('age1').value;
	var age2 = document.getElementById('age2').value;
	var buttonHolder = document.getElementById('buttonholder');
	
	//do some validation
	
	//change the button graphic to the search
	buttonHolder.innerHTML = "<img src='images/buttons/doingsearch.gif' alt='search is being proccessed' />";

	//all ok send for processing
	getData("ajax/getSearchResults.php?gender1=" + gender1 + "&gender2" + gender2 + "&postcode=" + postcode + "&age1=" + age1 + "&age2" + age2, 1);
}

function outputSearhResults(xmlData){
	
	var resultsDiv = document.getElementById("searchresults");
	var documentNode = xmlData.documentElement;
	var results = documentNode.attributes[0].nodeValue;
	var children = documentNode.childNodes;
	var resultsString = "Your search returned " + results + " results";

	html = resultsString + "<br /><br />";
	
	alert(documentNode.childNodes.attributes.length);

	for(x = 0; x < children.length; x++){
		username = children[x].attributes[0].nodeValue;
		distance = children[x].attributes[1].nodeValue;
		
		html = html + "<a href='show-member.html' title='view " + username + "\'s profile'>" + username + " - " + distance + " miles <br />";
	}
	
	//undide the div
	resultsDiv.style.display='block';
	resultsDiv.innerHTML = html;
}

function hideUnhide(theDiv){
	var theDiv = document.getElementById(theDiv);
	
	if(theDiv.style.display == 'block') theDiv.style.display='none';
	else theDiv.style.display='block';
}

// From http://www.massless.org/mozedit/
function mozWrap(txtarea, open, close)
{
	var selLength = txtarea.textLength;
	var selStart = txtarea.selectionStart;
	var selEnd = txtarea.selectionEnd;
	if (selEnd == 1 || selEnd == 2)
		selEnd = selLength;

	var s1 = (txtarea.value).substring(0,selStart);
	var s2 = (txtarea.value).substring(selStart, selEnd)
	var s3 = (txtarea.value).substring(selEnd, selLength);
	txtarea.value = s1 + open + s2 + close + s3;
	return;
}

// Insert at Claret position. Code from
// http://www.faqts.com/knowledge_base/view.phtml/aid/1052/fid/130
function storeCaret(textEl) {
	if (textEl.createTextRange) textEl.caretPos = document.selection.createRange().duplicate();
}