/**********************************************************************************
 * Web2Messenger JavaScript Source                                                *
 * -------------------------------                                                *
 * Copyright 2005-2006 A.Gillard and F.Hardijzer unless otherwise indicated for a *
 *   specific JavaScript function                                                 *
 * No code from this file may be used anywhere other than www.web2messenger.com   *
 *   unless a different license is specified for a specific function, in which    *
 *   case the conditions of that license apply for the specified function only.   *
 **********************************************************************************/

var langphrases = Array();
function lang(id) {
	return langphrases[id];
}

/**
  * Handles the deletion of a large number of messages on the Message Archive page
  */
function massDel() {
	if (confirm(lang('massDel_CONFIRM'))) {
		document.getElementById('massaction').value="del";
		document.getElementById('massform').submit();
	} else {
		alert(lang('massDel_NOACTION'));
	}
}

/**
  * Handles the moving of a large number of messages on the Message Archive page
  */
function massMove() {
	document.getElementById('massaction').value="move";
	document.getElementById('massform').submit();
}

/**
  * Deletes all messages from the Trash
  */
function emptyTrash() {
	if (confirm(lang('emptyTrash_CONFIRM'))) {
		document.getElementById('massaction').value="emptytrash";
		document.getElementById('massform').submit();
	} else {
		alert(lang('emptyTrash_NOACTION'));
	}
}

/**
  * Sets the status of all the checkboxes in the mass move/delete list to the given direction
  *
  * @param boolean direction
  */
function changeAll(direction) {
	var boxList = document.getElementById('massform').elements;
	for(var i=0; i<boxList.length; i++) {
		if (boxList[i].type=='checkbox' && boxList[i].id.substr(0,12)=='masscheckbox')
			boxList[i].checked = direction;
	}
}

/**
  * Handles the "Check/Uncheck All" checkbox on the Message Archive etc pages
  *
  * @param object what
  */
function handleCheckUncheckAll(what) {
	if (what.checked == true)
		changeAll(true);
	else
		changeAll(false);
}

/**
  * Handles the creation of a new Message Directory
  */
function addDir(){
	document.getElementById('diraction').value='add';
	var name = prompt(lang('addDir_DIRNAME'));
	if (name!="" && name!=null) {
		if (name.length <= 64) {
			document.getElementById('dirvalue').value=name;
			document.getElementById('dirform').submit();
		} else {
			//Name is too long!
			alert(lang('addDir_TOOLONG'));
		}
	} else if (name=="") {
		alert(lang('addDir_NEEDANAME'));
	}
}

/**
  * Handles the deletion of a Message Directory
  *
  * @param integer id
  */
function delDir(id){
	if (confirm(lang('delDir_CONFIRM'))) {
		document.getElementById('diraction').value='del';
		document.getElementById('dirvalue').value=id;
		document.getElementById('dirform').submit();
	} else {
		alert(lang('delDir_NOACTION'));
	}
}

/**
  * Handles the deletion of a ban on the Bans Management page
  *
  * @param integer id
  */
function delBan(id) {
	if (confirm(lang('delBan_CONFIRM'))) {
		document.getElementById('delid').value=id;
		document.getElementById('delform').submit();
	} else {
		alert(lang('delBan_NOACTION'));
	}
}

/**
  * Transports the user to the page they specify in the current area of the site
  *
  * @param string query
  * @param integer maxpage
  */
function gotoPage(query,maxpage) {
	var dest = prompt(lang('gotoPage_SELECTbefore')+maxpage+lang('gotoPage_SELECTafter'));
	if (dest <= maxpage && dest != null) {
		document.location='/?'+query+dest;
	} else if (dest > maxpage) {
		alert(lang('gotoPage_NOEXISTbefore')+maxpage+lang('gotoPage_NOEXISTafter'));
	}
}

/**
  * Confirms the reporting of a message
  */
