// <cfprocessingdirective pageEncoding="utf-8">

// vim:set fileencoding=utf-8: 

// JS functions for the webSMS interface.

// Author: Atli Christianse <atli@isuus.com>

// (c) Issus Mobile 2006



// TODO: convert &yacute;

// checkAllInGroup() skal gerast.



// Maybe todo: Use an object or struct to store userinfo instead of a bunch of plain variables.

/* **************************************************

 * Config:

 * *************************************************/
var checkUnicode = false;
var numMsgs = 0;

regularChar = new Array();
doubleChar = new Array();
for (var i = 0; i < 1024; i++){
 	regularChar[i] = 0;  
}
for (var i = 0; i < 128; i++){
	regularChar[i] = i;
	doubleChar[i] = 0;		
}
	
doubleChar[12] = 10;
doubleChar[94] = 20;
doubleChar[123] = 40;
doubleChar[125] = 41;
doubleChar[92] = 47;
doubleChar[91] = 60;
doubleChar[126] = 61;
doubleChar[93] = 62;
doubleChar[124] = 64;	

regularChar[64] = 0;
regularChar[163] = 1;
regularChar[36] = 2;
regularChar[165] = 3;
regularChar[232] = 4;
regularChar[233] = 5;
regularChar[249] = 6;
regularChar[236] = 7;
regularChar[242] = 8;
regularChar[199] = 9;
/*regularChar[216] = 11;
regularChar[248] = 12;
regularChar[197] = 14;
regularChar[229] = 15;*/
regularChar[916] = 16;
regularChar[95] = 17;
regularChar[934] = 18;
regularChar[915] = 19;
regularChar[923] = 20;
regularChar[937] = 21;
regularChar[928] = 22;
regularChar[936] = 23;
regularChar[931] = 24;
regularChar[920] = 25;
regularChar[926] = 26;
/*regularChar[198] = 28;
regularChar[230] = 29;*/
regularChar[223] = 30;
regularChar[201] = 31;
regularChar[164] = 36;
regularChar[161] = 64;
regularChar[192] = 91;
regularChar[214] = 92;
regularChar[209] = 93;
regularChar[220] = 94;
regularChar[167] = 95;
regularChar[191] = 96;
regularChar[228] = 123;
regularChar[246] = 124;
regularChar[241] = 125;
regularChar[252] = 126;
regularChar[224] = 127;	

