/*
Surveylyzer / Carmil 1
(c) 2006-2009
helpers.js
(SHA1 code is copyrighted to others, see the comment near the relevant object)
*/


 
 
 

if ( typeof(window.nssy) == 'undefined' ) { window.nssy= new Object (); };
if ( typeof(window.nssy.hostnameAlternate) == 'undefined' ) { window.nssy.hostnameAlternate= location.hostname; }
if ( typeof(window.nssy.portAlternate) == 'undefined' ) { window.nssy.portAlternate= location.port; }

nssy.setAlternateHost = function (host)
{
this.hostnameAlternate= host;
};

nssy.setAlternatePort = function (port)
{
this.portAlternate= port;
};

nssy.getHostname = function ()
{
var host= location.hostname;
if ( typeof(this.hostnameAlternate) != 'undefined' )
{
host= this.hostnameAlternate;
}
return host;
};

nssy.getPort = function ()
{
var port= location.port;
if ( typeof(this.portAlternate) != 'undefined' )
{
port= this.portAlternate;
}
return port;
}

nssy.getHostPort = function ()
{
var host= nssy.getHostname();
var port= nssy.getPort();
if ((port != "") && (port != 0))
{
host= host + ":" + port;
}
return host;
}

function getHttpCgibin()
{
return "http://" + nssy.getHostPort() + nssy.getScriptsRel("http:");
}

function getHttpsCgibin()
{
return "https://" + nssy.getHostPort() + nssy.getScriptsRel("https:");
}

function getHttpDocs()
{
return "http://" + nssy.getHostPort();
}

function getHttpsDocs()
{
return "https://" + nssy.getHostPort();
}

 

function getCgibin()
{
return (location.protocol == "https:") ? getHttpsCgibin() : getHttpCgibin() ;
}

nssy.getScriptPath= function (base)
{
 
var path= ((location.protocol == "https:") ? "https:" : "http:") + "//" + nssy.getHostPort() + "/surveys/ap_" + base + ".cgi";
return path;
}

function getDocs()
{
return (location.protocol == "https:") ? getHttpsDocs() : getHttpDocs() ;
}


 
 
 

function DebugHelper (identifier)
{
this.idprefix= "";

this.setIdentifier = function (txt)
{
this.idprefix= txt + ": ";
};

this.print = function (msg)
{
if (window.dump)
{
 
window.dump(msg);
}
else if ((window.Debug) && (window.Debug.write))
{
 
window.Debug.write(msg);
}
else if ((window.console) && (window.console.log))
{
 
window.console.log(msg);
}
else
{
var isDebug= false;
try { isDebug= (nssy.getConfigAbbr() == "Hm"); } catch(exc)	{ }
if (isDebug)
{
var node= document.getElementById('idDebugConsole');
if (node == null)
{
node= document.createElement('pre')
node.id= 'idDebugConsole';
node.style.fontSize= "xx-small";
node.style.color= "white";
document.body.appendChild(node);
}
node.appendChild( document.createTextNode(msg));
}
}
};

this.println = function (msg)
{
this.print(msg + "\r\n");
};

this.trace = function (msg)
{
this.println("  " + this.idprefix + msg);
};

this.warn = function (msg)
{
this.println("+ " + this.idprefix + msg);
};

this.error = function (msg)
{
this.println("! " + this.idprefix + msg);
debugger;
};

this.ctor = function (identifier)
{
if (identifier != null)
{
this.setIdentifier(identifier);
}
};
this.ctor(identifier);
}

 

/**
* Sets a Cookie with the given name and value.
*
* name       Name of the cookie
* value      Value of the cookie
* [expires]  Expiration date of the cookie (default: end of current session)
* [path]     Path where the cookie is valid (default: path of calling document)
* [domain]   Domain where the cookie is valid
*              (default: domain of calling document)
* [secure]   Boolean value indicating if the cookie transmission requires a
*              secure transmission
*/
function setCookie(name, value, expires, path, domain, secure)
{
document.cookie= name + "=" + escape(value) +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "; path=/") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}


/**
* Gets the value of the specified cookie.
*
* name  Name of the desired cookie.
*
* Returns a string containing value of specified cookie,
*   or null if cookie does not exist.
*/
function getCookie(name)
{
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1)
{
begin = dc.indexOf(prefix);
if (begin != 0)
return null;
}
else
{
begin += 2;
}
var end = document.cookie.indexOf(";", begin);
if (end == -1)
{
end = dc.length;
}
return unescape(dc.substring(begin + prefix.length, end));
}

/**
* Deletes the specified cookie.
*
* name      name of the cookie
* [path]    path of the cookie (must be same as path used to create cookie)
* [domain]  domain of the cookie (must be same as domain used to create cookie)
*/
function deleteCookie(name, path, domain)
{
if (getCookie(name))
{
document.cookie = name + "=" +
((path) ? "; path=" + path : "; path=/") +
((domain) ? "; domain=" + domain : "") +
"; expires=Thu, 01-Jan-70 00:00:01 GMT";
}
}

function getAndDeleteCookie(name)
{
var cookie= getCookie(name);
deleteCookie(name);
return cookie;
}

/**
* date - any instance of the Date object. Commonly - "new Date()" for current time
*
* returns: the `date` object.
*/
function getExpirationData( date, days, hours, mins )
{
if (0)
{
var base = new Date(0);
var skew = base.getTime();
if (skew > 0)
date.setTime(date.getTime() - skew);
}

 
date.setTime(date.getTime() + (mins * 60000) + (hours * 3600000) + (days * 86400000));
return date;
}

function getCookieMulti(mainkey, subkey)
{
var multistr= getCookie(mainkey);
if (multistr == null)
return null;
var parts= multistr.split('&');
var val= "";
var i= 0;

for ( ; i < parts.length ; ++i )
{
var entry= parts[i].split('=');
if (unescape(entry[0]) == subkey)
{
val= unescape(entry[1]);
break;
}
}

return val;
}

 
 
function setCookieMulti(mainkey, subkey, value, expires, path, domain, secure)
{
var cookieMulti= "";
var isReplaceExisting= false;
var multistr= getCookie(mainkey);
if (multistr != null)
{
var parts= multistr.split('&');
var i= 0;
for ( ; i < parts.length ; ++i )
{
var entry= parts[i].split('=');
if (unescape(entry[0]) == subkey)
{
entry[1]= ((value == null) ? null : escape(value));
isReplaceExisting= true;
}
if (entry[1] != null)
{
if (cookieMulti != "")
{
cookieMulti= cookieMulti + "&";
}
cookieMulti= cookieMulti + entry[0] + "=" + entry[1];
}
}
}
if ((! isReplaceExisting ) && (value != null))
{
if (cookieMulti != "")
{
cookieMulti= cookieMulti + "&";
}
cookieMulti= cookieMulti + escape(subkey) + "=" + escape(value);
}
if (cookieMulti == "")
{
deleteCookie(mainkey, path, domain);
}
else
{
setCookie(mainkey, cookieMulti, expires, path, domain, secure);
}
}

 
 

function saveIePersistenceData(id, storageName, expireMinutes)
{
var ok= false;

var nodeStorage= document.getElementById(id);
if (nodeStorage)
{
try
{
var when = getExpirationData(new Date(), 0, 0, expireMinutes);
nodeStorage.expires= when.toUTCString();
nodeStorage.save(storageName);
ok= true;
}
catch(err)
{
 
alert(err);
}
}

return ok;
}

function loadIePersistenceData(id, storageName)
{
var ok= false;

var nodeStorage= document.getElementById(id);
if (nodeStorage)
{
try
{
nodeStorage.load(storageName);
ok= true;
}
catch(err)
{
 
}
}

return ok;
}

function getIePersistenceData(id, field)
{
var val;
var nodeStorage= document.getElementById(id);
if (nodeStorage)
{
val= nodeStorage.getAttribute(field);
}

return val;
}

function setIePersistenceData(id, field, val)
{
var nodeStorage= document.getElementById(id);
if (nodeStorage)
{
if (val == null)
{
nodeStorage.removeAttribute(field);
}
else
{
nodeStorage.setAttribute(field, val);
}
}
}

 
 

/**
* Returns: error code, or zero if valid
*/
function getEmailValidation (email)
{
if ((email == null) || (email == ""))
return 1;

var returnval= /^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i.test(email);
if (!returnval)
return 2;

 

return 0;
}