function messageReport() {
	if (confirm(lang('messageReport_CONFIRM'))) {
		document.getElementById('msgaction').value='report';
		document.getElementById('msgform').submit();
	} else {
		alert(lang('messageReport_NOACTION'));
	}
}

/**
  * Handles the banning of a user
  */
function messageSenderBan() {
	var banName = prompt(lang('messageSenderBan_PROMPT'));
	if (banName!=null) {
		document.getElementById('banname').value=banName;
		document.getElementById('msgaction').value='ban';
		document.getElementById('msgform').submit();
	} else {
		alert(lang('messageSenderBan_NOACTION'));
	}
}

/**
  * Confirms the deletion of a message
  */
function messageDelete() {
	if (confirm(lang('messageDelete_CONFIRM'))) {
		document.getElementById('msgaction').value='delete';
		document.getElementById('msgform').submit();
	} else {
		alert(lang('messageDelete_NOACTION'));
	}
}

var lastTextareaLength=0;
var lastTextareaValue = "";
/**
  * Limits the length of the supplied textarea to the supplied length
  *
  * @param object textarea
  * @param integer maxLength
  */
function limitTextarea(textarea, maxLength) {
	if (textarea.value.length > lastTextareaLength) {
		//Contents has increased in length... Is it now too long?
		if (textarea.value.length > maxLength) {
			//Yes! Set it back to the last safe value
			textarea.value = lastTextareaValue;
		} //No
	}
	lastTextareaLength=textarea.value.length;
	lastTextareaValue=textarea.value;
}

/**
  * Confirms the deletion of multiple global bans
  */
function checkForm(form) {
	if (confirm(lang('checkForm_CONFIRM'))) {
		return true;
	} else {
		alert(lang('checkForm_NOACTION'));
		return false;
	}
}

/**
  * Handles the deletion of a friend from the Friends List
  *
  * @param integer Friend's UserID
  */
function handleFriendDeletion(userid) {
	if (confirm(lang('handleFriendDeletion_CONFIRM'))) {
		document.getElementById('friendactionfield').value = "delete";
		document.getElementById('friendidfield').value = userid;
		document.getElementById('friendactionform').submit();
	} else {
		alert(lang('handleFriendDeletion_NOACTION'));
	}
}

/**
  * Handles the addition of a new friend in the Friends List page
  */
function addNewFriend(username) {
	if (username==null || username==undefined)
		username = prompt(lang('addNewFriend_PROMPT'));
	if (username != null && username != "") {
		document.getElementById('friendactionfield').value = "add";
		document.getElementById('friendidfield').value = username;
		document.getElementById('friendactionform').submit();
	}
}

/**
  * Adds the specified emoticon code to the Send Message textarea
  * 
  * @param string code
  */
function addEmot(code) {
	document.getElementById('messagebox').value += code;
	document.getElementById('messagebox').focus();
}

/**
  * Sets the "disabled" property of the three Date of Birth fields to the specified value
  * 
  * @param string endis
  */
function disableDOBFields(endis) {
	document.getElementById('dob_day').disabled=endis;
	document.getElementById('dob_month').disabled=endis;
	document.getElementById('dob_year').disabled=endis;
}

/**
  * Shows or hides the emoticons table and changes the show/hide emoticons text
  *
  * @param object link
  */
function showHideEmots(link) {
	var table = document.getElementById('emot_table');
	if (table.style.display=="none") {
		table.style.display="block";
		link.innerHTML=lang('showHideEmots_HIDE');
	} else {
		table.style.display="none";
		link.innerHTML=lang('showHideEmots_SHOW');
	}
}

/**
  * Emulates the function of the max-height and max-width styles that IE6 doesn't support
  * Not always 100% reliable for some reason, despite the algorithm being sound...
  *
  * @author Andrew Gillard <lorddeath@gmail.com>
  * @copyright Copyright ©2005, Andrew Gillard
  * @version 1.1 2005-11-29
  * @license http://opensource.org/licenses/gpl-license.php GNU Public License
  *
  * Usage:
  * <img src="./path/to/image.jpg" style="max-height:50px; max-width: 100px;" onload="resizeImage(this,100,50);" />
  *
  * @param object image
  * @param integer maxWidth
  * @param integer maxHeight
  */