/*checkCharsLeft = function(tarea){
	
	
	if (isUnicode(Form.Element.getValue(tarea))) {
		if (tarea.name == 'predefinedsmstext'){
			if (Form.Element.getValue(tarea).length > 280)
				tarea.value = Form.Element.getValue(tarea).substring(0, 280);
			
			$('preCharsUsed').value = 280 - Form.Element.getValue(tarea).length;
			checkUnicode = true;
			var msgs = 0;
			if (parseInt($('preCharsUsed').value) <= 70) {
				
				numMsgs = 4;
				msgs = 4;
			}
			else if (parseInt($('preCharsUsed').value) > 70 && parseInt($('preCharsUsed').value) <= 140) {
				numMsgs = 3;
				msgs = 3;
			}
			else if (parseInt($('preCharsUsed').value) > 140 && parseInt($('preCharsUsed').value) <= 210) {
				numMsgs = 2;
				msgs = 2;
			}
			else if (parseInt($('preCharsUsed').value) > 210 && parseInt($('preCharsUsed').value) <= 280) {
				numMsgs = 1;
				msgs = 1;
			}
			$('preNumberOfSms').value = msgs;
			
			new Effect.Appear('pre_unicode_notif', {duration: 0.5});
		}
		else{
			if (Form.Element.getValue(tarea).length > 280)
				tarea.value = Form.Element.getValue(tarea).substring(0, 280);
			
			$('charsUsed').value = 280 - Form.Element.getValue(tarea).length;
			checkUnicode = true;
			var msgs = 0;
			if (parseInt($('charsUsed').value) <= 70) {
				
				numMsgs = 4;
				msgs = 4;
			}
			else if (parseInt($('charsUsed').value) > 70 && parseInt($('charsUsed').value) <= 140) {
				numMsgs = 3;
				msgs = 3;
			}
			else if (parseInt($('charsUsed').value) > 140 && parseInt($('charsUsed').value) <= 210) {
				numMsgs = 2;
				msgs = 2;
			}
			else if (parseInt($('charsUsed').value) > 210 && parseInt($('charsUsed').value) <= 280) {
				numMsgs = 1;
				msgs = 1;
			}
			$('numberOfSms').value = msgs;
			
			new Effect.Appear('unicode_notif', {duration: 0.5});
		}
	}
	else {
		if (tarea.name == 'predefinedsmstext'){
			var text = Form.Element.getValue(tarea).substring(0, 640);
			
			if(getGSM7CharsLength(text) > 640){
				while(getGSM7CharsLength(text) > 640) {
					text = text.substring(0, text.length - 1);
				}
				
				tarea.value = text;
			}
			else{
				if (getGSM7CharsLength(Form.Element.getValue(tarea)) > 640)
				tarea.value = text;
				
			}
				
			//$('preCharsUsed').value = 160 - getGSM7CharsLength(text);
			$('preCharsUsed').value = 640 - getGSM7CharsLength(tarea.value);
			checkUnicode = false;
			var msgs = 0;
			if (parseInt($('preCharsUsed').value) <= 160) {
				
				numMsgs = 4;
				msgs = 4;
			}
			else if (parseInt($('preCharsUsed').value) > 160 && parseInt($('preCharsUsed').value) <= 320) {
				numMsgs = 3;
				msgs = 3;
			}
			else if (parseInt($('preCharsUsed').value) > 320 && parseInt($('preCharsUsed').value) <= 480) {
				numMsgs = 2;
				msgs = 2;
			}
			else if (parseInt($('preCharsUsed').value) > 480 && parseInt($('preCharsUsed').value) <= 640) {
				numMsgs = 1;
				msgs = 1;
			}
			$('preNumberOfSms').value = msgs;
			
			if (Element.visible($('pre_unicode_notif'))) new Effect.Fade('pre_unicode_notif', {duration: 0.5});
		}
		else{
			
			var text = Form.Element.getValue(tarea).substring(0, 640);
			
			if(getGSM7CharsLength(text) > 640){
				while(getGSM7CharsLength(text) > 640) {
					text = text.substring(0, text.length - 1);
				}
				
				tarea.value = text;
			}
			else{
				if (getGSM7CharsLength(Form.Element.getValue(tarea)) > 640)
				tarea.value = text;
				
			}
							
				
			//$('charsUsed').value = 160 - getGSM7CharsLength(text);
			$('charsUsed').value = 640 - getGSM7CharsLength(tarea.value);
			
			var msgs = 0;
			checkUnicode = false;
			if (parseInt($('charsUsed').value) <= 160) {
				
				numMsgs = 4;
				msgs = 4;
			}
			else if (parseInt($('charsUsed').value) > 160 && parseInt($('charsUsed').value) <= 320) {
				numMsgs = 3;
				msgs = 3;
			}
			else if (parseInt($('charsUsed').value) > 320 && parseInt($('charsUsed').value) <= 480) {
				numMsgs = 2;
				msgs = 2;
			}
			else if (parseInt($('charsUsed').value) > 480 && parseInt($('charsUsed').value) <= 640) {
				numMsgs = 1;
				msgs = 1;
			}
			$('numberOfSms').value = msgs;
			
			if (Element.visible($('unicode_notif'))) new Effect.Fade('unicode_notif', {duration: 0.5});
		}
	}
	
	
}*/