/**
* Returns: error code, or zero if valid
*/
function getUrlValidation (url)
{
if ((url == null) || (url == ""))
return 1;

var returnval= /^(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/i.test(url);
if (!returnval)
return 2;

 

return 0;
}

 
function convertErrObjToStr(exc, isVerbose)
{
var str= "Type: " + typeof(exc);
var isKnownType= false;
try	{ if (exc instanceof Error)	{ str= str + "\nName: " + exc.name + "\nMessage: " + exc.message ; isKnownType= true; } } catch(eignore) {}
try	{ if (exc instanceof String) { str= str + "String: " + exc;	isKnownType= true; } } catch(eignore) {}
 
try { if ((typeof(string) != 'undefined') && (exc instanceof string)) { str= str + "string: " + exc; isKnownType= true; } } catch(eignore) {}
if (isVerbose)
{
 
try { if (typeof(exc.fileName) != 'undefined') { str= str + "\nFile: " + exc.fileName; } } catch(eignore) {}
try { if (typeof(exc.lineNumber) != 'undefined') { str= str + "\nLine: " + exc.lineNumber; } } catch(eignore) {}
try { if (typeof(exc.stack) != 'undefined') { str= str + "\nStack: " + exc.stack; } } catch(eignore) {}
}
if (! isKnownType) { try { str= str + "\nTS: " + exc.toString(); } catch(eignore) {} }
return str;
}

 
 
 

function MyNodeConstantsObject ()
{
 
this.ELEMENT_NODE                   = 1;
this.ATTRIBUTE_NODE                 = 2;
this.TEXT_NODE                      = 3;
this.CDATA_SECTION_NODE             = 4;
this.ENTITY_REFERENCE_NODE          = 5;
this.ENTITY_NODE                    = 6;
this.PROCESSING_INSTRUCTION_NODE    = 7;
this.COMMENT_NODE                   = 8;
this.DOCUMENT_NODE                  = 9;
this.DOCUMENT_TYPE_NODE             = 10;
this.DOCUMENT_FRAGMENT_NODE         = 11;
this.NOTATION_NODE                  = 12;
}
MyNodeConstants = new MyNodeConstantsObject ();

 
function removeAllChilds(element)
{
if (element != null)
{
while ( element.hasChildNodes() )
{
element.removeChild( element.lastChild );
}
}
}

 
function removeAllAttributes(element)
{
if (element != null)
{
var attrs= element.attributes;
if (attrs != null)
{
var names= new Array ();
var i= 0;
for ( ; i < attrs.length ; ++i )
{
var anattr= attrs.item(i);
names.push( anattr.nodeName );
}
i= 0;
for ( ; i < names.length ; ++i )
{
element.removeAttribute(names[i]);
}
}
}
}

 
function removeIntermediateNode(node)
{
if ((node == null) || (node == node.ownerDocument.documentElement))
{
return false;
}

var parent= node.parentNode;
while ( node.hasChildNodes() )
{
var achild= node.firstChild;
 
 
parent.appendChild(achild);
}
parent.removeChild(node);

return true;
}

 
function swapSiblingNodes (ids1, ids2)
{
var nodeOption1= document.getElementById(ids1);
var nodeOption2= document.getElementById(ids2);

var parent= nodeOption1.parentNode;

var isSpaw= false;
var nodeNext= nodeOption1.nextSibling;
if (nodeNext != null)
{
if (nodeNext != nodeOption2)
{
try
{
parent.replaceChild( nodeOption1, nodeOption2 );
}
catch(err)
{
throw("Swap (#4AC8) : " + err);
}
parent.insertBefore(nodeOption2, nodeNext);
isSpaw= true;
}
else
{
nodeNext= nodeOption2.nextSibling;
parent.replaceChild( nodeOption2, nodeOption1 );
parent.insertBefore(nodeOption1, nodeNext);
isSpaw= true;
}
}
else
{
nodeNext= nodeOption1.nextSibling;
parent.replaceChild( nodeOption1, nodeOption2 );
parent.insertBefore(nodeOption2, nodeNext);
isSpaw= true;
}
return isSpaw;
}

 
function getElementByAttr(parent, attr, value, deep)
{
var nodeFind= null;
if (parent != null)
{
var children= parent.childNodes;
var i= 0;
for ( ; (i < children.length) && (nodeFind == null); ++i )
{
var achild= children.item(i);
 
if ((achild.nodeType == MyNodeConstants.ELEMENT_NODE) &&
(
(achild.getAttribute(attr) == value) ||
((attr == "class") && (achild.className == value))
)
)
{
nodeFind= achild;
}
else if (deep)
{
nodeFind= getElementByAttr( achild, attr, value, deep );
}
}
}
return nodeFind;
}

 
function getIdentPrefix(depth)
{
var str = "";
var ident= depth;
for ( ; ident > 0; --ident )
{
str = str + "\t";
}
return str;
}

function convertEncodeXmlText(txt)
{
var enc= "";
var i= 0;
for ( ; i < txt.length; ++i )
{
var ch= txt.charAt(i);
var code= txt.charCodeAt(i);
if (ch == "<")
{
enc= enc + "&lt;";
}
else if (ch == ">")
{
enc= enc + "&gt;";
}
else if (ch == "&")
{
enc= enc + "&amp;";
}
else if ((code > 127) || (code < 32))
{
enc= enc + "&#" + code + ";";
}
else
{
enc= enc + ch;
}
}
return enc;
}

function convertXmlToStr0(nodeSource, depth, isIdent)
{
if (nodeSource == null)
return "";

var str= "";

if (nodeSource.nodeName == "#document")
{
str= str + '<?xml version="1.0" ?>' + convertXmlToStr0(nodeSource.documentElement, depth, isIdent);
}
else if (nodeSource.nodeName == "#text")
{
str= str + convertEncodeXmlText(nodeSource.nodeValue);
}
else if (nodeSource.nodeName == "#comment")
{
str= str + "<!-- " + nodeSource.nodeValue + " -->";
}
else if (nodeSource.nodeName == "#cdata-section")
{
str= str + "<![CDATA[" + nodeSource.nodeValue + "]]>";
}
else
{
if (isIdent)
{
str= str + "\n" + getIdentPrefix(depth);
}

str= str + "<" + nodeSource.nodeName;
if ((!nodeSource.hasAttributes) || nodeSource.hasAttributes())
{
var attrs= nodeSource.attributes;
if (attrs != null)
{
var i= 0;
for ( ; i < attrs.length ; ++i )
{
var anattr= attrs.item(i);
if ((anattr.nodeValue != null) && (anattr.nodeValue != ""))
{
str= str + ' ' + anattr.nodeName + '="' + convertEncodeXmlText(anattr.nodeValue) + '"';
}
}
}
}

if (nodeSource.hasChildNodes())
{
str = str + ">";
var children= nodeSource.childNodes;
if (children != null)
{
var i= 0;
for ( ; i < children.length ; ++i )
{
var achild= children.item(i);
str = str + convertXmlToStr0(achild, depth+1, isIdent);
}
}

str = str + "</" + nodeSource.nodeName + ">";
}
else
{
str = str + " />";
}
}

return str;
}

function convertXmlToString(nodeSource)
{
return convertXmlToStr0(nodeSource, 0, true);
}

 
 
function doImportNode(nodeSource, doc, isDeep)
{
var nodeNew= null;
if (nodeSource != null)
{
if (document.importNode)
{
nodeNew= doc.importNode(nodeSource, isDeep);
}
else
{
 

try
{
if (nodeSource.nodeName == "#text")
{
nodeNew= doc.createTextNode(nodeSource.nodeValue);
}
else if (nodeSource.nodeName == "#comment")
{
nodeNew= doc.createComment(nodeSource.nodeValue);
}
else if (nodeSource.nodeName == "#cdata-section")
{
nodeNew= doc.createCDATASection(nodeSource.nodeValue);
}
else
{
nodeNew= doc.createElement(nodeSource.nodeName);
}

if ((!nodeSource.hasAttributes) || nodeSource.hasAttributes())
{
var attrs= nodeSource.attributes;
if (attrs != null)
{
var i= 0;
for ( ; i < attrs.length ; ++i )
{
var anattr= attrs.item(i);
if ((anattr.nodeValue != null) && (anattr.nodeValue != ""))
{
nodeNew.setAttribute( anattr.nodeName, anattr.nodeValue );
}
}
}
}

try
{
nodeNew.nodeValue= nodeSource.nodeValue;
}
catch(err)
{
}


if (isDeep && nodeSource.hasChildNodes())
{
var children= nodeSource.childNodes;
if (children != null)
{
var i= 0;
for ( ; i < children.length ; ++i )
{
var achild= children.item(i);
var nodeNewChild= doImportNode(achild, doc, true);
nodeNew.appendChild(nodeNewChild);
}
}
}
}
catch(err)
{
alert(err.toString() +"\n" + nodeSource.nodeName);
}
}
}
return nodeNew;
}

 
function createEmptyIeDocument()
{
var doc= null;
if (window.ActiveXObject)
{
doc = new ActiveXObject("MSXML2.DOMDocument");
}
return doc;
}

 
function createEmptyDocument()
{
var doc= null;
if ((document.implementation) && (document.implementation.createDocument))
{
 
 
doc= document.implementation.createDocument("","",null);
}
else
{
doc = createEmptyIeDocument ();
}
return doc;
}

 
function createDocumentFromXmlString(xmlstring)
{
var doc= null;
if ((document.implementation) && (document.implementation.createDocument))
{
var parser= new DOMParser ();
 
doc= parser.parseFromString( xmlstring, "text/xml" );
}
else if (window.ActiveXObject)
{
doc = createEmptyIeDocument ();
doc.loadXML( xmlstring );
}
else
{
throw "Browser does not support this";
}

return doc;
}

 
function writeXmlToElement (idElement, xmlElement )
{
var element= document.getElementById( idElement );
if (element != null)
{
removeAllChilds(element);
if ((document.implementation) && (document.implementation.createDocument))
{
var identifyTransform= '	\
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">	\
<xsl:template match="node()|@*"><xsl:copy><xsl:apply-templates select="node()|@*" /></xsl:copy></xsl:template>	\
</xsl:stylesheet>	\
';

var stylesheet= createDocumentFromXmlString(identifyTransform);
var xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet( stylesheet );
 
 
var resultDocument = xsltProcessor.transformToFragment( xmlElement, document );
element.appendChild(resultDocument);
}
else if (window.ActiveXObject)
{
element.innerHTML= xmlElement.xml;
}
else
{
throw "Browser does not support this";
}
}
}

 
function writeXhtmlToElement (idElement, strXhtmlRoot )
{
var element= document.getElementById( idElement );
if (element != null)
{
removeAllChilds(element);

if ((document.implementation) && (document.implementation.createDocument))
{
var strXhtml= strXhtmlRoot.replace(/&nbsp;/g, "<c1_nbsp/>" );
strXhtml= strXhtml.replace(/&copy;/g, "<c1_copy/>" );
strXhtml= strXhtml.replace(/&trade;/g, "<c1_trade/>" );

var doc= createDocumentFromXmlString( strXhtml );

var transform= '	\
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">	\
<xsl:output method="html" />	\
<xsl:template match="c1_nbsp"><xsl:text disable-output-escaping="yes">&#x00A0;</xsl:text></xsl:template>	\
<xsl:template match="c1_copy"><xsl:text disable-output-escaping="yes">&#x00A9;</xsl:text></xsl:template>	\
<xsl:template match="c1_trade"><xsl:text disable-output-escaping="yes">&#x2122;</xsl:text></xsl:template>	\
<xsl:template match="node()|@*"><xsl:copy><xsl:apply-templates select="node()|@*" /></xsl:copy></xsl:template>	\
</xsl:stylesheet>	\
';

var stylesheet= createDocumentFromXmlString(transform);

var xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet( stylesheet );
 
var nodeResult= xsltProcessor.transformToFragment( doc, document );
 
 

element.appendChild(nodeResult);
}
else if (window.ActiveXObject)
{
element.innerHTML= strXhtmlRoot;
}
else
{
throw "Browser does not support this";
}
}
}

 
 

function getXmlHttpObj()
{
 
 
if ( typeof(XMLHttpRequest) != 'undefined' )
{
return new XMLHttpRequest();
}

var arrAX= ['Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.4.0', 'Msxml2.XMLHTTP.3.0', 'Msxml2.XMLHTTP', 'Microsoft.XMLHTTP'];
var i= 0;
for( ; i < arrAX.length ; ++i )
{
try
{
return new ActiveXObject( arrAX[i] );
}
catch (err)
{
 
}
}
return null;
}

 
function XmlDefualtLoaded ()
{
this.onXmlLoaded = function (xmlreq)
{
 
 
}

this.onError = function (xmlreq, err)
{
alert("There was a problem while loading the data.\n.\n" + err);
}
}

function XmlRequest ()
{
this.req= null;
this.callback= null;
this.context= null;

 
this.processChange = function ()
{
if ((this.req) && (this.req.readyState == 4))
{
try
{
var statusCode= -1;
var statusText= "";
try
{
statusCode= this.req.status;
statusText= this.req.statusText;
}
catch (exc1)
{
 
}

if (statusCode == 200)
{
if (this.callback.onXmlLoaded)
{
try
{
this.callback.onXmlLoaded(this);
}
catch (exc)
{
this.callback.onError(this, "Exc5: " + convertErrObjToStr(exc) );
}
}
}
else
{
if (statusCode != -1)
{
if (this.callback.onError)
{
this.callback.onError(this, statusText + " (" + statusCode + ")" );
}
}
}
}
catch (exc)
{
if (this.callback.onError)
{
this.callback.onError(this, "Exc1: " + convertErrObjToStr(exc) );
}
}
}
};

 
this.loadAsync = function (url, callback, context, postdoc)
{
try
{
this.callback= callback;
this.context= context;
var myThis= this;

var method= (postdoc == null) ? "GET" : "POST";

this.req = getXmlHttpObj();
if ( this.req != null )
{
if (this.req.overrideMimeType)
{
this.req.overrideMimeType('text/xml');
}
 
if (this.req.validateOnParse)
{
 
this.req.validateOnParse= false;
}
this.req.onreadystatechange = function () { myThis.processChange(); };
this.req.open(method, url, true);

try
{
if (this.req.setRequestHeader)
{
if (postdoc != null)
{
 
 
this.req.setRequestHeader('Content-Type', 'text/xml; charset=UTF-8');
}
 
}
}
catch (excRH)
{
 
}
this.req.send(postdoc);
}
else
{
if (this.callback.onError)
{
this.callback.onError(this, "Browser does not support AJAX.");
}
}
}
catch (err)
{
if (this.callback.onError)
{
this.callback.onError(this, "Exc2: " + err );
}
}
};
}

 

function XmlIsland ()
{
this.STATUS_ERR= -1;
this.STATUS_UNKNOWN= 0;
this.STATUS_OK= 1;

this.reqxml= new XmlRequest ();
this.reqxsl= new XmlRequest ();
this.idelement= null;

this.xmlstatus= this.STATUS_UNKNOWN;
this.xlsstatus= this.STATUS_UNKNOWN;

this.callback= null;
this.context= null;

 
this.onXmlLoaded = function (xmlreq)
{
 
if (xmlreq.context == 1)
{
this.xmlstatus= this.STATUS_OK;
}
else
{
this.xlsstatus= this.STATUS_OK;
}

if ((this.xmlstatus == this.STATUS_OK) && (this.xlsstatus == this.STATUS_OK))
{
var element= document.getElementById( this.idelement );
while ( element.hasChildNodes() )
{
element.removeChild( element.lastChild );
}

if (document.implementation && document.implementation.createDocument)
{
var xsltProcessor = new XSLTProcessor();
var xsldoc= this.reqxsl.req.responseXML;
var xmldoc= this.reqxml.req.responseXML;
if (xsldoc && xmldoc)
{
xsltProcessor.importStylesheet( xsldoc );
var resultDocument = xsltProcessor.transformToFragment( xmldoc, document );
element.appendChild(resultDocument);

if (this.callback.onXmlLoaded)
{
this.callback.onXmlLoaded(this.reqxml);
}
}
}
else if (window.ActiveXObject)
{
var xml = createEmptyIeDocument ();
var xsl = createEmptyIeDocument ();

xml.loadXML( this.reqxml.req.responseXML.documentElement.xml );
xsl.loadXML( this.reqxsl.req.responseXML.documentElement.xml );

element.innerHTML= xml.transformNode( xsl );

if (this.callback.onXmlLoaded)
{
this.callback.onXmlLoaded(this.reqxml);
}
}
else
{
this.onError(this, "Browser does not support AJAX.");
}
}
};

 
this.onError = function (xmlreq, err)
{
if (this.callback.onError)
{
this.callback.onError(this, err);
}
};

 
this.loadAsync = function (urlxml, urlxsl, idelement, callback, context, postdoc)
{
this.idelement= idelement;
this.callback= callback;
this.context= context;

if (this.callback == null)
{
this.callback= new XmlDefualtLoaded ();
}

this.reqxml.loadAsync( urlxml, this, 1, postdoc );
this.reqxsl.loadAsync( urlxsl, this, 0, null );
};
}

function absolutizeRelativeFilename (anchor, relative)
{
if ((relative == null) || (relative == ""))
{
return anchor;
}
if (	(relative.substr(0, 5) == "http:") ||
(relative.substr(0, 6) == "https:") ||
(relative.substr(0, 4) == "ftp:") ||
(relative.substr(0, 5) == "file:"))
{
return relative;
}

if (relative.charAt(0) == "/")
{
throw "TODO /xxx";
}

var findSlash= anchor.lastIndexOf("/");
if (findSlash < 0)
{
 
return anchor;
}

if (relative.substr(0, 2) == "./")
{
relative= relative.substr(2);
}

return anchor.substr( 0, findSlash ) + "/" + relative;
}


 
function XsltTransformer ()
{
this.nodeTarget= null;
this.xmldoc= null;
this.stylesheetdoc= null;

this.setTarget = function (nodeTarget)
{
this.nodeTarget= nodeTarget;
}

this.setXmlDocument = function (xmldoc)
{
this.xmldoc= xmldoc;
}

this.setStylesheetDocument = function (stylesheetdoc)
{
this.stylesheetdoc= stylesheetdoc;
}

this.absolutizeXsltExternals0 = function (xsltdoc, baseuri, nsprefix, ns)
{
var arrinc= new Array();
arrinc.push("include")
arrinc.push("import")

var wix= 0;
for ( ; wix < arrinc.length; ++wix )
{
var nodesIncluded= null;
if (xsltdoc.getElementsByTagNameNS)
{
nodesIncluded= xsltdoc.getElementsByTagNameNS( ns, arrinc[wix] );
}
else
{
 
nodesIncluded= xsltdoc.getElementsByTagName( nsprefix + ":" + arrinc[wix] );
}

if (nodesIncluded != null)
{
var i= 0;
for ( ; i < nodesIncluded.length ; ++i )
{
var anodeInclude= nodesIncluded.item(i);

var attrname= "href";
var href= null;
var isUseNS= false;
if (anodeInclude.getAttributeNS)
{
href= anodeInclude.getAttributeNS( ns, attrname );
}
isUseNS= ((href != null) && (href != ""))
if (! isUseNS)
{
href= anodeInclude.getAttribute( attrname );
}
var newhref= absolutizeRelativeFilename(baseuri, href);
if (isUseNS)
{
anodeInclude.setAttributeNS( ns, attrname, newhref  );
}
else
{
anodeInclude.setAttribute( attrname, newhref );
}

if (false)
{
if ( typeof(anodeInclude.setAttributeNS) != 'undefined')
{
anodeInclude.setAttributeNS("http://www.w3.org/XML/1998/namespace", "base", baseuri);
}
else
{
anodeInclude.setAttribute("xml:base", baseuri);
}
}
}
}
}
}

this.fixXsltDoc = function (baseuri, nsprefix, ns)
{
if (nsprefix == null)
{
nsprefix= "xsl";
}
if (ns == null)
{
ns= "http://www.w3.org/1999/XSL/Transform";
}

this.absolutizeXsltExternals0(this.stylesheetdoc, baseuri, nsprefix, ns);
if ( typeof(this.stylesheetdoc.resolveExternals) != 'undefined' );
{
 
this.stylesheetdoc.resolveExternals= true;
}
if ( typeof(this.stylesheetdoc.setProperty) != 'undefined' );
{
 
 
try  { this.stylesheetdoc.setProperty("AllowDocumentFunction", true); }	catch(exc) { }

 
try { this.stylesheetdoc.setProperty("MaxElementDepth", 256); }	catch(exc) { }
}

 
};

this.transform = function ()
{
var err= null;

try
{
removeAllChilds(this.nodeTarget);
if (document.implementation && document.implementation.createDocument)
{
var xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet( this.stylesheetdoc );
var result = xsltProcessor.transformToFragment( this.xmldoc, this.nodeTarget.ownerDocument );
this.nodeTarget.appendChild(result);
}
else if (window.ActiveXObject)
{
var xml = null;

if (this.xmldoc.documentElement.xml)
{
xml= this.xmldoc;
}
else
{
 
var tmpxmldoc= createEmptyDocument();
var nodeRoot= doImportNode( this.xmldoc.documentElement, tmpxmldoc, true);
tmpxmldoc.appendChild(nodeRoot);

xml= tmpxmldoc;
 
 
 
}

this.nodeTarget.innerHTML= xml.transformNode( this.stylesheetdoc );
}
else
{
throw "Browser does not support this (#187D)";
}
}
catch (exc)
{
 
err= exc;
}
return err;
}
}

 
function XmlIslandLoadXslt ()
{
this.urlxsl= "";
this.doc= null;
this.reqxsl= new XmlRequest ();
this.element= null;

this.callback= null;
this.context= null;

 
this.onXmlLoaded = function (xmlreq)
{
try
{
var xsltdoc= xmlreq.req.responseXML;

var transformer= new XsltTransformer();
transformer.setTarget(this.element);
transformer.setXmlDocument(this.doc);
transformer.setStylesheetDocument(xsltdoc);
 
var err= transformer.transform();
if (err == null)
{
this.callback.onXmlLoaded(this);
}
else
{
this.onError(this, err);
}
}
catch(exc)
{
this.onError(this, exc );
}
};

 
this.onError = function (xmlreq, err)
{
this.callback.onError(this, err);
};

 
this.loadAsync = function (doc, urlxsl, element, callback, context, postdoc)
{
this.doc= doc;	//// If this is the reply from XMLHttpRequest use `xmlreq.req.responseXML`
this.element= element;
this.callback= callback;
this.context= context;
this.urlxsl= urlxsl;

if (this.callback == null)
{
this.callback= new XmlDefualtLoaded ();
}

this.reqxsl.loadAsync( urlxsl, this, 0, postdoc );
};
}

 
function getDirectChildByTag (node, tag)
{
var nodeFound= null;
if ( node.hasChildNodes() )
{
var children = node.childNodes;
var count    = children.length ;
for ( var a = 0 ; a < count ; ++a )
{
var nodeChild = children.item(a);
if ( nodeChild.nodeType == MyNodeConstants.ELEMENT_NODE )
{
if ( nodeChild.nodeName == tag )
{
nodeFound= nodeChild;
break;
}
}
}
}

return nodeFound;
}

 
function getValidTextOfFirstXmlElement (nodeslist)
{
try
{
 
return nodeslist[0].firstChild.data;
}
catch (err)
{
}
return "";
}

 
function getValidTextOfXmlElement (node)
{
try
{
 
return node.firstChild.nodeValue;
}
catch (err)
{
}
return "";
}

 
function setTextInElelemt(element, text)
{
if (element != null)
{
removeAllChilds(element);
if (text != null)
{
element.appendChild( element.ownerDocument.createTextNode(text) );
}
}
}

function setTextInElelemtById(idElement, text)
{
var element= document.getElementById(idElement);
setTextInElelemt(element, text);
}

 
function isBrowserIE6()
{
return (navigator.userAgent.search( /MSIE 6./ ) >= 0);
}

 
function forceRerenderSelectsForIE6(nodeParent)
{
if ( isBrowserIE6() )
{
 
var nodesSelect= nodeParent.getElementsByTagName("SELECT");
if ((nodesSelect != null) && (nodesSelect.length > 0))
{
var i= 0;
for ( ; i < nodesSelect.length ; ++i )
{
var nodeSelect= nodesSelect.item(i);
var displayOld= nodeSelect.style.display;
if (displayOld != "none")
{
nodeSelect.style.display= "none";
nodeSelect.style.display= displayOld;
}
}
}
}
}

 
function addClassNameToNode(node, classname)
{
if (node == null)
return;

 
var pos= node.className.indexOf(classname);
if (pos < 0)
{
node.className= node.className + " " + classname;
}
forceRerenderSelectsForIE6(node);
}

function removeClassNameFromNode(node, classname)
{
if (node == null)
return;

 
var pos= node.className.indexOf(classname);
if (pos >= 0)
{
node.className= node.className.substr(0, pos) + node.className.substr(pos + classname.length);
}
forceRerenderSelectsForIE6(node);
}

 
function getInnerWidth()
{
var v= 0;
if (window.innerWidth)
{
v= window.innerWidth;
}
else
{
var iebody= (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body ;
if (iebody.clientWidth)
{
v= iebody.clientWidth;
}
}
return parseInt(v);
}

function getInnerHeight()
{
var v= 0;
if (window.innerHeight)
{
v= window.innerHeight;
}
else
{
var iebody= (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body ;
if (iebody.clientHeight)
{
v= iebody.clientHeight;
}
}
return parseInt(v);
}

 
function getPageXOffset()
{
var v= 0;
if (window.pageXOffset)
{
v= window.pageXOffset;
}
else
{
var iebody= (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body ;
if (iebody.scrollLeft)
{
v= iebody.scrollLeft;
}
}
return parseInt(v);
}

function getPageYOffset()
{
var v= 0;
if (window.pageYOffset)
{
v= window.pageYOffset;
}
else
{
var iebody= (document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body ;
if (iebody.scrollTop)
{
v= iebody.scrollTop;
}
}
return parseInt(v);
}


 
 
function buildXmlFromForm (form, nodeRoot)
{
if (nodeRoot == null)
{
throw 'assert';
}

var doc= nodeRoot.ownerDocument;
var childs= form.childNodes;
var i;

var isAddParam= false;
for (i=0; i < childs.length; ++i)
{
var achild= childs.item(i);
isAddParam=
(
( achild.tagName == "INPUT" ) &&
(
(achild.type == "text") ||
(achild.type == "password") ||
(achild.type == "hidden") ||
((achild.type == "radio") && (achild.checked)) ||
((achild.type == "checkbox") && (achild.checked))
)
) ||
( achild.tagName == "SELECT" ) ||
( achild.tagName == "TEXTAREA" );
if (isAddParam)
{
var node= doc.createElement(achild.name);
var text= doc.createTextNode(achild.value);
node.appendChild(text);
nodeRoot.appendChild(node);
}
buildXmlFromForm(achild, nodeRoot);
}
}

 
 
 
function getFromQueryString (form)
{
var childs= form.childNodes;
var i;
var querystr= "";
var isAddParam= false;
for (i=0; i < childs.length; ++i)
{
var achild= childs.item(i);
isAddParam=
(
( achild.tagName == "INPUT" ) &&
(
(achild.type == "text") ||
(achild.type == "password") ||
(achild.type == "hidden") ||
((achild.type == "radio") && (achild.checked)) ||
((achild.type == "checkbox") && (achild.checked))
)
) ||
( achild.tagName == "SELECT" );
if (isAddParam)
{
querystr=
querystr + ( querystr.length != 0 ? "&" : "" ) +
encodeURIComponent(achild.name) + "=" + encodeURIComponent(achild.value) ;
}
var subqs= getFromQueryString( achild );
if (subqs.length > 0)
{
querystr= querystr + ( querystr.length != 0 ? "&" : "" ) + subqs;
}
}
return querystr;
}

 
function getUtf8BytesString(unicodestr)
{
var str= "";
var encoded= encodeURIComponent(unicodestr);

var i= 0;
for ( ; i < encoded.length; ++i)
{
var ch= encoded.charAt(i);
if (ch == "%")
{
var codehex= encoded.substr(i+1, 2);
var val= parseInt(codehex, 16);
str += String.fromCharCode(val);
i += 2;
}
else
{
str += ch;
}
}

return str;
}

 
function getLangsFromBrowser ()
{
var langs= new Array();
 
if (window.navigator.language)
{
langs.push( window.navigator.language );
}
 
if (window.navigator.userLanguage)
{
langs.push( window.navigator.userLanguage );
}
if (window.navigator.browserLanguage)
{
langs.push( window.navigator.browserLanguage );
}
if (window.navigator.systemLanguage)
{
langs.push( window.navigator.systemLanguage );
}
return langs;
}

 
function setDocumentBasePath(doc, basepath)
{
var nodeHead= null;
var heads= doc.documentElement.getElementsByTagName("head");
if (heads.length == 0)
{
nodeHead= doc.createElement("head");
doc.documentElement.appendChild(nodeHead);
}
else
{
nodeHead= heads.item(0);
}

var nodeBase= null;
var bases= nodeHead.getElementsByTagName("base");
if (bases.length == 0)
{
nodeBase= doc.createElement("base");
nodeHead.appendChild(nodeBase);
}
else
{
nodeBase= bases.item(0);
}
nodeBase.href= basepath;
}

 
function getDocumentBasePath(doc)
{
var nodeHead= doc.getElementsByTagName('head').item(0);
var bases= nodeHead.getElementsByTagName("base");
var base;
if (bases.length == 0)
{
base= window.self.location;
}
else
{
base= bases.item(0).href;
}
return base;
}

 
function isNonEmptyString(str)
{
if (str == null)
{
return false;
}

var val;
if (str instanceof String)
{
val= str;
}
else
{
val= str.toString();
}

if (val == null)
{
return false;
}

if (val.length == 0)
{
return false;
}

return true;
}

 
function getValidString(str)
{
if (str != null)
{
return str;
}
return "";
}

 
 
 

/*
form - DOM Element represeting the form.
visible - boolean. `true` for show, `false` for hide

This is actually a workarround to a bug in IE(6?) and Opera(8?) where z-index of some form-controls is always in priority to other elements
See: http://support.microsoft.com/kb/177378
*/
function setFormElementsVisibility (form, isVisible)
{
if (form != null)
{
var childs= form.childNodes;
var i;
for (i=0; i < childs.length; ++i)
{
var achild= childs.item(i);
var isSetVisibilityNeeded= ( achild.tagName == "SELECT" );
if (isSetVisibilityNeeded)
{
achild.style.visibility= isVisible ? "visible" : "hidden";
}
setFormElementsVisibility( achild, isVisible );
}
}
}

 
function hideToolTip (id)
{
var tooltipOBJ = document.getElementById(id);
tooltipOBJ.style.visibility = "hidden";
}

 
function showToolTip ( id, event )
{
var x,y;
if (self.pageYOffset)
{
 
x = self.pageXOffset;
y = self.pageYOffset;
}
else if (document.documentElement && document.documentElement.scrollTop)
{
 
x = document.documentElement.scrollLeft;
y = document.documentElement.scrollTop;
}
else if (document.body)
{
 
x = document.body.scrollLeft;
y = document.body.scrollTop;
}

var tooltipOBJ = document.getElementById(id);
tooltipOBJ.style.left = (event.clientX + x) + "px";
tooltipOBJ.style.top = (event.clientY + y) + "px";
tooltipOBJ.style.visibility = "visible";
}

 
function openGlossary(url)
{
 
var winref= window.open(url, "ap_glossary", "left=10,top=10,width=500,height=400,directories=no,location=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes");
winref.focus();
return false;
}

 
function filterGlossaries()
{
var splits= /^(.+[#])([a-zA-Z0-9]+)$/.exec(document.location);
var idGlos= splits[2];

var parent= document.getElementById("idGlossaries");
if (parent != null)
{
var childs= parent.childNodes;
var i= 0;
for ( ; i < childs.length; ++i)
{
var achild= childs.item(i);
if (achild.className == "clsGlossary")
{
achild.style.display= ( achild.id == idGlos ? "block" : "none" );
}
}
window.self.scrollTo(0,0);
}
}

 
function isBlockedTag (tagname)
{
 
var isBlocked=
( (tagname == "DIV") || (tagname == "P") || (tagname == "FORM") || (tagname == "PRE")
|| (tagname == "FIELDSET") || (tagname == "HR") || (tagname == "UL")
|| (tagname == "H1") || (tagname == "H2") || (tagname == "H3")
|| (tagname == "H4") || (tagname == "H5") || (tagname == "H6")
|| (tagname == "OPTION")
)
return isBlocked;
}

 
function showHtmlNode(node, flag)
{
if (node != null)
{
var isBlocked= isBlockedTag(node.tagName);
if ( isBlocked )
{
node.style.display= flag ? "block" : "none";
/*
var curval= node.style.display;
if (flag && (curval != "block"))
{
node.style.display= "block";
}
else if ((!flag) && (curval != "none"))
{
node.style.display= "none";
}
*/
}
else
{
node.style.display= flag ? "inline" : "none";
/*
var curval= node.style.display;
if (flag && (curval != "inline"))
{
node.style.display= "inline";
}
else if ((!flag) && (curval != "none"))
{
node.style.display= "none";
}
*/
}
 
}
}

 
function showHtmlElement(idElement, flag)
{
var node = document.getElementById(idElement);
showHtmlNode(node, flag);
}

 
function enableHtmlElement(idElement, flag)
{
var node = document.getElementById(idElement);
if (node != null)
{
try
{
node.disabled= !flag;
}
catch(exc)
{
 
}
}
}

nssy.scrollToAnchor = function (nameAnchor)
{
var nodeTarget= document.anchors.namedItem(nameAnchor);
if (nodeTarget == null)
{
return;
}
 
try { nodeTarget.focus(); }	catch(exc) { }
if (nodeTarget.scrollIntoView)
{
nodeTarget.scrollIntoView(true);
}
};


 
 
 
function PopupDivDialog (nodePopup)
{
this.TIMEOUT_MILLISEC= 700;
this.nodePopup= nodePopup;
 
this.nodeLowZIndex= document.body;
this.timer= null;

this.fixIE6LackPositionFixed0 = function ()
{
this.nodePopup.style.top= getPageYOffset() + "px";
this.nodePopup.style.left= 0;
this.nodePopup.style.width= getInnerWidth() + "px";
this.nodePopup.style.height= getInnerHeight() + "px";

var that= this;
this.timer= setTimeout(function(){that.fixIE6LackPositionFixed0();}, this.TIMEOUT_MILLISEC);
};

this.show = function ()
{
if (isBrowserIE6())
{
if (this.nodePopup.parentNode != document.body)
{
/* IE6 does not support position:fixed so we use position:absolute relative to body */
this.nodePopup.parentNode.removeChild(this.nodePopup);
document.body.appendChild(this.nodePopup);
}
this.nodePopup.style.position= "absolute";
this.fixIE6LackPositionFixed0();

/* Workarrount to MS-KB177378 */
addClassNameToNode(this.nodeLowZIndex, "clsSyLowZIndexForm");
}
this.nodePopup.style.display= "block";
};

this.hide = function ()
{
this.nodePopup.style.display= "none";
if (isBrowserIE6())
{
clearTimeout(this.timer);
this.timer= null;
removeClassNameFromNode(this.nodeLowZIndex, "clsSyLowZIndexForm");
}
};

this.release= function ()
{
window.g_popupdialogs[this.ix]= null;
};
}


nssy.PopupGeneric = function ()
{
this.init = function (id, nodeForm)
{
var nodePop= document.getElementById(id);
if (nodePop == null)
{
nodePop= document.createElement("DIV");
nodePop.id= id;
nodePop.className= "clsPopup";
document.body.appendChild(nodePop);
}
removeAllChilds(nodePop);
var nodeContent= document.createElement("DIV");
nodeContent.className= "clsPopupContent";
nodePop.appendChild(nodeContent);
{
var nodeBG= document.createElement("DIV");
nodeBG.className= "clsPopupBackground";
 
nodeBG.appendChild( document.createTextNode("\u00A0") );
nodePop.appendChild(nodeBG);
}
nodeContent.appendChild(nodeForm);
return nodePop;
};
};

nssy.PopupStdDialog = function (msg, inp, buttons, lang, urlImg)
{
this.generic= new nssy.PopupGeneric();
var isRTL= ((lang == "ar") || (lang == "he"));

var nodeForm= document.createElement("FORM");
nodeForm.action="javascript: void(0);";
nodeForm.className="clsPopupForm";
nodeForm.style.padding= "1em";
nodeForm.style.direction= isRTL ? "rtl" : "ltr";
nodeForm.dir= isRTL ? "rtl" : "ltr";

var nodeTbl= document.createElement("TABLE");
nodeForm.appendChild(nodeTbl);
var nodeTBody= document.createElement("TBODY");
nodeTbl.appendChild(nodeTBody);
var nodeTr= document.createElement("TR");
nodeTBody.appendChild(nodeTr);

if ((urlImg != null) && (urlImg != ""))
{
var nodeTd= document.createElement("TD");
nodeTr.appendChild(nodeTd);
var nodeImg= document.createElement("IMG");
nodeImg.alt= "";
nodeImg.src= urlImg;
nodeTd.appendChild(nodeImg);
nodeTd.style.verticalAlign= "top";
}

var nodeTd= document.createElement("TD");
nodeTr.appendChild(nodeTd);
var nodeMessage= document.createElement("DIV");
nodeTd.appendChild(nodeMessage);

var lines= msg.split("\n");
var maxLineLen= 0;
var ln= 0;
for ( ; ln < lines.length; ++ln )
{
if (ln > 0)
{
nodeMessage.appendChild( document.createElement("BR") );
}
nodeMessage.appendChild( document.createTextNode(lines[ln]) );
if (lines[ln].length > maxLineLen)
{
maxLineLen= lines[ln].length;
}
}
nodeForm.appendChild(nodeTbl);
nodeMessage.style.marginBottom= "1em";
nodeMessage.style.textAlign= isRTL ? "right" : "left" ;
 
 

 
var minWidth= Math.max(10, Math.round(maxLineLen * 0.5));
nodeForm.style.width= minWidth + "em";

if (inp != null)
{
var nodeInputPane= document.createElement("DIV");
nodeInputPane.appendChild(inp);
nodeInputPane.style.marginBottom= "1em";
nodeForm.appendChild(nodeInputPane);
}

var nodeButtonsPane= document.createElement("DIV");
nodeButtonsPane.style.textAlign= "center";
 

var id= "idSyPopupAlert";
var nodePop= this.generic.init(id, nodeForm);
this.popup= new PopupDivDialog(nodePop);
var that= this;

var nodeBtnDef= null;
var bix= 0;
for ( ; bix < buttons.length; ++bix )
{
var btn= buttons[bix];

var nodeBtn= document.createElement("INPUT");
nodeBtn.type= "button";
nodeBtn.value= btn.label;
nodeBtn.mycallback= btn.callback;
nodeBtn.onclick= function(){ that.popup.hide(); if (this.mycallback) { this.mycallback(); } };
nodeBtn.style.marginLeft= "0.3em";
nodeBtn.style.marginRight= "0.3em";

nodeButtonsPane.appendChild(nodeBtn);
if (btn.def)
{
nodeBtnDef= nodeBtn;
}
}
nodeForm.appendChild(nodeButtonsPane);

this.popup.show();
if (nodeBtnDef)
{
nodeBtnDef.focus();
}
}

nssy.PopupAlert = function ()
{
this.strtbl= null;
this.message= "";
this.callback= null;
this.lang= "";
this.urlImg= getDocs() + "/polls/images/mb_information.png";

this.setMessage = function (msg) { this.message= msg; };
this.setCallback = function (func) { this.callback= func; };
this.setLang = function (lang) { this.lang= lang; };
this.setImage = function (url) { this.urlImg= url; };

this.go = function ()
{
this.strtbl= new StringTable (getDocs() + "/polls/xml/strtbl_en.xml", "general", this.lang);

if (this.callback == null)
{
this.callback= function(alerter){};
}
var that= this;
var buttons= new Array();
var btn= new Object ()
btn.label= this.strtbl.get("idBtnOk");
btn.callback= function() { that.callback(that); };
btn.def= true;
buttons.push(btn);
nssy.PopupStdDialog(this.message, null, buttons, this.lang, this.urlImg);
};

this.alert = function (msg, lang, func)
{
this.setMessage(msg);
this.setCallback(func);
this.setLang(lang);
this.go();
};
};

nssy.PopupConfirm = function ()
{
this.strtbl= null;
this.message= "";
this.callback= null;
this.lang= "";
this.urlImg= getDocs() + "/polls/images/mb_question.png";

this.setMessage = function (msg) { this.message= msg; };
this.setCallback = function (func) { this.callback= func; };
this.setLang = function (lang) { this.lang= lang; };
this.setImage = function (url) { this.urlImg= url; };

this.go = function ()
{
this.strtbl= new StringTable (getDocs() + "/polls/xml/strtbl_en.xml", "general", this.lang);

if (this.callback == null)
{
this.callback= function(flag,confirmer){};
}
var that= this;
var buttons= new Array();
{
var btn= new Object ()
btn.label= this.strtbl.get("idBtnOk");;
btn.callback= function() { that.callback(true, that); };
btn.def= true;
buttons.push(btn);
}
{
var btn= new Object ()
btn.label= this.strtbl.get("idBtnCancel");;
btn.callback= function() { that.callback(false, that); };
btn.def= false;
buttons.push(btn);
}
nssy.PopupStdDialog( this.message, null, buttons, this.lang, this.urlImg);
};
this.confirm = function (msg, lang, func)
{
this.setMessage(msg);
this.setCallback(func);
this.setLang(lang);
this.go();
};
};

nssy.PopupPrompt = function ()
{
this.strtbl= null;
this.message= "";
this.defVal= "";
this.callback= null;
this.lang= "";
this.urlImg= getDocs() + "/polls/images/mb_question.png";

this.setMessage = function (msg) { this.message= msg; };
this.setDefaultValue = function (val) { this.defVal= val; };
this.setCallback = function (func) { this.callback= func; };
this.setLang = function (lang) { this.lang= lang; };
this.setImage = function (url) { this.urlImg= url; };

this.go = function ()
{
this.strtbl= new StringTable (getDocs() + "/polls/xml/strtbl_en.xml", "general", this.lang);

var nodeInput= document.createElement("INPUT");
nodeInput.type= "text";
nodeInput.value= this.defVal;
nodeInput.style.width= "100%";

if (this.callback == null)
{
this.callback= function(val,prompter){};
}
var buttons= new Array();
var that= this;
{
var btn= new Object ()
btn.label= this.strtbl.get("idBtnOk");
btn.callback= function() { that.callback(nodeInput.value, that); };
btn.def= true;
buttons.push(btn);
}
{
var btn= new Object ()
btn.label= this.strtbl.get("idBtnCancel");
btn.callback= function() { that.callback(null, that); };
btn.def= false;
buttons.push(btn);
}
nssy.PopupStdDialog( this.message, nodeInput, buttons, this.lang, this.urlImg);
 
};
this.prompt = function (msg, defVal, lang, func)
{
this.setMessage(msg);
this.setDefaultValue(defVal);
this.setCallback(func);
this.setLang(lang);
this.go();
};
};


 
 

function AssociativeArray ()
{
this.length = 0;
this.items = new Array();

this.remove = function(key)
{
var tmp_value;
if (typeof(this.items[key]) != 'undefined')
{
this.length--;
var tmp_value = this.items[key];
delete this.items[key];
}

return tmp_value;
};

this.get = function(key)
{
return this.items[key];
};

this.put = function()
{
if (arguments.length % 2 != 0)
{
throw "Expecting an even number of arguments.";
}
for (var i = 0; i < arguments.length; i += 2)
{
if (typeof(arguments[i + 1]) == 'undefined')
{
this.remove(arguments[i]);
}
else
{
this.items[arguments[i]] = arguments[i + 1];
this.length++;
}
}
};

this.exists = function(key)
{
return typeof(this.items[key]) != 'undefined';
};
}

 
 
 

 
window.g_limitersInput= new Array();
 
window.g_limitersTimer= null;
window.LIMITERS_TIMEOUT_MILLISEC= 3000;

function TextInputLimiterDefaultCallback (strtbl)
{
this.strtbl= strtbl;

this.setNodeStyle= function (nodeInput, nodeMsg, isExceed)
{
if (isExceed)
{
 
 
nodeInput.style.color= "gray";
nodeMsg.style.color= "red";
 
}
else
{
 
nodeInput.style.color= "black";
nodeMsg.style.color= "black";
 
}
};

this.getMessageText= function (isExceed, numChurs)
{
var msg;
if (isExceed)
{
if (this.strtbl != null)
{
msg= this.strtbl.format("idTxtInpLmtExceed", numChurs);
}
else
{
msg= "Text exceed the allowed length by " + numChurs + " characters.";
}
}
else
{
if (this.strtbl != null)
{
msg= this.strtbl.format("idTxtInpLmtRemain", numChurs);
}
else
{
msg= "Characters remaining: " + numChurs;
}
}
return msg;
};
}

window.OnTimerTextInputLimiter = function ()
{
 
var i= 0;
for ( ; i < window.g_limitersInput.length; ++i )
{
var limiter= window.g_limitersInput[i];
if (limiter != null)
{
limiter.onTimer();
}
}
window.g_limitersTimer= setTimeout( "window.OnTimerTextInputLimiter ();", window.LIMITERS_TIMEOUT_MILLISEC);
}

function TextInputLimiter (idInput, idMsg, maxChars, callback, strtbl)
{
this.idInput= idInput;
this.idMsg= idMsg;
this.nodeInput= document.getElementById(this.idInput);
this.nodeMsg= document.getElementById(this.idMsg);
this.maxChars= maxChars;
this.callback= callback;

this.ix= window.g_limitersInput.length;
window.g_limitersInput.push( this );

if (this.callback == null)
{
this.callback= new TextInputLimiterDefaultCallback (strtbl);
}

 

 
 
if (this.ix == 0)
{
 
window.g_limitersTimer= setTimeout( "window.OnTimerTextInputLimiter ();", window.LIMITERS_TIMEOUT_MILLISEC);
};


this.onTimer= function ()
{
 
if (this.nodeInput != null)
{
if (
(this.nodeInput.tagName == "TEXTAREA") ||
(
(this.nodeInput.tagName == "INPUT") &&
((this.nodeInput.type == "text") || (this.nodeInput.type == "password"))
)
)
{
var len= this.nodeInput.value.length;
var delta= this.maxChars - len ;
if (delta < 0)
{
this.callback.setNodeStyle(this.nodeInput, this.nodeMsg, true);
this.setMsg0( this.nodeMsg, this.callback.getMessageText(true, -delta) );
}
else
{
this.callback.setNodeStyle(this.nodeInput, this.nodeMsg, false);
this.setMsg0( this.nodeMsg, this.callback.getMessageText(false, delta) );
}
}

 
}
};

this.setMsg0= function (nodeMsg, msg)
{
if (nodeMsg != null)
{
while ( nodeMsg.hasChildNodes() )
{
nodeMsg.removeChild( nodeMsg.lastChild );
}
nodeMsg.appendChild( document.createTextNode(msg) );
}
};

this.release= function ()
{
 
window.g_limitersInput[this.ix]= null;
 
};

}

 
function trimWhiteSpaces(str)
{
if (str == null)
return "";

var WHITESPACES= " \t\n\r";

var str2= str;
while ((str2.length > 0) && (WHITESPACES.indexOf(str2.charAt(0)) >= 0))
{
str2= str2.substr(1, str2.length-1);
}
while ((str2.length > 0) && (WHITESPACES.indexOf(str2.charAt(str2.length-1)) >= 0))
{
str2= str2.substr(0, str2.length-1);
}
return str2;
}

 
function findElementInArray(arr, el)
{
var pos= -1;

if (arr != null)
{
var i= 0;
for ( ; (i< arr.length); ++i)
{
if ( arr[i] == el )
{
pos= i;
break;
}
}
}
return pos;
}

 
function getQueryStringParam (param, defVal)
{
var pattern="^(.+[?])(.*[&])*(" + param + "[=])([A-Za-z0-9\.\,\%\_\@\+-]+)([&#].*)?$";
var regex= new RegExp(pattern);
var val= regex.exec( document.location );
if (val == null)
{
return defVal;
}
return decodeURIComponent( val[4] );
};

 
function appendQsParam (url, param, val)
{
var delim= "&";
var pos= url.indexOf("?", 0);
if (pos < 0)
{
delim= "?";
}
return url + delim + encodeURIComponent(param) + "=" +
((val == null) ? "" : encodeURIComponent(val));
};

 
function MapIdsDoc (doc, isCache)
{
this.doc= doc;
this.isCache= isCache;
this.map= new Object();

this.getElementById= function(id)
{
var node= null;
if (isCache)
{
node= this.map[id];
if (node == null)
{
node= this.doc.getElementById(id);
this.map[id]= node;
}
}
else
{
node= this.doc.getElementById(id);
}
return node;
};

this.assignNewDoc= function(doc)
{
this.doc= doc;
this.map= new Object();
};

this.flushAll= function()
{
 
this.map= new Object();
};
};

function Digest ()
{
/* This code is an object-oriented version of Chris Veness code. */
/* From his website: "... See below for the source code of the JavaScript implementation. You are welcome to re-use these scripts [without any warranty express or implied] provided you retain my copyright notice and when possible a link to my website. If you have any queries or find any problems, please contact me." */
/* (c) 2002-2005 Chris Veness */
/* http://www.movable-type.co.uk/scripts/SHA-1.html */

this.sha1= function (msg)
{
 
var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];

 

msg += String.fromCharCode(0x80); // add trailing '1' bit to string [5.1.1]

 
var l = Math.ceil(msg.length/4) + 2;  // long enough to contain msg plus 2-word length
var N = Math.ceil(l/16);              // in N 16-int blocks
var M = new Array(N);
for (var i=0; i<N; i++) {
M[i] = new Array(16);
for (var j=0; j<16; j++) {  // encode 4 chars per integer, big-endian encoding
M[i][j] = (msg.charCodeAt(i*64+j*4)<<24) | (msg.charCodeAt(i*64+j*4+1)<<16) |
(msg.charCodeAt(i*64+j*4+2)<<8) | (msg.charCodeAt(i*64+j*4+3));
}
}
 
M[N-1][14] = ((msg.length-1) >>> 30) * 8;
M[N-1][15] = ((msg.length-1)*8) & 0xffffffff;

 
var H0 = 0x67452301;
var H1 = 0xefcdab89;
var H2 = 0x98badcfe;
var H3 = 0x10325476;
var H4 = 0xc3d2e1f0;

 

var W = new Array(80); var a, b, c, d, e;
for (var i=0; i<N; i++) {

 
for (var t=0;  t<16; t++) W[t] = M[i][t];
for (var t=16; t<80; t++) W[t] = this.ROTL(W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16], 1);

 
a = H0; b = H1; c = H2; d = H3; e = H4;

 
for (var t=0; t<80; t++) {
var s = Math.floor(t/20); // seq for blocks of 'f' functions and 'K' constants
var T = (this.ROTL(a,5) + this.f(s,b,c,d) + e + K[s] + W[t]) & 0xffffffff;
e = d;
d = c;
c = this.ROTL(b, 30);
b = a;
a = T;
}

 
H0 = (H0+a) & 0xffffffff;  // note 'addition modulo 2^32'
H1 = (H1+b) & 0xffffffff;
H2 = (H2+c) & 0xffffffff;
H3 = (H3+d) & 0xffffffff;
H4 = (H4+e) & 0xffffffff;
}

return this.toHexStr(H0) + this.toHexStr(H1) + this.toHexStr(H2) + this.toHexStr(H3) + this.toHexStr(H4);
};

 
 
 
this.f = function (s, x, y, z)
{
switch (s) {
case 0: return (x & y) ^ (~x & z);
case 1: return x ^ y ^ z;
case 2: return (x & y) ^ (x & z) ^ (y & z);
case 3: return x ^ y ^ z;
}
};

 
 
 
this.ROTL = function (x, n)
{
return (x<<n) | (x>>>(32-n));
}

 
 
 
 
 
this.toHexStr = function(num)
{
var s="", v;
for (var i=7; i>=0; i--) { v = (num>>>(i*4)) & 0xf; s += v.toString(16); }
return s;
};

};

function sha1Hash(msg)
{
var d= new Digest();
var h= d.sha1(msg);
 
return h;
};


 
 
 

if ( typeof(window.nssy) == 'undefined' ) { window.nssy= new Object (); };
if ( typeof(window.nssy.flagUseAjaxProxy) == 'undefined' ) { window.nssy.flagUseAjaxProxy= false; }

nssy.setUseAjaxProxy = function ( flag )
{
this.flagUseAjaxProxy= flag;
};

nssy.isUseAjaxProxy = function ()
{
var flag= false;
if ( typeof(this.flagUseAjaxProxy) != 'undefined' )
{
flag= this.flagUseAjaxProxy;
}

return flag;
}

nssy.MyXmlRequest = function ()
{
this.QUANTUM= 500;
this.mydebugger= new DebugHelper("MyXmlRequest");
this.callback= null;
this.context= null;
this.proxyurl= null;
this.postdata= "";
this.cookie= "";

this.getNodePreferHead = function ()
{
var node= null
var heads = document.getElementsByTagName('head');
if (heads && (heads.length > 0))
{
node= heads[0];
}
else
{
node= document.body;
}
return node;
}

this.proxyPartialData = function ()
{
var more= (this.postdata.length > this.QUANTUM);
var partdata;
if (more)
{
partdata= this.postdata.substr(0, this.QUANTUM);
this.postdata= this.postdata.substr(this.QUANTUM);
}
else
{
partdata= this.postdata;
this.postdata= "";
}
this.mydebugger.trace( "More:" + more + " Q:" + partdata.length + " L:" + this.postdata.length );

var that= this;
var url= this.proxyurl + "&more=" + (more ? "1" : "0") + "&cookie=" + this.cookie + "&data=" + encodeURIComponent( partdata );
nssy.onXmlProxyLoad= function(ok, docxml, err, nextcookie)
{
that.mydebugger.trace("onXmlProxyLoad: OK:" + ok + " Err:" + err + " Cookie:" + nextcookie);
if (ok)
{
if (nextcookie == "")
{
if (that.postdata.length > 0)
{
throw "assert (extra data) 66D0";
}
that.req= new Object();
that.req.readyState= 4;
that.req.status= 200;
that.req.statusText= "OK";
that.req.responseXML= docxml;

that.callback.onXmlLoaded(that);
}
else
{
if (that.postdata.length == 0)
{
throw "assert (missing data) 66D1";
}
that.cookie= nextcookie;
that.proxyPartialData();
}
}
else
{
that.callback.onError(that, err);
}
};
 

var nodeJS= document.createElement("SCRIPT");
nodeJS.setAttribute("src", url);
nodeJS.setAttribute("type", "text/javascript");

this.getNodePreferHead().appendChild(nodeJS);
};


this.loadAsync = function (url, callback, context, postdoc)
{
this.callback= callback;
this.context= context;
if (nssy.isUseAjaxProxy())
{
var basepath= "";
var script= url;
var posLastSlash= url.lastIndexOf("/");
if (posLastSlash >= 0)
{
basepath= url.substr(0, posLastSlash);
script= url.substr(posLastSlash + 1);
}
this.proxyurl= basepath + '/ap_xml2js_proxy.pl?script=' + encodeURIComponent( script );

this.postdata= "";
if (postdoc != null)
{
try
{
this.postdata= convertXmlToString(postdoc);
}
catch(exc)
{
this.mydebugger.warn(convertErrObjToStr(exc));
}
}

this.proxyPartialData();
}
else
{
 
var areq= new XmlRequest();
areq.loadAsync(url, callback, context, postdoc);
}
};
};

function getServiceName ()
{
return "Surveylyzer";
}

window.g_cookiesMulti= new Array(
"ap_id", "ap_nick", "ap_gender",
"ap_birthyear", "ap_birthmonth", "ap_birthmonday",
"ap_anon_age", "ap_anon_gender", "ap_manager", "ap_prt_when",
"ap_lang", "ap_serverctime", "ap_diffctime"
).sort();
window.g_cookiesMultiSec= new Array("ap_session", "ap_challenge", "ap_prt_poll", "ap_prt_pwd").sort();
window.g_cookiesMultiPersistent= new Array("ap_nick_remember").sort();
window.g_cookiesNormalPersistentShort= new Array("ap_refcode", "ap_refcode_flw").sort();
window.g_cookiesPassthrough= new Array(
"ap_recent_poll_type", "ap_recent_poll", "ap_recent_member_id", "ap_recent_member_nick",
"ap_email_reg", "ap_restricted_page", "ap_subject", "ap_recent_mode", "ap_cookie"
);
window.g_cookiesVotesAnonymous= new Array("ap_votes_anonymous").sort();
window.g_cookiesVotesUser= new Array("ap_votes_user").sort();



function getSymetricKey ()
{
var blabla= "x" +
document.domain +
navigator.appName +
navigator.appCodeName +
navigator.appVersion +
navigator.platform +
navigator.userAgent +
screen.width +
screen.height +
screen.colorDepth +
screen.availWidth +
screen.availHeight;

var hash= sha1Hash( blabla );

var arr= new Array();
var i= 0;
for ( ; i < hash.length; ++i )
{
var ch= hash.charAt(i);
if ((ch >= "0") && (ch <= "9"))
{
arr[ arr.length ]= ch.charCodeAt(0) - "0".charCodeAt(0);
}
else if ((ch >= "a") && (ch <= "f"))
{
arr[ arr.length ]= 10 + ch.charCodeAt(0) - "a".charCodeAt(0);
}
else if ((ch >= "A") && (ch <= "F"))
{
arr[ arr.length ]= 10 + ch.charCodeAt(0) - "A".charCodeAt(0);
}
}

 

return arr;
}

function encryptSimple (str)
{
if ((str == null) || (str == ""))
return str;

var sk= getSymetricKey();

var newstr= "";
var i= 0;
for ( ; i < str.length; ++i )
{
newstr= newstr + String.fromCharCode(str.charCodeAt(i) + sk[i % sk.length] );
}

 
return newstr;
}

function decryptSimple (str)
{
if ((str == null) || (str == ""))
return str;

var sk= getSymetricKey();

var newstr= "";
var i= 0;
for ( ; i < str.length; ++i )
{
newstr= newstr + String.fromCharCode(str.charCodeAt(i) - sk[i % sk.length]);
}

 
return newstr;
}

 
function getMyCookie(name)
{
if (findElementInArray(window.g_cookiesMulti, name) >= 0)
{
return getCookieMulti("ap_currentuser", name);
}
else if (findElementInArray(window.g_cookiesMultiSec, name) >= 0)
{
var val;
 
if (false && window.globalStorage)
{
var storage= window.globalStorage.namedItem(window.location.hostname);
var storageitem= storage.getItem(name);
val= ((storageitem == null) ? null : storageitem.value);
}
else if (false && window.sessionStorage)
{
var storageitem= window.sessionStorage.getItem(name);
val= ((storageitem == null) ? null : storageitem.value);
}
else
{
if (false)
{
 
val= getIePersistenceData("idStoreUserData", name);
if (val == null)
{
val= getCookieMulti("ap_sec", name);
}
}
else
{
var scrambled= getCookieMulti("ap_sec", name);
val= decryptSimple( scrambled );
}
}
return val;
}
else if (findElementInArray(window.g_cookiesMultiPersistent, name) >= 0)
{
return getCookieMulti("ap_longterm", name);
}
else if (findElementInArray(window.g_cookiesNormalPersistentShort, name) >= 0)
{
return getCookie(name);
}
else if (findElementInArray(window.g_cookiesPassthrough, name) >= 0)
{
return getCookieMulti("ap_passthrough", name);
}
else if (findElementInArray(window.g_cookiesVotesAnonymous, name) >= 0)
{
return getCookie(name);
}
else if (findElementInArray(window.g_cookiesVotesUser, name) >= 0)
{
return getCookie(name);
}

return getCookie(name);
}

function setMyCookie(name, value)
{
if (findElementInArray(window.g_cookiesMulti, name) >= 0)
{
setCookieMulti("ap_currentuser", name, value);
}
else if (findElementInArray(window.g_cookiesMultiSec, name) >= 0)
{
 
if (false && window.globalStorage)
{
var storage= window.globalStorage.namedItem(window.location.hostname);
storage.setItem(name, value);
}
else if (false && window.sessionStorage)
{
window.sessionStorage.setItem(name, value);
}
else
{
if (false)
{
setIePersistenceData("idStoreUserData", name, value);
if (! saveIePersistenceData("idStoreUserData", "SY1", 1000))
{
setCookieMulti("ap_sec", name, value, null, null, null, false);
}
}
else
{
var scrambled= encryptSimple(value);
setCookieMulti("ap_sec", name, scrambled, null, null, null, false);
}
}
}
else if (findElementInArray(window.g_cookiesMultiPersistent, name) >= 0)
{
var expire= getExpirationData(new Date(), 365, 0, 0);
setCookieMulti("ap_longterm", name, value, expire);
}
else if (findElementInArray(window.g_cookiesNormalPersistentShort, name) >= 0)
{
var expire= getExpirationData(new Date(), 1, 0, 0);
return setCookie(name, value, expire);
}
else if (findElementInArray(window.g_cookiesPassthrough, name) >= 0)
{
setCookieMulti("ap_passthrough", name, value, expire);
}
else if (findElementInArray(window.g_cookiesVotesAnonymous, name) >= 0)
{
var expire= getExpirationData(new Date(), 365, 0, 0);
setCookie(name, value, expire);
}
else if (findElementInArray(window.g_cookiesVotesUser, name) >= 0)
{
setCookie(name, value);
}
else
{
setCookie(name, value);
}
}

function deleteMyCookie(name)
{
setMyCookie(name, null);
}

function getAndDeleteMyCookie(name)
{
var cookie= getMyCookie(name);
deleteMyCookie(name);
return cookie;
}

 
function deleteVoteCookie(idCookie)
{
var cookie= "ap_votes_" + idCookie;
deleteMyCookie(cookie);
}

 
function setVoteCookie(idPoll, idCookie)
{
var mydebbuger= new DebugHelper("setVoteCookie");
var cookie= "ap_votes_" + idCookie;
var separator= "_";
var maxlen= 512;

mydebbuger.trace("vote: " + idCookie + " : " + idPoll);
var votes= getMyCookie(cookie);
if (votes == null)
{
votes= separator;
mydebbuger.trace("no cookie found: " + cookie);
}

var pos= votes.indexOf( separator + idPoll + separator );
if (pos < 0)
{
if ((votes.length == 0) || (votes.charAt(0) != separator))
{
votes= separator + votes ;
}
votes= separator + idPoll + votes ;
if (votes.length > maxlen)
{
votes= votes.substr(0, maxlen);
}
setMyCookie( cookie, votes );
mydebbuger.trace("set cookie: " + cookie + " : " +  votes);
}
}

 
function isVoteCookie(idPoll, idCookie)
{
var cookie= "ap_votes_" + idCookie;
var separator= "_";
var votes= getMyCookie(cookie);
if (votes == null)
{
return false;
}

var pos= votes.indexOf( separator + idPoll + separator );
return (pos >= 0);
}

nssy.getRandomCookie = function ()
{
var c= getMyCookie("randomc");
if (c == null)
{
c= Math.round(Math.random()*1000000);
setMyCookie("randomc", c);
}
return c;
}


function getChallengeReponse(challenge, session)
{
var response= sha1Hash(sha1Hash(String(session)) + String(challenge) );
return response;
}

 
nssy.getPreferredLang = function (langOverride)
{
if ((langOverride != null) && (langOverride != ""))
{
return langOverride;
}

var cookieLang= getMyCookie("ap_lang");
if ((cookieLang != null) && (cookieLang != ""))
{
return cookieLang;
}

var alang= 'en';
var langs= getLangsFromBrowser();
for (i= 0; i < langs.length; ++i)
{
if (! ( /^[Ee][Nn]([-].*)?$/.test(langs[i]) ))
{
alang= langs[i];
}
if (langs.length > 0)
{
alang= langs[0];
}
}
var splits= /^([A-Za-z]{2})([-].*)?$/.exec(alang);
if (splits.length > 1)
{
alang= splits[1];
}
return alang;
}

 
function CurrentUser ()
{
this.isManager = function ()
{
var ckmanager= parseInt(getMyCookie( "ap_manager" ));
return ((!isNaN(ckmanager)) && (ckmanager != 0));
};

this.isSignedIn = function ()
{
var nick= getMyCookie("ap_nick");
var session= getMyCookie("ap_session");
var uid= getMyCookie( "ap_id" );
var challenge= getMyCookie( "ap_challenge" );

var flagSingedIn= false;
if ( isNonEmptyString(nick) && isNonEmptyString(session) && isNonEmptyString(uid) && isNonEmptyString(challenge) )
{
 
flagSingedIn= true;
}

return flagSingedIn;
};

this.getUid = function ()
{
var uid= parseInt(getMyCookie("ap_id"));
return isNaN(uid) ? 0 : uid;
};

this.getNickname = function ()
{
var nick= getMyCookie("ap_nick");
return nick;
};

this.getQS = function ()
{
var uid= parseInt(getMyCookie( "ap_id" ));
var session= getMyCookie("ap_session");
var challenge= getMyCookie( "ap_challenge" );

var code= getChallengeReponse(challenge, session);

var qs= "uid=" + encodeURIComponent(uid) +
"&challenge=" + encodeURIComponent(challenge) +
"&code=" + encodeURIComponent(code)
;
return qs;
};
}

 
function isSignedIn ()
{
var curuser= new CurrentUser();
return curuser.isSignedIn();
}

 
function getSignedInUserQS ()
{
var curuser= new CurrentUser();
return curuser.getQS();
}

 
function getScriptDummyParam ()
{
 
 
var date= new Date();
var MILLISEC_PER_CACHE_CYCLE= 300000;
return Math.round(date.getTime()/MILLISEC_PER_CACHE_CYCLE);
}

 
function addUserGreeting(lang)
{
var strtbl= new StringTable (getDocs() + "/polls/xml/strtbl_en.xml", "greeting", lang);

var objMember= document.getElementById("memberinfo");
if (objMember != null)
{
removeAllChilds(objMember);

var curuserUG= new CurrentUser();
if (curuserUG.isSignedIn())
{
var anchorSignout= document.createElement('a');
if (lang == "he")
{
anchorSignout.href= getDocs() + "/polls/signout_heb.html";
}
else
{
anchorSignout.href= getDocs() + "/polls/signout.html";
}
anchorSignout.target= "_top";
anchorSignout.appendChild( document.createTextNode(strtbl.get("idGreetSignOut")));

var anchorAccount= document.createElement('a');
if (lang == "he")
{
anchorAccount.href= getDocs() + "/polls/cpanel_heb.html";
}
else
{
anchorAccount.href= getDocs() + "/polls/cpanel.html";
}
anchorAccount.target= "_top";
anchorAccount.appendChild( document.createTextNode(strtbl.get("idGreetControlPanel")) );

var nodeUser= document.createElement('SPAN');
nodeUser.appendChild( document.createTextNode(curuserUG.getNickname()) );
nodeUser.className= "clsUserName";
objMember.appendChild( document.createTextNode(strtbl.get("idGreetLoggedInAs")+": " ) );
objMember.appendChild( nodeUser );
objMember.appendChild( document.createTextNode(". ") );
objMember.appendChild( anchorAccount );
objMember.appendChild( document.createTextNode(" | ") );
objMember.appendChild( anchorSignout );

}
else
{
var anchorJoin= document.createElement('a');
if (lang == "he")
{
anchorJoin.href= getDocs() + "/polls/register_heb.html";
}
else
{
anchorJoin.href= getDocs() + "/polls/register.html";
}
anchorJoin.target= "_top";
anchorJoin.appendChild( document.createTextNode(strtbl.get("idGreetRegister")) );

var anchorSignIn= document.createElement('a');
if (lang == "he")
{
anchorSignIn.href= getDocs() + "/polls/signin_heb.html";
}
else
{
anchorSignIn.href= getDocs() + "/polls/signin.html";
}
anchorSignIn.target= "_top";
anchorSignIn.appendChild( document.createTextNode(strtbl.get("idGreetSignIn")) );

objMember.appendChild( document.createTextNode(strtbl.get("idGreetHelloGuest") + " : ") );
objMember.appendChild( anchorJoin );
objMember.appendChild( document.createTextNode(" | ") );
objMember.appendChild( anchorSignIn );
}
}
var objLangs= document.getElementById("languages");
if (objLangs != null)
{
removeAllChilds(objLangs);

var langs= getLangsFromBrowser();
var cookieLang= getMyCookie("ap_lang");
if ((cookieLang != null) && (cookieLang != ""))
{
langs.push(cookieLang);
}
var i;
var isHe= false;
for (i= 0; i < langs.length; ++i)
{
isHe= isHe || ( /^[hH][eE]([-][a-zA-Z][a-zA-Z])?$/.test( langs[i] ) );
}
if (isHe)
{
var anchorHe= document.createElement('a');
anchorHe.href= getDocs() + "/heb.html";
anchorHe.target= "_top";
anchorHe.appendChild( document.createTextNode("\u05E2\u05D1\u05E8\u05D9\u05EA") );
objLangs.appendChild(anchorHe);

 
 
 
 
 
 

}
}
}

 
function greet (mainsection, lang)
{
addUserGreeting(lang);
}

 
function greetGlossary (lang)
{
}

 
function greetPoll (mode, lang)
{
if (mode != "construction")
{
addUserGreeting(lang);
}
}

 
function SignOutCallback ()
{
this.onXmlLoaded = function (xmlreq)
{
};

this.onError = function (xmlreq, err)
{
};
}

function signoutQuietly (lang)
{
 

deleteMyCookie("ap_nick");
deleteMyCookie("ap_session");
deleteMyCookie("ap_id");
deleteMyCookie("ap_challenge");
deleteMyCookie("ap_gender");
deleteMyCookie("ap_birthyear");
deleteMyCookie("ap_birthmonth");
deleteMyCookie("ap_birthmonday");
deleteMyCookie("ap_manager");
deleteMyCookie("ap_prt_poll");
deleteMyCookie("ap_prt_pwd");
deleteMyCookie("ap_prt_when");

setServerTimeCookie(0);

deleteVoteCookie("user");

addUserGreeting(lang);
}

function PollsActions(lang)
{
this.mydebugger= new DebugHelper("PollsActions");
this.lang= lang;
this.strtbl= new StringTable (getDocs() + "/polls/xml/strtbl_en.xml", "polls_list", this.lang);

this.setBusy = function(isBusy)
{
document.body.style.cursor= (isBusy ? "wait" : "auto");
};

this.ChangeStatusCallback = function (parent, idPoll)
{
this.parent= parent;
this.idPoll= idPoll;

this.onXmlLoaded = function (xmlreq)
{
this.parent.setBusy(false);
try
{
var doc = xmlreq.req.responseXML.documentElement;
var status = getValidTextOfFirstXmlElement( doc.getElementsByTagName('status') );
if (status == "OK")
{
showPollQuestionnaire(this.idPoll, false);
}
else
{
var debugerr = getValidTextOfFirstXmlElement( doc.getElementsByTagName('debug-err') );
this.parent.mydebugger.warn("Status: " + status + " Error: " + debugerr);
if (confirm( this.parent.strtbl.get("idErrGeneralOperationFailed") ))
{
alert("Status: " + status + "\nError: " + debugerr );
}

var curuser= new CurrentUser();
showMemberById( curuser.getUid(), curuser.getNickname(), false, this.parent.lang );
}
}
catch (exc)
{
if (confirm( this.parent.strtbl.get("idErrGeneralOperationFailed") ))
{
alert(convertErrObjToStr(exc));
}
this.parent.mydebugger.warn(convertErrObjToStr(exc));
}
};

this.onError = function (xmlreq, err)
{
this.parent.mydebugger.warn(convertErrObjToStr(err));
this.parent.setBusy(false);
if (confirm( this.parent.strtbl.get("idErrGeneralOperationFailed") ))
{
alert(convertErrObjToStr(err) );
}
};
};

this.changeStatus = function (idPoll, statusNew)
{
var curuser= new CurrentUser();
var url= getCgibin() + "/ap_change_poll_status.pl?" +
curuser.getQS() +
"&id_poll=" + encodeURIComponent(idPoll) +
"&status=" + encodeURIComponent(statusNew)
;

 
this.setBusy(true);
var loader= new XmlRequest();
loader.loadAsync(url, new this.ChangeStatusCallback(this, idPoll), null, null);
}

this.closeQuestionnaire = function(idPoll)
{
if (confirm( this.strtbl.get("idConfirmClose") ))
{
this.changeStatus(idPoll, "closed");
}
};
this.pauseQuestionnaire = function(idPoll)
{
if (confirm( this.strtbl.get("idConfirmPause") ))
{
this.changeStatus(idPoll, "paused");
}
};
this.resumeQuestionnaire = function(idPoll)
{
if (confirm( this.strtbl.get("idConfirmResume") ))
{
this.changeStatus(idPoll, "open");
}
};

this.upgradeQuestionnaire = function(idPoll)
{
setMyCookie( "ap_recent_poll", idPoll );
var url= getDocs() + "/polls/upgrade_pre.html?id_poll=" + encodeURIComponent(idPoll);
window.self.location= url;
};

this.showPollResults = function (idPoll, isNewWindow)
{
setMyCookie( "ap_recent_poll", idPoll );
var url= getDocs();
if (this.lang == "he")
{
url= url + "/polls/results_heb.html"
}
else
{
url= url + "/polls/results.html"
}
url= appendQsParam(url, "id_poll", idPoll );
url= appendQsParam(url, "lang_ui", this.lang );
url= appendInvitationToUrl(url, idPoll);
window.open(url, isNewWindow ? "_blank" : "_top" );
};

this.editPollQuestionnaire = function (idPoll, mode, isNewWindow)
{
setMyCookie( "ap_recent_poll", idPoll );
setMyCookie( "ap_recent_poll_type", "basic" );
setMyCookie( "ap_recent_mode", mode );
var url= getDocs();
if (this.lang == "he")
{
url= url + "/polls/polls_create_basic_heb.html"
}
else
{
url= url + "/polls/polls_create_basic.html"
}
 
window.open(url, isNewWindow ? "_blank" : "_self"  );
};

}

function signout (lang)
{
var curuser= new CurrentUser ();
var url= getCgibin() + "/ap_signout.pl?" + curuser.getQS();
 

var request= new XmlRequest();
request.loadAsync( url, new SignOutCallback(), null, null );

signoutQuietly (lang);
}

function assureSignedIn (pageid, lang)
{
var isSingedIn= isSignedIn();
if (!isSingedIn)
{
if (isNonEmptyString(pageid))
{
setMyCookie("ap_restricted_page", pageid);
}
else
{
deleteMyCookie("ap_restricted_page");
}
var url= getDocs();
if (lang == "he")
{
url= url + "/polls/signin_heb.html"
}
else
{
url= url + "/polls/signin.html"
}
window.self.location= url;
}
}

function showMemberById(id, nick, isNewWindow, lang)
{
setMyCookie( "ap_recent_member_id", id );
setMyCookie( "ap_recent_member_nick", nick );
var url= getDocs();
if (lang == "he")
{
url= url + "/polls/member_profile_heb.html";
}
else
{
url= url + "/polls/member_profile.html";
}
window.open(url, isNewWindow ? "_blank" : "_top" );
}

function appendInvitationToUrl(url, idPoll)
{
var currentPoll= getQueryStringParam("id_poll", "0");
 
if (currentPoll == idPoll)
{
 
var inviteeEmail= getQueryStringParam("invitee", "");
var invitationCode= getQueryStringParam("invitation", "");
if (inviteeEmail != "")
{
url = url + "&invitee=" + encodeURIComponent(inviteeEmail) +
"&invitation=" + encodeURIComponent(invitationCode);
}
}
return url;
}

function showPollResults(idPoll, isNewWindow, lang)
{
new PollsActions(lang).showPollResults(idPoll, isNewWindow);
}

function showPollQuestionnaire(idPoll, isNewWindow)
{
setMyCookie( "ap_recent_poll", idPoll );
var url= getDocs() + "/polls/show_poll.html?id_poll=" + encodeURIComponent(idPoll);
url= appendInvitationToUrl(url, idPoll);
 
window.open(url, isNewWindow ? "_blank" : "_top" );
}

function composePrivateMessage(uid_receiver, nickname_receiver, isNewWindow, subject)
{
setMyCookie( "ap_recent_member_id", uid_receiver );
setMyCookie( "ap_recent_member_nick", nickname_receiver );
setMyCookie( "ap_subject", subject );
var url= getDocs() + "/polls/compose_prvt_msg.html";
window.open(url, isNewWindow ? "_blank" : "_self" );
}

function readInbox()
{
var url= getDocs() + "/polls/mailbox.html";
window.self.location= url;
}

function editPollQuestionnaire(idPoll, mode, isNewWindow, lang)
{
new PollsActions(lang).editPollQuestionnaire(idPoll, mode, isNewWindow);
}


function setServerTimeCookie (serverctime)
{
if ((serverctime == null) || (serverctime == 0) || isNaN(serverctime) )
{
deleteMyCookie("ap_serverctime");
deleteMyCookie("ap_diffctime");
}
else
{
var clientctime= Math.round( new Date().getTime() / 1000 );
var diffctime= clientctime - serverctime;

setMyCookie( "ap_serverctime", serverctime );
setMyCookie( "ap_diffctime", diffctime );
}
}

 
function DefaultSignInCallback()
{
this.onSignedIn = function ()
{
};
}

function DynamicSignIn ()
{
this.mydebugger= new DebugHelper("DynamicSignIn");
this.strtbl= null;
this.callback= null;
this.lang= '';

this.onSignInSuccess = function (xmlresponse)
{
var doc = xmlresponse.documentElement;
var nick= getValidTextOfFirstXmlElement( doc.getElementsByTagName('nickname') );
var uid= getValidTextOfFirstXmlElement( doc.getElementsByTagName('id') );
var sess= getValidTextOfFirstXmlElement( doc.getElementsByTagName('sess') );
var challenge= getValidTextOfFirstXmlElement( doc.getElementsByTagName('challenge') );
var gender= getValidTextOfFirstXmlElement( doc.getElementsByTagName('gender') );
var birthyear= getValidTextOfFirstXmlElement( doc.getElementsByTagName('birth-year') );
var birthmonth= getValidTextOfFirstXmlElement( doc.getElementsByTagName('birth-month') );
var birthmonday= getValidTextOfFirstXmlElement( doc.getElementsByTagName('birth-monday') );
var count_unread_messages= getValidTextOfFirstXmlElement( doc.getElementsByTagName('count-unread-messages') );
var manager= getValidTextOfFirstXmlElement( doc.getElementsByTagName('manager') );
var serverctime= getValidTextOfFirstXmlElement( doc.getElementsByTagName('ctime') );

setServerTimeCookie( serverctime );

setMyCookie( "ap_nick", nick );
setMyCookie( "ap_id", uid );
setMyCookie( "ap_session", sess );
setMyCookie( "ap_challenge", challenge );
setMyCookie( "ap_gender", gender );
setMyCookie( "ap_birthyear", birthyear );
setMyCookie( "ap_birthmonth", birthmonth );
setMyCookie( "ap_birthmonday", birthmonday );
setMyCookie( "ap_manager", manager );

deleteVoteCookie("user");
var nodeVotes= doc.getElementsByTagName("votes");
if ((nodeVotes != null) && (nodeVotes.length > 0))
{
var nodesPolls= nodeVotes.item(0).getElementsByTagName("poll-id");
if (nodesPolls != null)
{
for (var i=0; i < nodesPolls.length; ++i)
{
var	nodePoll= nodesPolls.item(i);
try
{
var idPollVoted= nodePoll.firstChild.nodeValue;
setVoteCookie(idPollVoted, "user");
}
catch (exc)
{
 
}
}
}
}

var remember= document.getElementById("idSignInRemember");
if (remember.checked)
{
setMyCookie( "ap_nick_remember", nick );
}
else
{
deleteMyCookie( "ap_nick_remember" );
}

if (this.callback && this.callback.onSignedIn)
{
addUserGreeting(this.lang);
this.callback.onSignedIn();
}
};

 
this.SignInCallback = function (parent)
{
this.parent= parent;

this.onXmlLoaded = function (xmlreq)
{
showHtmlElement("idSignInPleaseWait", false);
var submit= document.getElementById("idSignInSubmit");
submit.disabled = false;
try
{
var doc = xmlreq.req.responseXML.documentElement;
var status = getValidTextOfFirstXmlElement( doc.getElementsByTagName('status') );

if (status == "OK")
{
this.parent.onSignInSuccess(xmlreq.req.responseXML);
}
else if (status == "NOT_FOUND")
{
setTextInElelemtById("idSignInErrMsg", this.parent.strtbl.get("idDynSignInNoAuth") );
}
else if (status == "TEMP_DOWN")
{
 
setTextInElelemtById("idSignInErrMsg", this.parent.strtbl.get("idErrGeneralTempDown") );
}
else if (status == "NOT_ACTIVATED")
{
setTextInElelemtById("idSignInErrMsg", this.parent.strtbl.get("idDynSignInNotActivatedErr") );
var isExplain= confirm( this.parent.strtbl.get("idDynSignInNotActivated") );
if (isExplain)
{
window.open( getDocs() + "/polls/signin_activation.html", "_blank" );
}
}
else
{
var err = getValidTextOfFirstXmlElement( doc.getElementsByTagName('debug-err') );
this.parent.mydebugger.warn(err);
if (confirm( this.parent.strtbl.get("idErrGeneralOperationFailed") ))
{
 
alert( status + " " + err );
}
}
}
catch (exc)
{
this.parent.mydebugger.warn(convertErrObjToStr(exc));
if (confirm( this.parent.strtbl.get("idErrGeneralOperationFailed") ))
{
alert(convertErrObjToStr(exc));
}
}
};

this.onError = function (xmlreq, err)
{
showHtmlElement("idSignInPleaseWait", false);
var submit= document.getElementById("idSignInSubmit");
submit.disabled = false;

this.parent.mydebugger.warn(convertErrObjToStr(err));
if (confirm( this.parent.strtbl.get("idErrGeneralOperationFailed") ))
{
alert(convertErrObjToStr(err));
}
};
}

 
this.onChallengeSuccess = function (xmlresponse)
{
var doc = xmlresponse.documentElement;

var nick= document.getElementById("idSignInNick");
var password= document.getElementById("idSignInPassword");
var challenge = getValidTextOfFirstXmlElement( doc.getElementsByTagName('challenge') );

var utf8bytes= getUtf8BytesString(password.value);
var code= sha1Hash(sha1Hash(utf8bytes) + challenge );
var url= getCgibin() + "/ap_signin.pl?nickname=" + encodeURIComponent(nick.value) + "&password=" + encodeURIComponent(code);

showHtmlElement("idSignInPleaseWait", true);
var submit= document.getElementById("idSignInSubmit");
submit.disabled = true;

var requestSignIn= new XmlRequest();
requestSignIn.loadAsync( url, new this.SignInCallback(this), null, null );
}

this.SignInChallengeCallback = function (parent)
{
this.parent= parent;

this.onXmlLoaded = function (xmlreq)
{
showHtmlElement("idSignInPleaseWait", false);
var submit= document.getElementById("idSignInSubmit");
submit.disabled = false;
try
{
var doc = xmlreq.req.responseXML.documentElement;
var status = getValidTextOfFirstXmlElement( doc.getElementsByTagName('status') );

if (status == "OK")
{
this.parent.onChallengeSuccess(xmlreq.req.responseXML);
}
else if (status == "NOT_FOUND")
{
setTextInElelemtById("idSignInErrMsg", this.parent.strtbl.get("idDynSignInNoAuth") );
}
else if (status == "TEMP_DOWN")
{
 
setTextInElelemtById("idSignInErrMsg", this.parent.strtbl.get("idErrGeneralTempDown") );
}
else
{
var debugerr = getValidTextOfFirstXmlElement( doc.getElementsByTagName('debug-err') );
this.parent.mydebugger.warn("Status: " + status + "\nError: " + debugerr);
if (confirm( this.parent.strtbl.get("idErrGeneralOperationFailed") ))
{
alert("Status: " + status + "\nError: " + debugerr );
}
}
}
catch (exc)
{
this.parent.mydebugger.warn(convertErrObjToStr(exc));
if (confirm( this.parent.strtbl.get("idErrGeneralOperationFailed") ))
{
alert(convertErrObjToStr(exc) );
}
}
};

this.onError = function (xmlreq, err)
{
showHtmlElement("idSignInPleaseWait", false);
var submit= document.getElementById("idSignInSubmit");
submit.disabled = false;

this.parent.mydebugger.warn(convertErrObjToStr(err));
if (confirm( this.parent.strtbl.get("idErrGeneralOperationFailed") ))
{
alert(convertErrObjToStr(err) );
}
};
}



this.prepareFormSignIn = function ()
{
var remember= getMyCookie("ap_nick_remember");
if (remember != null)
{
var nick= document.getElementById("idSignInNick");
nick.value= remember;

var remember= document.getElementById("idSignInRemember");
remember.checked= true;
}
}

 
this.validateFormSignIn = function ()
{
setTextInElelemtById("idSignInErrMsg", "");

var nick= document.getElementById("idSignInNick");
if ( nick.value == "" )
{
setTextInElelemtById("idSignInErrMsg", this.strtbl.get("idDynSignInMissingNickname") );
nick.focus();
return false;
}
if ( ! /^[A-Za-z0-9]*([\-\_]?[A-Za-z0-9]+)*[\-\_]?$/.test(nick.value) )
{
setTextInElelemtById("idSignInErrMsg", this.strtbl.get("idDynSignInInvalidNickname") );
nick.focus();
return false;
}

var pwd1= document.getElementById("idSignInPassword");
if ( pwd1.value == "" )
{
setTextInElelemtById("idSignInErrMsg",  this.strtbl.get("idDynSignInMissingPassword") );
pwd1.focus();
return false;
}
if ( pwd1.value.length < 4 )
{
setTextInElelemtById("idSignInErrMsg",  this.strtbl.get("idDynSignInInvalidPassword") );
pwd1.focus();
return false;
}

var submit= document.getElementById("idSignInSubmit");
submit.disabled = true;

var url= getCgibin() + "/ap_get_challenge.pl?nickname=" + encodeURIComponent(nick.value);
 

showHtmlElement("idSignInPleaseWait", true);
var requestChallenge= new XmlRequest();
requestChallenge.loadAsync( url, new this.SignInChallengeCallback(this), null, null );

return false;
}


this.go = function(idElement, callback, lang)
{
this.callback= callback;
this.lang= lang;
this.strtbl= new StringTable (getDocs() + "/polls/xml/strtbl_en.xml", "dynamic_sign_in", this.lang);
 

var strXhtml= '	\
<div>	\
<fieldset>	\
<legend><span class="clsLeft">\u00A0</span><span class="clsMid">%login%</span><span class="clsRight">\u00A0</span></legend>	\
<form id="idSignInForm" action="javascript: void(0);" >	\
<p id="idSignInErrMsg" class="clsErrorMsg">	\
</p>	\
<div style="margin-bottom: 20px;">	\
<div class=""><label for="idSignInNick">%nickname%</label></div> 	\
<span dir="ltr" style="direction: ltr;">	\
<input id="idSignInNick" name="nickname" size="16" maxlength="16" type="text" />	\
</span>	\
<div class="">	\
<input id="idSignInRemember" name="remember" type="checkbox" /><label for="idSignInRemember">%rememberme%</label>	\
</div>	\
</div>	\
<div style="margin-bottom: 20px;">	\
<div class=""><label for="idSignInPassword">%password%</label></div> 	\
<span dir="ltr" style="direction: ltr;">	\
<input id="idSignInPassword" name="password" size="16" maxlength="16" type="password" />	\
</span>	\
<a 	class="clsExplain"	\
href="../polls/signin_tips.html#idTTPassword"	\
target="ap_glossary"	\
title="More info"	\
onclick="javascript: return openGlossary(this.href);" ><span class="clsExplainText">%tiphelp%</span></a>	\
</div>	\
<div style="margin-bottom: 20px;">	\
<input id="idSignInSubmit" name="signin" value="%signin%" type="submit" />	\
</div>	\
</form>	\
<div id="idSignInPleaseWait" style="display: none;">	\
<p class="clsPleaseWait">%pleasewait%...</p>	\
</div>	\
</fieldset>	\
</div>	\
';

strXhtml= strXhtml.replace( /%login%/g, this.strtbl.get("idDynSignInLogin") );
strXhtml= strXhtml.replace( /%nickname%/g, this.strtbl.get("idDynSignInNickname") );
strXhtml= strXhtml.replace( /%password%/g, this.strtbl.get("idDynSignInPassword") );
strXhtml= strXhtml.replace( /%rememberme%/g, this.strtbl.get("idDynSignInRememberMe") );
strXhtml= strXhtml.replace( /%signin%/g, this.strtbl.get("idDynSignInSignIn") );
strXhtml= strXhtml.replace( /%tiphelp%/g, this.strtbl.get("idTipHelp") );
strXhtml= strXhtml.replace( /%pleasewait%/g, this.strtbl.get("idPleaseWait") );

if (this.callback == null)
{
this.callback= new DefaultSignInCallback();
}

writeXhtmlToElement( idElement, strXhtml );

var nodeForm= document.getElementById("idSignInForm");
var that= this;
nodeForm.onsubmit= function() { that.validateFormSignIn(); };

this.prepareFormSignIn();

var node= document.getElementById("idSignInNick");
node.focus();
};
};


window.g_dynamicSignIn= null;
 
function doDynamicSignIn (idElement, callback, lang)
{
if (window.g_dynamicSignIn == null)
{
window.g_dynamicSignIn= new DynamicSignIn();
}
window.g_dynamicSignIn.go(idElement, callback, lang);
}

 
function TuringObj (idElement)
{
this.mydebugger= new DebugHelper("TuringObj");
this.strtbl= new StringTable (getDocs() + "/polls/xml/strtbl_en.xml", "turing_obj", null);

this.DIGITS= 5;
this.idElement= idElement;
this.enc= 0;
this.lang= '';
this.isRLT= false;

this.setLang= function(lang)
{
this.lang= lang;
this.isRLT= ((this.lang == "he") || (this.lang == "ar"));
 
this.strtbl= new StringTable (getDocs() + "/polls/xml/strtbl_en.xml", "turing_obj", this.lang);
};

this.doDynamicTuring = function ()
{
var nodeTuring= document.getElementById(this.idElement);
var strXhtml= '	\
<div>	\
<input id="idTuringEnc" name="turing_enc" type="hidden" />	\
<div id="idTuringImgBlock">	\
<img style="height: 32px;" id="idTuringImg" alt="%imgalt%" src="" />	\
</div>	\
<div id="idTuringPleaseWait" style="display: none;">	\
<p class="clsPleaseWait">%pleasewait%...</p>	\
</div>	\
<div style="float: %dir%;">	\
<label for="idTuringInp">%turingfield%: &nbsp;</label>	\
</div>	\
<input id="idTuringInp" name="turing" size="7" maxlength="15" type="text" />	\
<div style="clear: both; font-size: .8em;">	\
%instructions%	\
</div>	\
</div>	\
';
strXhtml= strXhtml.replace( /%dir%/g, this.isRLT ? "right" : "left" );
strXhtml= strXhtml.replace( /%turingfield%/g, this.strtbl.get("idTuringObjField") );
strXhtml= strXhtml.replace( /%imgalt%/g, this.strtbl.get("idTuringObjImageSubstitute") );
strXhtml= strXhtml.replace( /%pleasewait%/g, this.strtbl.get("idPleaseWait") );

strXhtml= strXhtml.replace( /%instructions%/g,
this.strtbl.format("idTuringObjIntructions", this.DIGITS,
'<a id="idNewTuring" href="javascript: void(0);" onclick="javascript: new TuringObj(\'' + idElement + '\').reload(); return false;">',
'</a>'
) );

strXhtml= strXhtml.replace( /%idElement%/g, "'" + idElement + "'");
strXhtml= strXhtml.replace( /%digits%/g, this.DIGITS);

writeXhtmlToElement( idElement, strXhtml );
this.reload();
};

 
this.CallbackTuring = function TuringCallback (parent)
{
this.parent= parent;

this.onXmlLoaded = function (xmlreq)
{
showHtmlElement("idTuringPleaseWait", false);
try
{
var doc = xmlreq.req.responseXML.documentElement;
this.enc = getValidTextOfFirstXmlElement(doc.getElementsByTagName('enc'));
this.parent.setTuringEnc(this.enc);
}
catch (exc)
{
var img= document.getElementById("idTuringImg");
img.alt= this.parent.strtbl.get("idTuringObjLoadFailed");
img.src= "";
}
};

this.onError = function (xmlreq, err)
{
this.parent.mydebugger.warn(convertErrObjToStr(err));
showHtmlElement("idTuringPleaseWait", false);
var img= document.getElementById("idTuringImg");
img.alt= this.parent.strtbl.get("idTuringObjLoadFailed");
img.src= "";
};
};

 
this.reload = function ()
{
var nodeTuringInput= document.getElementById("idTuringInp");
nodeTuringInput.value= '';
nodeTuringInput.focus();

var img= document.getElementById("idTuringImg");
img.alt= "Loading turing number";
img.src= getDocs() + "/polls/images/LoadingTuring.png" ;
showHtmlElement("idTuringPleaseWait", true);

var callback= new this.CallbackTuring(this);
var request= new nssy.MyXmlRequest();
request.loadAsync( getCgibin() + "/ap_get_turing_enc.pl", callback, null, null );
};

 
this.getTuringEnc = function ()
{
return this.enc;
};

 
this.setTuringEnc = function (enc)
{
this.enc= enc;

var img= document.getElementById("idTuringImg");
img.src= getCgibin() + "/ap_turing.pl?val=" + this.enc;
img.alt= this.strtbl.get("idTuringObjImageSubstitute");

var nodeHiddenEnc= document.getElementById("idTuringEnc");
nodeHiddenEnc.value= this.enc;

var nodeTuringInput= document.getElementById("idTuringInp");
nodeTuringInput.value= '';
};

 
this.getTuringUser = function ()
{
var nodeTuringInput= document.getElementById("idTuringInp");
return (nodeTuringInput == null) ? 0 : nodeTuringInput.value;
};

 
this.focus = function ()
{
var nodeTuringInput= document.getElementById("idTuringInp");
if (nodeTuringInput != null)
{
nodeTuringInput.focus();
}
};

this.hide = function ()
{
 
 
showHtmlElement(this.idElement, false);
};

 
this.isValidUserInput = function (isShowErr)
{
var val= this.getTuringUser();
if ((val == null) || (val.length != this.DIGITS ))
{
if (isShowErr)
{
this.focus();
alert( this.strtbl.format("idTuringObjInvalidLen", this.DIGITS) );
}
return false;
}
return true;
};
};

 
function isValidPassword (pwd)
{
if ((pwd == null) || (pwd.length < 4) || (pwd.length > 20))
{
return false;
}

return true;
}

 
window.g_logvisitTimer= null;
function LogVisit ()
{
this.TIMEOUT_MILLISEC= 3000;
this.timer= null;

this.LogVisitCallback = function (parent)
{
this.parent= parent;

this.onXmlLoaded = function (xmlreq)
{
};
this.onError = function (xmlreq, err)
{
};
};

this.onTimer = function ()
{
var referrer= "";
if (document.referrer && (document.referrer!=""))
{
referrer= document.referrer;
}

var date= new Date();
var url= getCgibin() + "/ap_log_visit.pl?page=" + encodeURIComponent(document.location) +
"&now=" + encodeURIComponent(date.getTime()) + "&ref=" + encodeURIComponent(referrer);
var requestLogVisit= new XmlRequest();
requestLogVisit.loadAsync( url, new this.LogVisitCallback(this), null, null );
clearTimeout(this.timer);
this.timer= null;
};

this.go = function ()
{
g_logvisitTimer= this;
var cmd= "window.g_logvisitTimer.onTimer();";
this.timer= setTimeout( cmd, this.TIMEOUT_MILLISEC);
};
}

function goPollsMembers ()
{
var mydebugger= new DebugHelper("goPollsMembers");
if (document.referrer && (document.referrer!=""))
{
var referrer= document.referrer;
if (referrer.indexOf( location.hostname ) < 0)
{
setMyCookie("ap_ref", referrer);
}
}

var subdomain= '';
var parts= /^([a-zA-Z0-9\-]+)([.].*)$/.exec( location.hostname );
if ((parts != null) && (parts.length > 1) && (parts[1] != "www"))
{
subdomain= parts[1];
}

 

var isDirectRef= false;
var refcode= getQueryStringParam("rcs", "");
if (refcode == "")
{
if (document.referrer && (document.referrer != ""))
{
if ( /^(http[s]?[:][/][/])?local[.]affiliate-demo[.]com([/].*)?$/i.test(document.referrer))
{
refcode= "local-demo";
isDirectRef= true;
}
}
}
else
{
isDirectRef= true;
}

if ((refcode == null) || (refcode == ""))
{
refcode= getMyCookie("ap_refcode");
}
if ((refcode == null) || (refcode == ""))
{
if (subdomain != "")
{
 
}
}
if ((refcode != null) && (refcode != ""))
{
if (refcode == "x")
{
 
setMyCookie("ap_refcode", "");
refcode = "";
}
else
{
setMyCookie("ap_refcode", refcode);
if (isDirectRef)
{
setMyCookie("ap_refcode_flw", "1");
}
}
}
 
}
goPollsMembers();




 
 

function getExportedFunctions ()
{
return [
 
'getHttpCgibin', 'getHttpsCgibin', 'getHttpDocs', 'getHttpsDocs', 'getCgibin', 'getDocs',
 
'DebugHelper', 'setCookie', 'getCookie', 'deleteCookie', 'getAndDeleteCookie', 'getExpirationData',
'getCookieMulti', 'setCookieMulti',
'saveIePersistenceData', 'loadIePersistenceData', 'getIePersistenceData', 'setIePersistenceData',
'getEmailValidation', 'MyNodeConstantsObject',
'removeAllChilds', 'removeAllAttributes', 'removeIntermediateNode', 'swapSiblingNodes', 'getElementByAttr',
'getIdentPrefix', 'convertXmlToString', 'doImportNode',
'createEmptyIeDocument', 'createEmptyDocument', 'createDocumentFromXmlString', 'writeXmlToElement',
'writeXhtmlToElement', 'getXmlHttpObj', 'XmlDefualtLoaded', 'XmlRequest', 'XmlIsland',
'XmlIslandLoadXslt', 'XsltTransformer', 'getDirectChildByTag', 'getValidTextOfFirstXmlElement', 'setTextInElelemt', 'setTextInElelemtById',
'addClassNameToNode', 'removeClassNameFromNode', 'getInnerWidth', 'getInnerHeight', 'getPageXOffset', 'getPageYOffset',
'isBrowserIE6',
'buildXmlFromForm', 'getFromQueryString', 'getUtf8BytesString', 'getLangsFromBrowser', 'setDocumentBasePath',
'getDocumentBasePath', 'isNonEmptyString', 'getValidString', 'setFormElementsVisibility',
'hideToolTip', 'showToolTip', 'openGlossary', 'filterGlossaries', 'showHtmlElement', 'showHtmlNode', 'isBlockedTag',
'enableHtmlElement',
'PopupDivDialog', 'AssociativeArray', 'TextInputLimiterDefaultCallback', 'TextInputLimiter',
'convertErrObjToStr', 'trimWhiteSpaces', 'findElementInArray', 'getQueryStringParam',
'MapIdsDoc',
'Digest', 'sha1Hash',
 
'greet', 'greetGlossary', 'greetPoll', 'signout', 'signoutQuietly', 'assureSignedIn', 'isSignedIn', 'getChallengeReponse',
'showMemberById', 'readInbox', 'editPollQuestionnaire',
'doDynamicSignIn', 'showPollResults', 'showPollQuestionnaire', 'composePrivateMessage',
'getMyCookie', 'setMyCookie', 'deleteMyCookie', 'setVoteCookie', 'isVoteCookie',
'getAndDeleteMyCookie', 'getSignedInUserQS', 'TuringObj', 'isValidPassword',
'CurrentUser', 'getServiceName', 'getScriptDummyParam', 'LogVisit'
];
}

 
 
 
 

if (window.nssy && window.nssy.onLoadScript) { window.nssy.onLoadScript('helpers'); }

/* End of file */