function resizeImage(image,maxWidth,maxHeight) {
	if (!image.style.maxHeight || !image.style.maxWidth) {
		//Maxheight/width aren't supported so we need to emulate them
		var height=image.height;
		var width=image.width;
		if (height > maxHeight || width > maxWidth) {
			//Image is too big
			if ((width/height) > (maxWidth/maxHeight)) {
				//Needs width to be decreased
				width=maxWidth;
				height=Math.round((height/width)*maxWidth);
			} else if (image.width == image.height) {
				//Square
				max = (maxWidth > maxHeight) ? maxHeight : maxWidth;
				width=max;
				height=max;
			} else {
				//Needs height to be decreased
				height=maxHeight;
				width=Math.round((width/height)*maxHeight);
			}
			image.height=height;
			image.width=width;
		}
	}
}

/**
  * Calls resizeImage() on each image on the page whose name starts with the specified imgid
  *
  * @param string imgid
  * @param integer maxWidth
  * @param integer maxHeight
  */
function resizeImages(imgid,maxWidth,maxHeight) {
	var imgs = document.images;
	for (var i=0; i<imgs.length; i++) {
		img = imgs[i];
		if (img.name.substring(0,imgid.length) == imgid)
			resizeImage(img, maxWidth, maxHeight);
	}
}

/**
  * Handles the deletion of a Link Exchange link
  *
  * @param integer linkid
  */
function delLink(linkid) {
	if (confirm(lang('delLink_CONFIRM'))) {
		document.location="/?act=link_exchange&delete="+linkid;
	} else {
		alert(lang('delLink_NOACTION'));
	}
}

/**
  * Generates a number of invitation URLs
  *
  * @param integer maximum number of invites
  */
function createInviteURLs(max) {
	var num = prompt(lang('createInviteURLs_PROMPTbefore')+max+lang('createInviteURLs_PROMPTafter'));
	if (num > max) {
		alert(lang('createInviteURLs_ERRORbefore')+max+lang('createInviteURLs_ERRORafter'));
		return;
	}
	if (num <= 0) {
		return;
	}
	document.getElementById('urlnum').value=num;
	document.getElementById('urlform').submit();
}

/**
  * Calculates the security of the password in reg_password
  *
  * @author Andrew Gillard <lorddeath@gmail.com>
  * @copyright Copyright ©2005, Andrew Gillard
  * @version 1.0 2005-09-10
  * @license http://opensource.org/licenses/gpl-license.php GNU Public License
  *
  * Usage:
  *   <input type="password" name="password" id="password" onchange="CheckPassSecurity('password');" onkeyup="CheckPassSecurity('password');" /><br />
  *   <img src="/images/pass_grey.png" id="pass_grey" alt="Javascript Required - Try Ctrl+F5" title="Try hitting Ctrl+F5" />
  *   <img src="/images/pass_red.png" id="pass_red" alt="Insecure Password" style="display:none;" />
  *   <img src="/images/pass_orange.png" id="pass_orange" alt="Average Password" style="display:none;" />
  *   <img src="/images/pass_green.png" id="pass_green" alt="Secure Password" style="display:none;" />
  *   <span id="pass_strength"></span>
  *   <script language="JavaScript" type="text/javascript">CheckPassSecurity('password');</script>
  *
  * @param string ID of the password field
  */
/**
  * Calculates the security of the password in reg_password
  * 
  * @param string ID of the password field
  */