checkCharsLeft = function(tarea){
	
	
	if (isUnicode(Form.Element.getValue(tarea))) {
		if (tarea.name == 'predefinedsmstext'){
			if (Form.Element.getValue(tarea).length > 268)
				tarea.value = Form.Element.getValue(tarea).substring(0, 268);
			
			$('preCharsUsed').value = 268 - Form.Element.getValue(tarea).length;
			checkUnicode = true;
			var msgs = 0;
			if (parseInt($('preCharsUsed').value) <= 70) {
				
				numMsgs = 4;
				msgs = 4;
			}
			else if (parseInt($('preCharsUsed').value) > 70 && parseInt($('preCharsUsed').value) <= 134) {
				numMsgs = 3;
				msgs = 3;
			}
			else if (parseInt($('preCharsUsed').value) > 134 && parseInt($('preCharsUsed').value) <= 201) {
				numMsgs = 2;
				msgs = 2;
			}
			else if (parseInt($('preCharsUsed').value) > 201 && parseInt($('preCharsUsed').value) <= 268) {
				numMsgs = 1;
				msgs = 1;
			}
			
			$('preNumberOfSms').value = msgs;
			
			//new Effect.Appear('pre_unicode_notif', {duration: 0.5});
		}
		else{
			if (Form.Element.getValue(tarea).length > 268)
				tarea.value = Form.Element.getValue(tarea).substring(0, 268);
			
			$('charsUsed').value = 268 - Form.Element.getValue(tarea).length;
			checkUnicode = true;
			var msgs = 0;
			if (parseInt($('charsUsed').value) <= 70) {
				
				numMsgs = 4;
				msgs = 4;
			}
			else if (parseInt($('charsUsed').value) > 70 && parseInt($('charsUsed').value) <= 134) {
				numMsgs = 3;
				msgs = 3;
			}
			else if (parseInt($('charsUsed').value) > 134 && parseInt($('charsUsed').value) <= 201) {
				numMsgs = 2;
				msgs = 2;
			}
			else if (parseInt($('charsUsed').value) > 201 && parseInt($('charsUsed').value) <= 268) {
				numMsgs = 1;
				msgs = 1;
			}
			
			$('numberOfSms').value = msgs;
			
			//new Effect.Appear('unicode_notif', {duration: 0.5});
		}
	}
	else {
		if (tarea.name == 'predefinedsmstext'){
			var text = Form.Element.getValue(tarea).substring(0, 612);
			
			if(getGSM7CharsLength(text) > 612){
				while(getGSM7CharsLength(text) > 612) {
					text = text.substring(0, text.length - 1);
				}
				
				tarea.value = text;
			}
			else{
				if (getGSM7CharsLength(Form.Element.getValue(tarea)) > 612)
				tarea.value = text;
				
			}
				
			//$('preCharsUsed').value = 160 - getGSM7CharsLength(text);
			$('preCharsUsed').value = 612 - getGSM7CharsLength(tarea.value);
			checkUnicode = false;
			var msgs = 0;
			if (parseInt($('preCharsUsed').value) <= 160) {
				
				numMsgs = 4;
				msgs = 4;
			}
			else if (parseInt($('preCharsUsed').value) > 160 && parseInt($('preCharsUsed').value) <= 306) {
				numMsgs = 3;
				msgs = 3;
			}
			else if (parseInt($('preCharsUsed').value) > 306 && parseInt($('preCharsUsed').value) <= 459) {
				numMsgs = 2;
				msgs = 2;
			}
			else if (parseInt($('preCharsUsed').value) > 459 && parseInt($('preCharsUsed').value) <= 612) {
				numMsgs = 1;
				msgs = 1;
			}

			$('preNumberOfSms').value = msgs;
			
			//if (Element.visible($('pre_unicode_notif'))) new Effect.Fade('pre_unicode_notif', {duration: 0.5});
		}
		else{
			
			var text = Form.Element.getValue(tarea).substring(0, 612);
			
			if(getGSM7CharsLength(text) > 612){
				while(getGSM7CharsLength(text) > 612) {
					text = text.substring(0, text.length - 1);
				}
				
				tarea.value = text;
			}
			else{
				if (getGSM7CharsLength(Form.Element.getValue(tarea)) > 612)
				tarea.value = text;
				
			}
							
				
			//$('charsUsed').value = 160 - getGSM7CharsLength(text);
			$('charsUsed').value = 612 - getGSM7CharsLength(tarea.value);
			
			var msgs = 0;
			checkUnicode = false;
			if (parseInt($('charsUsed').value) <= 160) {
				
				numMsgs = 4;
				msgs = 4;
			}
			else if (parseInt($('charsUsed').value) > 160 && parseInt($('charsUsed').value) <= 306) {
				numMsgs = 3;
				msgs = 3;
			}
			else if (parseInt($('charsUsed').value) > 306 && parseInt($('charsUsed').value) <= 459) {
				numMsgs = 2;
				msgs = 2;
			}
			else if (parseInt($('charsUsed').value) > 459 && parseInt($('charsUsed').value) <= 612) {
				numMsgs = 1;
				msgs = 1;
			}
			
			$('numberOfSms').value = msgs;
			
			//if (Element.visible($('unicode_notif'))) new Effect.Fade('unicode_notif', {duration: 0.5});
		}
	}
	
	
}

/*maxSMSCharsRemaining = function(text){
	if (isUnicode(text)) $('charsUsed').value = (280 - text.length);
	else $('charsUsed').value = (640 - unicodeToGSM7(text).length);
}*/

maxSMSCharsRemaining = function(text){
	if (isUnicode(text)) $('charsUsed').value = (268 - text.length);
	else $('charsUsed').value = (612 - unicodeToGSM7(text).length);
}

isUnicode = function(text){
	for (var i = 0; i < text.length; i++){		
		var var1 = false;
		var var2 = false;

		if (text.charCodeAt(i) >= regularChar.length)
			var1 = true;
		if (regularChar[text.charCodeAt(i)] == 0)
			var1 = true;
		
		if (text.charCodeAt(i) >= doubleChar.length)
			var2 = true;
		if (doubleChar[text.charCodeAt(i)] == 0)
			var2 = true;
				
		if (var1 == true && var2 == true)
			return true;
	}
	return false;
}

getGSM7CharsLength = function(text){
	return unicodeToGSM7(text).length;
}

