function showMenu(sub) {
  var menu = document.getElementById(sub);
  if (menu.getAttribute('timer')) {
    clearTimeout(menu.getAttribute('timer'));
  }
  menu.style.display = 'block';
}

function hideMenu(sub) {
  var menu = document.getElementById(sub);
  var timer = setTimeout("document.getElementById('" + sub + "').style.display = 'none'", 50);
  menu.setAttribute('timer', timer);
}

function goMenu(file) {
  document.location = file;
}

function subOver(sub) {
  sub.style.backgroundColor='#ffffff';
  sub.style.color='#000000';
}

function subOut(sub) {
  sub.style.backgroundColor='';
  sub.style.color='#f0f0f0';
}

function openPlenary(speaker) {
  window.open('/plenary.php?speaker=' + speaker, 'plenary_speaker', 'width=765,height=515');
}


//v1.7
// Flash Player Version Detection
// Detect Client Browser type
// Copyright 2005-2008 Adobe Systems Incorporated.  All rights reserved.
var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

function ControlVersion() {
	var version;
	var axo;
	var e;
	// NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry
	try {
		// version will be set for 7.X or greater players
		axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
		version = axo.GetVariable("$version");
	} catch (e) {
	}
	if (!version)	{
		try {
			// version will be set for 6.X players only
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");

			// installed player is some revision of 6.0
			// GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
			// so we have to be careful.

			// default to the first public version
			version = "WIN 6,0,21,0";
			// throws if AllowScripAccess does not exist (introduced in 6.0r47)
			axo.AllowScriptAccess = "always";
			// safe to call for 6.0r47 or greater
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}
	if (!version)	{
		try {
			// version will be set for 4.X or 5.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = axo.GetVariable("$version");
		} catch (e) {
		}
	}
	if (!version)	{
		try {
			// version will be set for 3.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
			version = "WIN 3,0,18,0";
		} catch (e) {
		}
	}
	if (!version)	{
		try {
			// version will be set for 2.X player
			axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			version = "WIN 2,0,0,11";
		} catch (e) {
			version = -1;
		}
	}

	return version;
}

// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer() {
	// NS/Opera version >= 3 check for Flash plugin in plugin array
	var flashVer = -1;

	if (navigator.plugins != null && navigator.plugins.length > 0) {
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
			var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
			var descArray = flashDescription.split(" ");
			var tempArrayMajor = descArray[2].split(".");
			var versionMajor = tempArrayMajor[0];
			var versionMinor = tempArrayMajor[1];
			var versionRevision = descArray[3];
			if (versionRevision == "") {
				versionRevision = descArray[4];
			}
			if (versionRevision[0] == "d") {
				versionRevision = versionRevision.substring(1);
			} else if (versionRevision[0] == "r") {
				versionRevision = versionRevision.substring(1);
				if (versionRevision.indexOf("d") > 0) {
					versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
				}
			}
			var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
		}
	}
	// MSN/WebTV 2.6 supports Flash 4
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
	// WebTV 2.5 supports Flash 3
	else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
	// older WebTV supports Flash 2
	else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
	else if ( isIE && isWin && !isOpera ) {
		flashVer = ControlVersion();
	}
	return flashVer;
}

// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision) {
	versionStr = GetSwfVer();
	if (versionStr == -1 ) {
		return false;
	} else if (versionStr != 0) {
		if(isIE && isWin && !isOpera) {
			// Given "WIN 2,0,0,11"
			tempArray         = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
			tempString        = tempArray[1];			// "2,0,0,11"
			versionArray      = tempString.split(",");	// ['2', '0', '0', '11']
		} else {
			versionArray      = versionStr.split(".");
		}
		var versionMajor      = versionArray[0];
		var versionMinor      = versionArray[1];
		var versionRevision   = versionArray[2];
        	// is the major.revision >= requested major.revision AND the minor version >= requested minor
		if (versionMajor > parseFloat(reqMajorVer)) {
			return true;
		} else if (versionMajor == parseFloat(reqMajorVer)) {
			if (versionMinor > parseFloat(reqMinorVer))
				return true;
			else if (versionMinor == parseFloat(reqMinorVer)) {
				if (versionRevision >= parseFloat(reqRevision))
					return true;
			}
		}
		return false;
	}
}

function AC_AddExtension(src, ext) {
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?');
  else
    return src + ext;
}

function AC_Generateobj(objAttrs, params, embedAttrs) {
  var str = '';
  if (isIE && isWin && !isOpera) {
    str += '<object ';
    for (var i in objAttrs) {
      str += i + '="' + objAttrs[i] + '" ';
    }
    str += '>';
    for (var i in params) {
      str += '<param name="' + i + '" value="' + params[i] + '" /> ';
    }
    str += '</object>';
  } else {
    str += '<embed ';
    for (var i in embedAttrs) {
      str += i + '="' + embedAttrs[i] + '" ';
    }
    str += '> </embed>';
  }
  document.write(str);
}