function CheckPassSecurity(fieldID) {
	var pass = document.getElementById(fieldID).value;
	var strength = 0;
	var max = 10;
	
	//Calculate the strength
	if (pass.length >= 5) strength++; //5+ chars
	if (pass.length >= 10) strength++; //10+ chars
	if (/[A-Z]/.exec(pass) != null) strength++; //Caps
	if (/[A-Z].*[A-Z]/.exec(pass) != null) strength++; //Multiple caps
	if (/[a-z]/.exec(pass) != null) strength++; //Lowercase
	if (/[a-z].*[a-z]/.exec(pass) != null) strength++; //Multiple lowercase
	if (/[0-9]/.exec(pass) != null) strength++; //Numbers
	if (/[0-9].*[0-9]/.exec(pass) != null) strength++; //Multiple numbers
	if (/[^A-Za-z0-9]/.exec(pass) != null) strength++; //Symbols
	if (/[^A-Za-z0-9].*[^A-Za-z0-9]/.exec(pass) != null) strength++; //Multiple numbers
	
	//Display strength
	var red = "none";
	var orange = "none";
	var green = "none";
	var grey = "none";
	var percent = Math.round((strength / max) * 100);
	if (percent < 34) {
		red = "inline";
	} else if (percent < 67) {
		orange = "inline";
	} else {
		green = "inline";
	}
	document.getElementById('pass_red').style.display = red;
	document.getElementById('pass_orange').style.display = orange;
	document.getElementById('pass_green').style.display = green;
	document.getElementById('pass_grey').style.display = grey;
	document.getElementById('pass_strength').innerHTML = "("+percent+"%)";
}

/**
  * Selects the subscription type from the select box
  *
  * @param integer Subscription Bitmask bit
  */
function subExtend(SubBit) {
	var SubTypeBox = document.getElementById('SubscriptionType');
	for (var i=0; i<SubTypeBox.options.length; i++) {
		if (SubTypeBox.options[i].value == SubBit) {
			SubTypeBox.selectedIndex = i;
			populatePeriods();
			break;
		}
	}
}

/**
  * Removes all the options of the specified SELECT box
  *
  * @param object select to clear the options of
  */
function clearOptions(select) {
	select.options.length = 0;
}

/**
  * Adds an option to a select with the specified text and value
  *
  * @param object select to place the option at the end of
  * @param string text of the new option
  * @param string value of thew new option
  */
function addOption(select, text, value) {
	select[select.options.length] = new Option(text, value);
}

/**
  * Create the options of the Subscription Period box
  */
function populatePeriods() {
	var SubTypeBox = document.getElementById('SubscriptionType');
	var SubPeriodBox = document.getElementById('SubscriptionPeriod');
	var SubDescBox = document.getElementById('SubDescription');
	var PPItemName = document.getElementById('PPItemName');
	
	//Which subscription type bit is selected?
	var SubBit = SubTypeBox.options[SubTypeBox.selectedIndex].value;
	
	if (SubBit < 1) {
		clearOptions(SubPeriodBox);
		SubDescBox.innerHTML = "";
		SubPeriodBox.disabled = true;
	} else {
		clearOptions(SubPeriodBox);
		addOption(SubPeriodBox, lang('populatePeriods_SELECT'), "0");
		addOption(SubPeriodBox, lang('populatePeriods_1before')+SubTypePrices[SubBit][1]+lang('populatePeriods_1after'), "1");
		addOption(SubPeriodBox, lang('populatePeriods_3before')+SubTypePrices[SubBit][3]+lang('populatePeriods_3after'), "3");
		addOption(SubPeriodBox, lang('populatePeriods_6before')+SubTypePrices[SubBit][6]+lang('populatePeriods_6after'), "6");
		addOption(SubPeriodBox, lang('populatePeriods_12before')+SubTypePrices[SubBit][12]+lang('populatePeriods_12after'), "12");
		
		SubDescBox.innerHTML = SubTypeDescs[SubBit];
		
		PPItemName.value = "Web2Messenger ("+SubTypeNames[SubBit]+")";
		
		SubPeriodBox.disabled = false;
		createPPItemNumber();
	}
}