unicodeToGSM7 = function(text){
	var ret = '';
	
	if (isUnicode(text)){
		for (var i = 0; i < text.length; i++){		
			if (text.charCodeAt(i) < regularChar.length){
				if (regularChar[text.charCodeAt(i)] != 0)
					ret += String.fromCharCode(regularChar[text.charCodeAt(i)]);
			}
			else if (text.charCodeAt(i) < doubleChar.length){
				if (doubleChar[text.charCodeAt(i)] != 0)
					ret += '\u001B' + String.fromCharCode(doubleChar[text.charCodeAt(i)]);
			}
			else{
				ret += '?';
			}
		}
	}
	else {
		for (var i = 0; i < text.length; i++){		
			if (doubleChar[text.charCodeAt(i)] != 0){
				ret += '\u001B' + String.fromCharCode(doubleChar[text.charCodeAt(i)]);				
			}
			else{
				ret += text.charAt(i);				
			}
		}	
	}
		
	/*
	for (var i = 0; i < text.length; i++){
		if (isUnicode(text[i])){
			if (text.charCodeAt(i) < regularChar.length){
				if (regularChar[text.charCodeAt(i)] != 0)
					ret += String.fromCharCode(regularChar[text.charCodeAt(i)]);
			}
			else if (text.charCodeAt(i) < doubleChar.length){
				if (doubleChar[text.charCodeAt(i)] != 0)
					ret += '\u001B' + String.fromCharCode(doubleChar[text.charCodeAt(i)]);
			}
			else{
				ret += '?';
			}
		}
		else{
			if (doubleChar[text.charCodeAt(i)] != 0)
				ret += '\u001B' + String.fromCharCode(doubleChar[text.charCodeAt(i)]);
			else
				ret += text[i];
		}		
	}	
	*/
	return ret;
}

function getURLParam(strParamName){
  var strReturn = "";
  var strHref = window.location.href;
  if ( strHref.indexOf("?") > -1 ) {
    var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
    var aQueryString = strQueryString.split("&");
    for ( var iParam = 0; iParam < aQueryString.length; iParam++ ) {
      if (aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1 ){
        var aParam = aQueryString[iParam].split("=");
        strReturn = aParam[1];
        break;
      }
    }
  }
  return unescape(strReturn);
}
 
function getElementContent(elid)

{

	return elid.innerHTML;

}
function setElementContent(elid, content)

{

	if(document.all)

	{

		elid.innerHTML = content;

	}

	else if (document.createElement && document.getElementById)

	{

		elid.innerHTML = content;

	}

}
/*  websms (form) */
/*function convertLetters() {

  // (c) Isuus Mobile 2006



  // Save cursor pos.



  if( ! document.selection) {  //  IE



  // DOS style new-line -> UNIX style new-line.

  this.document.webSmsForm.smsMsg.value = this.document.webSmsForm.smsMsg.value.replace(/\x0D\x0A/g,"\x0A");

  // Faroese and Icelandic letters lower(iso)|lower(utf8)

  //                            upper(iso)|upper(uft8)

  // Get cursor position

  this.document.webSmsForm.smsMsg.value = this.document.webSmsForm.smsMsg.value.replace(/\xe1|\xC3\xA1/g,"a");  // ÃÂÃÂ¡

  this.document.webSmsForm.smsMsg.value = this.document.webSmsForm.smsMsg.value.replace(/\xc1|\xC3\x81/g,"A");  // ÃÂÃÂ

  this.document.webSmsForm.smsMsg.value = this.document.webSmsForm.smsMsg.value.replace(/\xF3|\xC3\xB3/g,"o");  // ÃÂÃÂ³

  this.document.webSmsForm.smsMsg.value = this.document.webSmsForm.smsMsg.value.replace(/\xD1|\xC3\x93/g,"O");  // ÃÂÃÂ

  this.document.webSmsForm.smsMsg.value = this.document.webSmsForm.smsMsg.value.replace(/\xFA|\xC3\xBA/g,"u");  // ÃÂÃÂº

  this.document.webSmsForm.smsMsg.value = this.document.webSmsForm.smsMsg.value.replace(/\xDA|\xC3\x9A/g,"U");  // ÃÂÃÂ

  this.document.webSmsForm.smsMsg.value = this.document.webSmsForm.smsMsg.value.replace(/\xED|\xC3\xAD/g,"i");  // ÃÂÃÂ­

  this.document.webSmsForm.smsMsg.value = this.document.webSmsForm.smsMsg.value.replace(/\xCD|\xC3\x8D/g,"I");  // ÃÂÃÂ

  this.document.webSmsForm.smsMsg.value = this.document.webSmsForm.smsMsg.value.replace(/\xf0|\xC3\xB0/g,"d");  // ÃÂÃÂ°

  this.document.webSmsForm.smsMsg.value = this.document.webSmsForm.smsMsg.value.replace(/\xd0|\xC3\x90/g,"D");  // ÃÂÃÂ

  this.document.webSmsForm.smsMsg.value = this.document.webSmsForm.smsMsg.value.replace(/\xfe|\xC3\xBE/g,"p");  // ÃÂÃÂ¾

  this.document.webSmsForm.smsMsg.value = this.document.webSmsForm.smsMsg.value.replace(/\xde|\xC3\x9E/g,"P");  // ÃÂÃÂ

  }

// if(document.selection) { // IE

  //setCursorPosition(this.document.webSmsForm.smsMsg, cursorStartPoint, cursorEndPoint);

  //return true;

 // } 

}*/

