AddEventListener afterOpen to Document

The CS3 scripting guide specifically mentions that you can use the "afterOpen" event on either an Application or Document object. I seem unable to bind to the afterOpen event on a document, however. What I am trying to do is detect certain files being opened, read metadata from them, close that document, and open a new document based on the metadata of the original.
It sounds like it should be easy, but the "afterOpen" event is a little misleading. Although it contains information about the document, the application has not yet finished opening the document - meaning it does not yet have a window or has not yet become the activeDocument. I have a reference to the document being opened, but addEventListener has now apparent effect and I cannot call doc.close() without a javascript error being thrown.
The code is fairly straightforward so far:
function doAfterOpen(event) {
var doc = event.parent;
//read from the first story
var story = doc.stories.firstItem();
if(story) {
var realFilePath = story.extractLabel("realPath");
//I now have the realpath and need to close this temporary document
doc.close(); <--- Throws a javascript error: 1 (I'm guessing cause it's not yet open which belies the afterOpen name)
-- OR --
doc.addEventListener("afterOpen",function(event) { alert("docOpen"); })) <---- it never fires
Anyone have any idea if there is actually a way to bind to a REAL afterOpen event, meaning that the document as in fact been opened???

I just jumped on this bandwagon. When I realized that afterOpen fires before the first window appears, I tried opening one in my event handler:
//DESCRIPTION: Start-up Script
#target indesign
#targetengine 'onOpen'
(function() {
  app.eventListeners.add("afterOpen", afterOpen);
  function afterOpen(myEvent) {
    myEvent.target.windows.add();
This worked. The window was drawn. But when I tried to close the window, InDesign CS4 crashed. To be thorough, I shall now go through the process again to make sure it is repeatable ... Yes it is. I just tried again with a different document -- happens it was one that had to be converted from CS3. Same thing happened. One window only which on closing caused the crash.
Then, restarting CS4 caused the document to be recovered with two windows.
Looks like APID is the way to go if you want to do anything useful with a document when it opens.
Dave

Similar Messages

  • (JS)(CS3) eventListeners: afterOpen UNSTABLE

    Hello everyone,
    I was able to emulate what inEventScript CS2 plug-in did, using the EventListener new function build into CS3. UNFORTUNATELY as soon as I close the document(s), InDesign crashes. The script is reliable as it has been used in CS2 for the past 6 months. All I did was to write the script that creates the event. The event gets triggered, the script executes and the handler closes once the script is finished. I can open several Docs. and they all get scripted correctly. It looks like something terminates INCORRECTLY once I close one of the document!
    Any suggestion or input will be greatly appreciated. Alex.
    Here is the EVENT Script.
    ===============================================================
    #target indesign
    #targetengine "session"
    app.scriptPreferences.version = 5.0;
    //******************** BEGIN Main ********************
    main();
    function main()
    //** Number 0
    app.addEventListener( "afterOpen", EventOpen, true);
    function EventOpen (itsEvent)
    app.scriptArgs.set("Event_Listener", itsEvent.parent.toSource());
    var myExeSrcFile = new File (app.scriptArgs.get("Event_Open"));
    if (myExeSrcFile.exists)
    myExeSrcFile.open ('r:(read)')
    app.doScript(myExeSrcFile, ScriptLanguage.javascript);
    myExeSrcFile.close();
    alert ("Finished Execution"); //*** Debug: Confirms HANDLER termination
    else
    alert ("Error! Missing File:\n\n" + myExeSrcFile.fsName);
    return;
    =================================================================
    The scriptArgs are defined during a Startup Script. The "Event_Listener" passes the document opened as an argument to the script and is correctly evaluated w/i the "Event_Open" script.

    Hi Harbs,
    I get your point but can't apply it.
    doc = File(mypath)
    doc.pageItems.length > error
    doc.filePath = mypath > error (read-only)
    doc = File(mypath).open() > error
    Do you mean if(app.documents[0].filePath = mypath)...?
    thx
    Loic

  • AfterOpen listener

    I am trying to set up a listener for InDesign, so that every time a doc is opened, "Overprint Preview" is turned on. I have the following script saved in the InDesign Startup Scripts folder:
    #targetengine 'session'
    main()
    function main()
    var myApplicationEventListener = app.addEventListener('afterOpen', myafterOpenHandler, false)
    function myafterOpenHandler(myEvent)
    //turn Overprint Preview on
    var myMenuAction = app.menuActions.item("$ID/Overprint Preview")
    myMenuAction.invoke()
    The menu invoke works by itself just fine, if a doc is open.
    But the script itself errors, just before the doc opens, presumably because the menu is not available yet, since the doc is not showing. The error is as follows:
    JavaScript Error!
    Error Number: 53762
    Error String: Action is not enabled.
    Line: 27
    Source: myMenuAction.invoke()
    Any ideas on this?????

    Rick, have You ever been able to fix that problem?
    If so I would be interested in Your solution.

  • [CS3 JS] event crashes InDesign

    Scripting ladies and gentlemen,
    I'm working on this event script that searches for linked PDF files and
    lets the user copy/relink them. Using the afterOpen eventListener however
    crashes InDesign no matter what I do. This is also the case with
    beforeClose. It appears that my function cnvrtPDFlnk is causing the crash
    (I'm able to alert succesfully with the afterOpen event if I //-comment
    the cnvrtPDFLnk(myDocument)).
    Do one of you scripting gurues have a tip?
    #targetengine "session"
    main();
    function main() {
       app.addEventListener("afterOpen", myEventFunction, false);
    function myEventFunction(myEvent) {
       var myDocument = myEvent.parent;
       var label = docLabel(myDocument, "PDFCheck");
       if(label) {
          //myEvent.stopPropagation();
          //myEvent.preventDefault();
          exit();
       else {
          cnvrtPDFLnk(myDocument);
    function docLabel(myDocument, key) {
       var hasLabel = (eval(myDocument.extractLabel(key))?true:false);
       return hasLabel;
    function cnvrtPDFLnk(myDocument) {
       var graphics = myDocument.allGraphics;
       var link; var linkExt; var linkType; var linkPath; var linkPageRef; var myConfirm; var myFolder; var myFile; var myOrgPath;
       var myLinkObjects = [];
       for (var i = 0; i < graphics.length; i++) {        
          link = graphics[i].itemLink;
          linkExt = link.filePath.split('.').pop().toLowerCase(); 
          linkType = link.linkType.toLowerCase();       
          if (linkExt == 'pdf' || linkType.match('pdf') != null) {
             link.show();
             if(myConfirm= confirm(link.name+"\nDo you want to convert this link?")?myLinkObjects.push(link):alert("Link skipped!\n"+link.name));
       if (myLinkObjects.length > 0) {
          myFolder = Folder.selectDialog("Point me to a hotfolder..");
          copyLink(myLinkObjects, myFolder); // run copyLink function - copies links according to myfolder
          if(myConfirm = confirm("Do you want to relink now?")) {
             reLink(myLinkObjects); // run reLink function - relinks according to myFile dialogue
             app.menuActions.item("Fit Page in Window").invoke();
             app.menuActions.item("First Page").invoke();    
       myDocument.insertLabel("PDFCheck", "true");
       }// no links
    }// end cnvrtPDFLnk
    Best regards,
    Rasmus

    Hi Rasmus,
    Here is an example of scripted plug-in — very simple yet useful for me.
    Its goal is to check color settings in InDesign and Photoshop after a document opens. We use two profiles at work: one for the main part of our magazine and another profile for its cover and the inset for another magazine. Sometimes, although rarely, we forget to switch on the correct setting.
    That's where the plug-in comes to the aid. After a document opens it checks if the file name contains certain characters – e.g. if file name starts with "Obl_" that means that this is a cover and the script checks the color settings, if they are not correct it gives warning.
    Here is short description of how to do it:
    Create a new scripted plug-in project from APIDTemplate.indd file.
    Open APID panel
    Enter 'docLoaded' into Event Filter field and press Enter
    Here is the script that does the job (the script file is generated in the same folder as indd-file):
    if (theItem.eventCode == "docLoaded") {
       var gKasmyDoc = app.activeDocument;
       var gKasDocumentName = app.activeDocument.name;
       KasCheckProfile();
       KasinfoFromPS();
    function KasCheckProfile(){
       var myIssueNumber = parseInt(gKasDocumentName.substr(2, 3));
       if (gKasDocumentName.substr(0, 2) == "Q_" && myIssueNumber >= 730 && myIssueNumber <= 999 && gKasDocumentName.match("_Vshivka") == null){
          if (app.colorSettings.workingSpaceCMYK != "ISO Web Coated"){
             alert("Внимание! Для газеты должен использоваться провиль \"ISO Web Coated\", а установлен. — " + app.colorSettings.workingSpaceCMYK);
       if (gKasDocumentName.substr(0, 2) == "Q_" && myIssueNumber >= 730 && myIssueNumber <= 999 && gKasDocumentName.match("_Vshivka") != null){
          if (app.colorSettings.workingSpaceCMYK != "ImationMatchprn175lpi_avr.icc          "){
             alert("Внимание! Для вшивки должен использоваться провиль \"ImationMatchprn175lpi_avr.icc\", а установлен. — " + app.colorSettings.workingSpaceCMYK);
       else if (gKasDocumentName.substr(0, 4) == "Obl_"){
          if (app.colorSettings.workingSpaceCMYK != "ImationMatchprn175lpi_avr.icc          "){
    //         alert("Внимание! Для обложки должен использоваться провиль \"ImationMatchprn175lpi_avr.icc\", а установлен. — " + app.colorSettings.workingSpaceCMYK);
             if (confirm("Внимание! Для обложки должен использоваться провиль \"ImationMatchprn175lpi_avr.icc\", а установлен. — " + app.colorSettings.workingSpaceCMYK)) {
                app.colorSettings.cmsSettings = "Listovaya Mashina";
    function KasinfoFromPS() {
       var bt = new BridgeTalk;
       bt.target = "photoshop";
       bt.body = "app.colorSettings;"
       bt.onResult = function(resObj) {
          var myResult = resObj.body;
          KascheckPsColorSettings(myResult);
       bt.send();
    function KascheckPsColorSettings(myColorSettings){
       var myIssueNumber = parseInt(gKasDocumentName.substr(2, 3));
       if (gKasDocumentName.substr(0, 2) == "Q_" && myIssueNumber >= 730 && myIssueNumber <= 999 && gKasDocumentName.match("_Vshivka") == null){
          if (myColorSettings != "ISO Web Coated"){
             alert("Внимание в Photoshop! Для газеты должен использоваться провиль \"ISO Web Coated\", а установлен. — \"" + myColorSettings + "\"");
       if (gKasDocumentName.substr(0, 2) == "Q_" && myIssueNumber >= 730 && myIssueNumber <= 999 && gKasDocumentName.match("_Vshivka") != null){
          if (myColorSettings != "Listovaya Mashina"){
             alert("Внимание в Photoshop! Для вшивки должен использоваться провиль \"ImationMatchprn175lpi_avr.icc\", а установлен. — \"" + myColorSettings + "\"");
       else if (gKasDocumentName.substr(0, 4) == "Obl_"){
          if (myColorSettings != "Listovaya Mashina"){
             alert("Внимание в Photoshop! Для обложки должен использоваться провиль \"ImationMatchprn175lpi_avr.icc\", а установлен. — \"" + myColorSettings + "\"");
    You can put your own stuff into the script:
    if (theItem.eventCode == "docLoaded") {
    // do your stuff here
    And finally generate the plug-in.
    Kasyan

  • [JS] (CS3) eventListener & doScript

    Hello everyone,
    Is it possible to create an eventListener, like "afterOpen" that would trigger a script file?
    In CS2, I wrote a few scripts that were managed by inEventScript Plug-in. We are upgrading to CS3 and this plug-in was not transported to CS3 since "eventListener" is available.
    So if possible, what is the syntax to execute the doScript within the Event Handler Function? It would not be app.doScript. So what?
    Thank you, Alex.

    I am running into another issue now.
    It does execute the script "afterOpen", but it is displaying my alert "No document open!!!" from my test: app.documents.lenght == 0.
    So is there no Open Document altough it is an "after"???
    The goal is to be able to execute some my regular script AND have have them attached to some events ("Open, Close, Copy & Paste). Or am I stuck to modify & include them in the STARTUP script. I know I can use event.parent to access the Document opened.
    Also, are there events attached to pasting & copying (Before &/or after)?
    Here is the Startup script.
    #targetengine "session"
    main();
    function main()
    var myScriptName = app.activeScript.fsName;
    var myScriptPath = app.activeScript.path;
    // var myPath = app.filePath + "/Scripts/Scripts Panel/~InEventScript/";
    //** Number 0
    var myFile = new File (myScriptPath+"/PrePressOPEN.jsx");
    if (myFile.exists)
    app.addEventListener( "afterOpen", myFile, false );
    else
    alert ("File:\n" + myFile.fsName + "\n...has NOT been Installed!!!");

  • [JS CS4] Getting unexpected filenames - *TempScratchDocument*

    Hi,
    I have a Startup Script which launches event handlers to write to a log file when an InDesign document is opened and closed.
    The functions write the filename, username and time of the event to the log file but I am getting unexpected filenames written to the log and wondered if anyone could explain where these are coming from.
    An example from the log file is:
    Started: Untitled-4 lhusband Wed Jun 09 2010 10:55:34
    Finished: -/*TempScratchDocument*/- lhusband Wed Jun 09 2010 10:55:34
    It is the -/*TempScratchDocument*/- bit I don't understand.
    My thoughts are that doing a copy/paste or saving a snippet or putting something in a library could be creating a "new" temporary document somewhere in InDesign memory, but I cannot replicate this on my own PC.
    This script is running on 30 PCs and I only get this for 2 or 3 users.
    The event listeners are:
    var myEventListener1 = app.addEventListener("afterOpen", openJob, false);
    var myEventListener2 = app.addEventListener("afterSaveAs",openJob, false);
    var myEventListener3 = app.addEventListener("afterNew",openJob, false);
    var myEventListener4 = app.addEventListener("beforeClose", closeJob, false);
    var myEventListener5 = app.addEventListener("beforeSaveAs",closeJob, false);
    The two function called are:
    function openJob(myEvent) {
            var myDate = new Date;
            var myTime = myDate.toString();
            var myEventTime = myTime.slice(0,-9);
            var user=getUser(); // function to get username
           try  {   var myPath = myEvent.parent.fullName } catch(e) { var myPath = myEvent.parent.name } // to handle unsaved documents
        // Write to Jobs.Log
            myFile = File("//10.19.55.220/Logs/jobs.log");
            myFile2.open("a");
            myFile.write('\n' + "Started:" + '\t' + decodeURI(myPath) + '\t' + user + '\t' + myEventTime);
            myFile.close();
    } // end of function
    function closeJob(myEvent) {
            var myDate = new Date;
            var myTime = myDate.toString();
            var myEventTime = myTime.slice(0,-9);
            var user=getUser(); // function to get username
           try  {   var myPath = myEvent.parent.fullName } catch(e) { var myPath = myEvent.parent.name } // to handle unsaved documents
        // Write to Jobs.Log
            myFile = File("//10.19.55.220/Logs/jobs.log");
            myFile2.open("a");
            myFile.write('\n' + "Finished:" + '\t' + decodeURI(myPath) + '\t' + user + '\t' + myEventTime);
            myFile.close();
    } // end of function
    If anyone can shed any light on this I would be most grateful.
    Thanks
    Simon Kemp.

  • [CS3][JS] beforeClose event listener problem

    Hi all,
    I want my script to do the following: every time when a user closes a document, I wish for "Check Spelling..." dialog box to show up and after the user finishes spell-checking, the document should be closed.
    But instead, if I have one document open, I get an error: Error Number: 53762, Error String: Action is not enabled, and if more than one document open, the dialog opens in the wrong document.
    As far as I understand, the problem is that the menu action is invoked AFTER the document has already been closed – it is quite clear that opening the dialog with no documents open makes no sense – that’s why the error occurs.
    Does anybody know how to solve this? Why beforeClose event type doesn’t correspond to its name? The scripting guide states: “beforeClose – Appears after a close-document request is made but before the document is closed.”
    Here is the script:
    #targetengine "session"
    main();
    function main(){
       var myEventListener = app.addEventListener("beforeClose", myCheckSpelling, false);
    function myCheckSpelling(myEvent){
       app.menuActions.item("Check Spelling...").invoke();
    Kasyan

    Thank you Ole.
    I've been at it for about 6 months.
    I am providing 3 modules. All modules are in 1 folder. That's why the ScriptPath & Department variables.
    FYI: app.pdfPlacePreferences.pageNumber was used solved issues with InEvenScript plugin for CS2. That plugin was NOT handling a loop call. To solve it, I've used a variable to turn ON & OFF the handler. "Import" is used in the OPEN script, and that will execute the event!
    1) Startup. I trimmed it for you but I kept the orignal OPEN-Event disabled. See PrePressEVENT.
    2) PrePressTEST. It's a trimmed version of the actual PrePressOPEN. But it makes InDesign crash. FYI: PrePressOPEN works perfectly when triggered manualy (Script Panel).
    3) PrepressEVENT. Disabled in Startup, I am using this one so I can debug the EVENT and do actual work at the same time. Until it crashed of course.
    The window.add() is what makes it crash. Without it, fine. But if removed myDoc = app.activeDocument points to the wrong one!
    Thank you in advance. Hope this is clear enough.
    Module STARTUP
    =====================
    #target indesign
    #targetengine "session"
    app.scriptPreferences.version = 5.0;
    //******************** BEGIN Main ********************
    var myScriptName = app.activeScript.fsName;
    var myScriptPath = app.activeScript.path;
    var myErrorStyle = "*****Error while Updating!"
    var myMsgStyle = "*****No UpDate! (Delete to Reset)";
    var myDept = "PrePress";
    //*** Initialize SCRIPT Variables
    app.scriptArgs.clear();
    app.scriptArgs.set("Department", "PrePress");
    app.scriptArgs.set("ErrorStyle", "*****Error while Updating!");
    app.scriptArgs.set("MsgStyle", "*****No UpDate! (Delete to Reset)");
    app.scriptArgs.set("Event_Path", myScriptPath); //***Path to InEventScript Plug-In
    app.scriptArgs.set("Event_Test", myScriptPath + "/"+myDept+"TEST.jsx"); //*** Debugging MODULE
    app.scriptArgs.set("Event_Open", myScriptPath + "/"+myDept+"OPEN.jsx");
    app.scriptArgs.set("Event_Close", myScriptPath + "/"+myDept+"CLOSE.jsx");
    app.scriptArgs.set("Event_Copy", myScriptPath + "/"+myDept+"COPY.jsx");
    app.scriptArgs.set("Event_Clean", myScriptPath + "/"+myDept+"CLEAN.jsx");
    app.scriptArgs.set("Event_Print", myScriptPath + "/"+myDept+"PRINT.jsx");
    app.scriptArgs.set("Event_App", myScriptPath + "/"+myDept+"APPPreferences.jsx");
    app.scriptArgs.set("Event_Doc", myScriptPath + "/"+myDept+"DOCPreferences.jsx");
    //*** Initialize GLOBAL Variables
    app.pdfPlacePreferences.pageNumber = 1; //***Flag to PREVENT InEventScript Plug-In RECURSIVE (Loop)
    SkipWRDS = new Array;
    //*** REMOVE all EVENTS
    app.eventListeners.everyItem().remove();
    //******************** EVENTS ********************
    //app.addEventListener("afterOpen", EventOpen, false); //STILL INDESIGN CRASH with OPEN !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    var tmp = "List of Events loaded\n----------------------\n";
    var myEvents = app.eventListeners;
    for (var cpt = 0; cpt < myEvents.length; cpt++)
    tmp += "Event : " + myEvents[cpt].parent.name + "\tType: " + myEvents[cpt].eventType + "\n";
    //alert ("\tPREPRESS Area\n\t\==========\n\n"+tmp);
    alert ("\tTEST Area\n\t=======\n\n"+tmp);
    //******************** END Main ********************
    //****************** FUNCTIONS Definitions ********************
    function EventOpen (itsEvent)
    var myExeSrcFile = new File (app.scriptArgs.get("Event_Open"));
    if (myExeSrcFile.exists)
    if (app.pdfPlacePreferences.pageNumber == 99999)
    app.pdfPlacePreferences.pageNumber = 1; //***Flag to PREVENT InEventScript Plug-In RECURSIVE (Loop)
    else
    app.pdfPlacePreferences.pageNumber = 1; //***Flag to PREVENT InEventScript Plug-In RECURSIVE (Loop)
    // itsEvent.preventDefault();
    // itsEvent.stopPropagation();
    itsEvent.parent.windows.add(); //*** Doc. has no Window!!!
    myExeSrcFile.open ('r:(read)');
    app.doScript(myExeSrcFile, ScriptLanguage.javascript);
    myExeSrcFile.close();
    else
    alert ("Error! Missing File:\n\n" + myExeSrcFile.fsName);
    return;
    Module PrePressTEST
    =====================
    #target indesign
    //#include "PrePressLIBRARY.jsxinc"
    app.scriptPreferences.version = 5.0;
    //******************** BEGIN Main ********************
    if (app.modalState) //*** Alert already displayed
    exit();
    if (app.pdfPlacePreferences.pageNumber == 99999)
    app.pdfPlacePreferences.pageNumber = 1; //***Flag to PREVENT InEventScript Plug-In RECURSIVE (Loop)
    exit();
    if (app.documents.length == 0)
    exit();
    var myDoc = app.activeDocument;
    //*** ALL DOCUMENTS PREFERENCE
    myDoc.textPreferences.showInvisibles = true;
    myDoc.viewPreferences.showRulers = true;
    myDoc.layoutWindows[0].transformReferencePoint = AnchorPoint.centerAnchor;
    alert (myDoc.name);
    //******************** END Main ********************
    Module PrePressEVENT
    =====================
    #target indesign
    #targetengine "session"
    app.scriptPreferences.version = 5.0;
    //******************** BEGIN Main ********************
    var myEvents = app.eventListeners;
    var tmp = "\nList of Events removed\n------------------------\n";
    for (var cpt = myEvents.length-1 ; cpt >= 0 ; cpt--)
    if (myEvents[cpt].eventType == "afterOpen")
    tmp += "Event #" + cpt + "\tType: " + myEvents[cpt].eventType + "\n";
    myEvents[cpt].remove(); //*** There MAY be MORE than 1 instance.
    //******************** EVENTS ********************
    app.addEventListener("afterOpen", EventOpen, false);
    tmp += "\nList of Events loaded\n----------------------\n";
    var myEvents = app.eventListeners;
    for (var cpt = 0; cpt < myEvents.length; cpt++)
    tmp += "Event : " + myEvents[cpt].parent.name + "\tType: " + myEvents[cpt].eventType + "\n";
    alert ("\tTEST Area\n\t=======\n\n"+tmp);
    //******************** END Main ********************
    //****************** FUNCTIONS Definitions ********************
    function EventOpen (itsEvent)
    // app.scriptArgs.set("Event_Listener", itsEvent.parent.toSource()); //*** PASS Argument
    var myExeSrcFile = new File (app.scriptArgs.get("Event_Test"));
    if (myExeSrcFile.exists)
    if (app.pdfPlacePreferences.pageNumber == 99999)
    app.pdfPlacePreferences.pageNumber = 1; //***Flag to PREVENT InEventScript Plug-In RECURSIVE (Loop)
    else
    app.pdfPlacePreferences.pageNumber = 1; //***Flag to PREVENT InEventScript Plug-In RECURSIVE (Loop)
    EventInfo (itsEvent);
    itsEvent.preventDefault();
    itsEvent.stopPropagation();
    itsEvent.parent.windows.add(); //*** Doc. has no Window!!!
    myExeSrcFile.open ('r:(read)');
    app.doScript(myExeSrcFile, ScriptLanguage.javascript);
    myExeSrcFile.close();
    alert ("Executed...");
    else
    alert ("Error! Missing File:\n\n" + myExeSrcFile.fsName);
    return;
    function EventInfo (itsEvent)
    var myString = "Handling Event: " +itsEvent.eventType;
    myString += "\r\rTarget: " + itsEvent.target + " " +itsEvent.target.name;
    myString += "\rCurrent: " +itsEvent.currentTarget + " " + itsEvent.currentTarget.name;
    myString += "\r\rPhase: " + GetPhaseName(itsEvent.eventPhase );
    myString += "\rCaptures: " +itsEvent.captures;
    myString += "\rBubbles: " + itsEvent.bubbles;
    myString += "\r\rCancelable: " +itsEvent.cancelable;
    myString += "\rStopped: " +itsEvent.propagationStopped;
    myString += "\rCanceled: " +itsEvent.defaultPrevented;
    myString += "\r\rTime: " +itsEvent.timeStamp;
    alert(myString);
    function GetPhaseName(myPhase)
    switch(myPhase){
    case EventPhases.atTarget:
    myPhaseName = "At Target";
    break;
    case EventPhases.bubblingPhase:
    myPhaseName = "Bubbling";
    break;
    case EventPhases.capturingPhase:
    myPhaseName = "Capturing";
    break;
    case EventPhases.done:
    myPhaseName = "Done";
    break;
    case EventPhases.notDispatching:
    myPhaseName = "Not Dispatching";
    break;
    return myPhaseName;

  • Is it possible to remove user interaction in a eventListener ?

    Hi,
    I am working on two scripts that both need to deal with the user interaction.
    This following script works just fine. The only matter is that Indesign alerts me that the script prevented the UI dialog from opening.
    What if I don't want any alert ?
    #targetengine "newdialog"
    Application.prototype.main = function(){
         //app.addEventListener ("beforeNew", preventMe, false);
         var myMenuAction = app.menuActions.item("$ID/Document...");
         myMenuAction.addEventListener ("beforeInvoke", preventMe, false)
    function preventMe(myEvent){
         //alert(myEvent.cancelable);
         myEvent.stopPropagation();
         myEvent.preventDefault();
    app.main();
    I thought about userInteractionLevel but I tried to use it recently and I couldn't get it working. My intention was to get an automated update of my modified links when opening a file.
    It's like
    app.scriptPreferences.userInteractionLevel
    couldn't be set once the script has been launched.
    #targetengine "autolinkupdate"
    main();
    function main(){
         var myMenuAction = app.menuActions.item("$ID/kPMOpenDocTextKey");
         myMenuAction.addEventListener("beforeInvoke",removeInteraction,false);
         //app.addEventListener("beforeOpen",removeInteraction, false);
         app.addEventListener("afterOpen",updatelinks, false);
    function updatelinks(myEvent){
         var doc=myEvent.parent;
         var lk = doc.links;
         for(var i=0; i<lk.length; i++){
              try{
                   lk[i].update();
              catch(e){}
         app.scriptPreferences.userInteractionLevel = UserInteractionLevels.INTERACT_WITH_ALL;
    function removeInteraction(myEvent){
         app.scriptPreferences.userInteractionLevel = UserInteractionLevels.NEVER_INTERACT;
    So my question is : Is it possible to remove user interaction in a eventListener ?
    Thanks,
    Loic

    Assuiming NHTEST is a database link to the remote database connecting with SCOTT, use user_Tab_cols@NHTESTNicolas.

  • Collapsible Panel open on new page

    I am using the Spry Collapsible Panel as a sidebar menu. I
    would like to be able to click on a menu link, which takes me to a
    new page with the relevant panel staying open on that new page. Is
    this possible? If so, how do I make it happen? I am not great with
    codes and other jargon, so if someone could help me with "exactly"
    what I need to do, it would be most appreciated.
    Many thanks,
    Caryl

    First Include SpryDOMUtils.js in your file;
    Than add this script in the head of the page, or include it
    in a script.
    <script language="JavaScript" type="text/javascript">
    //please note, that my SpryDOMUtils.js is packed so i have a
    the extra onUNLOAD listener in the code below.
    // * Declare vars;
    var Spry;
    if (!Spry.Utils) Spry.Utils = {};
    var coll1; //declare vars outside the function so u can use
    then tab panel everywhere
    // * This is a addition to the SpryDomUtils.js U can include
    it under line #262
    // Or leave it in a javascript external / internal
    // This function will fire anything when u leave the current
    page.
    Spry.Utils.addUnLoadListener = function(handler)
    if (typeof window.addEventListener != 'undefined')
    window.addEventListener('unload', handler, false);
    else if (typeof document.addEventListener != 'undefined')
    document.addEventListener('unload', handler, false);
    else if (typeof window.attachEvent != 'undefined')
    window.attachEvent('onunload', handler);
    //This function will be used by cookie to check if the value
    is allready in the cookie, if so it returns it position
    Spry.Utils.CheckArray = function(a, s){
    for (i=0; i<a.length; i++){if (a
    == s)return i;}return null;
    * SPRY COOKIE; HOW TO USE;
    * constructor:
    Spry.Utils.Cookie(type,string,{name:'cookie_name',path:'/',days:'number'};
    * TYPE:
    * - create : this creates *saves* the cookie
    * : Spry.Utils.Cookie('create','string or
    array',{name:'Spry_Cookie'});
    * - get : this will return the cookie in array format
    * : Spry.Utils.Cookie('get','',{name:'Spry_Cookie'});
    * - destory: this will destroy the cookie
    * : Spry.Utils.Cookie('destroy','',{name:'Spry_Cookie'});
    * - add : this allows u to add value to the cookie with out
    creating a whole new string
    * it will place the add value behind the older cookie
    values, it checks if the value is allready in the cookie,
    * if it is, it will NOT add it in the cookie.
    * STRING:
    * This is the data what u want to store in to the cookie, it
    can be an Array or a normal string / var
    * OPTIONS:
    * - name: : this is the name of the cookie so u can identify
    it
    * - path: : optional path for the cookie;
    * - days: : the amount of days for the cookie to be saved.
    Spry.Utils.Cookie = function(type,string,options){
    if(type == 'create'){
    var expires='';
    if(options.days != null){
    var date = new Date();
    var UTCString;
    date.setTime(date.getTime()+(days*24*60*60*1000));
    expires = "; expires="+date.toUTCString();
    var thePath = '; path=/';
    if(options.path != null){
    thePath = '; path='+options.path;
    document.cookie =
    options.name+'='+escape(string)+expires+thePath;
    }else if(type == 'get'){
    var nameEQ = options.name + '=';
    var ca = document.cookie.split(';');
    for (var i=0; i<ca.length; i++){
    var c = ca;
    while (c.charAt(0)==' '){
    c = c.substring(1,c.length);
    }if (c.indexOf(nameEQ)==0) return
    unescape(c.substring(nameEQ.length,c.length)).split(",");
    }return null;
    }else if(type == 'destory'){
    Spry.Utils.Cookie('create','',{
    name: options.name
    }else if(type == 'add'){
    var c = Spry.Utils.Cookie('get','',{name:options.name});
    if (typeof string == 'object') {
    for (i = 0, str; str = string
    , i < string.length; i++) {
    if (Spry.Utils.CheckArray(c, str) == null)c.push(str);
    }else{
    if (Spry.Utils.CheckArray(c, string) == null) c.push(string)
    Spry.Utils.Cookie('create',c,{name:options.name});
    // * check if we have a panel to set from cookie value
    // * becouse we are using spry dom we can also include the
    tab construction within this function.
    Spry.Utils.addLoadListener(function(){
    //becouse cookie GET returns a array we have to add a var
    before it to store the data
    var tab = Spry.Utils.Cookie('get','',{name:'tabs_history'});
    coll1 = Spry.Widget.CollapsiblePanel('ID_OF_PANEL');
    if(tab == "open")coll1.open();
    else coll1.close();
    Spry.Utils.addUnLoadListener(function(){
    var classnames =
    document.getElementById('ID_OF_THE_PANEL').className;
    if(classnames.match("CollapsiblePanelOpen"))var tab =
    'open';
    else var tab = 'closed';
    //destroy old cookie (i want a clean cookie)
    Spry.Utils.Cookie('destory','',{name:'tabs_history'});
    //setting the new cookie value
    Spry.Utils.Cookie('create',tab,{name:'tabs_history'});
    </script>
    The best way to copy the script is to press the | Quote |
    button and copy it out of th quote becouse there are some taggs
    used by the forum sofware in it.
    If u have placed it in your header u need to do few edits.
    im using coll1 as collaps variable name (constructor) if u
    use a other, change it to yours.
    also change coll1 = new
    Spry.Widget.CollapsiblePanel("coll1"); to your desired ID
    This will solve your problem ;)
    To see it in action on tab panels (where i created it for)
    http://www.3rd-eden.com/Spry-it.com/examples/restyled_tabs/
    This is option 1. If u want 1 panel to be open on your page
    if the user want it. If u want to open a random panel on click
    function, u can use:
    http://labs.adobe.com/technologies/spry/samples/utils/URLUtilsSample.html
    SpryURLUtils.js
    This will read param's that u send true a url. and responds
    to it. U can see it in action with the tab panels in the example
    above.
    add this in the header of your page; (also include the
    SpryURLutils.js)
    <script type="text/javascript">
    // Grabs the values of the URL parameters for the current
    URL.
    var params = Spry.Utils.getLocationParamsAsObject();
    </script>
    and change your constructor like this
    <script type="text/javascript">
    //sets default as open.
    var ac1 = new
    Spry.Widget.CollapsiblePanel("myCollapsiblePanel",{contentIsOpen:(params.ac1open
    ? params.ac1open : true));
    </script>
    U can add this behind a url to activate it:
    <a href="testpage.html?ac1open=true" > test page ac1
    open </a>
    true is open, and false is closed. ;)
    I hope this helps :D

  • On a form w Validation, how to redirect to a custom page

    Hi. I have created a form in Dreamweaver CS5 that uses spry validation successfully. Once the form is submitted, the user is redirected to the home page. But I don't want that redirect.
    My question is, how can I have the validated page redirect to a custom thank you page I designed? I don't know the exact code/syntax to write to make it do what I want and, even if I had the code, I wouldn't know exactly where it should be placed. Please help if you can. Here's the source code. )BTW, when I use Dreamweaver Behaviors to add a URL redirect, it ignores the required validation and simply allows you to click the submit button and redirect.) Many thanks!
    <!DOCTYPE HTML>
    <html>
    <head>
    <meta charset="UTF-8">
    <link href="../_css/main.css" rel="stylesheet" media="screen, projection">
    <link href="../_css/forms.css" rel="stylesheet" media="screen, projection">
    <title></title>
    <!--[if lt IE 9]>
    <script src="http://ie7-js.googlecode.com/svn/version/2.1(beta4)/IE9.js"></script><![endif]-->
    <script src="../SpryAssets/SpryValidationTextField.js" type="text/javascript"></script>
    <link href="../SpryAssets/SpryValidationTextField.css" rel="stylesheet" type="text/css">
    <script type="text/javascript">
    <!-- **** I think the line of code for the redirect is here??...I just don't know how to write the code to redirect to the page I want ***** -->
    function MM_goToURL() { //v3.0
      var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
      for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
    </script>
    </head>
    <body>
    <header id="pageHeader">
    <a href="../index.htm"><img src="../_images/logo.gif" width="170" height="91" alt="HMN logo" id="logo"></a>
    <img src="../_images/tagline.png" width="296" height="92" alt="HMN tagline" id="tagline">
    </header>
    <nav id="mainNav">
    <ul>
    <li><a href="../index.htm">Home</a></li>
    <li><a href="../press.htm">Press</a></li>
    <li><a href="../about.htm">About</a></li>
    <li><a href="../contact.htm">Contact</a></li>
    </ul>
    </nav>
    <br class="clear">
    <div class="headerContact">
    </div>
    <article>
      <!-- The file webformmailer.php sits on the web server at godaddy.com in case that matters -->
    <section id="Request">
    <p id="intro">To request your link for the downloadable <span id="highlight">Media Kit</span>, please provide the following information:</p>
    <form name="Request" method="post" action="../../webformmailer.php"> <p id="formCaption">Fields marked with * are required.</p>
      <p><span id="sprytextfield1">
        <label for="first_name">First Name:*</label>
        <input type="text" name="first_name" id="first_name">
        <span class="textfieldRequiredMsg">(required)</span></span></p>
      <p><span id="sprytextfield2">
        <label for="last_name">Last Name:*</label>
        <input type="text" name="last_name" id="last_name">
        <span class="textfieldRequiredMsg">(required)</span></span></p>
      <p><span id="sprytextfield3">
        <label for="company">Company:*</label>
        <input type="text" name="company" id="company">
        <span class="textfieldRequiredMsg">(required)</span></span></p>
      <p>
        <label for="address">Address:</label>
        <input type="text" name="address" id="address">
      </p>
      <p>
        <label for="address_2">Address 2:</label>
        <input type="text" name="address_2" id="address_2">
      </p>
      <p>
        <label for="city">City:</label>
        <input type="text" name="city" id="city">
      </p>
      <p>
        <label for="state">State:</label>
        <input type="text" name="state" id="state">
      </p>
      <p>
        <label for="zip">Zip:</label>
        <input type="text" name="zip" id="zip">
      </p>
      <p><span id="sprytextfield4">
      <label for="email">Email:*</label>
      <input type="text" name="email" id="email">
      <span class="textfieldRequiredMsg">(required)</span><span class="textfieldInvalidFormatMsg">Invalid format.</span></span> </p>
      <p>
      <input name="submit" type="image" id="submit" onClick="MM_goToURL('parent','media_kit_download.htm');return document.MM_returnValue" src="../_images/btn_submit.png">
      </p>
      <p> </p>
    </form>
    <p>
    </p>
    </div>
    </div>
    </section>
    </article>
    <script type="text/javascript">
    var sprytextfield1 = new Spry.Widget.ValidationTextField("sprytextfield1", "none", {validateOn:["blur"]});
    var sprytextfield2 = new Spry.Widget.ValidationTextField("sprytextfield2", "none", {validateOn:["blur"]});
    var sprytextfield3 = new Spry.Widget.ValidationTextField("sprytextfield3", "none", {validateOn:["blur"]});
    var sprytextfield4 = new Spry.Widget.ValidationTextField("sprytextfield4", "email", {validateOn:["blur"]});
    </script>
    </body>
    </html>

    Thanks for replying. The  URL you've bolded is actually the correct page I'd like the redirect to go to when the form is successfully submitted after validation. But for some reason, that URL request is being ignored and the redirect brings me back to the index page in the root directory. I don't see anywhere in the code that makes the request to do that. Unless that's a default behavior if I've gotten the redirect wrong?
    I don't know if this is helpful, but there is also a .js file that Dreamweaver created and attached to the above HTML source file. The .js file appears to have all the spry code validation including code for features and widgets I'm not even using. I searched through the code several times trying to identify where there might be a redirect to the index page but didn't recognize anything that made sense to me. Here is the complete, unedited file:
    // SpryValidationTextField.js - version 0.38 - Spry Pre-Release 1.6.1
    // Copyright (c) 2006. Adobe Systems Incorporated.
    // All rights reserved.
    // Redistribution and use in source and binary forms, with or without
    // modification, are permitted provided that the following conditions are met:
    //   * Redistributions of source code must retain the above copyright notice,
    //     this list of conditions and the following disclaimer.
    //   * Redistributions in binary form must reproduce the above copyright notice,
    //     this list of conditions and the following disclaimer in the documentation
    //     and/or other materials provided with the distribution.
    //   * Neither the name of Adobe Systems Incorporated nor the names of its
    //     contributors may be used to endorse or promote products derived from this
    //     software without specific prior written permission.
    // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
    // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
    // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
    // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
    // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
    // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
    // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    // POSSIBILITY OF SUCH DAMAGE.
    (function() { // BeginSpryComponent
    if (typeof Spry == "undefined") window.Spry = {}; if (!Spry.Widget) Spry.Widget = {};
    Spry.Widget.BrowserSniff = function()
        var b = navigator.appName.toString();
        var up = navigator.platform.toString();
        var ua = navigator.userAgent.toString();
        this.mozilla = this.ie = this.opera = this.safari = false;
        var re_opera = /Opera.([0-9\.]*)/i;
        var re_msie = /MSIE.([0-9\.]*)/i;
        var re_gecko = /gecko/i;
        var re_safari = /(applewebkit|safari)\/([\d\.]*)/i;
        var r = false;
        if ( (r = ua.match(re_opera))) {
            this.opera = true;
            this.version = parseFloat(r[1]);
        } else if ( (r = ua.match(re_msie))) {
            this.ie = true;
            this.version = parseFloat(r[1]);
        } else if ( (r = ua.match(re_safari))) {
            this.safari = true;
            this.version = parseFloat(r[2]);
        } else if (ua.match(re_gecko)) {
            var re_gecko_version = /rv:\s*([0-9\.]+)/i;
            r = ua.match(re_gecko_version);
            this.mozilla = true;
            this.version = parseFloat(r[1]);
        this.windows = this.mac = this.linux = false;
        this.Platform = ua.match(/windows/i) ? "windows" :
                        (ua.match(/linux/i) ? "linux" :
                        (ua.match(/mac/i) ? "mac" :
                        ua.match(/unix/i)? "unix" : "unknown"));
        this[this.Platform] = true;
        this.v = this.version;
        if (this.safari && this.mac && this.mozilla) {
            this.mozilla = false;
    Spry.is = new Spry.Widget.BrowserSniff();
    Spry.Widget.ValidationTextField = function(element, type, options)
        type = Spry.Widget.Utils.firstValid(type, "none");
        if (typeof type != 'string') {
            this.showError('The second parameter in the constructor should be the validation type, the options are the third parameter.');
            return;
        if (typeof Spry.Widget.ValidationTextField.ValidationDescriptors[type] == 'undefined') {
            this.showError('Unknown validation type received as the second parameter.');
            return;
        options = Spry.Widget.Utils.firstValid(options, {});
        this.type = type;
        if (!this.isBrowserSupported()) {
            //disable character masking and pattern behaviors for low level browsers
            options.useCharacterMasking = false;
        this.init(element, options);
        //make sure we validate at least on submit
        var validateOn = ['submit'].concat(Spry.Widget.Utils.firstValid(this.options.validateOn, []));
        validateOn = validateOn.join(",");
        this.validateOn = 0;
        this.validateOn = this.validateOn | (validateOn.indexOf('submit') != -1 ? Spry.Widget.ValidationTextField.ONSUBMIT : 0);
        this.validateOn = this.validateOn | (validateOn.indexOf('blur') != -1 ? Spry.Widget.ValidationTextField.ONBLUR : 0);
        this.validateOn = this.validateOn | (validateOn.indexOf('change') != -1 ? Spry.Widget.ValidationTextField.ONCHANGE : 0);
        if (Spry.Widget.ValidationTextField.onloadDidFire)
            this.attachBehaviors();
        else
            Spry.Widget.ValidationTextField.loadQueue.push(this);
    Spry.Widget.ValidationTextField.ONCHANGE = 1;
    Spry.Widget.ValidationTextField.ONBLUR = 2;
    Spry.Widget.ValidationTextField.ONSUBMIT = 4;
    Spry.Widget.ValidationTextField.ERROR_REQUIRED = 1;
    Spry.Widget.ValidationTextField.ERROR_FORMAT = 2;
    Spry.Widget.ValidationTextField.ERROR_RANGE_MIN = 4;
    Spry.Widget.ValidationTextField.ERROR_RANGE_MAX = 8;
    Spry.Widget.ValidationTextField.ERROR_CHARS_MIN = 16;
    Spry.Widget.ValidationTextField.ERROR_CHARS_MAX = 32;
    /* validation parameters:
    *  - characterMasking : prevent typing of characters not matching an regular expression
    *  - regExpFilter : additional regular expression to disalow typing of characters
    *        (like the "-" sign in the middle of the value); use for partial matching of the currently typed value;
    *         the typed value must match regExpFilter at any moment
    *  - pattern : enforce character on each position inside a pattern (AX0?)
    *  - validation : function performing logic validation; return false if failed and the typedValue value on success
    *  - minValue, maxValue : range validation; check if typedValue inside the specified range
    *  - minChars, maxChars : value length validation; at least/at most number of characters
    Spry.Widget.ValidationTextField.ValidationDescriptors = {
        'none': {
        'custom': {
        'integer': {
            characterMasking: /[\-\+\d]/,
            regExpFilter: /^[\-\+]?\d*$/,
            validation: function(value, options) {
                if (value == '' || value == '-' || value == '+') {
                    return false;
                var regExp = /^[\-\+]?\d*$/;
                if (!regExp.test(value)) {
                    return false;
                options = options || {allowNegative:false};
                var ret = parseInt(value, 10);
                if (!isNaN(ret)) {
                    var allowNegative = true;
                    if (typeof options.allowNegative != 'undefined' && options.allowNegative == false) {
                        allowNegative = false;
                    if (!allowNegative && value < 0) {
                        ret = false;
                } else {
                    ret = false;
                return ret;
        'real': {
            characterMasking: /[\d\.,\-\+e]/i,
            regExpFilter: /^[\-\+]?\d(?:|\.,\d{0,2})|(?:|e{0,1}[\-\+]?\d{0,})$/i,
            validation: function (value, options) {
                var regExp = /^[\+\-]?[0-9]+([\.,][0-9]+)?([eE]{0,1}[\-\+]?[0-9]+)?$/;
                if (!regExp.test(value)) {
                    return false;
                var ret = parseFloat(value);
                if (isNaN(ret)) {
                    ret = false;
                return ret;
        'currency': {
            formats: {
                'dot_comma': {
                    characterMasking: /[\d\.\,\-\+\$]/,
                    regExpFilter: /^[\-\+]?(?:[\d\.]*)+(|\,\d{0,2})$/,
                    validation: function(value, options) {
                        var ret = false;
                        //2 or no digits after the comma
                        if (/^(\-|\+)?\d{1,3}(?:\.\d{3})*(?:\,\d{2}|)$/.test(value) || /^(\-|\+)?\d+(?:\,\d{2}|)$/.test(value)) {
                            value = value.toString().replace(/\./gi, '').replace(/\,/, '.');
                            ret = parseFloat(value);
                        return ret;
                'comma_dot': {
                    characterMasking: /[\d\.\,\-\+\$]/,
                    regExpFilter: /^[\-\+]?(?:[\d\,]*)+(|\.\d{0,2})$/,
                    validation: function(value, options) {
                        var ret = false;
                        //2 or no digits after the comma
                        if (/^(\-|\+)?\d{1,3}(?:\,\d{3})*(?:\.\d{2}|)$/.test(value) || /^(\-|\+)?\d+(?:\.\d{2}|)$/.test(value)) {
                            value = value.toString().replace(/\,/gi, '');
                            ret = parseFloat(value);
                        return ret;
        'email': {
            characterMasking: /[^\s]/,
            validation: function(value, options) {
                var rx = /^[\w\.-]+@[\w\.-]+\.\w+$/i;
                return rx.test(value);
        'date': {
            validation: function(value, options) {
                var formatRegExp = /^([mdy]+)[\.\-\/\\\s]+([mdy]+)[\.\-\/\\\s]+([mdy]+)$/i;
                var valueRegExp = this.dateValidationPattern;
                var formatGroups = options.format.match(formatRegExp);
                var valueGroups = value.match(valueRegExp);
                if (formatGroups !== null && valueGroups !== null) {
                    var dayIndex = -1;
                    var monthIndex = -1;
                    var yearIndex = -1;
                    for (var i=1; i<formatGroups.length; i++) {
                        switch (formatGroups[i].toLowerCase()) {
                            case "dd":
                                dayIndex = i;
                                break;
                            case "mm":
                                monthIndex = i;
                                break;
                            case "yy":
                            case "yyyy":
                                yearIndex = i;
                                break;
                    if (dayIndex != -1 && monthIndex != -1 && yearIndex != -1) {
                        var maxDay = -1;
                        var theDay = parseInt(valueGroups[dayIndex], 10);
                        var theMonth = parseInt(valueGroups[monthIndex], 10);
                        var theYear = parseInt(valueGroups[yearIndex], 10);
                        // Check month value to be between 1..12
                        if (theMonth < 1 || theMonth > 12) {
                            return false;
                        // Calculate the maxDay according to the current month
                        switch (theMonth) {
                            case 1:    // January
                            case 3: // March
                            case 5: // May
                            case 7: // July
                            case 8: // August
                            case 10: // October
                            case 12: // December
                                maxDay = 31;
                                break;
                            case 4:    // April
                            case 6: // June
                            case 9: // September
                            case 11: // November
                                maxDay = 30;
                                break;
                            case 2: // February
                                if ((parseInt(theYear/4, 10) * 4 == theYear) && (theYear % 100 != 0 || theYear % 400 == 0)) {
                                    maxDay = 29;
                                } else {
                                    maxDay = 28;
                                break;
                        // Check day value to be between 1..maxDay
                        if (theDay < 1 || theDay > maxDay) {
                            return false;
                        // If successfull we'll return the date object
                        return (new Date(theYear, theMonth - 1, theDay));   //JavaScript requires a month between 0 and 11
                } else {
                    return false;
        'time': {
            validation: function(value, options) {
                //    HH:MM:SS T
                var formatRegExp = /([hmst]+)/gi;
                var valueRegExp = /(\d+|AM?|PM?)/gi;
                var formatGroups = options.format.match(formatRegExp);
                var valueGroups = value.match(valueRegExp);
                //mast match and have same length
                if (formatGroups !== null && valueGroups !== null) {
                    if (formatGroups.length != valueGroups.length) {
                        return false;
                    var hourIndex = -1;
                    var minuteIndex = -1;
                    var secondIndex = -1;
                    //T is AM or PM
                    var tIndex = -1;
                    var theHour = 0, theMinute = 0, theSecond = 0, theT = 'AM';
                    for (var i=0; i<formatGroups.length; i++) {
                        switch (formatGroups[i].toLowerCase()) {
                            case "hh":
                                hourIndex = i;
                                break;
                            case "mm":
                                minuteIndex = i;
                                break;
                            case "ss":
                                secondIndex = i;
                                break;
                            case "t":
                            case "tt":
                                tIndex = i;
                                break;
                    if (hourIndex != -1) {
                        var theHour = parseInt(valueGroups[hourIndex], 10);
                        if (isNaN(theHour) || theHour > (formatGroups[hourIndex] == 'HH' ? 23 : 12 )) {
                            return false;
                    if (minuteIndex != -1) {
                        var theMinute = parseInt(valueGroups[minuteIndex], 10);
                        if (isNaN(theMinute) || theMinute > 59) {
                            return false;
                    if (secondIndex != -1) {
                        var theSecond = parseInt(valueGroups[secondIndex], 10);
                        if (isNaN(theSecond) || theSecond > 59) {
                            return false;
                    if (tIndex != -1) {
                        var theT = valueGroups[tIndex].toUpperCase();
                        if (
                            formatGroups[tIndex].toUpperCase() == 'TT' && !/^a|pm$/i.test(theT) ||
                            formatGroups[tIndex].toUpperCase() == 'T' && !/^a|p$/i.test(theT)
                            return false;
                    var date = new Date(2000, 0, 1, theHour + (theT.charAt(0) == 'P'?12:0), theMinute, theSecond);
                    return date;
                } else {
                    return false;
        'credit_card': {
            characterMasking: /\d/,
            validation: function(value, options) {
                var regExp = null;
                options.format = options.format || 'ALL';
                switch (options.format.toUpperCase()) {
                    case 'ALL': regExp = /^[3-6]{1}[0-9]{12,18}$/; break;
                    case 'VISA': regExp = /^4(?:[0-9]{12}|[0-9]{15})$/; break;
                    case 'MASTERCARD': regExp = /^5[1-5]{1}[0-9]{14}$/; break;
                    case 'AMEX': regExp = /^3(4|7){1}[0-9]{13}$/; break;
                    case 'DISCOVER': regExp = /^6011[0-9]{12}$/; break;
                    case 'DINERSCLUB': regExp = /^3(?:(0[0-5]{1}[0-9]{11})|(6[0-9]{12})|(8[0-9]{12}))$/; break;
                if (!regExp.test(value)) {
                    return false;
                var digits = [];
                var j = 1, digit = '';
                for (var i = value.length - 1; i >= 0; i--) {
                    if ((j%2) == 0) {
                        digit = parseInt(value.charAt(i), 10) * 2;
                        digits[digits.length] = digit.toString().charAt(0);
                        if (digit.toString().length == 2) {
                            digits[digits.length] = digit.toString().charAt(1);
                    } else {
                        digit = value.charAt(i);
                        digits[digits.length] = digit;
                    j++;
                var sum = 0;
                for(i=0; i < digits.length; i++ ) {
                    sum += parseInt(digits[i], 10);
                if ((sum%10) == 0) {
                    return true;
                return false;
        'zip_code': {
            formats: {
                'zip_us9': {
                    pattern:'00000-0000'
                'zip_us5': {
                    pattern:'00000'
                'zip_uk': {
                    characterMasking: /[\dA-Z\s]/,
                    validation: function(value, options) {
                        //check one of the following masks
                        // AN NAA, ANA NAA, ANN NAA, AAN NAA, AANA NAA, AANN NAA
                        return /^[A-Z]{1,2}\d[\dA-Z]?\s?\d[A-Z]{2}$/.test(value);
                'zip_canada': {
                    characterMasking: /[\dA-Z\s]/,
                    pattern: 'A0A 0A0'
                'zip_custom': {}
        'phone_number': {
            formats: {
                //US phone number; 10 digits
                'phone_us': {
                    pattern:'(000) 000-0000'
                'phone_custom': {}
        'social_security_number': {
            pattern:'000-00-0000'
        'ip': {
            characterMaskingFormats: {
                'ipv4': /[\d\.]/i,
                'ipv6_ipv4': /[\d\.\:A-F\/]/i,
                'ipv6': /[\d\.\:A-F\/]/i
            validation: function (value, options) {
                return Spry.Widget.ValidationTextField.validateIP(value, options.format);
        'url': {
            characterMasking: /[^\s]/,
            validation: function(value, options) {
                //fix for ?ID=223429 and ?ID=223387
                /* the following regexp matches components of an URI as specified in http://tools.ietf.org/html/rfc3986#page-51 page 51, Appendix B.
                    scheme    = $2
                    authority = $4
                    path      = $5
                    query     = $7
                    fragment  = $9
                var URI_spliter = /^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
                var parts = value.match(URI_spliter);
                if (parts && parts[4]) {
                    //encode each component of the domain name using Punycode encoding scheme: http://tools.ietf.org/html/rfc3492
                    var host  = parts[4].split(".");
                    var punyencoded = '';
                    for (var i=0; i<host.length; i++) {
                        punyencoded = Spry.Widget.Utils.punycode_encode(host[i], 64);
                        if (!punyencoded) {
                            return false;
                        } else {
                            if (punyencoded != (host[i] + "-")) {
                                host[i] = 'xn--' + punyencoded;
                    host = host .join(".");
                    //the encoded domain name is replaced into the original URL to be validated again later as URL
                    value = value.replace(URI_spliter, "$1//" + host + "$5$6$8");
                //fix for ?ID=223358 and ?ID=223594
                //the following validates an URL using ABNF rules as defined in http://tools.ietf.org/html/rfc3986 , Appendix A., page 49
                //except host which is extracted by match[1] and validated separately
                 * userinfo=    (?:(?:[a-z0-9\-\._~\!\$\&\'\(\)\*\+\,\;\=:]|%[0-9a-f]{2,2})*\@)?
                 * host=            (?:((?:(?:[a-z0-9][a-z0-9\-]*[a-z0-9]|[a-z0-9])\.)*(?:[a-z][a-z0-9\-]*[a-z0-9]|[a-z])|(?: \[[^\]]*\]))
                 * pathname=    (?:\/(?:[a-z0-9\-\._~\!\$\&\'\(\)\*\+\,\;\=\:\@]|%[0-9a-f]{2,2})*)*
                 * query=            (?:\?(?:[a-z0-9\-\._~\!\$\&\'\(\)\*\+\,\;\=\:\@\/\?]|%[0-9a-f]{2,2})*)?
                 * anchor=        (?:\#(?:[a-z0-9\-\._~\!\$\&\'\(\)\*\+\,\;\=\:\@\/\?]|%[0-9a-f]{2,2})*)?
                var regExp = /^(?:https?|ftp)\:\/\/(?:(?:[a-z0-9\-\._~\!\$\&\'\(\)\*\+\,\;\=:]|%[0-9a-f]{2,2})*\@)?(?: ((?:(?:[a-z0-9][a-z0-9\-]*[a-z0-9]|[a-z0-9])\.)*(?:[a-z][a-z0-9\-]*[a-z0-9]|[a-z])|(?:\[[^ \]]*\]))(?:\:[0-9]*)?)(?:\/(?:[a-z0-9\-\._~\!\$\&\'\(\)\*\+\,\;\=\:\@]|%[0-9a-f]{2,2})*)*( ?:\?(?:[a-z0-9\-\._~\!\$\&\'\(\)\*\+\,\;\=\:\@\/\?]|%[0-9a-f]{2,2})*)?(?:\#(?:[a-z0-9\-\._ ~\!\$\&\'\(\)\*\+\,\;\=\:\@\/\?]|%[0-9a-f]{2,2})*)?$/i;
                var valid = value.match(regExp);
                if (valid) {
                    //extract the  address from URL
                    var address = valid[1];
                    if (address) {
                        if (address == '[]') {
                            return false;
                        if (address.charAt(0) == '[' ) {
                            //IPv6 address or IPv4 enclosed in square brackets
                            address = address.replace(/^\[|\]$/gi, '');
                            return Spry.Widget.ValidationTextField.validateIP(address, 'ipv6_ipv4');
                        } else {
                            if (/[^0-9\.]/.test(address)) {
                                return true;
                            } else {
                                //check if hostname is all digits and dots and then check for IPv4
                                return Spry.Widget.ValidationTextField.validateIP(address, 'ipv4');
                    } else {
                        return true;
                } else {
                    return false;
    2.2.1. Preferred
    x:x:x:x:x:x:x:x, where the 'x's are the hexadecimal values of the eight 16-bit pieces of the address.
    Examples:
        FEDC:BA98:7654:3210:FEDC:BA98:7654:3210
        1080:0:0:0:8:800:200C:417A
    Note that it is not necessary to write the leading zeros in an
    individual field, but there must be at least one numeral in every
    field (except for the case described in 2.2.2.).
    2.2.2. Compressed
    The use of "::" indicates multiple groups of 16-bits of zeros.
    The "::" can only appear once in an address.  The "::" can also be
    used to compress the leading and/or trailing zeros in an address.
        1080:0:0:0:8:800:200C:417A --> 1080::8:800:200C:417A
        FF01:0:0:0:0:0:0:101 --> FF01::101
        0:0:0:0:0:0:0:1 --> ::1
        0:0:0:0:0:0:0:0 --> ::
    2.5.4 IPv6 Addresses with Embedded IPv4 Addresses
        IPv4-compatible IPv6 address (tunnel IPv6 packets over IPv4 routing infrastructures)
        ::0:129.144.52.38
        IPv4-mapped IPv6 address (represent the addresses of IPv4-only nodes as IPv6 addresses)
        ::ffff:129.144.52.38
    The text representation of IPv6 addresses and prefixes in Augmented BNF (Backus-Naur Form) [ABNF] for reference purposes.
    [ABNF http://tools.ietf.org/html/rfc2234]
          IPv6address = hexpart [ ":" IPv4address ]
          IPv4address = 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT
          IPv6prefix  = hexpart "/" 1*2DIGIT
          hexpart = hexseq | hexseq "::" [ hexseq ] | "::" [ hexseq ]
          hexseq  = hex4 *( ":" hex4)
          hex4    = 1*4HEXDIG
    Spry.Widget.ValidationTextField.validateIP = function (value, format)
        var validIPv6Addresses = [
            //preferred
            /^(?:[a-f0-9]{1,4}:){7}[a-f0-9]{1,4}(?:\/\d{1,3})?$/i,
            //various compressed
            /^[a-f0-9]{0,4}::(?:\/\d{1,3})?$/i,
            /^:(?::[a-f0-9]{1,4}){1,6}(?:\/\d{1,3})?$/i,
            /^(?:[a-f0-9]{1,4}:){1,6}:(?:\/\d{1,3})?$/i,
            /^(?:[a-f0-9]{1,4}:)(?::[a-f0-9]{1,4}){1,6}(?:\/\d{1,3})?$/i,
            /^(?:[a-f0-9]{1,4}:){2}(?::[a-f0-9]{1,4}){1,5}(?:\/\d{1,3})?$/i,
            /^(?:[a-f0-9]{1,4}:){3}(?::[a-f0-9]{1,4}){1,4}(?:\/\d{1,3})?$/i,
            /^(?:[a-f0-9]{1,4}:){4}(?::[a-f0-9]{1,4}){1,3}(?:\/\d{1,3})?$/i,
            /^(?:[a-f0-9]{1,4}:){5}(?::[a-f0-9]{1,4}){1,2}(?:\/\d{1,3})?$/i,
            /^(?:[a-f0-9]{1,4}:){6}(?::[a-f0-9]{1,4})(?:\/\d{1,3})?$/i,
            //IPv6 mixes with IPv4
            /^(?:[a-f0-9]{1,4}:){6}(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{1,3})?$/i,
            /^:(?::[a-f0-9]{1,4}){0,4}:(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{1,3})?$/i,
            /^(?:[a-f0-9]{1,4}:){1,5}:(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{1,3})?$/i,
            /^(?:[a-f0-9]{1,4}:)(?::[a-f0-9]{1,4}){1,4}:(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{1,3})?$/i,
            /^(?:[a-f0-9]{1,4}:){2}(?::[a-f0-9]{1,4}){1,3}:(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{1,3})?$/i,    
            /^(?:[a-f0-9]{1,4}:){3}(?::[a-f0-9]{1,4}){1,2}:(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{1,3})?$/i,
            /^(?:[a-f0-9]{1,4}:){4}(?::[a-f0-9]{1,4}):(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{1,3})?$/i
        var validIPv4Addresses = [
            //IPv4
            /^(\d{1,3}\.){3}\d{1,3}$/i
        var validAddresses = [];
        if (format == 'ipv6' || format == 'ipv6_ipv4') {
            validAddresses = validAddresses.concat(validIPv6Addresses);
        if (format == 'ipv4' || format == 'ipv6_ipv4') {
            validAddresses = validAddresses.concat(validIPv4Addresses);
        var ret = false;
        for (var i=0; i<validAddresses.length; i++) {
            if (validAddresses[i].test(value)) {
                ret = true;
                break;
        if (ret && value.indexOf(".") != -1) {
            //if address contains IPv4 fragment, it must be valid; all 4 groups must be less than 256
            var ipv4 = value.match(/:?(?:\d{1,3}\.){3}\d{1,3}/i);
            if(!ipv4) {
                return false;
            ipv4 = ipv4[0].replace(/^:/, '');
            var pieces = ipv4.split('.');
            if (pieces.length != 4) {
                return false;
            var regExp = /^[\-\+]?\d*$/;
            for (var i=0; i< pieces.length; i++) {
                if (pieces[i] == '') {
                    return false;
                var piece = parseInt(pieces[i], 10);
                if (isNaN(piece) || piece > 255 || !regExp.test(pieces[i]) || pieces[i].length>3 || /^0{2,3}$/.test(pieces[i])) {
                    return false;
        if (ret && value.indexOf("/") != -1) {
            // if prefix-length is specified must be in [1-128]
            var prefLen = value.match(/\/\d{1,3}$/);
            if (!prefLen) return false;
            var prefLenVal = parseInt(prefLen[0].replace(/^\//,''), 10);
            if (isNaN(prefLenVal) || prefLenVal > 128 || prefLenVal < 1) {
                return false;
        return ret;
    Spry.Widget.ValidationTextField.onloadDidFire = false;
    Spry.Widget.ValidationTextField.loadQueue = [];
    Spry.Widget.ValidationTextField.prototype.isBrowserSupported = function()
        return Spry.is.ie && Spry.is.v >= 5 && Spry.is.windows
            ||
        Spry.is.mozilla && Spry.is.v >= 1.4
            ||
        Spry.is.safari
            ||
        Spry.is.opera && Spry.is.v >= 9;
    Spry.Widget.ValidationTextField.prototype.init = function(element, options)
        this.element = this.getElement(element);
        this.errors = 0;
        this.flags = {locked: false, restoreSelection: true};
        this.options = {};
        this.event_handlers = [];
        this.validClass = "textfieldValidState";
        this.focusClass = "textfieldFocusState";
        this.requiredClass = "textfieldRequiredState";
        this.hintClass = "textfieldHintState";
        this.invalidFormatClass = "textfieldInvalidFormatState";
        this.invalidRangeMinClass = "textfieldMinValueState";
        this.invalidRangeMaxClass = "textfieldMaxValueState";
        this.invalidCharsMinClass = "textfieldMinCharsState";
        this.invalidCharsMaxClass = "textfieldMaxCharsState";
        this.textfieldFlashTextClass = "textfieldFlashText";
        if (Spry.is.safari) {
            this.flags.lastKeyPressedTimeStamp = 0;
        switch (this.type) {
            case 'phone_number':options.format = Spry.Widget.Utils.firstValid(options.format, 'phone_us');break;
            case 'currency':options.format = Spry.Widget.Utils.firstValid(options.format, 'comma_dot');break;
            case 'zip_code':options.format = Spry.Widget.Utils.firstValid(options.format, 'zip_us5');break;
            case 'date':
                options.format = Spry.Widget.Utils.firstValid(options.format, 'mm/dd/yy');
                break;
            case 'time':
                options.format = Spry.Widget.Utils.firstValid(options.format, 'HH:mm');
                options.pattern = options.format.replace(/[hms]/gi, "0").replace(/TT/gi, 'AM').replace(/T/gi, 'A');
                break;
            case 'ip':
                options.format = Spry.Widget.Utils.firstValid(options.format, 'ipv4');
                options.characterMasking = Spry.Widget.ValidationTextField.ValidationDescriptors[this.type].characterMaskingFormats[ options.format];
                break;
        //retrieve the validation type descriptor to be used with this instance (base on type and format)
        //widgets may have different validations depending on format (like zip_code with formats)
        var validationDescriptor = {};
        if (options.format && Spry.Widget.ValidationTextField.ValidationDescriptors[this.type].formats) {
            if (Spry.Widget.ValidationTextField.ValidationDescriptors[this.type].formats[options.format] ) {
                Spry.Widget.Utils.setOptions(validationDescriptor, Spry.Widget.ValidationTextField.ValidationDescriptors[this.type].formats[options.format]) ;
        } else {
            Spry.Widget.Utils.setOptions(validationDescriptor, Spry.Widget.ValidationTextField.ValidationDescriptors[this.type]);
        //set default values for some parameters which were not aspecified
        options.useCharacterMasking = Spry.Widget.Utils.firstValid(options.useCharacterMasking, false);
        options.hint = Spry.Widget.Utils.firstValid(options.hint, '');
        options.isRequired = Spry.Widget.Utils.firstValid(options.isRequired, true);
        options.additionalError = Spry.Widget.Utils.firstValid(options.additionalError, false);
        if (options.additionalError)
            options.additionalError = this.getElement(options.additionalError);
        //set widget validation parameters
        //get values from validation type descriptor
        //use the user specified values, if defined
        options.characterMasking = Spry.Widget.Utils.firstValid(options.characterMasking, validationDescriptor.characterMasking);
        options.regExpFilter = Spry.Widget.Utils.firstValid(options.regExpFilter, validationDescriptor.regExpFilter);
        options.pattern = Spry.Widget.Utils.firstValid(options.pattern, validationDescriptor.pattern);
        options.validation = Spry.Widget.Utils.firstValid(options.validation, validationDescriptor.validation);
        if (typeof options.validation == 'string') {
            options.validation = eval(options.validation);
        options.minValue = Spry.Widget.Utils.firstValid(options.minValue, validationDescriptor.minValue);
        options.maxValue = Spry.Widget.Utils.firstValid(options.maxValue, validationDescriptor.maxValue);
        options.minChars = Spry.Widget.Utils.firstValid(options.minChars, validationDescriptor.minChars);
        options.maxChars = Spry.Widget.Utils.firstValid(options.maxChars, validationDescriptor.maxChars);
        Spry.Widget.Utils.setOptions(this, options);
        Spry.Widget.Utils.setOptions(this.options, options);
    Spry.Widget.ValidationTextField.prototype.destroy = function() {
        if (this.event_handlers)
            for (var i=0; i<this.event_handlers.length; i++) {
                Spry.Widget.Utils.removeEventListener(this.event_handlers[i][0], this.event_handlers[i][1], this.event_handlers[i][2], false);
        try { delete this.element; } catch(err) {}
        try { delete this.input; } catch(err) {}
        try { delete this.form; } catch(err) {}
        try { delete this.event_handlers; } catch(err) {}
        try { this.selection.destroy(); } catch(err) {}
        try { delete this.selection; } catch(err) {}
        var q = Spry.Widget.Form.onSubmitWidgetQueue;
        var qlen = q.length;
        for (var i = 0; i < qlen; i++) {
            if (q[i] == this) {
                q.splice(i, 1);
                break;
    Spry.Widget.ValidationTextField.prototype.attachBehaviors = function()
        if (this.element) {
            if (this.element.nodeName == "INPUT") {
                this.input = this.element;
            } else {
                this.input = Spry.Widget.Utils.getFirstChildWithNodeNameAtAnyLevel(this.element, "INPUT");
        if (this.input) {
            if (this.maxChars) {
                this.input.removeAttribute("maxLength");
            this.putHint();
            this.compilePattern();
            if (this.type == 'date') {
                this.compileDatePattern();
            this.input.setAttribute("AutoComplete", "off");
            this.selection = new Spry.Widget.SelectionDescriptor(this.input);
            this.oldValue = this.input.value;
            var self = this;
            this.event_handlers = [];
            this.event_handlers.push([this.input, "keydown", function(e) { if (self.isDisabled()) return true; return self.onKeyDown(e || event); }]);
            this.event_handlers.push([this.input, "keypress", function(e) { if (self.isDisabled()) return true; return self.onKeyPress(e || event); }]);
            if (Spry.is.opera) {
                this.event_handlers.push([this.input, "keyup", function(e) { if (self.isDisabled()) return true; return self.onKeyUp(e || event); }]);
            this.event_handlers.push([this.input, "focus", function(e) { if (self.isDisabled()) return true; return self.onFocus(e || event); }]);
            this.event_handlers.push([this.input, "blur", function(e) { if (self.isDisabled()) return true; return self.onBlur(e || event); }]);
            this.event_handlers.push([this.input, "mousedown", function(e) { if (self.isDisabled()) return true; return self.onMouseDown(e || event); }]);
            var changeEvent =
                Spry.is.mozilla || Spry.is.opera || Spry.is.safari?"input":
                Spry.is.ie?"propertychange":
                "change";
            this.event_handlers.push([this.input, changeEvent, function(e) { if (self.isDisabled()) return true; return self.onChange(e || event); }]);
            if (Spry.is.mozilla || Spry.is.safari) {
                //oninput event on mozilla does not fire ondragdrop
                this.event_handlers.push([this.input, "dragdrop", function(e) { if (self.isDisabled()) return true; self.removeHint();return self.onChange(e || event); }]);
            } else if (Spry.is.ie){
                //ondrop&onpropertychange crash on IE
                this.event_handlers.push([this.input, "drop", function(e) { if (self.isDisabled()) return true; return self.onDrop(e || event); }]);
            for (var i=0; i<this.event_handlers.length; i++) {
                Spry.Widget.Utils.addEventListener(this.event_handlers[i][0], this.event_handlers[i][1], this.event_handlers[i][2], false);
            // submit
            this.form = Spry.Widget.Utils.getFirstParentWithNodeName(this.input, "FORM");
            if (this.form) {
                // if no "onSubmit" handler has been attached to the current form, attach one
                if (!this.form.attachedSubmitHandler && !this.form.onsubmit) {
                    this.form.onsubmit = function(e) { e = e || event; return Spry.Widget.Form.onSubmit(e, e.srcElement || e.currentTarget) };
                    this.form.attachedSubmitHandler = true;                
                if (!this.form.attachedResetHandler) {
                    Spry.Widget.Utils.addEventListener(this.form, "reset", function(e) { e = e || event; return Spry.Widget.Form.onReset(e, e.srcElement || e.currentTarget) }, false);
                    this.form.attachedResetHandler = true;                
                // add the currrent widget to the "onSubmit" check queue;
                Spry.Widget.Form.onSubmitWidgetQueue.push(this);
    Spry.Widget.ValidationTextField.prototype.isDisabled = function() {
        return this.input && (this.input.disabled || this.input.readOnly) || !this.input;
    Spry.Widget.ValidationTextField.prototype.getElement = function(ele)
        if (ele && typeof ele == "string")
            return document.getElementById(ele);
        return ele;
    Spry.Widget.ValidationTextField.addLoadListener = function(handler)
        if (typeof window.addEventListener != 'undefined')
            window.addEventListener('load', handler, false);
        else if (typeof document.addEventListener != 'undefined')
            document.addEventListener('load', handler, false);
        else if (typeof window.attachEvent != 'undefined')
            window.attachEvent('onload', handler);
    Spry.Widget.ValidationTextField.processLoadQueue = function(handler)
        Spry.Widget.ValidationTextField.onloadDidFire = true;
        var q = Spry.Widget.ValidationTextField.loadQueue;
        var qlen = q.length;
        for (var i = 0; i < qlen; i++)
            q[i].attachBehaviors();
    Spry.Widget.ValidationTextField.addLoadListener(Spry.Widget.ValidationTextField.processLoa dQueue);
    Spry.Widget.ValidationTextField.addLoadListener(function(){
        Spry.Widget.Utils.addEventListener(window, "unload", Spry.Widget.Form.destroyAll, false);
    Spry.Widget.ValidationTextField.prototype.setValue = function(newValue) {
        this.flags.locked = true;
        this.input.value = newValue;
        this.flags.locked = false;
        this.oldValue = newValue;
        if (!Spry.is.ie) {
            this.onChange();
    * save the state of the input (selection and value) so we can revert to it
    * should call this just before modifying the input value
    Spry.Widget.ValidationTextField.prototype.saveState = function()
        this.oldValue = this.input.value;
        this.selection.update();
    Spry.Widget.ValidationTextField.prototype.revertState = function(revertValue)
        if (revertValue != this.input.value) {
            this.input.readOnly = true;
            this.input.value = revertValue;
            this.input.readOnly = false;
            if (Spry.is.safari && this.flags.active) {
                this.input.focus();
      if (this.flags.restoreSelection) {
        this.selection.moveTo(this.selection.start, this.selection.end);
        this.redTextFlash();
    Spry.Widget.ValidationTextField.prototype.removeHint = function()
        if (this.flags.hintOn) {
            this.input.value = "";
            this.flags.hintOn = false;
            this.removeClassName(this.element, this.hintClass);
            this.removeClassName(this.additionalError, this.hintClass);
    Spry.Widget.ValidationTextField.prototype.putHint = function()
        if(this.hint && this.input && this.input.type == "text" && this.input.value == "") {
            this.flags.hintOn = true;
            this.input.value = this.hint;
            this.addClassName(this.element, this.hintClass);
            this.addClassName(this.additionalError, this.hintClass);
    Spry.Widget.ValidationTextField.prototype.redTextFlash = function()
        var self = this;
        this.addClassName(this.element, this.textfieldFlashTextClass);
        setTimeout(function() {
            self.removeClassName(self.element, self.textfieldFlashTextClass)
        }, 100);
    Spry.Widget.ValidationTextField.prototype.doValidations = function(testValue, revertValue)
        if (this.isDisabled()) return false;
        if (this.flags.locked) {
            return false;
        if (testValue.length == 0 && !this.isRequired) {
            this.errors = 0;
            return false;
        this.flags.locked = true;
        var mustRevert = false;
        var continueValidations = true;
        if (!this.options.isRequired && testValue.length == 0) {
            continueValidations = false;
        var errors = 0;
        var fixedValue = testValue;
        //characterMasking - test if all characters are valid with the characterMasking (keyboard filter)
        if (this.useCharacterMasking && this.characterMasking) {
            for(var i=0; i<testValue.length; i++) {
                if (!this.characterMasking.test(testValue.charAt(i))) {
                    errors = errors | Spry.Widget.ValidationTextField.ERROR_FORMAT;
                    fixedValue = revertValue;
                    mustRevert = true;
                    break;
        //regExpFilter - character mask positioning (additional mask to restrict some characters only in some position)
        if (!mustRevert && this.useCharacterMasking && this.regExpFilter) {
            if (!this.regExpFilter.test(fixedValue)) {
                errors = errors | Spry.Widget.ValidationTextField.ERROR_FORMAT;
                mustRevert = true;
        //pattern - testValue matches the pattern so far
        if (!mustRevert && this.pattern) {
            var currentRegExp = this.patternToRegExp(testValue.length);
            if (!currentRegExp.test(testValue)) {
                errors = errors | Spry.Widget.ValidationTextField.ERROR_FORMAT;
                mustRevert = true;
            } else if (this.patternLength != testValue.length) {
                //testValue matches pattern so far, but it's not ok if it does not have the proper length
                //do not revert, but should show the error
                errors = errors | Spry.Widget.ValidationTextField.ERROR_FORMAT;
        if (fixedValue == '') {
            errors = errors | Spry.Widget.ValidationTextField.ERROR_REQUIRED;
        if (!mustRevert && this.pattern && this.useCharacterMasking) {
            var n = this.getAutoComplete(testValue.length);
            if (n) {
                fixedValue += n;
        if(!mustRevert && this.minChars !== null  && continueValidations) {
            if (testValue.length < this.minChars) {
                errors = errors | Spry.Widget.ValidationTextField.ERROR_CHARS_MIN;
                continueValidations = false;
        if(!mustRevert && this.maxChars !== null && continueValidations) {
            if (testValue.length > this.maxChars) {
                errors = errors | Spry.Widget.ValidationTextField.ERROR_CHARS_MAX;
                continueValidations = false;
        //validation - testValue passes widget validation function
        if (!mustRevert && this.validation && continueValidations) {
            var value = this.validation(fixedValue, this.options);
            if (false === value) {
                errors = errors | Spry.Widget.ValidationTextField.ERROR_FORMAT;
                continueValidations = false;
            } else {
                this.typedValue = value;
        if(!mustRevert && this.validation && this.minValue !== null && continueValidations) {
            var minValue = this.validation(this.minValue.toString(), this.options);
            if (minValue !== false) {
                if (this.typedValue < minValue) {
                    errors = errors | Spry.Widget.ValidationTextField.ERROR_RANGE_MIN;
                    continueValidations = false;
        if(!mustRevert && this.validation && this.maxValue !== null && continueValidations) {
            var maxValue = this.validation(this.maxValue.toString(), this.options);
            if (maxValue !== false) {
                if( this.typedValue > maxValue) {
                    errors = errors | Spry.Widget.ValidationTextField.ERROR_RANGE_MAX;
                    continueValidations = false;
        //an invalid value was tested; must make sure it does not get inside the input
        if (this.useCharacterMasking && mustRevert) {
            this.revertState(revertValue);
        this.errors = errors;
        this.fixedValue = fixedValue;
        this.flags.locked = false;
        return mustRevert;
    Spry.Widget.ValidationTextField.prototype.onChange = function(e)
        if (Spry.is.opera && this.flags.operaRevertOnKeyUp) {
            return true;
        if (Spry.is.ie && e && e.propertyName != 'value') {
            return true;

  • [JS CS3] Problem with EventListener

    Hello,
    I am having a problem passing information from two functions to a third when those functions are invoked by an eventListener. Below is the code, very simplified.
    The first function will get the last word of each text frame at the moment the file is opened.
    In the second function, the last word of each text frame will be recorded at the moment of Save.
    The third function will compare the two arrays and get the page number where the last word has moved. This script is to tell the user if there is any text flow from one page to another while making minor changes.
    The problem is that the first two functions only return the function itself and not the values of the function.
    If I assign the first two functions to variables, the third function works correctly but the eventListener does not recognize the functions. I have to comment out the eventListeners and call the first two functions outside of them.
    Any advice to help me solve this would be helpful.
    Thanks,
    Tom
    #targetengine "session"
    main();
    function main(){
    var myEventListener1 = app.addEventListener("afterOpen",arrLastWordsOnOpen, false);
    var myEventListener2 = app.addEventListener("afterSave",arrLastWordsOnSave, false);
    var myEventListener3 = app.addEventListener("afterSave",compare, false);
    function arrLastWordsOnOpen(){
    var a = 5;
    alert(a);
    return a;
    function arrLastWordsOnSave(){
    var b = 6;
    alert(b);
    return b;
    function compare(){
        var c = arrLastWordsOnOpen+arrLastWordsOnSave;
        alert(c);

    Hi Tom,
    Your three functions are registered as event handlers, so they are intended to be automatically called when the corresponding events occur, so this is —generally— a wrong approach to call such functions by yourself from other points of your code. What you need is to store the results computed by arrLastWordsOnOpen and arrLastWordsOnSave, so that the third handler can use the values. Since you are using a persistent engine, you could simply declare a and b at the main() level. Then arrLastWordsOnOpen would update a, arrLastWordsOnSave would update b,and compare just needs to set c = a + b;
    If you don't want to 'pollute' the outer scope of the handler functions, you can also store the computed values as new properties of the functions themselves:
    #targetengine "session"
    main();
    function main()
         var myEventListener1 = app.addEventListener("afterOpen",arrLastWordsOnOpen, false);
         var myEventListener2 = app.addEventListener("afterSave",arrLastWordsOnSave, false);
         var myEventListener3 = app.addEventListener("afterSave",compare, false);
         function arrLastWordsOnOpen()
              var a = 5;
              alert(a);
              arrLastWordsOnOpen.computedValue = a;
         function arrLastWordsOnSave()
              var b = 6;
              alert(b);
              arrLastWordsOnSave.computedValue = b;
         function compare()
              var c = arrLastWordsOnOpen.computedValue + arrLastWordsOnSave.computedValue;
              alert(c);
    Hope that helps.
    @+
    Marc

  • A simple Spry Accordion Question (I think)

    Hi all:
    I've searched but can't find, but I think this is a simple one.
    I've created a basic Spry accordion menu with DW/CS3 - Insert/Spry/Spry Accordion. How do I get the first "Content 1" to be hidden/not visible upon page load. Right now, the "Lable 2" must be clicked to hide the "Content 1" which of course shows the "Content 2"? Guessing it's in the JS, but I'm not sure. TIA for any help. HTML and JS Code below.
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Untitled Document</title>
    <script src="SpryAssets/SpryAccordion.js" type="text/javascript"></script>
    <link href="SpryAssets/SpryAccordion.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
    <div id="Accordion1" class="Accordion" tabindex="0">
      <div class="AccordionPanel">
        <div class="AccordionPanelTab">Label 1</div>
        <div class="AccordionPanelContent">Content 1</div>
      </div>
      <div class="AccordionPanel">
        <div class="AccordionPanelTab">Label 2</div>
        <div class="AccordionPanelContent">Content 2</div>
      </div>
    </div>
    <script type="text/javascript">
    <!--
    var Accordion1 = new Spry.Widget.Accordion("Accordion1");
    //-->
    </script>
    </body>
    </html>
    JAVASCRIPT
    var Spry;
    if (!Spry) Spry = {};
    if (!Spry.Widget) Spry.Widget = {};
    Spry.Widget.Accordion = function(element, opts)
        this.element = this.getElement(element);
        this.defaultPanel = 0;
        this.hoverClass = "AccordionPanelTabHover";
        this.openClass = "AccordionPanelOpen";
        this.closedClass = "AccordionPanelClosed";
        this.focusedClass = "AccordionFocused";
        this.enableAnimation = true;
        this.enableKeyboardNavigation = true;
        this.currentPanel = null;
        this.animator = null;
        this.hasFocus = null;
        this.duration = 500;
        this.previousPanelKeyCode = Spry.Widget.Accordion.KEY_UP;
        this.nextPanelKeyCode = Spry.Widget.Accordion.KEY_DOWN;
        this.useFixedPanelHeights = true;
        this.fixedPanelHeight = 0;
        Spry.Widget.Accordion.setOptions(this, opts, true);
        // Unfortunately in some browsers like Safari, the Stylesheets our
        // page depends on may not have been loaded at the time we are called.
        // This means we have to defer attaching our behaviors until after the
        // onload event fires, since some of our behaviors rely on dimensions
        // specified in the CSS.
        if (Spry.Widget.Accordion.onloadDidFire)
            this.attachBehaviors();
        else
            Spry.Widget.Accordion.loadQueue.push(this);
    Spry.Widget.Accordion.onloadDidFire = false;
    Spry.Widget.Accordion.loadQueue = [];
    Spry.Widget.Accordion.addLoadListener = function(handler)
        if (typeof window.addEventListener != 'undefined')
            window.addEventListener('load', handler, false);
        else if (typeof document.addEventListener != 'undefined')
            document.addEventListener('load', handler, false);
        else if (typeof window.attachEvent != 'undefined')
            window.attachEvent('onload', handler);
    Spry.Widget.Accordion.processLoadQueue = function(handler)
        Spry.Widget.Accordion.onloadDidFire = true;
        var q = Spry.Widget.Accordion.loadQueue;
        var qlen = q.length;
        for (var i = 0; i < qlen; i++)
            q[i].attachBehaviors();
    Spry.Widget.Accordion.addLoadListener(Spry.Widget.Accordion.processLoadQueue);
    Spry.Widget.Accordion.prototype.getElement = function(ele)
        if (ele && typeof ele == "string")
            return document.getElementById(ele);
        return ele;
    Spry.Widget.Accordion.prototype.addClassName = function(ele, className)
        if (!ele || !className || (ele.className && ele.className.search(new RegExp("\\b" + className + "\\b")) != -1))
            return;
        ele.className += (ele.className ? " " : "") + className;
    Spry.Widget.Accordion.prototype.removeClassName = function(ele, className)
        if (!ele || !className || (ele.className && ele.className.search(new RegExp("\\b" + className + "\\b")) == -1))
            return;
        ele.className = ele.className.replace(new RegExp("\\s*\\b" + className + "\\b", "g"), "");
    Spry.Widget.Accordion.setOptions = function(obj, optionsObj, ignoreUndefinedProps)
        if (!optionsObj)
            return;
        for (var optionName in optionsObj)
            if (ignoreUndefinedProps && optionsObj[optionName] == undefined)
                continue;
            obj[optionName] = optionsObj[optionName];
    Spry.Widget.Accordion.prototype.onPanelTabMouseOver = function(panel)
        if (panel)
            this.addClassName(this.getPanelTab(panel), this.hoverClass);
    Spry.Widget.Accordion.prototype.onPanelTabMouseOut = function(panel)
        if (panel)
            this.removeClassName(this.getPanelTab(panel), this.hoverClass);
    Spry.Widget.Accordion.prototype.openPanel = function(panel)
        var panelA = this.currentPanel;
        var panelB = panel;
        if (!panelB || panelA == panelB)   
            return;
        var contentA;
        if( panelA )
            contentA = this.getPanelContent(panelA);
        var contentB = this.getPanelContent(panelB);
        if (! contentB)
            return;
        if (this.useFixedPanelHeights && !this.fixedPanelHeight)
            this.fixedPanelHeight = (contentA.offsetHeight) ? contentA.offsetHeight : contentA.scrollHeight;
        if (this.enableAnimation)
            if (this.animator)
                this.animator.stop();
            this.animator = new Spry.Widget.Accordion.PanelAnimator(this, panelB, { duration: this.duration });
            this.animator.start();
        else
            if(contentA)
                contentA.style.height = "0px";
            contentB.style.height = (this.useFixedPanelHeights ? this.fixedPanelHeight : contentB.scrollHeight) + "px";
        if(panelA)
            this.removeClassName(panelA, this.openClass);
            this.addClassName(panelA, this.closedClass);
        this.removeClassName(panelB, this.closedClass);
        this.addClassName(panelB, this.openClass);
        this.currentPanel = panelB;
    Spry.Widget.Accordion.prototype.openNextPanel = function()
        var panels = this.getPanels();
        var curPanelIndex = this.getCurrentPanelIndex();
        if( panels && curPanelIndex >= 0 && (curPanelIndex+1) < panels.length )
            this.openPanel(panels[curPanelIndex+1]);
    Spry.Widget.Accordion.prototype.openPreviousPanel = function()
        var panels = this.getPanels();
        var curPanelIndex = this.getCurrentPanelIndex();
        if( panels && curPanelIndex > 0 && curPanelIndex < panels.length )
            this.openPanel(panels[curPanelIndex-1]);
    Spry.Widget.Accordion.prototype.openFirstPanel = function()
        var panels = this.getPanels();
        if( panels )
            this.openPanel(panels[0]);
    Spry.Widget.Accordion.prototype.openLastPanel = function()
        var panels = this.getPanels();
        if( panels )
            this.openPanel(panels[panels.length-1]);
    Spry.Widget.Accordion.prototype.onPanelClick = function(panel)
        // if (this.enableKeyboardNavigation)
        //     this.element.focus();
        if (panel != this.currentPanel)
            this.openPanel(panel);
        this.focus();
    Spry.Widget.Accordion.prototype.onFocus = function(e)
        // this.element.focus();
        this.hasFocus = true;
        this.addClassName(this.element, this.focusedClass);
    Spry.Widget.Accordion.prototype.onBlur = function(e)
        // this.element.blur();
        this.hasFocus = false;
        this.removeClassName(this.element, this.focusedClass);
    Spry.Widget.Accordion.KEY_UP = 38;
    Spry.Widget.Accordion.KEY_DOWN = 40;
    Spry.Widget.Accordion.prototype.onKeyDown = function(e)
        var key = e.keyCode;
        if (!this.hasFocus || (key != this.previousPanelKeyCode && key != this.nextPanelKeyCode))
            return true;
        var panels = this.getPanels();
        if (!panels || panels.length < 1)
            return false;
        var currentPanel = this.currentPanel ? this.currentPanel : panels[0];
        var nextPanel = (key == this.nextPanelKeyCode) ? currentPanel.nextSibling : currentPanel.previousSibling;
        while (nextPanel)
            if (nextPanel.nodeType == 1 /* Node.ELEMENT_NODE */)
                break;
            nextPanel = (key == this.nextPanelKeyCode) ? nextPanel.nextSibling : nextPanel.previousSibling;
        if (nextPanel && currentPanel != nextPanel)
            this.openPanel(nextPanel);
        if (e.stopPropagation)
            e.stopPropagation();
        if (e.preventDefault)
            e.preventDefault();
        return false;
    Spry.Widget.Accordion.prototype.attachPanelHandlers = function(panel)
        if (!panel)
            return;
        var tab = this.getPanelTab(panel);
        if (tab)
            var self = this;
            Spry.Widget.Accordion.addEventListener(tab, "click", function(e) { return self.onPanelClick(panel); }, false);
            Spry.Widget.Accordion.addEventListener(tab, "mouseover", function(e) { return self.onPanelTabMouseOver(panel); }, false);
            Spry.Widget.Accordion.addEventListener(tab, "mouseout", function(e) { return self.onPanelTabMouseOut(panel); }, false);
    Spry.Widget.Accordion.addEventListener = function(element, eventType, handler, capture)
        try
            if (element.addEventListener)
                element.addEventListener(eventType, handler, capture);
            else if (element.attachEvent)
                element.attachEvent("on" + eventType, handler);
        catch (e) {}
    Spry.Widget.Accordion.prototype.initPanel = function(panel, isDefault)
        var content = this.getPanelContent(panel);
        if (isDefault)
            this.currentPanel = panel;
            this.removeClassName(panel, this.closedClass);
            this.addClassName(panel, this.openClass);
        else
            this.removeClassName(panel, this.openClass);
            this.addClassName(panel, this.closedClass);
            content.style.height = "0px";
        this.attachPanelHandlers(panel);
    Spry.Widget.Accordion.prototype.attachBehaviors = function()
        var panels = this.getPanels();
        for (var i = 0; i < panels.length; i++)
            this.initPanel(panels[i], i == this.defaultPanel);
        if (this.enableKeyboardNavigation)
            // XXX: IE doesn't allow the setting of tabindex dynamically. This means we can't
            // rely on adding the tabindex attribute if it is missing to enable keyboard navigation
            // by default.
            var tabIndexAttr = this.element.attributes.getNamedItem("tabindex");
            // if (!tabIndexAttr) this.element.tabindex = 0;
            if (tabIndexAttr)
                var self = this;
                Spry.Widget.Accordion.addEventListener(this.element, "focus", function(e) { return self.onFocus(e); }, false);
                Spry.Widget.Accordion.addEventListener(this.element, "blur", function(e) { return self.onBlur(e); }, false);
                Spry.Widget.Accordion.addEventListener(this.element, "keydown", function(e) { return self.onKeyDown(e); }, false);
    Spry.Widget.Accordion.prototype.getPanels = function()
        return this.getElementChildren(this.element);
    Spry.Widget.Accordion.prototype.getCurrentPanel = function()
        return this.currentPanel;
    Spry.Widget.Accordion.prototype.getCurrentPanelIndex = function()
        var panels = this.getPanels();
        for( var i = 0 ; i < panels.length; i++ )
            if( this.currentPanel == panels[i] )
                return i;
        return 0;
    Spry.Widget.Accordion.prototype.getPanelTab = function(panel)
        if (!panel)
            return null;
        return this.getElementChildren(panel)[0];
    Spry.Widget.Accordion.prototype.getPanelContent = function(panel)
        if (!panel)
            return null;
        return this.getElementChildren(panel)[1];
    Spry.Widget.Accordion.prototype.getElementChildren = function(element)
        var children = [];
        var child = element.firstChild;
        while (child)
            if (child.nodeType == 1 /* Node.ELEMENT_NODE */)
                children.push(child);
            child = child.nextSibling;
        return children;
    Spry.Widget.Accordion.prototype.focus = function()
        if (this.element && this.element.focus)
            this.element.focus();
    Spry.Widget.Accordion.PanelAnimator = function(accordion, panel, opts)
        this.timer = null;
        this.interval = 0;
        this.stepCount = 0;
        this.fps = 0;
        this.steps = 10;
        this.duration = 500;
        this.onComplete = null;
        this.panel = panel;
        this.panelToOpen = accordion.getElement(panel);
        this.panelData = [];
        Spry.Widget.Accordion.setOptions(this, opts, true);
        // If caller specified speed in terms of frames per second,
        // convert them into steps.
        if (this.fps > 0)
            this.interval = Math.floor(1000 / this.fps);
            this.steps = parseInt((this.duration + (this.interval - 1)) / this.interval);
        else if (this.steps > 0)
            this.interval = this.duration / this.steps;
        // Set up the array of panels we want to animate.
        var panels = accordion.getPanels();
        for (var i = 0; i < panels.length; i++)
            var p = panels[i];
            var c = accordion.getPanelContent(p);
            if (c)
                var h = c.offsetHeight;
                if (h == undefined)
                    h = 0;
                if (p == panel || h > 0)
                    var obj = new Object;
                    obj.panel = p;
                    obj.content = c;
                    obj.fromHeight = h;
                    obj.toHeight = (p == panel) ? (accordion.useFixedPanelHeights ? accordion.fixedPanelHeight : c.scrollHeight) : 0;
                    obj.increment = (obj.toHeight - obj.fromHeight) / this.steps;
                    obj.overflow = c.style.overflow;
                    this.panelData.push(obj);
                    c.style.overflow = "hidden";
                    c.style.height = h + "px";
    Spry.Widget.Accordion.PanelAnimator.prototype.start = function()
        var self = this;
        this.timer = setTimeout(function() { self.stepAnimation(); }, this.interval);
    Spry.Widget.Accordion.PanelAnimator.prototype.stop = function()
        if (this.timer)
            clearTimeout(this.timer);
            // If we're killing the timer, restore the overflow
            // properties on the panels we were animating!
            if (this.stepCount < this.steps)
                for (i = 0; i < this.panelData.length; i++)
                    obj = this.panelData[i];
                    obj.content.style.overflow = obj.overflow;
        this.timer = null;
    Spry.Widget.Accordion.PanelAnimator.prototype.stepAnimation = function()
        ++this.stepCount;
        this.animate();
        if (this.stepCount < this.steps)
            this.start();
        else if (this.onComplete)
            this.onComplete();
    Spry.Widget.Accordion.PanelAnimator.prototype.animate = function()
        var i, obj;
        if (this.stepCount >= this.steps)
            for (i = 0; i < this.panelData.length; i++)
                obj = this.panelData[i];
                if (obj.panel != this.panel)
                    obj.content.style.height = "0px";
                obj.content.style.overflow = obj.overflow;
                obj.content.style.height = obj.toHeight + "px";
        else
            for (i = 0; i < this.panelData.length; i++)
                obj = this.panelData[i];
                obj.fromHeight += obj.increment;
                obj.content.style.height = obj.fromHeight + "px";

    On the bottom of yourpage you have this:
    var Accordion1 = new Spry.Widget.Accordion("Accordion1");
    Change it to this:
    var Accordion1 = new Spry.Widget.Accordion("Accordion1", { useFixedPanelHeights: false, defaultPanel: -1 });
    Ken Ford

  • Tool tip to not move

    Hi I'm a big fan. long time lurker first time poster
    Currently the position of the tool tip depends on where the cursor first hovers over the image.  Is there a way for the tool tip to appear in the same place no mater where the image is hovered?
    below is the js and css
    thanks
    // SpryTooltip.js - version 0.9 - Spry 1.6.1
    (function() { // BeginSpryComponent
    if (typeof Spry == "undefined") window.Spry = {}; if (!Spry.Widget) Spry.Widget = {};
    Spry.Widget.BrowserSniff = function()
    var b = navigator.appName.toString();
    var up = navigator.platform.toString();
    var ua = navigator.userAgent.toString();
    this.mozilla = this.ie = this.opera = this.safari = false;
    var re_opera = /Opera.([0-9\.]*)/i;
    var re_msie = /MSIE.([0-9\.]*)/i;
    var re_gecko = /gecko/i;
    var re_safari = /(applewebkit|safari)\/([\d\.]*)/i;
    var r = false;
    if ( (r = ua.match(re_opera))) {
    this.opera = true;
    this.version = parseFloat(r[1]);
    } else if ( (r = ua.match(re_msie))) {
    this.ie = true;
    this.version = parseFloat(r[1]);
    } else if ( (r = ua.match(re_safari))) {
    this.safari = true;
    if(parseFloat(r[2]) < 420)
    this.version = 2;
    else
    this.version = 3;
    } else if (ua.match(re_gecko)) {
    var re_gecko_version = /rv:\s*([0-9\.]+)/i;
    r = ua.match(re_gecko_version);
    this.mozilla = true;
    this.version = parseFloat(r[1]);
    this.windows = this.mac = this.linux = false;
    this.Platform = ua.match(/windows/i) ? "windows" :
    (ua.match(/linux/i) ? "linux" :
    (ua.match(/mac/i) ? "mac" :
    ua.match(/unix/i)? "unix" : "unknown"));
    this[this.Platform] = true;
    this.v = this.version;
    if (this.safari && this.mac && this.mozilla) {
    this.mozilla = false;
    Spry.is = new Spry.Widget.BrowserSniff();
    Spry.Widget.Tooltip = function(tooltip_element, trigger_selector, options)
    options = Spry.Widget.Utils.firstValid(options, {});
    this.init(trigger_selector, tooltip_element, options);
    if (Spry.Widget.Tooltip.onloadDidFire)
    this.attachBehaviors();
    Spry.Widget.Tooltip.loadQueue.push(this);
    Spry.Widget.Tooltip.prototype.init = function(trigger_element, tooltip_element, options)
    var Utils = Spry.Widget.Utils;
    this.triggerElements = Utils.getElementsByClassName(trigger_element);
    this.tooltipElement = Utils.getElement(tooltip_element);
    options.showDelay = parseInt(Utils.firstValid(options.showDelay, 0), 10);
    options.hideDelay = parseInt(Utils.firstValid(options.hideDelay, 0), 10);
    if (typeof this.triggerElements == 'undefined' || !(this.triggerElements.length > 0))
    this.showError('The element(s) "' + trigger_element + '" do not exist in the page');
    return false;
    if (typeof this.tooltipElement == 'undefined' || !this.tooltipElement)
    this.showError('The element "' + tooltip_element + '" do not exists in the page');
    return false;
    this.listenersAttached = false;
    this.hoverClass = "";
    this.followMouse = false;
    this.offsetX = 15;
    this.offsetY = 15;
    this.closeOnTooltipLeave = false;
    this.useEffect = false;
    Utils.setOptions(this, options);
    this.animator = null;
    for (var i =0; i < this.triggerElements.length; i++)
    if (!this.triggerElements[i].className)
    this.triggerElements[i].className = '';
    if (this.useEffect){
    switch (this.useEffect.toString().toLowerCase()){
    case 'blind': this.useEffect = 'Blind'; break;
    case 'fade': this.useEffect = 'Fade'; break;
    default:
    this.useEffect = false;
    this.visibleTooltip = false;
    // Hack for FF 3 - Safari 3: force painting of the element, in order to have the correct display
    this.tooltipElement.offsetHeight;
    // Optimisation: save browser work if display is already 'none'
    if (Spry.Widget.Utils.getStyleProperty(this.tooltipElement, 'display') != 'none')
    this.tooltipElement.style.display = 'none';
    if (typeof this.offsetX != 'numeric')
    this.offsetX = parseInt(this.offsetX, 10);
    if (isNaN(this.offsetX))
    this.offsetX = 0;
    if (typeof this.offsetY != 'numeric')
    this.offsetY = parseInt(this.offsetY, 10);
    if (isNaN(this.offsetY))
    this.offsetY = 0;
    this.tooltipElement.style.position = 'absolute';
    this.tooltipElement.style.top = '0px';
    this.tooltipElement.style.left = '0px';
    Spry.Widget.Tooltip.onloadDidFire = false;
    Spry.Widget.Tooltip.loadQueue = [];
    Spry.Widget.Tooltip.addLoadListener = function(handler)
    if (typeof window.addEventListener != 'undefined')
    window.addEventListener('load', handler, false);
    else if (typeof document.addEventListener != 'undefined')
    document.addEventListener('load', handler, false);
    else if (typeof window.attachEvent != 'undefined')
    window.attachEvent('onload', handler);
    Spry.Widget.Tooltip.processLoadQueue = function(handler)
    Spry.Widget.Tooltip.onloadDidFire = true;
    var q = Spry.Widget.Tooltip.loadQueue;
    var qlen = q.length;
    for (var i = 0; i < qlen; i++)
    if (!q[i].listenersAttached)
    q[i].attachBehaviors();
    Spry.Widget.Tooltip.addLoadListener(Spry.Widget.Tooltip.processLoadQueue);
    Spry.Widget.Tooltip.prototype.addClassName = function(ele, className)
    if (!ele || !className)
    return;
    if (ele.className.indexOf(className) == -1)
    ele.className += (ele.className ? " " : "") + className;
    Spry.Widget.Tooltip.prototype.removeClassName = function(ele, className)
    if (!ele || !className )
    return;
    ele.className = ele.className.replace(new RegExp("\\s*\\b" + className + "\\b", "g"), "");
    Spry.Widget.Tooltip.prototype.showTooltip = function()
    if (!this.visibleTooltip)
    this.tooltipElement.style.visibility = 'hidden';
    this.tooltipElement.style.zIndex = '9999';
    this.tooltipElement.style.display = 'block';
    Spry.Widget.Utils.putElementAt(this.tooltipElement, this.pos, {x:this.offsetX, y:this.offsetY}, true);
    if(Spry.is.ie && Spry.is.version == '6')
    this.createIframeLayer(this.tooltipElement);
    if (!this.visibleTooltip)
    if (this.useEffect)
    if (typeof this.showEffect == 'undefined')
    this.showEffect = new Spry.Widget.Tooltip[this.useEffect](this.tooltipElement, {from: 0, to: 1});
    this.showEffect.start();
    else
    this.tooltipElement.style.visibility = 'visible';
    this.visibleTooltip = true;
    Spry.Widget.Tooltip.prototype.hideTooltip = function(quick)
    if (this.useEffect && !quick)
    if (typeof this.hideEffect == 'undefined')
    this.hideEffect = new Spry.Widget.Tooltip[this.useEffect](this.tooltipElement, {from: 1, to: 0});
    this.hideEffect.start();
    else
    if (typeof this.showEffect != 'undefined')
    this.showEffect.stop();
    this.tooltipElement.style.display = 'none';
    if(Spry.is.ie && Spry.is.version == '6')
    this.removeIframeLayer(this.tooltipElement);
    if (this.hoverClass && !this.hideTimer)
    for (var i = 0; i < this.triggerElements.length; i++)
    this.removeClassName(this.triggerElements[i], this.hoverClass);
    this.visibleTooltip = false;
    Spry.Widget.Tooltip.prototype.displayTooltip = function(show) {
    if (this.tooltipElement)
    if (this.hoverClass){
    for (var i = 0; i < this.triggerElements.length; i++)
    this.removeClassName(this.triggerElements[i], this.hoverClass);
    if (show)
    if (this.hideTimer)
    clearInterval(this.hideTimer);
    delete(this.hideTimer);
    if (this.hoverClass)
    if (typeof this.triggerHighlight != 'undefined')
    this.addClassName(this.triggerHighlight, this.hoverClass);
    var self = this;
    this.showTimer = setTimeout(function(){self.showTooltip()}, this.showDelay);
    else
    if (this.showTimer)
    clearInterval(this.showTimer);
    delete(this.showTimer);
    var self = this;
    this.hideTimer = setTimeout(function(){self.hideTooltip();}, this.hideDelay);
    this.refreshTimeout();
    Spry.Widget.Tooltip.prototype.onMouseOverTrigger = function(e)
    var target = '';
    if (Spry.is.ie)
    target = e.srcElement;
    else
    target = e.target;
    var contains = Spry.Widget.Utils.contains;
    for (var i = 0; i < this.triggerElements.length; i++)
    if (contains(this.triggerElements[i], target))
    target = this.triggerElements[i];
    break;
    if (i == this.triggerElements.length) return;
    if (this.visibleTooltip && this.triggerHighlight && this.triggerHighlight == target)
    if (this.hideTimer)
    clearInterval(this.hideTimer);
    delete(this.hideTimer);
    if (this.hoverClass)
    if (typeof this.triggerHighlight != 'undefined')
    this.addClassName(this.triggerHighlight, this.hoverClass);
    return;
    var pos = Spry.Widget.Utils.getAbsoluteMousePosition(e);
    this.pos = {x: pos.x + this.offsetX, y: pos.y + this.offsetY};
    this.triggerHighlight = target;
    Spry.Widget.Tooltip.closeAll();
    this.displayTooltip(true);
    Spry.Widget.Tooltip.prototype.onMouseMoveTrigger = function(e)
    var pos = Spry.Widget.Utils.getAbsoluteMousePosition(e);
    this.pos = {x: pos.x + this.offsetX, y: pos.y + this.offsetY};
    if (this.visibleTooltip)
    this.showTooltip();
    Spry.Widget.Tooltip.prototype.onMouseOutTrigger = function(e)
    var target = '';
    if (Spry.is.ie)
    target = e.toElement;
    else
    target = e.relatedTarget;
    var contains = Spry.Widget.Utils.contains;
    for (var i=0; i < this.triggerElements.length; i++)
    if (contains(this.triggerElements[i], target))
    return;
    this.displayTooltip(false);
    Spry.Widget.Tooltip.prototype.onMouseOutTooltip = function(e)
    var target = '';
    if (Spry.is.ie)
    target = e.toElement;
    else
    target = e.relatedTarget;
    var contains = Spry.Widget.Utils.contains;
    if (contains(this.tooltipElement, target))
    return;
    this.displayTooltip(false);
    Spry.Widget.Tooltip.prototype.onMouseOverTooltip = function(e)
    if (this.hideTimer)
    clearInterval(this.hideTimer);
    delete(this.hideTimer);
    if (this.hoverClass)
    if (typeof this.triggerHighlight != 'undefined')
    this.addClassName(this.triggerHighlight, this.hoverClass);
    Spry.Widget.Tooltip.prototype.refreshTimeout = function()
    if (Spry.Widget.Tooltip.refreshTimeout != null)
    clearTimeout(Spry.Widget.Tooltip.refreshTimeout);
    Spry.Widget.Tooltip.refreshTimeout = null;
    Spry.Widget.Tooltip.refreshTimeout = setTimeout(Spry.Widget.Tooltip.refreshAll, 100);
    Spry.Widget.Tooltip.prototype.destroy = function()
    for (var k in this)
    try{
    if (typeof this.k == 'object' && typeof this.k.destroy == 'function') this.k.destroy();
    delete this.k;
    }catch(err){}
    Spry.Widget.Tooltip.prototype.checkDestroyed = function()
    // checks the parent node. If it exists, then the element is still in the DOM
    if (!this.tooltipElement || this.tooltipElement.parentNode == null)
    return true;
    return false;
    Spry.Widget.Tooltip.prototype.attachBehaviors = function()
    var self = this;
    var ev = Spry.Widget.Utils.addEventListener;
    for (var i=0; i< this.triggerElements.length; i++)
    ev(this.triggerElements[i], 'mouseover', function(e) {self.onMouseOverTrigger(e || event); return true;}, false);
    ev(this.triggerElements[i], 'mouseout', function(e) {self.onMouseOutTrigger(e || event); return true;}, false);
    if (this.followMouse)
    ev(this.triggerElements[i], 'mousemove', function(e) {self.onMouseMoveTrigger(e || event); return true;}, false);
    if (this.closeOnTooltipLeave)
    ev(this.tooltipElement, 'mouseover', function(e){self.onMouseOverTooltip(e || event); return true;}, false);
    ev(this.tooltipElement, 'mouseout', function(e){self.onMouseOutTooltip(e || event); return true;}, false);
    this.listenersAttached = true;
    // createIframeLayer for Tooltip
    // creates an IFRAME underneath a tooltip element so that it will show above form controls and ActiveX
    Spry.Widget.Tooltip.prototype.createIframeLayer = function(tooltip)
    if (typeof this.iframeLayer == 'undefined')
    var layer = document.createElement('iframe');
    layer.tabIndex = '-1';
    layer.src = 'javascript:"";';
    layer.scrolling = 'no';
    layer.frameBorder = '0';
    layer.className = 'iframeTooltip';
    tooltip.parentNode.appendChild(layer);
    this.iframeLayer = layer;
    this.iframeLayer.style.left = tooltip.offsetLeft + 'px';
    this.iframeLayer.style.top = tooltip.offsetTop + 'px';
    this.iframeLayer.style.width = tooltip.offsetWidth + 'px';
    this.iframeLayer.style.height = tooltip.offsetHeight + 'px';
    this.iframeLayer.style.display = 'block';
    // removeIframeLayer for Tooltip Element
    // removes an IFRAME underneath a tooltip to reveal any form controls and ActiveX
    Spry.Widget.Tooltip.prototype.removeIframeLayer =  function(tooltip)
    if (this.iframeLayer)
    this.iframeLayer.style.display = 'none';
    Spry.Widget.Tooltip.prototype.showError = function(msg)
    alert('Spry.Widget.Tooltip ERR: ' + msg);
    Spry.Widget.Tooltip.refreshAll = function()
    var q = Spry.Widget.Tooltip.loadQueue;
    var qlen = q.length;
    for (var i = 0; i < qlen ; i++)
    if (q[i].checkDestroyed())
    // the trigger element is no longer in the dom, we should remove the current widget.
    q[i].destroy();
    q.splice(i, 1);
    i--;
    qlen = q.length;
    Spry.Widget.Tooltip.closeAll = function()
    var q = Spry.Widget.Tooltip.loadQueue;
    var qlen = q.length;
    for (var i = 0; i < qlen ; i++)
    if (q[i].visibleTooltip)
    q[i].hideTooltip(true);
    if (q[i].showTimer)
    clearTimeout(q[i].showTimer);
    if (q[i].hideTimer)
    clearTimeout(q[i].hideTimer);
    Spry.Widget.Tooltip.Animator = function(element, opts)
    this.timer = null;
    this.fps = 60;
    this.duration = 500;
    this.startTime = 0;
    this.transition = Spry.Widget.Tooltip.Animator.defaultTransition;
    this.onComplete = null;
    if (typeof element == 'undefined') return;
    this.element = Spry.Widget.Utils.getElement(element);
    Spry.Widget.Utils.setOptions(this, opts, true);
    this.interval = this.duration / this.fps;
    Spry.Widget.Tooltip.Animator.defaultTransition = function(time, begin, finish, duration) { time /= duration; return begin + ((2 - time) * time * finish); };
    Spry.Widget.Tooltip.Animator.prototype.start = function()
    var self = this;
    this.startTime = (new Date).getTime();
    this.beforeStart();
    this.timer = setInterval(function() { self.stepAnimation(); }, this.interval);
    Spry.Widget.Tooltip.Animator.prototype.stop = function()
    if (this.timer)
    clearTimeout(this.timer);
    this.timer = null;
    Spry.Widget.Tooltip.Animator.prototype.stepAnimation = function(){};
    Spry.Widget.Tooltip.Animator.prototype.beforeStart = function(){};
    Spry.Widget.Tooltip.Animator.prototype.destroy = function()
    for (var k in this)
    try
    delete this.k;
    }catch(err){}
    Spry.Widget.Tooltip.Fade = function(element, opts)
    Spry.Widget.Tooltip.Animator.call(this, element, opts);
    if (Spry.is.ie)
    this.origOpacity = this.element.style.filter;
    else
    this.origOpacity = this.element.style.opacity;
    Spry.Widget.Tooltip.Fade.prototype = new Spry.Widget.Tooltip.Animator();
    Spry.Widget.Tooltip.Fade.prototype.constructor = Spry.Widget.Tooltip.Fade;
    Spry.Widget.Tooltip.Fade.prototype.stepAnimation = function()
    var curTime = (new Date).getTime();
    var elapsedTime = curTime - this.startTime;
    var i, obj;
    if (elapsedTime >= this.duration)
    this.beforeStop();
    this.stop();
    return;
    var ht = this.transition(elapsedTime, this.from, this.to - this.from, this.duration);
    if (Spry.is.ie)
    var filter = this.element.style.filter.replace(/alpha\s*\(\s*opacity\s*=\s*[0-9\.]{1,3}\)/, '');
    this.element.style.filter = filter + 'alpha(opacity=' + parseInt(ht * 100, 10) + ')';
    else
    this.element.style.opacity = ht;
    this.element.style.visibility = 'visible';
    this.element.style.display = 'block';
    Spry.Widget.Tooltip.Fade.prototype.beforeStop = function()
    if (this.from > this.to)
    this.element.style.display = 'none';
    if (Spry.is.mozilla)
    this.element.style.filter = this.origOpacity;
    else
    this.element.style.opacity = this.origOpacity;
    Spry.Widget.Tooltip.Blind = function(element, opts)
    this.from = 0;
    this.to = 100;
    Spry.Widget.Tooltip.Animator.call(this, element, opts);
    this.element.style.visibility = 'hidden';
    this.element.style.display = 'block';
    this.origHeight = parseInt(Spry.Widget.Utils.getStyleProperty(this.element, 'height'),10);
    if (isNaN(this.origHeight))
    this.origHeight = this.element.offsetHeight;
    if (this.to == 0)
    this.from = this.origHeight;
    else
    this.to = this.origHeight;
    Spry.Widget.Tooltip.Blind.prototype = new Spry.Widget.Tooltip.Animator();
    Spry.Widget.Tooltip.Blind.prototype.constructor = Spry.Widget.Tooltip.Blind;
    Spry.Widget.Tooltip.Blind.prototype.beforeStart = function()
    this.origOverflow = Spry.Widget.Utils.getStyleProperty(this.element, 'overflow');
    this.element.style.overflow = 'hidden';
    Spry.Widget.Tooltip.Blind.prototype.stepAnimation = function()
    var curTime = (new Date).getTime();
    var elapsedTime = curTime - this.startTime;
    var i, obj;
    if (elapsedTime >= this.duration)
    this.beforeStop();
    this.stop();
    return;
    var ht = this.transition(elapsedTime, this.from, this.to - this.from, this.duration);
    this.element.style.height = Math.floor(ht) + 'px';
    this.element.style.visibility = 'visible';
    this.element.style.display = 'block';
    Spry.Widget.Tooltip.Blind.prototype.beforeStop = function()
    this.element.style.overflow = this.origOverflow;
    if (this.from > this.to)
    this.element.style.display = 'none';
    this.element.style.height = this.origHeight + 'px';
    // Spry.Widget.Utils
    if (!Spry.Widget.Utils) Spry.Widget.Utils = {};
    Spry.Widget.Utils.setOptions = function(obj, optionsObj, ignoreUndefinedProps)
    if (!optionsObj)
    return;
    for (var optionName in optionsObj)
    if (ignoreUndefinedProps && optionsObj[optionName] == undefined)
    continue;
    obj[optionName] = optionsObj[optionName];
    Spry.Widget.Utils.getElement = function(ele)
    if (ele && typeof ele == "string")
    return document.getElementById(ele);
    return ele;
    Spry.Widget.Utils.getElementsByClassName = function(sel)
    if (!sel.length > 0)
    return null;
    var selectors = sel.split(',');
    var el = [];
    for (var i =0; i < selectors.length; i++)
    var cs = selectors[i];
    var chunk = cs.split(' ');
    var parents = [];
    parents[0] = [];
    parents[0][0] = document.body;
    for (var j = 0; j < chunk.length; j++)
    var tokens = Spry.Widget.Utils.getSelectorTokens(chunk[j]);
    for (var k =0; k < parents[j].length; k++)
    var childs = parents[j][k].getElementsByTagName('*');
    parents[j+1] = [];
    for (var l=0; l < childs.length; l++)
    if (Spry.Widget.Utils.hasSelector(childs[l], tokens))
    parents[j+1].push(childs[l]);
    if (parents[j])
    for (var k = 0; k < parents[j].length; k++)
    el.push(parents[j][k]);
    return el;
    Spry.Widget.Utils.firstValid = function()
    var ret = null;
    var a = Spry.Widget.Utils.firstValid;
    for(var i=0; i< a.arguments.length; i++)
    if (typeof(a.arguments[i]) != 'undefined')
    ret = a.arguments[i];
    break;
    return ret;
    Spry.Widget.Utils.getSelectorTokens = function(str)
    str = str.replace(/\./g, ' .');
    str = str.replace(/\#/g, ' #');
    str = str.replace(/^\s+|\s+$/g,"");
    return str.split(' ');
    Spry.Widget.Utils.hasSelector = function(el, tokens)
    for (var i =0; i< tokens.length; i++)
    switch (tokens[i].charAt(0))
    case '.': if (!el.className || el.className.indexOf(tokens[i].substr(1)) == -1) return false; break;
    case '#': if (!el.id || el.id != tokens[i].substr(1)) return false; break;
    default: if (el.nodeName.toLowerCase != tokens[i]) return false; break;
    return true;
    Spry.Widget.Utils.addEventListener = function(element, eventType, handler, capture)
    try
    if (element.addEventListener)
    element.addEventListener(eventType, handler, capture);
    else if (element.attachEvent)
    element.attachEvent("on" + eventType, handler);
    catch (e) {}
    Spry.Widget.Utils.getStyleProperty = function(element, prop)
    var value;
    var camelized = Spry.Widget.Utils.camelize(prop);
    try
    if (element.style)
    value = element.style[camelized];
    if (!value)
    if (document.defaultView && document.defaultView.getComputedStyle)
    var css = document.defaultView.getComputedStyle(element, null);
    value = css ? css.getPropertyValue(prop) : null;
    else if (element.currentStyle)
    value = element.currentStyle[camelized];
    catch (e) {}
    return value == 'auto' ? null : value;
    Spry.Widget.Utils.camelize = function(str)
    if (str.indexOf('-') == -1)
    return str;
    var oStringList = str.split('-');
    var isFirstEntry = true;
    var camelizedString = '';
    for(var i=0; i < oStringList.length; i++)
    if(oStringList[i].length>0)
    if(isFirstEntry)
    camelizedString = oStringList[i];
    isFirstEntry = false;
    else
    var s = oStringList[i];
    camelizedString += s.charAt(0).toUpperCase() + s.substring(1);
    return camelizedString;
    * Spry.Widget.Utils.getPixels
    * returns the value of a CSS property as Int, converting medium to 2
    * @param {DOMElement} m - elements
    * @param {String} s -
    Spry.Widget.Utils.getPixels = function (m, s)
    var v = Spry.Widget.Utils.getStyleProperty(m, s);
    if (v == "medium") {
    v = 2;
    } else {
    v = parseInt(v, 10);
    v = isNaN(v)?0:v;
    return v;
    Spry.Widget.Utils.getAbsoluteMousePosition = function(ev)
    var pos = {x:0, y:0};
    if (ev.pageX)
    pos.x = ev.pageX;
    else if (ev.clientX)
    pos.x = ev.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
    if (isNaN(pos.x)) pos.x = 0;
    if (ev.pageY)
    pos.y = ev.pageY;
    else if (ev.clientY)
    pos.y = ev.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
    if (isNaN(pos.y)) pos.y = 0;
    return pos;
    * Spry.Widget.Utils.getBorderBox
    * returns a border box object (x,y,width,height) which perfectly covers the el element and its borders
    * the x, y are absolute coordinates measured from from the window viewport
    * use the box as the second parameter in Spry.Widget.Utils.setBorderBox
    * @param {DOMElement or String} el -
    * @param {DOMDocument,optional} doc -
    Spry.Widget.Utils.getBorderBox = function (el, doc)
    doc = doc || document;
    if (typeof el == 'string')
    el = doc.getElementById(el);
    if (!el)
    return false;
    if (el.parentNode === null || Spry.Widget.Utils.getStyleProperty(el, 'display') == 'none')
    //element must be visible to have a box
    return false;
    var ret = {x:0, y:0, width:0, height:0};
    var parent = null;
    var box;
    if (el.getBoundingClientRect) { // IE
    box = el.getBoundingClientRect();
    var scrollTop = doc.documentElement.scrollTop || doc.body.scrollTop;
    var scrollLeft = doc.documentElement.scrollLeft || doc.body.scrollLeft;
    ret.x = box.left + scrollLeft;
    ret.y = box.top + scrollTop;
    ret.width = box.right - box.left;
    ret.height = box.bottom - box.top;
    } else if (doc.getBoxObjectFor) { // gecko
    box = doc.getBoxObjectFor(el);
    ret.x = box.x;
    ret.y = box.y;
    ret.width = box.width;
    ret.height = box.height;
    var btw = Spry.Widget.Utils.getPixels(el, "border-top-width");
    var blw = Spry.Widget.Utils.getPixels(el, "border-left-width");
    ret.x -= blw;
    ret.y -= btw;
    } else { // safari/opera
    ret.x = el.offsetLeft;
    ret.y = el.offsetTop;
    ret.width = el.offsetWidth;
    ret.height = el.offsetHeight;
    parent = el.offsetParent;
    if (parent != el)
    while (parent)
    ret.x += parent.offsetLeft;
    ret.y += parent.offsetTop;
    parent = parent.offsetParent;
    var blw = Spry.Widget.Utils.getPixels(el, "border-left-width");
    var btw = Spry.Widget.Utils.getPixels(el, "border-top-width");
    ret.x -= blw;
    ret.y -= btw;
    // opera & (safari absolute) incorrectly account for body offsetTop
    var ua = navigator.userAgent.toLowerCase();
    if (Spry.is.opera || Spry.is.safari && Spry.Widget.Utils.getStyleProperty(el, 'position') == 'absolute')
    ret.y -= doc.body.offsetTop;
    if (el.parentNode)
    parent = el.parentNode;
    else
    parent = null;
    while (parent && parent.tagName != 'BODY' && parent.tagName != 'HTML')
    ret.x -= (isNaN(parent.scrollLeft) ? 0 : parent.scrollLeft);
    ret.y -= (isNaN(parent.scrollTop)  ? 0 : parent.scrollTop);
    if (parent.parentNode)
    parent = parent.parentNode;
    else
    parent = null;
    return ret;
    * Spry.Widget.Utils.setBorderBox
    * puts the element el to the location specified by box
    * @param {DOMElement} el - the element to be placed
    * @param {Object} box - hash containing the x and y coordinates where to put el
    Spry.Widget.Utils.setBorderBox = function (el, box) {
    var pos = Spry.Widget.Utils.getBorderBox(el, el.ownerDocument);
    if (pos === false)
    return false;
    var delta = {
    x:Spry.Widget.Utils.getPixels(el, 'left'),
    y:Spry.Widget.Utils.getPixels(el, 'top')
    var new_pos = {x:0, y:0, w:0, h:0};
    if (typeof box.x == 'number') {
    new_pos.x = box.x - pos.x + delta.x;
    if (typeof box.y == 'number') {
    new_pos.y = box.y - pos.y + delta.y;
    if (typeof box.x == 'number') {
    el.style.left = new_pos.x + 'px';
    if (typeof box.y == 'number') {
    el.style.top = new_pos.y + 'px';
    return true;
    Spry.Widget.Utils.putElementAt = function (source, target, offset, biv)
    biv = Spry.Widget.Utils.firstValid(biv, true);
    var source_box = Spry.Widget.Utils.getBorderBox(source, source.ownerDocument);
    Spry.Widget.Utils.setBorderBox(source, target);
    if (biv)
    Spry.Widget.Utils.bringIntoView(source);
    return true;
    * Spry.Widget.Utils.bringIntoView
    * set the position of the source element so it is completely visible in the window
    * @param {DOMElemenet} source - the element to be
    Spry.Widget.Utils.bringIntoView = function (source) {
    var box = Spry.Widget.Utils.getBorderBox(source, source.ownerDocument);
    if (box === false) {
    return false;
    var current = {
    x:Spry.Widget.Utils.getPixels(source, 'left'),
    y:Spry.Widget.Utils.getPixels(source, 'top')
    var delta = {x:0, y:0};
    var offset_fix = {x:0, y:0};
    var strictm = source.ownerDocument.compatMode == "CSS1Compat";
    var doc = (Spry.is.ie && strictm || Spry.is.mozilla)?source.ownerDocument.documentElement:source.ownerDocument.body;
    offset_fix.x = Spry.Widget.Utils.getPixels(doc, 'border-left-width');
    offset_fix.y = Spry.Widget.Utils.getPixels(doc, 'border-top-width');
    var st = doc.scrollTop;
    var ch = self.innerHeight ? self.innerHeight : doc.clientHeight;
    var t = box.y + (Spry.is.ie?-offset_fix.y:offset_fix.y);
    var b = box.y + box.height + (Spry.is.ie?-offset_fix.y:offset_fix.y);
    if ( b - st > ch) {
    delta.y = ch - (b - st);
    if (t + delta.y < st) {
    delta.y = st-t;
    } else if (t < st) {
    delta.y = st - t;
    if (delta.y != 0) {
    source.style.top = (current.y + delta.y) + 'px';
    var sl = doc.scrollLeft;
    var cw = doc.clientWidth;
    var l = box.x + (Spry.is.ie?-offset_fix.x:offset_fix.x);
    var r = box.x + box.width + (Spry.is.ie?-offset_fix.x:offset_fix.x);
    if ( r - sl > cw) {
    delta.x = cw - (r - sl);
    if (l + delta.x < sl) {
    delta.x = sl-l;
    } else if (l < sl) {
    delta.x = sl - l;
    if (delta.x != 0) {
    source.style.left = (current.x + delta.x) + 'px';
    Spry.Widget.Utils.contains = function (who, what) {
    if (typeof who.contains == 'object') {
    return what && who && (who == what || who.contains(what));
    } else {
    var el = what;
    while(el) {
    try{
    if (el == who) {
    return true;
    el = el.parentNode;
    }catch(a){return false;}
    return false;
    })(); // EndSpryComponent
    @charset "UTF-8";
    /* SpryTooltip.css - version 0.2 - Spry 1.6.1 */
    /* Copyright (c) 2006. Adobe Systems Incorporated. All rights reserved. */
    /* HACK FOR IE: to make sure the tooltips show above form controls, we underlay each tooltip with an iframe */
    .iframeTooltip
    position: absolute;
    z-index: 1010;
    filter:alpha(opacity:0.1);
    .tooltipContent
    font-size: 11px;
    font-style: italic;
    color: #332c40;
    width: 96px;
    height: 51px;
    background: url(../_images/recipe/bubble2.png) no-repeat;
    font-family: "Comic Sans MS", cursive;
    margin: 0px;
    left: -200px;
    top: -200px;
    padding-top: 5px;
    vertical-align: middle;
    position: fixed;

    I couldn't get this script to work with my code:
    <a id="greensource" href="a"><img src="images/greensource.png" alt="Greensource Initiative" width="193" height="71" border="0" usemap="#Map7" id="sprytrigger6" title="Greensource Initiative" />
    <map name="Map7" id="Map7">
    <area shape="rect" coords="-22,-15,197,79" href="#" />
    </map>
    </a>
    <div class="tooltipContent" id="green">
    <div class="secondback">
    <div style="padding: 15px;">
    <h1>GREENSOURCE</h1>
    <h2>INITIATIVE&#8482;</h2>
    <p>Manufactred within Greensource Initiative&#8482; guildelines for use of recycled materials, renewable energy and non-hazardous packaging materials. RoHS Compliant.</p>
    <p class="morebutton"><a href="#">LEARN MORE</a></p>
    </div>
    </div>
    </div>
    <script type="text/javascript">
    <!--
    var sprytooltip7 = new Spry.Widget.Tooltip("green", "#greensource");
    //-->
    </script>
    Maybe someone can point out my problem?
    CSS:
    .tooltipContent
        margin: 0;
        padding: 0;
        background: #FFF url(../images/bottom-gradient.png) repeat-x bottom left;
        font-family: "Myriad Pro", Tahoma, Geneva, sans-serif;
        text-align: left;
        box-shadow: 2px 2px 4px #b6b5b6;
        -webkit-box-shadow: 2px 2px 4px #b6b5b6;
        -moz-box-shadow: 2px 2px 4px #b6b5b6;
        position: fixed;
    #green {
        position: absolute;
        border: none;
        top: 200px;
        left: 200px;

  • Spry Tabbed Panels 2 - Remember Last Tab

    Using the Spry UI Tabbed Panels 2, has anyone found a way for the page to remember which tabbed was last viewed?
    I can see that I can use the showPanel() method to set the panel, and I can use the getCurrentTabIndex() to retrieve the current tab index, but I am not sure what to do with them next.
    I am thinking about maybe setting a cookie with the current tab index, but I don't know what to attach the onclick event to. Should I use a spry selector to add the onclick attribute to the a tag that is automatically generated?
    Does anyone else have any clever ideas?
    Cheers,
    Steve

    THANK YOU VERY MUCH GRAMPS!:  THIS DID WORK!
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Spry Accordion</title>
    <link href="SpryAssets/SpryTabbedPanels.css" rel="stylesheet">
    </head>
    <body>
    <div id="TabbedPanels1" class="TabbedPanels">
      <ul class="TabbedPanelsTabGroup">
        <li class="TabbedPanelsTab" tabindex="0">Tab 1</li>
        <li class="TabbedPanelsTab" tabindex="0">Tab 2</li>
      </ul>
      <div class="TabbedPanelsContentGroup">
        <div class="TabbedPanelsContent">Content 1</div>
        <div class="TabbedPanelsContent">Content 2</div>
      </div>
    </div>
    <script src="SpryAssets/SpryTabbedPanels.js"></script>
    <script>
    var Spry; if (!Spry) Spry = {}; if (!Spry.Utils) Spry.Utils = {};
    // We need an unload listener so we can store the data when the user leaves the page
    // SpryDOMUtils.js only provides us with a load listener so we create this function
    Spry.Utils.addUnLoadListener = function(handler /* function */)
        if (typeof window.addEventListener != 'undefined')
            window.addEventListener('unload', handler, false);
        else if (typeof document.addEventListener != 'undefined')
            document.addEventListener('unload', handler, false);
        else if (typeof window.attachEvent != 'undefined')
            window.attachEvent('onunload', handler);
    Spry.Utils.Cookie = function(type /* String*/, name /* String */, value /* String or number */, options /* object */){
        var name = name + '=';
        if(type == 'create'){
            // start cookie String creation
            var str = name + value;
            // check if we have options to add
            if(options){
                // convert days and create an expire setting
                if(options.days){
                    var date = new Date();
                    str += '; expires=' + (date.setTime(date.getTime() + (options.days * 86400000 /* one day 24 hours x 60 min x 60 seconds x 1000 milliseconds */))).toGMTString();
                // possible path settings
                if(options.path){
                    str += '; path=' + options.path               
                // allow cookies to be set per domain
                if(options.domain){
                    str += '; domain=' + options.domain;
            } else {
                // always set the path to /
                str += '; path=/';
            // set the cookie
            document.cookie = str;
        } else if(type == 'read'){
            var c = document.cookie.split(';'),
                str = name,
                i = 0,
                length = c.length;
            // loop through our cookies
            for(; i < length; i++){
                while(c[i].charAt(0) == ' ')
                    c[i] = c[i].substring(1,c[i].length);
                    if(c[i].indexOf(str) == 0){
                        return c[i].substring(str.length,c[i].length);
            return false;
        } else {
            // remove the cookie, this is done by settings an empty cookie with a negative date
            Spry.Utils.Cookie('create',name,null,{days:-1});
    var cookie = Spry.Utils.Cookie('read','panel');
    //alert(cookie);
    var TabbedPanels1 = new Spry.Widget.TabbedPanels("TabbedPanels1", {defaultTab: cookie ? parseFloat(cookie) : 0});
    Spry.Utils.addUnLoadListener(function(){
        Spry.Utils.Cookie('create','panel',TabbedPanels1.getCurrentTabIndex());
    </script>
    </body>
    </html>

  • Tabbed Panel - Persistent State?

    Hi, I'm using a tabbed panel to separate the main subtopics
    for the main page of a website. The only problem I'm having is that
    the panel reverts to the default tab when you leave the page and
    then return. The only exceptions seem to have to do with the
    Browser caching the state temporarily. The tabbed panel samples
    have the same behavior.
    Does anyone know how to fix this problem?
    Thanks
    Tim Howells

    Save the tab number in a cookie and read the cookie on page
    load?
    to get the current tab:
    var varname = tp1.getCurrentTabIndex();
    (tp1 beein the var name of your tabbed panels)
    For the load listener have to include spryDOMUTILS.js
    and u can fire it usin this code
    Spry.Utils.addLoadListener(function(){ save stuff to cookie
    I have also created a onUNLOADlistener (that scripts get
    fired when people leave the page.
    open Spry DOMUtils.js and go to line 262 and this code under
    it.
    (or search for addLoadListener = function(handler)
    Spry.Utils.addUnLoadListener = function(handler)
    if (typeof window.addEventListener != 'undefined')
    window.addEventListener('unload', handler, false);
    else if (typeof document.addEventListener != 'undefined')
    document.addEventListener('unload', handler, false);
    else if (typeof window.attachEvent != 'undefined')
    window.attachEvent('onunload', handler);
    The onUnloadListener can be activated by
    Spry.Utils.addUnLoadListener(function(){ save stuff to cookie
    I also have a Spry.Utils.Cookie handler if u need it. message
    me, Than ill post it.
    I hope this covers your question,

Maybe you are looking for

  • Error 4000 burning CDs with iTunes 7.1

    iTunes checks the disc, then burns 3-4 songs, then cancels the CD burn wasting yet another disc. Also, I cannot backup my purchased songs with the backup feature. I get the same error 4000 when attempting to make a backup disc. These problems only be

  • If I log out of iTunes and log in with a different account, will all my apps and data be deleted?

    This is not only a question for my computer but also for my phone and my iPad. My mom has an Apple account that both she and I use. Unfortunately, without turning on iCloud, all of my Safari bookmarks are transported to her phone and her notes go to

  • How to .... create a hierarchical dimension in ODI?

    What are the steps to create a hierarchical dimension in ODI? For example: Employee dimension with 3 levels: L1, L2, L3 (will include SID, ID, ...) Any suggestions are appreciated !

  • Where is miro being configured

    Just as migo is configured in mm where is miro configured. suppose we have a stock of 10 units which includes 4 units whose miro has not been done. now we have 3 situations:- 1. we have all the 10 units and we want to do miro regarding these 4 units.

  • CS5 flash quits immediately upon opening

    I'm using a brand new mac OSX I bought a couple months ago. Flash 'quit unexpectedely', which is fine once, but continuously? I lists a bunch of code in it's 'comments' but refuses to open. I can't do any work. I have not 'restarted' my computer, I'm