function AC_FL_RunContent() {
  var ret =
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_SW_RunContent() {
  var ret =
    AC_GetArgs
    (  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
     , null
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType) {
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2) {
    var currArg = args[i].toLowerCase();
    switch (currArg){
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":
        args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[srcParamName] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblclick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "type":
      case "codebase":
      case "id":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace":
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "tabindex":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  ret.objAttrs["classid"] = classid;
  if (mimeType) ret.embedAttrs["type"] = mimeType;
  return ret;
}

function prepareInsert() {
  try {
    dojo.byId("abstractForm").scrollIntoView();
    dojo.byId("abstractForm").style.display = "";
    dojo.byId("abstractForm").reset();
    dojo.byId("abstractForm").task.value = "insert";
    dojo.byId("abstractResult").style.display = "none";
    dojo.byId("abstractFormStep1").style.display = "";
    curStep = 1;
  } catch(e) {
    alert(e.description);
  }
}

function prepareUpdate() {
  try {
    dojo.byId("abstractForm").scrollIntoView();
    dojo.byId("abstractForm").style.display = "";
    dojo.byId("abstractForm").reset();
    dojo.byId("abstractForm").task.value = "update";
    dojo.byId("abstractResult").style.display = "none";
    dojo.byId("abstractFormStep1").style.display = "";

    curStep = 1;
  } catch(e) {
    alert(e.description);
  }
}

function editThis(code) {
  cancel();
  editAbstract(code);
}

function printThis(code) {return;
  if (confirm("Each abstract will be printed in an A4 sized paper. To check that if it will overflow or not, print your abstract. Before printing your abstract, you should set your web browser's print settings like below:\n\nPaper size: A4\nHeader & Footer: none\nMargins: Top 25mm, Left 25mm, Right 25mm, Bottom 5mm")) {
    window.open('/manage/print.php?code=' + code, 'printAbstract', 'menubar=yes,toolbar=yes,status=yes,resizable=yes,scrollbars=yes');
  }
}

function findSubmissions(form) {
  try {
    if (!getValue(form.email)) {
      alert("You should enter the e-mail address");
      form.email.focus();
      return false;
    }

    dojo.io.bind ({
      url:      "/modules/tasks/FindAbstract.php",
      mimetype: "text/html",
      method:   "POST",
      content:  { 'email': getValue(form.email) },
      sync:     true,
      error:    function (type, errObj) { alert("[error] findSubmissions\n\n" + errObj.message); },
      load:     function (type, data, evt) {
        if (data.indexOf("__ERROR__") == -1) {
          try {
            eval(data);
          } catch(e) {
            alert(e.description);
            alert(data);
          }
        } else {
          alert("[ERROR] findSubmissions\n\n" + data.replace("__ERROR__", ""));
        }
      }
    });
  } catch (e) {
    alert(e.description);
  } finally {
    return false;
  }
}

function findPassword(code, email) {
  if (code && email) {
    dojo.io.bind ({
      url:      "/modules/tasks/FindPassword.php",
      mimetype: "text/html",
      method:   "POST",
      content:  { 'code': code, 'email': email },
      sync:     true,
      error:    function (type, errObj) { alert("[error] findPassword\n\n" + errObj.message); },
      load:     function (type, data, evt) {
        if (data.indexOf("__ERROR__") == -1) {
          try {
            eval(data);
          } catch(e) {
            alert(e.description);
            alert(data);
          }
        } else {
          alert(data);
          alert("[ERROR] findPassword\n\n" + data.replace("__ERROR__", ""));
        }
      }
    });
  }
}

function editAbstract(form) {
  try {
    if (typeof form == 'string') {
      var code = form;
      var pass = '__DIRECT__';
    } else {
      if (!getValue(form.abnum)) {
        alert("You should enter the abstract number");
        form.abnum.focus();
        return false;
      } else if (!getValue(form.abpass)) {
        alert("You should enter the abstract password");
        form.abpass.focus();
        return false;
      } else {
        var code = getValue(form.abnum);
        var pass = getValue(form.abpass);
      }
    }

    dojo.io.bind ({
      url:      "/modules/tasks/GetAbstract.php",
      mimetype: "text/html",
      method:   "POST",
      content:  { 'number': code, 'passwd': pass },
      sync:     true,
      error:    function (type, errObj) { alert("[error] editAbstract\n\n" + errObj.message); },
      load:     function (type, data, evt) {
        if (data.indexOf("__ERROR__") == -1) {
          try {
            eval(data);
          } catch(e) {
            alert(e.description);
            alert(data);
          }
        } else {
          alert("[ERROR] editAbstract\n\n" + data.replace("__ERROR__", ""));
        }
      }
    });
  } catch (e) {
    alert(e.description);
  } finally {
    return false;
  }
}

function printAbstract(form) {
  try {
    if (!getValue(form.abnum)) {
      alert("You should enter the abstract number");
      form.abnum.focus();
    } else {
      dojo.io.bind ({
        url:      "/modules/tasks/GetAbstract.php",
        mimetype: "text/html",
        method:   "POST",
        content:  { number: getValue(form.abnum) },
        sync:     true,
        error:    function (type, errObj) { alert("[error] editAbstract\n\n" + errObj.message); },
        load:     function (type, data, evt) {
          if (data.indexOf("__ERROR__") == -1) {
            try {
              eval(data);
            } catch(e) {
              alert(e.description);
              alert(data);
            }
          } else {
            alert("[ERROR] editAbstract\n\n" + data.replace("__ERROR__", ""));
          }
        }
      });
    }
  } catch (e) {
    alert(e.description);
  } finally {
    return false;
  }
}

function saveAuthor(form) {
  var onlyOneCorrespondingAuthorIsAllowed = false;

  if (!getValue(form.elements['author[last]'])) {
    alert('Please enter family name of the author');
    form.elements['author[last]'].focus();
    return false;
  } else if (!getValue(form.elements['author[first]'])) {
    alert('Please enter first name of the author');
    form.elements['author[first]'].focus();
    return false;
/*
  } else if (!getValue(form.elements['author[department]'])) {
    alert('Please enter the department.');
    form.elements['author[department]'].focus();
    return false;
*/
  } else if (!getValue(form.elements['author[institution]'])) {
    alert('Please enter the affiliation.');
    form.elements['author[institution]'].focus();
    return false;
  } else if (!getValue(form.elements['author[address]'])) {
    alert('Please enter the address.');
    form.elements['author[address]'].focus();
    return false;
  } else if (!getValue(form.elements['author[country]'])) {
    alert('Please select the country.');
    form.elements['author[country]'].focus();
    return false;
  } else {
    if (getValue(form.elements['author[department2]']) || getValue(form.elements['author[institution2]']) || getValue(form.elements['author[address2]']) || getValue(form.elements['author[country2]'])) {
      if (!getValue(form.elements['author[institution2]'])) {
        alert('Please enter the affiliation.');
        form.elements['author[institution2]'].focus();
        return false;
/*
      } else if (!getValue(form.elements['author[department2]'])) {
        alert('Please enter the department.');
        form.elements['author[department2]'].focus();
        return false;
*/
      } else if (!getValue(form.elements['author[address2]'])) {
        alert('Please enter the address.');
        form.elements['author[address2]'].focus();
        return false;
      } else if (!getValue(form.elements['author[country2]'])) {
        alert('Please select the country.');
        form.elements['author[country2]'].focus();
        return false;
      }
    }

    var str = getValue(form.elements['author[first]']) + ' ' + getValue(form.elements['author[last]'])
            + ' (' + getValue(form.elements['author[institution]']) + (getValue(form.elements['author[institution2]']) ? ' / ' + getValue(form.elements['author[institution2]']) : '')
            + (form.elements['author[correspon]'].checked ? ', Corresponding author' : '')
            + (form.elements['author[presenter]'].checked ? ', Presenting author' : '') + ')';

    if (form.elements['author[correspon]'].checked) {
      if (!getValue(form.elements['author[email]'])) {
        alert('Please enter the email address of corresponding author');
        form.elements['author[email]'].focus();
        return false;
      } else if (!getValue(form.elements['author[phone]'])) {
        alert('Please enter the phone number of corresponding author');
        form.elements['author[phone]'].focus();
        return false;
      } else if (!getValue(form.elements['author[fax]'])) {
        alert('Please enter the fax number of corresponding author');
        form.elements['author[fax]'].focus();
        return false;
      }

      if (onlyOneCorrespondingAuthorIsAllowed) {
        if (form.authors.options.length) {
          for (var i = 0, author; i < form.authors.options.length; i++) {
            author = dojo.json.evalJson(form.authors.options[i].getAttribute('author'));
            author.correspon = 0;
            form.authors.options[i].setAttribute('author', dojo.json.serialize(author));
          }
        }
      }
    }

    if (form.elements['author[presenter]'].checked && form.authors.options.length) {
      for (var i = 0; i < form.authors.options.length; i++) {
        author = dojo.json.evalJson(form.authors.options[i].getAttribute('author'));
        author.presenter = 0;
        form.authors.options[i].setAttribute('author', dojo.json.serialize(author));
      }
    }

    if (form.authors.disabled) { // edit author
      var option = form.authors.options[form.authors.selectedIndex];
      option.text = str;
    } else { // add author
      var option = document.createElement("OPTION");
      option.text = str;
      form.authors.options.add(option);
    }

    var author = {
      first       : getValue(form.elements['author[first]'       ]),
      last        : getValue(form.elements['author[last]'        ]),
      department  : getValue(form.elements['author[department]'  ]),
      institution : getValue(form.elements['author[institution]' ]),
      address     : getValue(form.elements['author[address]'     ]),
      country     : getValue(form.elements['author[country]'     ]),
      department2 : getValue(form.elements['author[department2]' ]),
      institution2: getValue(form.elements['author[institution2]']),
      address2    : getValue(form.elements['author[address2]'    ]),
      country2    : getValue(form.elements['author[country2]'    ]),
      email       : getValue(form.elements['author[email]'       ]),
      phone       : getValue(form.elements['author[phone]'       ]),
      fax         : getValue(form.elements['author[fax]'         ]),
      correspon   : form.elements['author[correspon]'].checked ? 1 : 0,
      presenter   : form.elements['author[presenter]'].checked ? 1 : 0
    };
    option.setAttribute('author', dojo.json.serialize(author));

    setValue(form.elements['author[first]'       ], '');
    setValue(form.elements['author[last]'        ], '');
    setValue(form.elements['author[department]'  ], '');
    setValue(form.elements['author[institution]' ], '');
    setValue(form.elements['author[address]'     ], '');
    setValue(form.elements['author[country]'     ], '');
    setValue(form.elements['author[department2]' ], '');
    setValue(form.elements['author[institution2]'], '');
    setValue(form.elements['author[address2]'    ], '');
    setValue(form.elements['author[country2]'    ], '');
    setValue(form.elements['author[email]'       ], '');
    setValue(form.elements['author[phone]'       ], '');
    setValue(form.elements['author[fax]'         ], '');
    form.elements['author[first]'    ].readOnly = false;
    form.elements['author[last]'     ].readOnly = false;
    form.elements['author[correspon]'].checked = false;
    form.elements['author[presenter]'].checked = false;

    form.authors.disabled = false;

    previewAuthors(form, 'authorsPreviewNames', 'authorsPreviewAddress');
  }
}

function cancelAuthor(form) {
  if (confirm('Do you want to cancel editting?')) {
    setValue(form.elements['author[first]'       ], '');
    setValue(form.elements['author[last]'        ], '');
    setValue(form.elements['author[department]'  ], '');
    setValue(form.elements['author[institution]' ], '');
    setValue(form.elements['author[address]'     ], '');
    setValue(form.elements['author[country]'     ], '');
    setValue(form.elements['author[department2]' ], '');
    setValue(form.elements['author[institution2]'], '');
    setValue(form.elements['author[address2]'    ], '');
    setValue(form.elements['author[country2]'    ], '');
    setValue(form.elements['author[email]'       ], '');
    setValue(form.elements['author[phone]'       ], '');
    setValue(form.elements['author[fax]'         ], '');
    form.elements['author[first]'    ].readOnly = false;
    form.elements['author[last]'     ].readOnly = false;
    form.elements['author[email]'    ].disabled = true;
    form.elements['author[phone]'    ].disabled = true;
    form.elements['author[fax]'      ].disabled = true;
    form.elements['author[correspon]'].checked = false;
    form.elements['author[presenter]'].checked = false;

    form.authors.disabled =  false;
  }
}

function editAuthor(form) {
  if (form.authors.selectedIndex == -1) {
    alert('Please select the author to edit.');
  } else {
    var author = dojo.json.evalJson(form.authors.options[form.authors.selectedIndex].getAttribute('author'));

    setValue(form.elements['author[first]'      ], author.first);
    setValue(form.elements['author[last]'       ], author.last);
    setValue(form.elements['author[department]' ], author.department);
    setValue(form.elements['author[institution]'], author.institution);
    setValue(form.elements['author[address]'    ], author.address);
    setValue(form.elements['author[country]'    ], author.country);
    setValue(form.elements['author[email]'      ], author.email);
    setValue(form.elements['author[phone]'      ], author.phone);
    setValue(form.elements['author[fax]'        ], author.fax);

    if (author.department2 ) setValue(form.elements['author[department2]' ], author.department2);
    if (author.institution2) setValue(form.elements['author[institution2]'], author.institution2);
    if (author.address2    ) setValue(form.elements['author[address2]'    ], author.address2);
    if (author.country2    ) setValue(form.elements['author[country2]'    ], author.country2);
    form.elements['author[correspon]'].checked = author.correspon == 1 ? true : false;
    form.elements['author[presenter]'].checked = author.presenter == 1 ? true : false;
    form.elements['author[email]'].disabled = author.correspon == 1 ? false : true;
    form.elements['author[phone]'].disabled = author.correspon == 1 ? false : true;
    form.elements['author[fax]'  ].disabled = author.correspon == 1 ? false : true;

    form.authors.disabled =  true;
  }
}

function copyAuthor(form) {
  if (form.authors.selectedIndex == -1) {
    alert('Please select the author to copy his/her information.');
  } else {
    var author = dojo.json.evalJson(form.authors.options[form.authors.selectedIndex].getAttribute('author'));

    setValue(form.elements['author[department]'  ], author.department);
    setValue(form.elements['author[institution]' ], author.institution);
    setValue(form.elements['author[address]'     ], author.address);
    setValue(form.elements['author[country]'     ], author.country);

    setValue(form.elements['author[department2]' ], author.department2);
    setValue(form.elements['author[institution2]'], author.institution2);
    setValue(form.elements['author[address2]'    ], author.address2);
    setValue(form.elements['author[country2]'    ], author.country2);
  }
}

function deleteAuthor(form) {
  if (form.authors.options.length > 0) {
    if (form.authors.selectedIndex == -1) {
      alert('Please select the author to remove from the list.');
    } else {
      var author = dojo.json.evalJson(form.authors.options[form.authors.selectedIndex].getAttribute('author'));
      if (confirm('Remove \'' + author.first + ' ' + author.last + '\' from the list?')) {
        form.authors.options[form.authors.selectedIndex] = null;
      }
    }
  }

  previewAuthors(form, 'authorsPreviewNames', 'authorsPreviewAddress');
}

function previewAuthors(form, divName, divAddress) {
  try {
    for (var i = 0, authors = []; i < form.authors.options.length; i++) {
      authors.push(dojo.json.evalJson(form.authors.options[i].getAttribute('author')));
    }
  } catch (ex) {
    alert('[ERROR] previewAuthors\n\n' + ex.description);
    return false;
  }

  if (authors.length == 0) {
    dojo.byId('authorsPreviewNames').innerHTML = 'Authors not entered';
    dojo.byId('authorsPreviewAddress').innerHTML = '';
  } else {
    dojo.io.bind ({
      url:      "/modules/tasks/getAuthors.php",
      mimetype: "text/plain",
      method:   "POST",
      content:  { 'authors': dojo.json.serialize(authors), 'divName': divName, 'divAddress': divAddress },
      sync:     true,
      error:    function (type, errObj) { alert("[error] previewAuthors\n\n" + errObj.message); },
      load:     function (type, data, evt) {
        if (data.indexOf("__ERROR__") == -1) {
          try {
            eval(data);
          } catch(e) {
            alert("[ERROR] previewAuthors: " + e.description);
            alert(data);
          }
        } else {
          alert("[Error] previewAuthors\n\n" + data.replace("__ERROR__", ""));
        }
      }
    });
  }
}

function moveUp(obj) {
  for (var i = 0; i < obj.options.length; i++) {
    if (obj.options[i].selected) {
      if (i != 0 && !obj.options[i - 1].selected) {
        swap(obj, i, i - 1);
        obj.options[i - 1].selected = true;
      }
    }
  }

  previewAuthors(obj.form, 'authorsPreviewNames', 'authorsPreviewAddress');
}

function moveDown(obj) {
  for (var i = obj.options.length - 1; i >= 0; i--) {
    if (obj.options[i].selected) {
      if (i != (obj.options.length - 1) && ! obj.options[i + 1].selected) {
        swap(obj, i, i + 1);
        obj.options[i+1].selected = true;
      }
    }
  }

  previewAuthors(obj.form, 'authorsPreviewNames', 'authorsPreviewAddress');
}

function swap(obj, i, j) {
  var o = obj.options;
  var i_selected = o[i].selected;
  var j_selected = o[j].selected;
  var t1 = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
  var t2 = new Option(o[j].text, o[j].value, o[j].defaultSelected, o[j].selected);

  t1.author = o[i].author;
  t2.author = o[j].author;
  o[i] = t2;
  o[j] = t1;
  o[i].selected = j_selected;
  o[j].selected = i_selected;
}

var curStep = 1;

function goStep(step) {
  var form = document.forms['abstractForm'];

  try {
    if (curStep == 1 && step == 2) {
      if (!getValue(form.elements['name'])) {
        alert('Please enter your name.');
        form.elements['name'].focus();
        return false;
      } else if (!getValue(form.elements['institution'])) {
        alert('Please enter your affiliation.');
        form.elements['institution'].focus();
        return false;
  /*
      } else if (!getValue(form.elements['department'])) {
        alert('Please enter your department.');
        form.elements['department'].focus();
        return false;
  */
      } else if (!getValue(form.elements['address'])) {
        alert('Please enter address.');
        form.elements['address'].focus();
        return false;
      } else if (!getValue(form.elements['city'])) {
        alert('Please enter city.');
        form.elements['city'].focus();
        return false;
      } else if (!getValue(form.elements['country'])) {
        alert('Please select country.');
        form.elements['country'].focus();
        return false;
      } else if (!getValue(form.elements['telephone'])) {
        alert('Please enter telephone number.');
        form.elements['telephone'].focus();
        return false;
      } else if (!getValue(form.elements['email'])) {
        alert('Please enter email address.');
        form.elements['email'].focus();
        return false;
      } else if (!isValidEmail(getValue(form.elements['email']), form.elements['email'])) {
        alert("E-mail address is not valid format");
        form.elements['email'].focus();
        return false;
      }
    } else if (curStep == 2 && step == 3) {
      if (!getValue(form.elements['topic'])) {
        alert('Please choose a symposium.');
        form.elements['topic'].focus();
        return false;
      } else if (!getValue(form.elements['ptype'])) {
        alert('Please select preferred presentation type.');
        form.elements['ptype'][0].focus();
        return false;
      } else if (!getValue(form.elements['title'])) {
        alert('Please enter abstract title.');
        //form.elements['title'].focus();
        return false;
      } else if (!getValue(form.elements['abstract'])) {
        alert('Please enter abstract text.');
        //form.elements['abstract'].focus();
        return false;
      }
    } else if (curStep == 3 && step == 4) {
      if (form.authors.options.length == 0) {
        alert('Please enter at least one author.');
        return false;
      } else {
        for (var i = 0, author = {}, iCorrespon = 0, iPresenter = 0; i < form.authors.options.length; i++) {
          author = dojo.json.evalJson(form.authors.options[i].getAttribute('author'));
          iCorrespon += author.correspon;
          iPresenter += author.presenter;

          if (!author.first) {
            form.authors.selectedIndex = i;
            editAuthor(form);
            form.elements['author[first]'].focus();
            alert('Please enter the first name of the author named "' + author.last + '"');
            return false;
          } else if (!author.last) {
            form.authors.selectedIndex = i;
            editAuthor(form);
            form.elements['author[last]'].focus();
            alert('Please enter the last name of the author named "' + author.first + '"');
            return false;
/*
          } else if (!author.department) {
            form.authors.selectedIndex = i;
            editAuthor(form);
            form.elements['author[department]'].focus();
            alert('Please enter the department of the author named "' + author.first + ' ' + author.last + '"');
            return false;
*/
          } else if (!author.institution) {
            form.authors.selectedIndex = i;
            editAuthor(form);
            form.elements['author[institution]'].focus();
            alert('Please enter the affiliation of the author named "' + author.first + ' ' + author.last + '"');
            return false;
          } else if (!author.address) {
            form.authors.selectedIndex = i;
            editAuthor(form);
            form.elements['author[address]'].focus();
            alert('Please enter the address(city) of the author named "' + author.first + ' ' + author.last + '"');
            return false;
          } else if (!author.country) {
            form.authors.selectedIndex = i;
            editAuthor(form);
            form.elements['author[country]'].focus();
            alert('Please select the country of the author named "' + author.first + ' ' + author.last + '"');
            return false;
          }
        }

        if (iCorrespon == 0) {
          alert('Please select corresponding author.');
          return false;
        } else if (iPresenter == 0) {
          alert('Please select presenting author.');
          return false;
        }

        dojo.byId('contact_name'       ).innerHTML = getValue(form.elements['catitle']) + ' ' + getValue(form.elements['name']);
        dojo.byId('contact_institution').innerHTML = getValue(form.elements['institution']);
        //dojo.byId('contact_department' ).innerHTML = getValue(form.elements['department']);
        dojo.byId('contact_address'    ).innerHTML = getValue(form.elements['address']);
        dojo.byId('contact_city'       ).innerHTML = getValue(form.elements['city']);
        dojo.byId('contact_country'    ).innerHTML = getValue(form.elements['country']);
        dojo.byId('contact_telephone'  ).innerHTML = getValue(form.elements['telephone']);
        dojo.byId('contact_fax'        ).innerHTML = getValue(form.elements['fax']);
        dojo.byId('contact_email'      ).innerHTML = getValue(form.elements['email']);
        dojo.byId('abstract_topic'     ).innerHTML = getValue(form.elements['topic']);
        dojo.byId('abstract_ptype'     ).innerHTML = form.elements['ptype'][getIndex(form.elements['ptype'])].getAttribute("ptype") + ' presentation';
        dojo.byId('abstract_title'     ).innerHTML = getValue(form.elements['title']);
        dojo.byId('abstract_text'      ).innerHTML = getValue(form.elements['abstract']);
        previewAuthors(form, 'abstract_names', 'abstract_addresses');
        for (var i = 0, author = {}, correspondence = []; i < form.authors.options.length; i++) {
          author = dojo.json.evalJson(form.authors.options[i].getAttribute('author'));
          if (author.correspon) {
            correspondence.push('*' + author.first + ' ' + author.last + ', e-mail: ' + author.email + (author.phone && author.phone != '555' ? ', Tel: ' + author.phone : '') + (author.fax && author.fax != '555' ? ', Fax: ' + author.fax : ''));
          }
        }
        if (dojo.byId('abstract_correspondence')) {
          var correspondenceStr = "";
          correspondenceStr += "<table cellpadding=0 cellspacing=0 border=0 width='100%' style='height: 6mm; margin-bottom: 1mm'><tr><td class='px13 LH110' valign=bottom>";
          correspondenceStr += correspondence.join(', ');
          correspondenceStr += "</td></tr></table>";
          dojo.byId('abstract_correspondence').innerHTML = correspondenceStr;
        }
      }
    }

    dojo.byId('abstractFormStep1').style.display = "none";
    dojo.byId('abstractFormStep2').style.display = "none";
    dojo.byId('abstractFormStep3').style.display = "none";
    dojo.byId('abstractFormStep4').style.display = "none";

    dojo.byId('abstractFormStep' + step).style.display = "";
    curStep = step;
  } catch (e) {
    alert(e.description);
  }
}

function cancel() {
  if (dojo.byId('_title_editor')) editor_setHTML("title", "");
  if (dojo.byId('_abstract_editor')) editor_setHTML("abstract", "");
  //dojo.byId("abstractCheckForm").style.display = "";
  //dojo.byId("abstractCheckForm").reset();
  dojo.byId("abstractForm").reset();
  dojo.byId('abstractFormStep1').style.display = "none";
  dojo.byId('abstractFormStep2').style.display = "none";
  dojo.byId('abstractFormStep3').style.display = "none";
  dojo.byId('abstractFormStep4').style.display = "none";
  dojo.byId("abstractForm").style.display = "none";
  document.forms['abstractForm'].authors.options.length = 0;
}

function saveAbstract(form) {
  try {
    // check the abstract height
    /*
    if (dojo.byId('abstract_preview').clientHeight > 900) {
      if (!confirm('The abstract you just entered is not fit in one page')) return false;
    }
*/
    // check abstract words count
    if (dojo.byId('abstract_text') && dojo.byId('abstract_text').innerText) {
      var abstractWords = dojo.byId('abstract_text').innerText.replace(/^\s+/g,'').replace(/\s+$/g,'').split(' ');
      /*
      for (var i = 0, _abstractWords = []; i < abstractWords.length; i++) {
        if (!in_array(abstractWords[i], ['a', 'an', 'the', 'above', 'about', 'at', 'after', 'among', 'around', 'before', 'behind', 'below', 'beside', 'beneath', 'between', 'by', 'down', 'during', 'for', 'from', 'in', 'into', 'near', 'of', 'on', 'over', 'out', 'since', 'through', 'till', 'to', 'toward', 'under', 'up', 'with', 'within', 'without'])) {
          _abstractWords.push(abstractWords[i]);
        }
      }
      */
      if (abstractWords.length > 450 || abstractWords.length < 150) {
        alert('Please adjust length of your abstract between 250 and 350 words. There are ' + abstractWords.length + ' words in your abstract.');
        return false;
      }

      // save authors
      if (form.authors.options.length == 0) {
        alert('Please enter at least one author.');
        return false;
      }

      for (var i = 0, authors = []; i < form.authors.options.length; i++) {
        authors.push(dojo.json.evalJson(form.authors.options[i].getAttribute('author')));
      }
    }

    var title = getValue(form.title);
    title = strip_tags(title, '<br><sub><sup><em><i><u><strike>');
    title = title.replace(/&nbsp;/ig, ' ').replace(/\s+/ig, ' ').replace(/^\s+/g,'').replace(/\s+$/g,'');
    setValue(form.title, title);
    setValue(form.authors2, dojo.json.serialize(authors));

    dojo.io.bind ({
      url:      "/modules/tasks/SaveAbstract.php",
      mimetype: "text/plain",
      method:   "POST",
      formNode: form,
      sync:     true,
      error:    function (type, errObj) { alert("[error] saveAbstract\n\n" + errObj.message); },
      load:     function (type, data, evt) {
        if (data.indexOf("__ERROR__") == -1) {
          try {
            eval(data);
          } catch(e) {
            alert("[ERROR] saveAbstract: " + e.description);
            alert(data);
          }
        } else {
          alert("[ERROR] saveAbstract\n\n" + data.replace("__ERROR__", ""));
        }
      }
    });
  } catch (e) {
    alert('[Error] saveAbstract\n\n' + e.description);
  } finally {
    return false;
  }
}

function sendEmail(email) {
  var emailWin = window.open('/manage/email.php?email='+email, 'emailWin', 'width=700,height=600');
}

function showComments(seq) {
  var commentWin = window.open('/review/comment.php?seq='+seq, 'commentWin', 'width=450,height=300');
}

function strip_tags(str,allowed_tags){
  var key='',allowed=false;var matches=[];var allowed_array=[];var allowed_tag='';var i=0;var k='';var html='';var replacer=function(search,replace,str){return str.split(search).join(replace);};if(allowed_tags){allowed_array=allowed_tags.match(/([a-zA-Z]+)/gi);}
  str+='';matches=str.match(/(<\/?[\S][^>]*>)/gi);for(key in matches){if(isNaN(key)){continue;}
  html=matches[key].toString();allowed=false;for(k in allowed_array){allowed_tag=allowed_array[k];i=-1;if(i!=0){i=html.toLowerCase().indexOf('<'+allowed_tag+'>');}
  if(i!=0){i=html.toLowerCase().indexOf('<'+allowed_tag+' ');}
  if(i!=0){i=html.toLowerCase().indexOf('</'+allowed_tag);}
  if(i==0){allowed=true;break;}}
  if(!allowed){str=replacer(html,"",str);}}
  return str;
}

function in_array(needle, haystack) {
  if (typeof haystack != 'object') return false;
  for (var i = 0; i < haystack.length; i++) {
    if (haystack[i] == needle) return true;
  }
  return false;
}

//
// Browser Detection script
// http://www.quirksmode.org/js/detect.html
//
// This returns:
//
// Browser name: BrowserDetect.browser
// Browser version: BrowserDetect.version
// OS name: BrowserDetect.OS
//

var BrowserDetect = {
  init: function () {
    this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
    this.version = this.searchVersion(navigator.userAgent)
      || this.searchVersion(navigator.appVersion)
      || "an unknown version";
    this.OS = this.searchString(this.dataOS) || "an unknown OS";
  },
  searchString: function (data) {
    for (var i=0;i<data.length;i++)  {
      var dataString = data[i].string;
      var dataProp = data[i].prop;
      this.versionSearchString = data[i].versionSearch || data[i].identity;
      if (dataString) {
        if (dataString.indexOf(data[i].subString) != -1)
          return data[i].identity;
      }
      else if (dataProp)
        return data[i].identity;
    }
  },
  searchVersion: function (dataString) {
    var index = dataString.indexOf(this.versionSearchString);
    if (index == -1) return;
    return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
  },
  dataBrowser: [
    {
      string: navigator.userAgent,
      subString: "Chrome",
      identity: "Chrome"
    },
    {   string: navigator.userAgent,
      subString: "OmniWeb",
      versionSearch: "OmniWeb/",
      identity: "OmniWeb"
    },
    {
      string: navigator.vendor,
      subString: "Apple",
      identity: "Safari",
      versionSearch: "Version"
    },
    {
      prop: window.opera,
      identity: "Opera"
    },
    {
      string: navigator.vendor,
      subString: "iCab",
      identity: "iCab"
    },
    {
      string: navigator.vendor,
      subString: "KDE",
      identity: "Konqueror"
    },
    {
      string: navigator.userAgent,
      subString: "Firefox",
      identity: "Firefox"
    },
    {
      string: navigator.vendor,
      subString: "Camino",
      identity: "Camino"
    },
    {    // for newer Netscapes (6+)
      string: navigator.userAgent,
      subString: "Netscape",
      identity: "Netscape"
    },
    {
      string: navigator.userAgent,
      subString: "MSIE",
      identity: "Explorer",
      versionSearch: "MSIE"
    },
    {
      string: navigator.userAgent,
      subString: "Gecko",
      identity: "Mozilla",
      versionSearch: "rv"
    },
    {     // for older Netscapes (4-)
      string: navigator.userAgent,
      subString: "Mozilla",
      identity: "Netscape",
      versionSearch: "Mozilla"
    }
  ],
  dataOS : [
    {
      string: navigator.platform,
      subString: "Win",
      identity: "Windows"
    },
    {
      string: navigator.platform,
      subString: "Mac",
      identity: "Mac"
    },
    {
         string: navigator.userAgent,
         subString: "iPhone",
         identity: "iPhone/iPod"
      },
    {
      string: navigator.platform,
      subString: "Linux",
      identity: "Linux"
    }
  ]

};
BrowserDetect.init();