function setCursorPosition(oInput,oStart,oEnd) {

    oInput.focus();

    if( oInput.setSelectionRange ) {

      if(oStart < oEnd) {

        oInput.setSelectionRange(oStart,oEnd);}

      else if(oEnd < oStart) {

        oInput.setSelectionRange(oEnd,oStart);}

    } else if( oInput.createTextRange ) {

        var range = oInput.createTextRange();

        range.collapse(true);

        range.moveEnd('character',oEnd);

        range.moveStart('character',oStart);

        range.select();

    }

}
function charCounter()

{

  return this.document.webSmsForm.smsMsg.value.length;

}
function numberSms()

{

  var nc = charCounter();

  var ns = 0;

  if(nc == 0) {

    return 0; }

  if(nc <= 160) { // single sms

    return 1; }

  while (nc > 0)  // split into multiple sms.

    {

      ns++;

      nc = nc-153;

    }

  return ns;

}
function smsMsgChange()

{
	checkCharsLeft($('smsMsg'));
	if (parseInt(this.document.webSmsForm.numberOfSms.value) > 0){
		
		if (global_url == 1){
		  updateBalanceInfo();
		}else{
			updateBalanceInfo1();
		}
	}
	/*
	if (charCounter() > 160)
		
		this.document.webSmsForm.smsMsg.value =  document.webSmsForm.smsMsg.value.substring(0,160); // Todo: 160 Chars Limit
	
		this.document.webSmsForm.charsUsed.value = charCounter();

		this.document.webSmsForm.numberOfSms.value = numberSms();

		updateBalanceInfo();

		//return 0;
	*/
}

function subjectChange(subjectCheck)

{

	if(! subjectCheck) { return -5; }

	if(subjectCheck.checked == false)

	{

		subjectCheck.form.subject.disabled = true;

		if(subjectCheck.form.subjectFromHour)

		{

			subjectCheck.form.subjectFromHour.disabled = true;

			subjectCheck.form.subjectFromMinute.disabled = true;

			subjectCheck.form.subjectToHour.disabled = true;

			subjectCheck.form.subjectToMinute.disabled = true;

		}

	} else {

		subjectCheck.form.subject.disabled = false;

		if(subjectCheck.form.subjectFromHour)

		{

			subjectCheck.form.subjectFromHour.disabled = false;

			subjectCheck.form.subjectFromMinute.disabled = false;

			subjectCheck.form.subjectToHour.disabled = false;

			subjectCheck.form.subjectToMinute.disabled = false;

		}

	}

	return 0;

}
function subjectUpdate()

{

	return 0; // disabled.

	sCheck = document.webSmsForm.subjectCheck;

	if(document.webSmsForm.subjectFromHour)

	{

		sFromH = document.webSmsForm.subjectFromHour;

		sFromM = document.webSmsForm.subjectFromMinute;

		sToH = document.webSmsForm.subjectToHour;

		sToM = document.webSmsForm.subjectToMinute;

	}

	if(sCheck.checked)

	{

		var msg;

		msg = "Aminning: " + document.webSmsForm.subject.value + ". ";

		if(document.webSmsForm.subjectFromHour)

		{

			msg += " Fra klokkan " + sFromH.value + ":" + sFromM.value;

			msg += " til " + sToH.value +  ":" + sToM.value + ".";

		}

		document.webSmsForm.smsMsg.value = msg;

		/*convertLetters();*/ smsMsgChange(); 

	}

	return 0;

}
function showDate(whenObj)

{

	if( typeof(whenObj) == 'undefined')

	{

		whenObj = document.webSmsForm.whenToSend;

	}

  if ( whenObj.value == "now" ) {

    //this.document.webSmsForm.recurring.style.visibility.hidden = true;

    this.document.webSmsForm.recurring.disabled = true;

    this.document.webSmsForm.dateBegin.disabled = true;

    this.document.webSmsForm.dateEnd.disabled = true;

	if(this.document.webSmsForm.sendTimeHour)

	{

		this.document.webSmsForm.sendTimeHour.disabled = true;

		this.document.webSmsForm.sendTimeMinute.disabled = true;

	}

    }

  else if ( (whenObj.value == "later" || whenObj.value == "nowAndLater") && this.document.webSmsForm.recurring.value == "once" ) {

    //this.document.webSmsForm.recurring.style.visibility.hidden = false;

    this.document.webSmsForm.recurring.disabled = false;

    this.document.webSmsForm.dateBegin.disabled = false;

    this.document.webSmsForm.dateEnd.disabled = true;

	if(this.document.webSmsForm.sendTimeHour)

{

    this.document.webSmsForm.sendTimeHour.disabled = false;

    this.document.webSmsForm.sendTimeMinute.disabled = false;

}

    }

  else {

    //this.document.webSmsForm.recurring.style.visibility.hidden = false;

    this.document.webSmsForm.recurring.disabled = false;

    this.document.webSmsForm.dateBegin.disabled = false;

    this.document.webSmsForm.dateEnd.disabled = false;

	if(this.document.webSmsForm.sendTimeHour)

{

    this.document.webSmsForm.sendTimeHour.disabled = false;

    this.document.webSmsForm.sendTimeMinute.disabled = false;

} 

   }

  return 0;

}
function addOption(sel, selText, selValue)