/**
  * Checks the value of the selected period and enables/disables the submit button
  * and fills in the PayPal Item Cost field
  */
function checkPeriod() {
	var SubTypeBox = document.getElementById('SubscriptionType');
	var SubBit = SubTypeBox.options[SubTypeBox.selectedIndex].value;
	var SubPeriodBox = document.getElementById('SubscriptionPeriod');
	if (SubPeriodBox.options.length <= 0) return; //Stop this script if the period box is empty
	var SubPeriod = SubPeriodBox.options[SubPeriodBox.selectedIndex].value;
	var SubmitButton = document.getElementById('SubscriptionSubmit');
	var PPItemCost = document.getElementById('PPItemCost');
	
	var SubPeriodSelection = SubPeriodBox.options[SubPeriodBox.selectedIndex].value;
	if (SubPeriodSelection <= 0) {
		SubmitButton.disabled = true;
		PPItemCost.value = "0.00";
	} else {
		SubmitButton.disabled = false;
		PPItemCost.value = SubTypePrices[SubBit][SubPeriod];
		createPPItemNumber();
	}
}

/**
  * Generates a PayPal Item Number which we use for tracking the user and what they're buying
  */
function createPPItemNumber() {
	var SubTypeBox = document.getElementById('SubscriptionType');
	var SubBit = SubTypeBox.options[SubTypeBox.selectedIndex].value;
	var SubPeriodBox = document.getElementById('SubscriptionPeriod');
	if (SubPeriodBox.options.length <= 0) return; //Stop this script if the period box is empty
	var SubPeriod = SubPeriodBox.options[SubPeriodBox.selectedIndex].value;
	var PPItemNumber = document.getElementById('PPItemNumber');
	PPItemNumber.value = UserID+":"+SubBit+":"+SubPeriod;
}

function checkMessage() {
	var text = document.getElementById('messagebox').value;
	if (/invit/i.exec(text) != null) {
		if (confirm(lang('checkMessage_CONFIRM'))) {
			return true;
		} else {
			return false;
		}
	}
}
function checkForm() {
	var filename = document.getElementById('displaypic').value;
	if (filename=="") {
		return confirm("This will delete your existing Display Picture. Are you sure?");
	} else {
		//Check the extension
		var valid = false;
		if (/png$/i.exec(filename) != null) valid=true;
		if (/jpg$/i.exec(filename) != null) valid=true;
		if (/jpeg$/i.exec(filename) != null) valid=true;
		if (/gif$/i.exec(filename) != null) valid=true;
		if (!valid) {
			alert("You have selected an unsuitable file. Allowed formats are:\nPNG\nGIF\nJPG/JPEG");
			document.getElementById('displaypic').value='';
			return false;
		} else {
			document.getElementById('dpprogressbar').style.visibility='visible';
			document.getElementById('dpsubmitbutton').disabled=true;
			document.getElementById('dpsubmitbuttonspan').style.display='none';
			document.getElementById('dpprogressbarspan').style.display='inline';
			return true;
		}
	}
}
function onFileChange(field) {
	var buttonValue = "Remove DP";
	if (field.value != "")
		buttonValue = "Change DP";
	document.getElementById('dpsubmitbutton').value = buttonValue;
}
function RSSSubscribe(id) {
	document.getElementById('rss_sub_id').value = id;
	document.getElementById('rss_sub_form').submit();
}
function RSSUnsubscribe(id) {
	if (confirm(lang('RSS_unsubscribe'))) {
		document.getElementById('rss_uns_id').value = id;
		document.getElementById('rss_uns_form').submit();
	} else {
		alert(lang('RSS_noaction'));
	}
}

function clearDefault(field) {
	if (field.value == field.defaultValue) {
		field.value = '';
	}
}
function unclearDefault(field) {
	if (field.value == '') {
		field.value = field.defaultValue;
	}
}