{

  sel.options[sel.length] = new Option(selText, selValue);

  if(sel.id == "recipients")
	  updateRecipients(sel);
}
function deleteOption(sel, selIndex)

{

  if( sel.length>0 )

    sel.options[selIndex] = null;

}
function moveOption(selFrom, selTo)

{

  var selLength = selFrom.length;

  var selectedText = new Array();

  var selectedValues = new Array();

  var selectedCount = 0;

  var i;

  // Find the selected Options in reverse order

  // and delete them from the 'from' Select.

  for(i=selLength-1; i>=0; i--)

  {

    if(selFrom.options[i].selected)

    {

      selectedText[selectedCount] = selFrom.options[i].text;

      selectedValues[selectedCount] = selFrom.options[i].value;

//      deleteOption(selFrom, i);

      selectedCount++;

    }

  }

  delete selectedText;

  delete selectedValues;

  // Add the selected text/values in reverse order.

  // This will add the Options to the 'to' Select

  // in the same order as they were in the 'from' Select.

  for(i=selectedCount-1; i>=0; i--)

  {

    addOption(selTo, selectedText[i], selectedValues[i]);

  }

  if(selTo.id == "recipients")
	  updateRecipients(selTo);

}
function deleteSelectedOptions(sel) {

	for(i=sel.length-1; i >= 0; i--) // remove selected <option>

	{

		if( sel.options[i].selected)

		{

			//deleteOption(sel, i);

			// It seems that Safari (Apple) dosn't won't delete the option with this method.
			try{
				sel.options[i] = null;
			}
			catch(e){}

			// sel.removeChild(sel.options[i]);

		}

	}

	var og = sel.childNodes;

	for(i=og.length-1; i >= 0; i--) // remove empty <optgroup>

	{

//		alert('og.childNodes('+i+').label='+og[i].label);

		if( og[i].childNodes.length == 0)

		{

			sel.removeChild(og[i]);

			if(typeof(og[i]) != 'undefined')

			{

				//alert('remove() failed, trying "=null;"');
			try{
				og[i] = null;
			}
			catch(e){}

			}

		}

	}

}
function selectAllOptions(sel){
	for(i=0; i < sel.options.length; i++){
		if (sel.options[i]){
			try{
				sel.options[i].selected = true;
			}
			catch(e){}
		}
	}
}
function countRecipients() {
// 	var msgs = numberSms();

	var r = document.getElementById('recipients');
	var type = '';
	var rcptsCount = 0;	

	for(o=0; o < r.options.length; o++) {

		type = String(r.options[o].value).substring(0,4);
		if( type == 'gid:') { // Count recipients in group.
			for(j=0; j < group.length; j++)	{
				if( type+group[j]['gid'] == r.options[o].value)	{
					rcptsCount += Number(group[j]['numberContacts']);
					break;
				}
			}
		} else if ( type == 'cid:' || type == 'tel:') { // Count recipient
			rcptsCount++;
		}
	}

	return rcptsCount;
}

function getPhoneNumberFromCid(cid) {
	if (cid.substr(0,4) == "cid:")
		cid = cid.substr(4);
	for (var c = 0; c < window.contact.length; c++) {
		if (window.contact[c].cid == cid) {
			return window.contact[c].phone;
		}
	}
	return null;
}

function getChargeForNumber(phoneNumber) {
	if (phoneNumber.substr(0,1) == "+") {
		phoneNumber = phoneNumber.substr(1);
	}
	if (phoneNumber.length <= 6) {
		phoneNumber = "298" + phoneNumber;
	} 
		
	for (var c = 0; c < countrychargecodes.length; c++) {
		if (phoneNumber.substr(0, countrychargecodes[c][0].length) == countrychargecodes[c][0]) {
			return countrychargecodes[c][1];
		} 
	}
		
	return 1;
}

function getCurrentMessageCost() {

	var recpt = document.getElementById("recipients");
	var retCost = 0;	

	for(var c=0; c < recpt.options.length; c++) {
		switch (String(recpt.options[c].value).substring(0,4)) {
			case "gid:": // ex "cid:3245"
			for(j=0; j < window.contact.length; j++)	{ // Loops thru all contacts, and if finds an contact that belongs to the group, add it.
				if(recpt.options[c].value == "gid:" + window.contact[j].gid) {
					retCost += getChargeForNumber(window.contact[j].phone);
				}
			}
			break;
			case "cid:": // ex "cid:3245"
				retCost += getChargeForNumber(getPhoneNumberFromCid(recpt.options[c].value));
			break;
			case "tel:": // ex. "+123456789"
				retCost += getChargeForNumber(recpt.options[c].value.substr(4));
			break;
			default:
			alert("Unknown item type.");
			break;			
		}
	}

	/*if (checkUnicode){
		//retCost *= Math.ceil(document.getElementById("smsMsg").value.length / 70);	
	}
	else{
		//retCost *= Math.ceil(document.getElementById("smsMsg").value.length / 160);	
	}*/
	
	retCost *= numMsgs;
	return retCost;
}


function updateBalanceInfo()

{

	var o   = document.getElementById('closeToSendButton');

	//var msgs = numberSms();
	var msgs = numMsgs;

	var cost = Math.round(getCurrentMessageCost() * 100) / 100;
	

	var insuffFunds = creditsAvailable - cost < 0 ? true : false


	if(document.getElementById('sendsms'))

	{

		var btn = document.getElementById('sendsms');

		var submitButton = 'send';

	}

	else if(document.getElementById('updateSms'))

	{

		var btn = document.getElementById('updateSms');

		var submitButton = 'update';

	}

	setElementContent(o, LCostIs.replace(/%s/, cost+' credits')); // LCost: 'Cost: %s.' or 'Pris: %s.' or 'Kostnaður: %s.'.
	//document.getElementById('cost_hidden').value = cost;
	var curMessageCost = getCurrentMessageCost() * 100;
	
		   document.getElementById("hiddenCost").value = curMessageCost;
		   
		// document.forms['webSmsForm'].hiddenCost.value = curMessageCost;
		 
	if (creditsAvailable - curMessageCost < 0) {
		if(document.getElementById('sendsms'))
			document.getElementById("sendsms").disabled = true;
		else if(document.getElementById('updateSms'))
			document.getElementById("updateSms").disabled = true;			
		document.getElementById("PurchuseCredit").style.display = "";
				
	} else {
		if(document.getElementById('sendsms'))
			document.getElementById("sendsms").disabled = false;
		else if(document.getElementById('updateSms'))
			document.getElementById("updateSms").disabled = false;			
		document.getElementById("PurchuseCredit").style.display = "none";
	}
	var curBalance = ((creditsAvailable - curMessageCost));
	
	document.getElementById("hiddenBalance").value = curBalance;
	document.getElementById("Credits1").innerHTML = curBalance/100;
	document.getElementById("Balance").innerHTML = (((creditsAvailable - curMessageCost) / 100)/7.5).toFixed(2) + " &euro;";
	
	/*if( submitButton == 'send' )

	{

		if( paymenttype == 1 ) // prepaid.

		{

			if( insuffFunds ) {

				btn.disabled = true;

				setElementContent(o, getElementContent(o) + ' ' + LNotEnoughCredits.replace(/%s/, creditsAvailable));

			} else {

				btn.disabled = false;

			}

		}

		else if ( paymenttype == 2 ) // postpaid.

		{

			if( insuffFunds )

			{

				if(creditsAvailable > 0)

					setElementContent(o, getElementContent(o) + ' ' + LBalanceGoesBelowZeroOK);

			}

		}

	}
*/
	//else if ( submitButton == 'update' ) // FIXME: what do we do when we're updating?

}

function updateBalanceInfo1()

{

	var o   = document.getElementById('closeToSendButton');

	//var msgs = numberSms();
	var msgs = numMsgs;

	var cost = Math.round(getCurrentMessageCost() * 100) / 100;
	

	var insuffFunds = creditsAvailable - cost < 0 ? true : false



	if(document.getElementById('sendsms'))

	{

		var btn = document.getElementById('sendsms');

		var submitButton = 'send';

	}

	else if(document.getElementById('updateSms'))

	{

		var btn = document.getElementById('updateSms');

		var submitButton = 'update';

	}

	setElementContent(o, LCostIs.replace(/%s/, cost+' credits')); // LCost: 'Cost: %s.' or 'Pris: %s.' or 'Kostnaður: %s.'.
	//document.getElementById('cost_hidden').value = cost;
	var curMessageCost = getCurrentMessageCost() * 100;
	
		   document.getElementById("hiddenCost").value = curMessageCost;
		// document.forms['webSmsForm'].hiddenCost.value = curMessageCost;
		 
	if (creditsAvailable - curMessageCost < 0) {
		if(document.getElementById('sendsms'))
			document.getElementById("sendsms").disabled = true;
		else if(document.getElementById('updateSms'))
			document.getElementById("updateSms").disabled = true;			
		document.getElementById("PurchuseCredit").style.display = "";
				
	} else {
		if(document.getElementById('sendsms'))
			document.getElementById("sendsms").disabled = false;
		else if(document.getElementById('updateSms'))
			document.getElementById("updateSms").disabled = false;			
		document.getElementById("PurchuseCredit").style.display = "none";
	}
	var curBalance = ((creditsAvailable - curMessageCost));
	
	document.getElementById("hiddenBalance").value = curBalance;
	
	document.getElementById("Credits1").innerHTML = curBalance/100;
	document.getElementById("Balance").innerHTML = (((creditsAvailable - curMessageCost) / 100)/7.5).toFixed(2) + " &euro;";
	
	/*if( submitButton == 'send' )

	{

		if( paymenttype == 1 ) // prepaid.

		{

			if( insuffFunds ) {

				btn.disabled = true;

				setElementContent(o, getElementContent(o) + ' ' + LNotEnoughCredits.replace(/%s/, creditsAvailable));

			} else {

				btn.disabled = false;

			}

		}

		else if ( paymenttype == 2 ) // postpaid.

		{

			if( insuffFunds )

			{

				if(creditsAvailable > 0)

					setElementContent(o, getElementContent(o) + ' ' + LBalanceGoesBelowZeroOK);

			}

		}

	}
*/
	//else if ( submitButton == 'update' ) // FIXME: what do we do when we're updating?

}

/*  Contacts  */
function compare(comparison, balance, elem){
	curCost = document.getElementById("hiddenCost").value;
	
	if(balance < curCost){
		alertUserCredits();
		
	}
	if (comparison == -1){
		alertUser();
	}
	if (balance >= curCost && comparison != -1){
		selectAllOptions(elem);
	}
}
function compare2(comparison, balance, elem){
	curCost = document.getElementById("hiddenCost").value;
	alert('Comparison:'+comparison);
	alert('Balance:'+balance);
	
	alert('curCost:'+curCost); return false;
	/*if(balance < curCost){
		alertUserCredits();
		return false;
	}
	if (comparison == -1){
		alertUser();
		return false;
	}
	if (balance >= curCost && comparison != -1){
		selectAllOptions(elem);
	}*/
}

function compare1(balance, elem){
	curCost = document.getElementById("hiddenCost").value;
	if(balance < curCost){
		alertUserCredits();
	}
	if (balance >= curCost){
		selectAllOptions(elem);
	}
}

function updateNewGroup() // Shows/hides text field depending on option selected.

{

	if (this.document.newContact.groupId.value == "new" )

		this.document.newContact.newGroupName.disabled = false;

	else

		this.document.newContact.newGroupName.disabled = true;

}

function updateContacts(sel, groupid)

{

  sel.options.length = 0;

  for(j=0; j <= contact.length-1; j++)

  {

    if( 'gid:'+contact[j]['gid'].toString() == groupid || contact[j]['gid'] == groupid || groupid == 0 ) // 0 is special, represents all groups.

    {

      sel.options[sel.options.length] = new Option(contact[j]['name'], 'cid:'+contact[j]['cid']);

    }

  }

}

function updateRecipients(oSel)

{

	// Apparently Safari (AppleWebKit) has trouble with optionGroups.

	if( ua = navigator.userAgent || navigator.appVersion || 'n/a') {

		if( ua.indexOf(' AppleWebKit/') != -1 ) {

			updateBalanceInfo(); // Se also bottom of this function.

			return;

			//alert("Found 'AppleWebKit' in ua='"+ ua +"'.");

		}

	}



	// TODO: check for duplicate cids.

	var listText = new Array();

	var listValue = new Array();

	var listLen = oSel.length;

	rcptsCount = 0;

//	global rcptsCount;

	for(i=0; i < oSel.length; i++) // Move data into array

	{

		listText[i]  = oSel.options[i].text;

		listValue[i] = oSel.options[i].value;

	}

	selectAllOptions(oSel);

	deleteSelectedOptions(oSel);



	var groups = new Array(3); // types are hardcoded.

	groups[0] = new Array("gid:", LGroups);

	groups[1] = new Array("cid:", LPersons);

	groups[2] = new Array("tel:", LPhoneNumbers);



	for(a=0; a < groups.length; a++) // Group and insert into (html-)list.

	{

		oOptgroup = document.createElement('optgroup');

		var items = 0;

		for(i=0; i < listLen; i++) 

		{

			if( String(listValue[i]).substring(0,4) == groups[a][0]) // Insert

			{

				oOption = document.createElement('option');

				oOptgroup.appendChild(oOption);

				oOption.text  = listText[i];

				oOption.value = listValue[i];

				items++;

			}

		}

		oOptgroup.label = groups[a][1] // +' ('+items+')';

		if(items > 0)

			oSel.appendChild(oOptgroup);

	}

	delete listText;

	delete listValue;

	if (global_url == 1){
		  updateBalanceInfo();
	}
	else{
		updateBalanceInfo1();
	} // Se also top of this function, (AppleWebKit check).

}



function jsToolBox(El, mOver)

{

	if(! mOver)

	{

		El.style.visibility = "hidden";

		return 0;

	}

	else if(mOver)

	{

		El.style.visibility = "visible";

		El.style.position = "absolute";

		// FIXME: top,left sould be (x,y) of the mouse cursor.

//		El.style.top = (document.body.clientHeight/2 - El.offsetHeight/2)+"px";

		El.style.top = (400)+"px";

		El.style.left = (document.body.clientWidth/2 - El.offsetWidth/2)+"px";

//		setMouseCoordinates();

//		alert("TB: Mouse (X,Y):\n"+posx+" , "+posy);

		return 0;

	}

}


