/*  Eternity Technologies

	www.etk.com.au
	2007-04-14

	Copyright 2007
    
    $Id: sybh.js 139 2007-07-27 03:21:39Z edward $
*/

/* Disable the HideMenu function in
   NetObjects implementations.   */

if (window.HideMenu) {
    window.HideMenu = function(){return;};
    window.onclick = HideMenu;
    document.onmouseup = HideMenu;
};

var etk = window.etk || { };
etk.Cookie = { };

/* Cookie is not meant to constructed. */

// Following code modified from http://javascript.internet.com/cookies/delicious-cookies.html

etk.Cookie.getCookie = function( name ) {
  var start = document.cookie.indexOf( name + "=" );
  var len = start + name.length + 1;
  if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
    return null;
  }
  if ( start == -1 ) {return null;}
  var end = document.cookie.indexOf( ";", len );
  if ( end == -1 ) {end = document.cookie.length;}
  return unescape( document.cookie.substring( len, end ) );
};

etk.Cookie.setCookie = function( name, value, expires, path, domain, secure ) {
  var today = new Date();
  today.setTime( today.getTime() );
  if ( expires ) {
    expires = expires * 1000 * 60 * 60 * 24;
  }
  var expires_date = new Date( today.getTime() + (expires) );
  document.cookie = name+"="+escape( value ) +
    ( ( expires ) ? ";expires="+expires_date.toGMTString() : "" ) + //expires.toGMTString()
    ( ( path ) ? ";path=" + path : "" ) +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
};

etk.Cookie.deleteCookie = function( name, path, domain ) {
  if ( etk.Cookie.getCookie( name ) ) {document.cookie = name + "=" +
    ( ( path ) ? ";path=" + path : "") +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ";expires=Thu, 01-Jan-1970 00:00:01 GMT";}
};



/*
    json.js
    2006-04-28
    http://www.json.org/json.js

*/
(function () {
    var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        s = {
            array: function (x) {
                var a = ['['], b, f, i, l = x.length, v;
                for (i = 0; i < l; i += 1) {
                    v = x[i];
                    f = s[typeof v];
                    if (f) {
                        v = f(v);
                        if (typeof v == 'string') {
                            if (b) {
                                a[a.length] = ',';
                            }
                            a[a.length] = v;
                            b = true;
                        }
                    }
                }
                a[a.length] = ']';
                return a.join('');
            },
            'boolean': function (x) {
                return String(x);
            },
            'null': function (x) {
                return "null";
            },
            number: function (x) {
                return isFinite(x) ? String(x) : 'null';
            },
            object: function (x) {
                if (x) {
                    if (x instanceof Array) {
                        return s.array(x);
                    }
                    var a = ['{'], b, f, i, v;
                    for (i in x) {
                        v = x[i];
                        f = s[typeof v];
                        if (f) {
                            v = f(v);
                            if (typeof v == 'string') {
                                if (b) {
                                    a[a.length] = ',';
                                }
                                a.push(s.string(i), ':', v);
                                b = true;
                            }
                        }
                    }
                    a[a.length] = '}';
                    return a.join('');
                }
                return 'null';
            },
            string: function (x) {
                if (/["\\\x00-\x1f]/.test(x)) {
                    x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                        var c = m[b];
                        if (c) {
                            return c;
                        }
                        c = b.charCodeAt();
                        return '\\u00' +
                            Math.floor(c / 16).toString(16) +
                            (c % 16).toString(16);
                    });
                }
                return '"' + x + '"';
            }
        };

    Object.prototype.toJSONString = function () {
        return s.object(this);
    };

    Array.prototype.toJSONString = function () {
        return s.array(this);
    };
})();

String.prototype.parseJSON = function () {
    try {
        
        return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
                this.replace(/"(\\.|[^"\\])*"/g, ''))) &&
            eval('(' + this + ')');        
    } catch (e) {
        return false;
    }
};



/* Copyright (c) 2006, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.net/yui/license.txt version: 0.10.0 */ 
/* yahoo-min.js + events-min.js + dom-min.js*/
var YAHOO=window.YAHOO||{};YAHOO.namespace=function(_1){if(!_1||!_1.length){return null;}var _2=_1.split(".");var _3=YAHOO;for(var i=(_2[0]=="YAHOO")?1:0;i<_2.length;++i){_3[_2[i]]=_3[_2[i]]||{};_3=_3[_2[i]];}return _3;};YAHOO.log=function(_5,_6){if(YAHOO.widget.Logger){YAHOO.widget.Logger.log(null,_5,_6);}else{return false;}};YAHOO.namespace("util");YAHOO.namespace("widget");YAHOO.namespace("example");
YAHOO.util.CustomEvent=function(_1,_2){this.type=_1;this.scope=_2||window;this.subscribers=[];if(YAHOO.util.Event){YAHOO.util.Event.regCE(this);}};YAHOO.util.CustomEvent.prototype={subscribe:function(fn,_4,_5){this.subscribers.push(new YAHOO.util.Subscriber(fn,_4,_5));},unsubscribe:function(fn,_6){var _7=false;for(var i=0,len=this.subscribers.length;i<len;++i){var s=this.subscribers[i];if(s&&s.contains(fn,_6)){this._delete(i);_7=true;}}return _7;},fire:function(){for(var i=0,len=this.subscribers.length;i<len;++i){var s=this.subscribers[i];if(s){var _10=(s.override)?s.obj:this.scope;s.fn.call(_10,this.type,arguments,s.obj);}}},unsubscribeAll:function(){for(var i=0,len=this.subscribers.length;i<len;++i){this._delete(i);}},_delete:function(_11){var s=this.subscribers[_11];if(s){delete s.fn;delete s.obj;}delete this.subscribers[_11];}};YAHOO.util.Subscriber=function(fn,obj,_13){this.fn=fn;this.obj=obj||null;this.override=(_13);};YAHOO.util.Subscriber.prototype.contains=function(fn,obj){return (this.fn==fn&&this.obj==obj);};if(!YAHOO.util.Event){YAHOO.util.Event=function(){var _14=false;var _15=[];var _16=[];var _17=[];var _18=[];var _19=[];var _20=[];var _21=0;var _22=[];var _23=[];var _24=0;return {POLL_RETRYS:200,POLL_INTERVAL:50,EL:0,TYPE:1,FN:2,WFN:3,SCOPE:3,ADJ_SCOPE:4,isSafari:(/Safari|Konqueror|KHTML/gi).test(navigator.userAgent),isIE:(!this.isSafari&&!navigator.userAgent.match(/opera/gi)&&navigator.userAgent.match(/msie/gi)),addDelayedListener:function(el,_26,fn,_27,_28){_16[_16.length]=[el,_26,fn,_27,_28];if(_14){_21=this.POLL_RETRYS;this.startTimeout(0);}},startTimeout:function(_29){var i=(_29||_29===0)?_29:this.POLL_INTERVAL;var _30=this;var _31=function(){_30._tryPreloadAttach();};this.timeout=setTimeout(_31,i);},onAvailable:function(_32,_33,_34,_35){_22.push({id:_32,fn:_33,obj:_34,override:_35});_21=this.POLL_RETRYS;this.startTimeout(0);},addListener:function(el,_36,fn,_37,_38){if(!fn||!fn.call){return false;}if(this._isValidCollection(el)){var ok=true;for(var i=0,len=el.length;i<len;++i){ok=(this.on(el[i],_36,fn,_37,_38)&&ok);}return ok;}else{if(typeof el=="string"){var oEl=this.getEl(el);if(_14&&oEl){el=oEl;}else{this.addDelayedListener(el,_36,fn,_37,_38);return true;}}}if(!el){return false;}if("unload"==_36&&_37!==this){_17[_17.length]=[el,_36,fn,_37,_38];return true;}var _41=(_38)?_37:el;var _42=function(e){return fn.call(_41,YAHOO.util.Event.getEvent(e),_37);};var li=[el,_36,fn,_42,_41];var _45=_15.length;_15[_45]=li;if(this.useLegacyEvent(el,_36)){var _46=this.getLegacyIndex(el,_36);if(_46==-1){_46=_19.length;_23[el.id+_36]=_46;_19[_46]=[el,_36,el["on"+_36]];_20[_46]=[];el["on"+_36]=function(e){YAHOO.util.Event.fireLegacyEvent(YAHOO.util.Event.getEvent(e),_46);};}_20[_46].push(_45);}else{if(el.addEventListener){el.addEventListener(_36,_42,false);}else{if(el.attachEvent){el.attachEvent("on"+_36,_42);}}}return true;},fireLegacyEvent:function(e,_47){var ok=true;var le=_20[_47];for(var i=0,len=le.length;i<len;++i){var _49=le[i];if(_49){var li=_15[_49];if(li&&li[this.WFN]){var _50=li[this.ADJ_SCOPE];var ret=li[this.WFN].call(_50,e);ok=(ok&&ret);}else{delete le[i];}}}return ok;},getLegacyIndex:function(el,_52){var key=this.generateId(el)+_52;if(typeof _23[key]=="undefined"){return -1;}else{return _23[key];}},useLegacyEvent:function(el,_54){if(!el.addEventListener&&!el.attachEvent){return true;}else{if(this.isSafari){if("click"==_54||"dblclick"==_54){return true;}}}return false;},removeListener:function(el,_55,fn,_56){if(!fn||!fn.call){return false;}if(typeof el=="string"){el=this.getEl(el);}else{if(this._isValidCollection(el)){var ok=true;for(var i=0,len=el.length;i<len;++i){ok=(this.removeListener(el[i],_55,fn)&&ok);}return ok;}}if("unload"==_55){for(i=0,len=_17.length;i<len;i++){var li=_17[i];if(li&&li[0]==el&&li[1]==_55&&li[2]==fn){delete _17[i];return true;}}return false;}var _57=null;if("undefined"==typeof _56){_56=this._getCacheIndex(el,_55,fn);}if(_56>=0){_57=_15[_56];}if(!el||!_57){return false;}if(el.removeEventListener){el.removeEventListener(_55,_57[this.WFN],false);}else{if(el.detachEvent){el.detachEvent("on"+_55,_57[this.WFN]);}}delete _15[_56][this.WFN];delete _15[_56][this.FN];delete _15[_56];return true;},getTarget:function(ev,_59){var t=ev.target||ev.srcElement;if(_59&&t&&"#text"==t.nodeName){return t.parentNode;}else{return t;}},getPageX:function(ev){var x=ev.pageX;if(!x&&0!==x){x=ev.clientX||0;if(this.isIE){x+=this._getScrollLeft();}}return x;},getPageY:function(ev){var y=ev.pageY;if(!y&&0!==y){y=ev.clientY||0;if(this.isIE){y+=this._getScrollTop();}}return y;},getXY:function(ev){return [this.getPageX(ev),this.getPageY(ev)];},getRelatedTarget:function(ev){var t=ev.relatedTarget;if(!t){if(ev.type=="mouseout"){t=ev.toElement;}else{if(ev.type=="mouseover"){t=ev.fromElement;}}}return t;},getTime:function(ev){if(!ev.time){var t=new Date().getTime();try{ev.time=t;}catch(e){return t;}}return ev.time;},stopEvent:function(ev){this.stopPropagation(ev);this.preventDefault(ev);},stopPropagation:function(ev){if(ev.stopPropagation){ev.stopPropagation();}else{ev.cancelBubble=true;}},preventDefault:function(ev){if(ev.preventDefault){ev.preventDefault();}else{ev.returnValue=false;}},getEvent:function(e){var ev=e||window.event;if(!ev){var c=this.getEvent.caller;while(c){ev=c.arguments[0];if(ev&&Event==ev.constructor){break;}c=c.caller;}}return ev;},getCharCode:function(ev){return ev.charCode||((ev.type=="keypress")?ev.keyCode:0);},_getCacheIndex:function(el,_64,fn){for(var i=0,len=_15.length;i<len;++i){var li=_15[i];if(li&&li[this.FN]==fn&&li[this.EL]==el&&li[this.TYPE]==_64){return i;}}return -1;},generateId:function(el){var id=el.id;if(!id){id="yuievtautoid-"+(_24++);el.id=id;}return id;},_isValidCollection:function(o){return (o&&o.length&&typeof o!="string"&&!o.tagName&&!o.alert&&typeof o[0]!="undefined");},elCache:{},getEl:function(id){return document.getElementById(id);},clearCache:function(){},regCE:function(ce){_18.push(ce);},_load:function(e){_14=true;},_tryPreloadAttach:function(){if(this.locked){return false;}this.locked=true;var _68=!_14;if(!_68){_68=(_21>0);}var _69=[];for(var i=0,len=_16.length;i<len;++i){var d=_16[i];if(d){var el=this.getEl(d[this.EL]);if(el){this.on(el,d[this.TYPE],d[this.FN],d[this.SCOPE],d[this.ADJ_SCOPE]);delete _16[i];}else{_69.push(d);}}}_16=_69;notAvail=[];for(i=0,len=_22.length;i<len;++i){var _71=_22[i];if(_71){el=this.getEl(_71.id);if(el){var _72=(_71.override)?_71.obj:el;_71.fn.call(_72,_71.obj);delete _22[i];}else{notAvail.push(_71);}}}_21=(_69.length===0&&notAvail.length===0)?0:_21-1;if(_68){this.startTimeout();}this.locked=false;},_unload:function(e,me){for(var i=0,len=_17.length;i<len;++i){var l=_17[i];if(l){var _75=(l[this.ADJ_SCOPE])?l[this.SCOPE]:window;l[this.FN].call(_75,this.getEvent(e),l[this.SCOPE]);}}if(_15&&_15.length>0){for(i=0,len=_15.length;i<len;++i){l=_15[i];if(l){this.removeListener(l[this.EL],l[this.TYPE],l[this.FN],i);}}this.clearCache();}for(i=0,len=_18.length;i<len;++i){_18[i].unsubscribeAll();delete _18[i];}for(i=0,len=_19.length;i<len;++i){delete _19[i][0];delete _19[i];}},_getScrollLeft:function(){return this._getScroll()[1];},_getScrollTop:function(){return this._getScroll()[0];},_getScroll:function(){var dd=document.documentElement;db=document.body;if(dd&&dd.scrollTop){return [dd.scrollTop,dd.scrollLeft];}else{if(db){return [db.scrollTop,db.scrollLeft];}else{return [0,0];}}}};}();YAHOO.util.Event.on=YAHOO.util.Event.addListener;if(document&&document.body){YAHOO.util.Event._load();}else{YAHOO.util.Event.on(window,"load",YAHOO.util.Event._load,YAHOO.util.Event,true);}YAHOO.util.Event.on(window,"unload",YAHOO.util.Event._unload,YAHOO.util.Event,true);YAHOO.util.Event._tryPreloadAttach();}
YAHOO.util.Dom=function(){var ua=navigator.userAgent.toLowerCase();var isOpera=(ua.indexOf('opera')!=-1);var isIE=(ua.indexOf('msie')!=-1&&!isOpera);var id_counter=0;return{get:function(el){if(typeof el!='string'&&!(el instanceof Array)){return el;}if(typeof el=='string'){return document.getElementById(el);}else{var collection=[];for(var i=0,len=el.length;i<len;++i){collection[collection.length]=this.get(el[i]);}return collection;}return null;},getStyle:function(el,property){var f=function(el){var value=null;var dv=document.defaultView;if(property=='opacity'&&el.filters){value=1;try{value=el.filters.item('DXImageTransform.Microsoft.Alpha').opacity/100;}catch(e){try{value=el.filters.item('alpha').opacity/100;}catch(e){}}}else if(el.style[property]){value=el.style[property];}else if(el.currentStyle&&el.currentStyle[property]){value=el.currentStyle[property];}else if(dv&&dv.getComputedStyle){var converted='';for(var i=0,len=property.length;i<len;++i){if(property.charAt(i)==property.charAt(i).toUpperCase()){converted=converted+'-'+property.charAt(i).toLowerCase();}else{converted=converted+property.charAt(i);}}if(dv.getComputedStyle(el,'')&&dv.getComputedStyle(el,'').getPropertyValue(converted)){value=dv.getComputedStyle(el,'').getPropertyValue(converted);}}return value;};return this.batch(el,f,this,true);},setStyle:function(el,property,val){var f=function(el){switch(property){case'opacity':if(isIE&&typeof el.style.filter=='string'){el.style.filter='alpha(opacity='+val*100+')';if(!el.currentStyle||!el.currentStyle.hasLayout){el.style.zoom=1;}}else{el.style.opacity=val;el.style['-moz-opacity']=val;el.style['-khtml-opacity']=val;}break;default:el.style[property]=val;}};this.batch(el,f,this,true);},getXY:function(el){var f=function(el){if(el.parentNode===null||this.getStyle(el,'display')=='none'){return false;}var parent=null;var pos=[];var box;if(el.getBoundingClientRect){box=el.getBoundingClientRect();var scrollTop=Math.max(document.documentElement.scrollTop,document.body.scrollTop);var scrollLeft=Math.max(document.documentElement.scrollLeft,document.body.scrollLeft);return[box.left+scrollLeft,box.top+scrollTop];}else if(document.getBoxObjectFor){box=document.getBoxObjectFor(el);var borderLeft=parseInt(this.getStyle(el,'borderLeftWidth'));var borderTop=parseInt(this.getStyle(el,'borderTopWidth'));pos=[box.x-borderLeft,box.y-borderTop];}else{pos=[el.offsetLeft,el.offsetTop];parent=el.offsetParent;if(parent!=el){while(parent){pos[0]+=parent.offsetLeft;pos[1]+=parent.offsetTop;parent=parent.offsetParent;}}if(ua.indexOf('opera')!=-1||(ua.indexOf('safari')!=-1&&this.getStyle(el,'position')=='absolute')){pos[0]-=document.body.offsetLeft;pos[1]-=document.body.offsetTop;}}if(el.parentNode){parent=el.parentNode;}else{parent=null;}while(parent&&parent.tagName!='BODY'&&parent.tagName!='HTML'){pos[0]-=parent.scrollLeft;pos[1]-=parent.scrollTop;if(parent.parentNode){parent=parent.parentNode;}else{parent=null;}}return pos;};return this.batch(el,f,this,true);},getX:function(el){return this.getXY(el)[0];},getY:function(el){return this.getXY(el)[1];},setXY:function(el,pos,noRetry){var f=function(el){var style_pos=this.getStyle(el,'position');if(style_pos=='static'){this.setStyle(el,'position','relative');style_pos='relative';}var pageXY=YAHOO.util.Dom.getXY(el);if(pageXY===false){return false;}var delta=[parseInt(YAHOO.util.Dom.getStyle(el,'left'),10),parseInt(YAHOO.util.Dom.getStyle(el,'top'),10)];if(isNaN(delta[0])){delta[0]=(style_pos=='relative')?0:el.offsetLeft;}if(isNaN(delta[1])){delta[1]=(style_pos=='relative')?0:el.offsetTop;}if(pos[0]!==null){el.style.left=pos[0]-pageXY[0]+delta[0]+'px';}if(pos[1]!==null){el.style.top=pos[1]-pageXY[1]+delta[1]+'px';}var newXY=this.getXY(el);if(!noRetry&&(newXY[0]!=pos[0]||newXY[1]!=pos[1])){var retry=function(){YAHOO.util.Dom.setXY(el,pos,true);};setTimeout(retry,0);}};this.batch(el,f,this,true);},setX:function(el,x){this.setXY(el,[x,null]);},setY:function(el,y){this.setXY(el,[null,y]);},getRegion:function(el){var f=function(el){return new YAHOO.util.Region.getRegion(el);};return this.batch(el,f,this,true);},getClientWidth:function(){return this.getViewportWidth();},getClientHeight:function(){return this.getViewportHeight();},getElementsByClassName:function(className,tag,root){var re=new RegExp('(?:^|\\s+)'+className+'(?:\\s+|$)');var method=function(el){return re.test(el['className']);};return this.getElementsBy(method,tag,root);},hasClass:function(el,className){var f=function(el){var re=new RegExp('(?:^|\\s+)'+className+'(?:\\s+|$)');return re.test(el['className']);};return this.batch(el,f,this,true);},addClass:function(el,className){var f=function(el){if(this.hasClass(el,className)){return;}el['className']=[el['className'],className].join(' ');};this.batch(el,f,this,true);},removeClass:function(el,className){var f=function(el){if(!this.hasClass(el,className)){return;}var re=new RegExp('(?:^|\\s+)'+className+'(?:\\s+|$)','g');var c=el['className'];el['className']=c.replace(re,' ');};this.batch(el,f,this,true);},replaceClass:function(el,oldClassName,newClassName){var f=function(el){this.removeClass(el,oldClassName);this.addClass(el,newClassName);};this.batch(el,f,this,true);},generateId:function(el,prefix){prefix=prefix||'yui-gen';var f=function(el){el=el||{};if(!el.id){el.id=prefix+id_counter++;}return el.id;};return this.batch(el,f,this,true);},isAncestor:function(haystack,needle){haystack=this.get(haystack);if(!haystack||!needle){return false;}var f=function(needle){if(haystack.contains&&ua.indexOf('safari')<0){return haystack.contains(needle);}else if(haystack.compareDocumentPosition){return!!(haystack.compareDocumentPosition(needle)&16);}else{var parent=needle.parentNode;while(parent){if(parent==haystack){return true;}else if(parent.tagName=='HTML'){return false;}parent=parent.parentNode;}return false;}};return this.batch(needle,f,this,true);},inDocument:function(el){var f=function(el){return this.isAncestor(document.documentElement,el);};return this.batch(el,f,this,true);},getElementsBy:function(method,tag,root){tag=tag||'*';root=this.get(root)||document;var nodes=[];var elements=root.getElementsByTagName(tag);if(!elements.length&&(tag=='*'&&root.all)){elements=root.all;}for(var i=0,len=elements.length;i<len;++i){if(method(elements[i])){nodes[nodes.length]=elements[i];}}return nodes;},batch:function(el,method,o,override){el=this.get(el);var scope=(override)?o:window;if(!el||el.tagName||!el.length){return method.call(scope,el,o);}var collection=[];for(var i=0,len=el.length;i<len;++i){collection[collection.length]=method.call(scope,el[i],o);}return collection;},getDocumentHeight:function(){var scrollHeight=-1,windowHeight=-1,bodyHeight=-1;var marginTop=parseInt(this.getStyle(document.body,'marginTop'),10);var marginBottom=parseInt(this.getStyle(document.body,'marginBottom'),10);var mode=document.compatMode;if((mode||isIE)&&!isOpera){switch(mode){case'CSS1Compat':scrollHeight=((window.innerHeight&&window.scrollMaxY)?window.innerHeight+window.scrollMaxY:-1);windowHeight=[document.documentElement.clientHeight,self.innerHeight||-1].sort(function(a,b){return(a-b);})[1];bodyHeight=document.body.offsetHeight+marginTop+marginBottom;break;default:scrollHeight=document.body.scrollHeight;bodyHeight=document.body.clientHeight;}}else{scrollHeight=document.documentElement.scrollHeight;windowHeight=self.innerHeight;bodyHeight=document.documentElement.clientHeight;}var h=[scrollHeight,windowHeight,bodyHeight].sort(function(a,b){return(a-b);});return h[2];},getDocumentWidth:function(){var docWidth=-1,bodyWidth=-1,winWidth=-1;var marginRight=parseInt(this.getStyle(document.body,'marginRight'),10);var marginLeft=parseInt(this.getStyle(document.body,'marginLeft'),10);var mode=document.compatMode;if(mode||isIE){switch(mode){case'CSS1Compat':docWidth=document.documentElement.clientWidth;bodyWidth=document.body.offsetWidth+marginLeft+marginRight;winWidth=self.innerWidth||-1;break;default:bodyWidth=document.body.clientWidth;winWidth=document.body.scrollWidth;break;}}else{docWidth=document.documentElement.clientWidth;bodyWidth=document.body.offsetWidth+marginLeft+marginRight;winWidth=self.innerWidth;}var w=[docWidth,bodyWidth,winWidth].sort(function(a,b){return(a-b);});return w[2];},getViewportHeight:function(){var height=-1;var mode=document.compatMode;if((mode||isIE)&&!isOpera){switch(mode){case'CSS1Compat':height=document.documentElement.clientHeight;break;default:height=document.body.clientHeight;}}else{height=self.innerHeight;}return height;},getViewportWidth:function(){var width=-1;var mode=document.compatMode;if(mode||isIE){switch(mode){case'CSS1Compat':width=document.documentElement.clientWidth;break;default:width=document.body.clientWidth;}}else{width=self.innerWidth;}return width;}};}();YAHOO.util.Region=function(t,r,b,l){this.top=t;this[1]=t;this.right=r;this.bottom=b;this.left=l;this[0]=l;};YAHOO.util.Region.prototype.contains=function(region){return(region.left>=this.left&&region.right<=this.right&&region.top>=this.top&&region.bottom<=this.bottom);};YAHOO.util.Region.prototype.getArea=function(){return((this.bottom-this.top)*(this.right-this.left));};YAHOO.util.Region.prototype.intersect=function(region){var t=Math.max(this.top,region.top);var r=Math.min(this.right,region.right);var b=Math.min(this.bottom,region.bottom);var l=Math.max(this.left,region.left);if(b>=t&&r>=l){return new YAHOO.util.Region(t,r,b,l);}else{return null;}};YAHOO.util.Region.prototype.union=function(region){var t=Math.min(this.top,region.top);var r=Math.max(this.right,region.right);var b=Math.max(this.bottom,region.bottom);var l=Math.min(this.left,region.left);return new YAHOO.util.Region(t,r,b,l);};YAHOO.util.Region.prototype.toString=function(){return("Region {"+"t: "+this.top+", r: "+this.right+", b: "+this.bottom+", l: "+this.left+"}");};YAHOO.util.Region.getRegion=function(el){var p=YAHOO.util.Dom.getXY(el);var t=p[1];var r=p[0]+el.offsetWidth;var b=p[1]+el.offsetHeight;var l=p[0];return new YAHOO.util.Region(t,r,b,l);};YAHOO.util.Point=function(x,y){this.x=x;this.y=y;this.top=y;this[1]=y;this.right=x;this.bottom=y;this.left=x;this[0]=x;};YAHOO.util.Point.prototype=new YAHOO.util.Region();

/*  Helper functions extensions to global objects.

*/
Array.prototype.lastIndexOf = function(anObject){
    for(var i = 0; i < this.length; i++){
        if(this[i] == anObject){
            return i;
        }
    }
    return -1;
};

var etk = window.etk || { };
etk.Presenter = { };

etk.Presenter = function(inContext){
    this.init(inContext);
};

etk.Presenter.prototype.init = function(inContext){
    this.context = inContext;
};

etk.Presenter.prototype.toString = function(){
    return "Presenter";
};

etk.Presenter.prototype.attachEventsTo = function(className, event, callback) {
    var elements = YAHOO.util.Dom.getElementsByClassName(className);
    var element = null;
    for (var i = 0; i < elements.length; i++){
        element = elements[i];
        if (element){
            YAHOO.util.Event.addListener(element, event, callback);
        }      
    }
};


var etk = window.etk || { };
etk.CommentPresenter = { };

etk.CommentPresenter = function(inContext){
    this.init(inContext);
};

etk.CommentPresenter.prototype = new etk.Presenter();
etk.CommentPresenter.parent = etk.Presenter.prototype;

etk.CommentPresenter.prototype.toString = function(){
    return "CommentPresenter";
};

etk.CommentPresenter.prototype.show = function(aComment){
    if (aComment.length === 0){
        this.showDefault();
        return;
    }
    var html = '<p>' + aComment + '</p>';
    document.getElementById(this.context).innerHTML = html;
};

etk.CommentPresenter.prototype.showDefault = function(){
    var html = '<p class="dimed">&nbsp;</p>';
    document.getElementById(this.context).innerHTML = html;
};

etk.CommentPresenter.prototype.showResults = function(results){
    if (results.length === 0){ 
        this.showDefault();
        return;
    }
    //Note that a change was made to display the linkText
    var html = "";
    for(var i=0; i < results.length; i++) {
            html += "<p>" + results[i].linkText + "</p>";
    }
    document.getElementById(this.context).innerHTML = html;
};



var etk = window.etk || { };
etk.Glossary = { };

// Constructor
etk.Glossary = function() {
    this.glossaryTerms = [];
};

etk.Glossary.prototype.toString = function() {
    return "Glossary";
};

etk.Glossary.prototype.addAnchorTags = function(inString) {
    /*  The replacement of spaces with &nbsp; has been used to stop a term like
        'business' matching within a longer term like 'normal business hours'.
        Note that the &nbsp; is stripped out in the lookup() function.
    */
    
    var result = inString;
    
    for (var i=0; i < this.glossaryTerms.length;i++){
        var regExp = new RegExp('('+ this.glossaryTerms[i].label + ')([ .?,:]|$)',"gi");
        
        result = result.replace(regExp, 
                function(str, p1, p2, offset, s){
                    var rep = p1.replace(/ /g, '&nbsp;');
                    return '<a class="etkGlossaryTerm" id= "etkGlossaryAtag" href="#">'+ rep + '</a>' + p2;
                });  
        
        //result = result.replace(regExp, '<a class="etkGlossaryTerm" href="#">$1</a>$2');
    }
    return result;

};


etk.Glossary.prototype.lookup = function(inString) {
    // Strip out $nbsp; added to the question string in 
    // addAnchorTags()
    
    var aString = inString.replace(/&nbsp;/g, ' ' );
    
    for(var i=0;i < this.glossaryTerms.length;i++){
        if (this.glossaryTerms[i].label.toLowerCase() == aString.toLowerCase()){
            return this.glossaryTerms[i].description;
        }
    }
    return "Glossary term not found";
};


var etk = window.etk || { };
etk.GlossaryTerm = { };

// Constructor
etk.GlossaryTerm = function() {
    this.label = "";
    this.description = "";
};

etk.GlossaryTerm.prototype.toString = function() {
    return "GlossaryTerm";
};



var etk = window.etk || { };
etk.NavBarPresenter = { };

etk.NavBarPresenter = function(inContext){
    this.init(inContext);
};

etk.NavBarPresenter.prototype = new etk.Presenter();
etk.NavBarPresenter.parent = etk.Presenter.prototype;

etk.NavBarPresenter.prototype.toString = function(){
    return "NavBarPresenter";
};

etk.NavBarPresenter.prototype.show = function(){
    var nextOption = "";
    var backOption = "";
    var startAgainOption = "";
    //The class is needed - not for css but to enable events to be attached
    nextOption = '<li id="etkNavNext"><a href="#" class="etkNavButton">Next</a></li>';
    backOption = '<li id="etkNavBack"><a href="#" class="etkNavButton">Back</a></li>';
    startAgainOption = '<li id="etkNavStartAgain"><a href="#" class="etkNavButton">Start again</a></li>';
    
    var html =  '<ul>' + backOption + startAgainOption + nextOption + '</ul>';
    document.getElementById(this.context).innerHTML = html;
};

etk.NavBarPresenter.prototype.attachEvents = function(aPresenter){
    YAHOO.util.Event.addListener("etkNavNext", 'click', function(evt) { aPresenter.nextClicked(); });
    YAHOO.util.Event.addListener("etkNavBack", 'click', function(evt) { aPresenter.backClicked(); });
    YAHOO.util.Event.addListener("etkNavStartAgain", 'click', function(evt) { aPresenter.startAgainClicked(); });
};


etk.NavBarPresenter.prototype.hideNextButton = function(){
    document.getElementById("etkNavNext").id = "etkNavNextHide";
};


var etk = window.etk || { };

etk.PagePresenter = { };

// PagePresenter constructor
etk.PagePresenter = function (aSybhManager) {
    this.sybhManager = aSybhManager;
    this.resultNotDisplayed = true;
    this.currentResponse = {};
    this.currentQuestion = {};
    
    this.progressBar = new etk.ProgressBarPresenter("etkProgressBorder");
    this.questionPresenter = new etk.QuestionPresenter("etkBody");
    this.resultPresenter = new etk.ResultPresenter("etkBody");
    this.userResponsePresenter = new etk.UserResponsePresenter("etkResponses");
    this.navBar = new etk.NavBarPresenter("etkNavBar");
    this.comment = new etk.CommentPresenter("etkComment");
};

etk.PagePresenter.prototype.refreshPageOnReturn = function() {
    var cookie = null;
    cookie = etk.Cookie.getCookie("etkResponses");
    // window.startQuestion returns true if startQuestion has been defined.
    if(cookie !== null || window.startQuestion) {
        this.show();
    } else {
        var xhr = newXMLHttpRequest();
        var etkPageBody ="";
        var path =  etkLibPath + "etkPageBody.txt";
        try 
	    {
		    xhr.open('GET', path, false);
    		xhr.setRequestHeader("Accept","text/plain");
        	xhr.send(null);
        	etkPageBody = xhr.responseText;	

	}
	catch (e){
	    etkPageBody = getEtkPageBody();
	}
        // substitute the place holder %etkLibPath% with the value of etkLibPath.
        etkPageBody = etkPageBody.replace(/%etkLibPath%/g, etkLibPath); 

        document.getElementById('etkContainer').innerHTML = etkPageBody;
    };

    function newXMLHttpRequest() {
        if (window.XMLHttpRequest)
            return new XMLHttpRequest();

        if (window.ActiveXObject) 
            return new ActiveXObject('Microsoft.XMLHTTP');

        return 
            null;
    } ;

    function getEtkPageBody(){
        var text = "";
            text += '<div id=\"etkStartMessage\">    <a href=\"#\" onclick=\"etkStart()\"><img src=\"%etkLibPath%sybh_logo.jpg\" alt=\"Start your business here logo\" width=\"400px\" height=\"96px\">'
            text += '</a><br/><br/><p><br/><a class=\"begin\" href=\"#\" onclick=\"etkStart()\">Click here to start</a><br/><br/></p><p> Start Your Business Here was developed by <a href=\"http://reroc.com.au\">    Riverina Eastern Regional Organisation of Councils</a> and <a href=\"http://etk.com.au\"> Eternity Technologies</a>.</p><a style=\"float:left\" href=\"http://www.reroc.com.au\" target= \"_blank\"><img src=\"%etkLibPath%reroc_logo.jpg\" alt=\"REROC Logo\" width=\"200px\" height=\"91px\"></a><a style=\"float:right\" href=\"http://etk.com.au\" target=\"_blank\">'
            text += '<img src=\"%etkLibPath%eternity_logo.jpg\" alt=\"ETK Logo\"></a></div>';
	    return text;
	};
};

etk.PagePresenter.prototype.show = function(){    
    this.setupPage();
    if (window.startQuestion){
        if (startQuestion)
            etk.Cookie.setCookie("etkResponses", startQuestion.toJSONString(), 30);
        //this.sybhManager.init();
        //this.currentQuestion = this.sybhManager.getQuestionForId(startQuestion);
    }
    this.currentQuestion = this.replay(); 
    this.navBar.attachEvents(this);  
    
    this.showPageBody();    
};

etk.PagePresenter.prototype.replay = function() {
    var cookie = null;
    cookie = etk.Cookie.getCookie("etkResponses");
    this.sybhManager.init();
    if (cookie === null){
        return this.sybhManager.firstQuestion();
    }
    
    return this.replayWith(cookie.parseJSON());
};

etk.PagePresenter.prototype.replayWith = function(responses){
    //responses is array of response strings.
    this.currentQuestion = this.sybhManager.firstQuestion();
    for (var i=0 ; i<responses.length ; i++){
        this.addUserResponse();
        this.currentResponse.response = responses[i];
        this.currentQuestion = this.sybhManager.nextQuestion();
        //progressPercantage called so that the lastIndex can be set!!
        this.sybhManager.progressPercentage(this.currentQuestion);
    }
    return this.currentQuestion;
};


etk.PagePresenter.prototype.showPageBody = function(){    
    this.progressBar.show(this.sybhManager.progressPercentage(this.currentQuestion));

    // Test for the type of object to present either a Question or a ResultSummary
    if (this.currentQuestion.isQuestion()){
        this.questionPresenter.show(this.currentQuestion);
        this.questionPresenter.attachEvents(this);

        this.comment.show(this.currentQuestion.comment);    
        // add the user reponse.
        this.addUserResponse();
    }
    
    if (this.currentQuestion.isUserResponseManager()){
        //Note this is a hack as questionPresenter sending the message toHTML() that 
        // is implemented in the questionPresenter.
        this.resultPresenter.show(this.sybhManager.responseManager.allResults());
        this.comment.show("");    
        this.resultPresenter.attachEvents(this);
        this.addNullUserResponse();
    }
    
    this.hideNextButtonAtEnd();

};

etk.PagePresenter.prototype.hideNextButtonAtEnd = function(){

    if (this.sybhManager.stream.atEnd() && this.currentQuestion.isUserResponseManager()){
        this.navBar.hideNextButton();
    } 
}

etk.PagePresenter.prototype.addUserResponse = function(){    
    this.currentResponse = new etk.UserResponse();
    this.currentResponse.question = this.currentQuestion;
    this.sybhManager.responseManager.addUserResponse(this.currentResponse);
};

etk.PagePresenter.prototype.addNullUserResponse = function(){    
    this.currentResponse = new etk.NullUserResponse();
    this.sybhManager.responseManager.addUserResponse(this.currentResponse);
};


etk.PagePresenter.prototype.setupPage = function(){
    var html = '<div id="etkPageBanner" ><img src="' + etkLibPath +'sybh_banner.jpg" alt="Start Your Business Here" /></div>';
    html += '<div id="etkProgressBorder"></div>';
    html += '<div id="etkBody"></div>'; 
    html += '<div id="etkComment"></div>';     
    html += '<div id="etkNavBar"></div>';
    document.getElementById('etkContainer').innerHTML = html;
    
    this.navBar.show();

};


//Event handlers

etk.PagePresenter.prototype.nextClicked = function() {    
    if (this.currentResponse.response !== null || 
            this.currentQuestion.isUserResponseManager()){ 
        this.currentQuestion = this.sybhManager.nextQuestion();
        this.showPageBody();
    }
    else {
        alert("Please select an option");
    }    
};

etk.PagePresenter.prototype.printResponsesClicked = function(showDetails) {
    userResults = null;
    if(showDetails) {
        userResults = this.sybhManager.responseManager.allResults();
    }
    this.userResponsePresenter.show(this.sybhManager.responseManager.getUserResponses(), userResults, this.sybhManager.properties);
};

etk.PagePresenter.prototype.backClicked = function() {
    this.sybhManager.responseManager.rewindCookie();
    window.location.reload();
};

etk.PagePresenter.prototype.startAgainClicked = function() {
    etk.Cookie.deleteCookie("etkResponses");
    window.location.reload();
};

etk.PagePresenter.prototype.responseClicked = function(evt) {
    var target = evt.target || evt.srcElement;
    var currentResponse = target.options[target.selectedIndex].innerHTML;
    this.currentResponse.response = currentResponse;

    var currentQuestion = this.currentQuestion;
/*    
    if(!currentQuestion.isBusinessTypeQuestion) {
        var results = currentQuestion.getResultsFor(currentResponse);  
        this.comment.showResults(results);
    }
    else this.comment.showDefault();
*/
};


etk.PagePresenter.prototype.glossaryTermClicked = function(evt) {
    var target = evt.target || evt.srcElement;
    var glossaryDescription = this.sybhManager.glossary.lookup(target.innerHTML);
    this.comment.show(glossaryDescription);
};



var etk = window.etk || { };
etk.ProgressBarPresenter = { };

etk.ProgressBarPresenter = function(inContext){
    this.init(inContext);
};

etk.ProgressBarPresenter.prototype = new etk.Presenter();
etk.ProgressBarPresenter.parent = etk.Presenter.prototype;

etk.ProgressBarPresenter.prototype.toString = function(){
    return "ProgressBarPresenter";
};

etk.ProgressBarPresenter.prototype.show = function(percentage){

    var html  = '<div class="etkProgressBarContainer">';
    html += '<div class="etkProgressBorder">';
    html += '<div style="width:' + percentage + '%" class="etkProgressBar"></div>';
    html += '<div class="etkProgressText">' + percentage + '%</div>';
    html += '</div>';
    document.getElementById(this.context).innerHTML = html;
};


var etk = window.etk || { };
etk.Question = { };

//Constructor
etk.Question = function(inQuestionId, inQuestionGroup, inQuestionText) {
    this.id             = inQuestionId;
    this.text           = inQuestionText;
    this.responses = [];
    this.defaults = {};
    this.isBusinessTypeQuestion = false;
    this.comment = "";
};

etk.Question.prototype.toString = function() {
	return "Question " + this.id;
};

etk.Question.prototype.isQuestion = function() {
	return true;
};

etk.Question.prototype.isUserResponseManager = function() {
	return false;
};

etk.Question.prototype.toHTML = function() {
    var html = '';
    html += '<div class="etkQuestion">';
    html += this.questionTextToHTML (this.text);
    html += this.responsesToHTML ();  
    html += '</div>';
    return html;
};

etk.Question.prototype.responsesToHTML = function(){
    var html = "";
    var size = this.responses.length + 1;
    if(size > 15) {size = 15;}
    html += '<div class="etkSelect">'
    html += '<select size=' + size + ' class="etkResponses">';   
    for (var index = 0; index < this.responses.length; index++){
        html += this.responseToHTML(this.responses[index].label);
    }
    html += "</select></div>";
    return html;
};

etk.Question.prototype.getResultsFor = function(aLabel) {
    for(var i=0; i < this.responses.length; i++) {
        if(this.responses[i].label == aLabel)
            {return this.responses[i].results;}
    }
    return [];
};

etk.Question.prototype.questionTextToHTML = function(aString){
    var html = "";
    html += "<p>" + aString + "</p>";
    return html;
};

etk.Question.prototype.responseToHTML = function(response){
    var html = "";   
    html += '<option class="etkResponse">';
    html += response;
    html += "</option>";
    return html;
};


var etk = window.etk || { };
etk.QuestionCategory = { };

etk.QuestionCategory = function(){
    this.name = "";
    this.questions = [];
    this.showResultPage = false;
};

etk.QuestionCategory.prototype.toString = function(){
    return "QuestionCategory";
};

etk.QuestionCategory.prototype.dropQuestion = function(inQuestion){
    var questionIndex = this.questions.lastIndexOf(inQuestion);
    
    if (questionIndex == -1 ){ return ;}
    
    for(var i = questionIndex; i < this.questions.length - 1; i++){
        this.questions[i] = this.questions[i+1];
    }
    this.questions.pop();
};


var etk = window.etk || {};
etk.QuestionPresenter = {};

etk.QuestionPresenter = function(inContext){
    this.init(inContext);
};

etk.QuestionPresenter.prototype = new etk.Presenter();
etk.QuestionPresenter.parent = etk.Presenter.prototype;

etk.QuestionPresenter.prototype.toString = function(){
    return "QuestionPresenter";
};

etk.QuestionPresenter.prototype.show = function(aQuestion){
    var html = aQuestion.toHTML();
    document.getElementById(this.context).innerHTML = html;
};

etk.QuestionPresenter.prototype.attachEvents = function(aPresenter){
    this.attachEventsTo("etkResponses", 
        "change", 
        function(evt) { aPresenter.responseClicked (evt);});  
    this.attachEventsTo("etkGlossaryTerm", 
        "click", 
        function(evt) { aPresenter.glossaryTermClicked (evt);});  
};



var etk = window.etk || { };
etk.QuestionTreeBuilder = { };

etk.QuestionTreeBuilder = function( ){
    this.questions = [];
    this.jsonRoot= {};  //contains the final tree of objects.
    this.questionId = 0;
};

etk.QuestionTreeBuilder.prototype.buildFromJson = function(inJsonString ){
//  inJsonString contains the questions grouped by categories. - array of arrays.
    modifiedJsonString = inJsonString.replace(/\r\n/g, '<br/>'); 
    
    //document.write('modifed json <br />');
    //document.write (modifiedJsonString);

    this.jsonRoot = modifiedJsonString.parseJSON();

    this.buildSybhManager();
    this.addGlossaryTermAnchorTags();
};

etk.QuestionTreeBuilder.prototype.buildSybhManager = function(){
    this.jsonRoot = this.copyProperties(this.jsonRoot, etk.SybhManager);

    var questionCategories = this.jsonRoot.categories;
    for (var i = 0; i < questionCategories.length; i++) {
        questionCategories[i] = this.copyProperties(questionCategories[i], etk.QuestionCategory);
        // At this point temp.questions references an array of json objects
        this.buildQuestions(questionCategories[i].questions);
    }
    this.jsonRoot.glossary = this.copyProperties(this.jsonRoot.glossary, etk.Glossary);
    this.buildGlossaryTerms(this.jsonRoot.glossary.glossaryTerms);
    this.buildDefaultResponses(this.jsonRoot.defaults);

    // properties may not exist in earlier versions of the sybh file.
    if (this.jsonRoot.properties){
        this.jsonRoot.properties = this.copyProperties(this.jsonRoot.properties, etk.Properties);
        this.buildProperties(this.jsonRoot.properties);
    }
};

etk.QuestionTreeBuilder.prototype.buildQuestions = function(inQuestions){
    for (var i = 0; i < inQuestions.length; i++){  
        inQuestions[i] = this.copyProperties(inQuestions[i], etk.Question); 
        this.buildResponses(inQuestions[i].responses);
    }
};

etk.QuestionTreeBuilder.prototype.buildDefaultResponses = function(inDefaults){
    for (var i = 0; i < inDefaults.length; i++){  
        inDefaults[i] = this.copyProperties(inDefaults[i], etk.DefaultResponse); 
    }
};


etk.QuestionTreeBuilder.prototype.buildResponses = function(inResponses){
    for (var i = 0; i < inResponses.length; i++){
        inResponses[i] = this.copyProperties(inResponses[i], etk.Response);
        this.buildResults(inResponses[i].results);
    }
};

etk.QuestionTreeBuilder.prototype.buildResults = function(inResults){
    for (var i = 0; i < inResults.length; i++){
        inResults[i] = this.copyProperties(inResults[i], etk.Result);
    }
};

etk.QuestionTreeBuilder.prototype.copyProperties = function(inObject, inClass){
    var temp = new inClass();
    for (var i in inObject) {
        if (typeof inObject[i] != "function") {
            temp[i] = inObject[i]; 
        }
    }
    return temp;
};

etk.QuestionTreeBuilder.prototype.buildGlossaryTerms = function(inGlossaryTerms){
    for (var i = 0; i < inGlossaryTerms.length; i++){
        inGlossaryTerms[i] = this.copyProperties(inGlossaryTerms[i], etk.GlossaryTerm);
    }
    inGlossaryTerms.sort(function(a,b){return b.label.length - a.label.length});
};

etk.QuestionTreeBuilder.prototype.addGlossaryTermAnchorTags = function(){
    var questions = this.jsonRoot.allQuestions();
    for (var i = 0; i < questions.length; i++){
        var each = questions[i];
        each.text = this.jsonRoot.glossary.addAnchorTags(each.text);
    };
};
    
etk.QuestionTreeBuilder.prototype.buildProperties = function(inProperties){
        /*
        0, -0, null, false, NaN, undefined, or the empty string ("") evaluate to false.
        false || expr returns the expr.
        */
        inProperties.councilAddress = inProperties.councilAddress || "";
        inProperties.councilUrl = inProperties.councilUrl || "";
        inProperties.emailContact = inProperties.emailContact || "";
        inProperties.dateModified = new Date(inProperties.dateModified);
};


var etk = window.etk || { };
etk.ReadStream = { };

etk.ReadStream = function(inArray){
    this.source = inArray;
    this.currentIndex = -1;
};

etk.ReadStream.prototype.next = function(){
    return this.source[++this.currentIndex];
};

etk.ReadStream.prototype.back = function(){
    return this.source[--this.currentIndex];
};

etk.ReadStream.prototype.skipToEnd = function(){
    this.currentIndex = this.source.length - 1;
};

etk.ReadStream.prototype.current = function() {
    return this.source[this.currentIndex];
};

etk.ReadStream.prototype.atEnd = function(){
    return this.source.length == this.currentIndex + 1;
};

etk.ReadStream.prototype.atStart = function(){
    return this.currentIndex < 1;
};

etk.ReadStream.prototype.toString = function(){
    return "ReadStream";
};


var etk = window.etk || { };
etk.Response = { };

etk.Response = function(){
    this.label = '';  //Yes, No etc.
    this.results = []; 
};

etk.Response.toString = function(){
    return "Response";
};


var etk = window.etk || { };
etk.ResultPresenter = { };

etk.ResultPresenter = function(inContext){
    this.init(inContext);
};

etk.ResultPresenter.prototype = new etk.Presenter();
etk.ResultPresenter.parent = etk.Presenter.prototype;

etk.ResultPresenter.prototype.toString = function(){
    return "ResultPresenter";
};

etk.ResultPresenter.prototype.show = function(results){
    var html = "";
    html += '<div id="etkResponseList">';
    
    for (var i = 0; i < results.length; i++){   
        var each = results[i];
        if (each.url){
            html += '<p class="etkResponseListItem"><a href = "'+ each.url + '">'+ each.linkText + '</a></p>';
        }else{
            html += '<p class="etkResponseListItem">'+ each.linkText + '</p>';            
        }
        if(each.description) {
            html += '<p class="etkResponseDescription">' + each.description + '</p>';
        }
    }
    
    html += '</div>';
    html += '<div id=etkPrintResponses>';
    html += '<ul><li>'   
    html += '<a href="#" class="etkPrintResponses">Print answers</a></li>';
    html += '<li><a href="#" class="etkPrintDetailedResponses">Print answers and responses</a></li>';
    html += '</ul></div>';
    document.getElementById(this.context).innerHTML = html;
};

etk.ResultPresenter.prototype.attachEvents = function(aPresenter){
    this.attachEventsTo("etkPrintResponses", 
        "click", 
        function(evt) { aPresenter.printResponsesClicked (false);});
    this.attachEventsTo("etkPrintDetailedResponses", 
        "click", 
        function(evt) { aPresenter.printResponsesClicked (true);});
};

var etk = window.etk || { };
etk.UserResponseManager = { };

etk.UserResponseManager = function() {
    this.userResponses = [];
    this.defaultResponses = [];  // record the default responses as 
};

etk.UserResponseManager.prototype.toString = function(){
    return "UserResponseManager";
};

etk.UserResponseManager.prototype.isQuestion = function() {
	return false;
};

etk.UserResponseManager.prototype.isUserResponseManager = function() {
	return true;
};

etk.UserResponseManager.prototype.getUserResponses = function(){
    var userResponses = [];
    for (var i = 0; i < this.userResponses.length ; i++) {
        if(this.userResponses[i].isUserResponse()) {
            userResponses = userResponses.concat(this.userResponses[i]);    
        }
    }
    return userResponses;

};

etk.UserResponseManager.prototype.allResults = function(){
    var allResults = [];
    var allResponses = this.userResponses.concat(this.defaultResponses); 
    for (var i = 0; i < allResponses.length ; i++) {
        allResults = allResults.concat(allResponses[i].results());    
    }
    return allResults;
};

etk.UserResponseManager.prototype.addUserResponse = function(aUserResponse){
    this.userResponses.push(aUserResponse);
};

etk.UserResponseManager.prototype.addDefaultUserResponse = function(aUserResponse){
    this.defaultResponses.push(aUserResponse);
};


etk.UserResponseManager.prototype.lastResponse = function(){
   return this.userResponses[this.userResponses.length - 1].response;
};

etk.UserResponseManager.prototype.allResponses = function(){
    var responses = [];
    for (var i = 0; i < this.userResponses.length ; i++) {
        responses.push(this.userResponses[i].response);
    }
    return responses;
};

etk.UserResponseManager.prototype.writeCookie = function(){
    var responses = this.allResponses();
    etk.Cookie.setCookie("etkResponses", responses.toJSONString(), 30);
};

etk.UserResponseManager.prototype.rewindCookie = function(){
    var responses = this.allResponses();
    if (responses.length == 1){
        etk.Cookie.deleteCookie("etkResponses");
    }else {
        responses.pop();
        responses.pop();
        etk.Cookie.deleteCookie("etkResponses");
        etk.Cookie.setCookie("etkResponses", responses.toJSONString(), 30);
    }
};

etk.UserResponseManager.prototype.getBusinessTypeResponseName = function(){
    var allUserResponses = this.userResponses;
    for (var i = 0; i < allUserResponses.length ; i++){
        if (allUserResponses[i].isUserResponse() && allUserResponses[i].question.isBusinessTypeQuestion){
            return allUserResponses[i].response;      
        }
    }
    return null;
};

/*  Required to implement the Question protocol for getResultsFor
*/
etk.UserResponseManager.prototype.getResultsFor = function(inLabel){
    return [];
};



var etk = window.etk || { };
etk.Result = { };

etk.Result = function (inId, inUrl, inText, inDescription){
    this.url = inUrl; //href
    this.linkText = inText; //anchor text
    this.description = inDescription;  // one or two line summary
};

etk.Result.prototype.toHTML = function() {
    var linkTextHtml = '<a href="' + this.url + '">' + this.linkText + '</a>';
    if(this.url === "#") 
        {linkTextHtml = '<b>' + this.title + '</b>';}
    return '<li>' + linkTextHtml + ' ' + this.description + '</li>';
};

etk.Result.prototype.toDetailedHTML = function() {
    var linkTextHtml = '<p class="title">' + this.linkText + '</p>\n';
    if(this.description.length > 0) {
        linkTextHtml += '<p>' + this.description + '</p>\n';
    }
    linkTextHtml += '<p>' + this.url + '</p>\n';
    return linkTextHtml;
};

etk.Result.prototype.toString = function (){
    return "Result, title: " + this.linkText;
};


var etk = window.etk || { };
etk.ResultList = { };


etk.ResultList = function( inQuestionGroup ) {
	this.results = [ ];
    this.questionTree = null;
    this.userResponse = null;
    this.questionGroup = inQuestionGroup;    
};

// When asked the ResultList should be able to build a set of results from the QuestionTree.  
// Will need to have access to the QuestionTree object to enable results to be accummulated.


etk.ResultList.prototype.buildResults = function(){
    this.results = [];
    var self = this;
    var loopBody = function(each){
        var response = each.userResponse;
        if (each.isQuestion ()) {
            self.addResults(each.getResultsFor(response));
        }    
    };
    this.questionTree.forEach(loopBody);
};

etk.ResultList.prototype.toHTML = function() {
    this.buildResults();
    var html = '<div id="etkResponseList">';
    html += "<p>You must comply with the following regulations to run your business</p>";
    html += '<ul>';
    for(var index = 0; index < this.results.length; index++) {
        html += this.results[index].toHTML();
    }
    html += "</ul></div>";
    html += '<p><a href="#" onclick="presenter.showQuestionAnswerHistory()">Click here</a> to get a summary of your answers</p>';
    return html;    
};

etk.ResultList.prototype.getFollowOnQuestions = function ( ) {
	return [];
};

etk.ResultList.prototype.isQuestion = function(){
    return false;
};

etk.ResultList.prototype.isABusinessTypeQuestion = function(){
    return false;
};

etk.ResultList.prototype.addResults = function(inResults){
    for (var index = 0; index < inResults.length; index++){
        this.results.push(inResults[index]);
    }
};

etk.ResultList.prototype.toString = function(){
    return "ResultList with " + this.results.length + " results";
};



var etk = window.etk || { };
etk.SybhManager = { };

etk.SybhManager = function() {
    this.categories = [];
    this.glossary = {};
    this.stream = {}; 
    this.responseManager = {};
    this.hasResultListBeenDisplayed = false;
    // lastIndex is a cached value.
    this.lastIndex = 0;
};

etk.SybhManager.prototype.init = function() {
    this.responseManager = new etk.UserResponseManager();
    this.hasResultListBeenDisplayed = false;
    this.stream = new etk.SybhStream(this);
};

etk.SybhManager.prototype.firstQuestion = function() {
    this.responseManager.writeCookie();
    return this.stream.next();
};

etk.SybhManager.prototype.nextQuestion = function() {
    // Need to accommodate for the first home based set of questions 
    // - this is a hard-coded special case.     
    if (this.stream.atStart() && this.responseManager.lastResponse() == 'No') {
        this.stream.skipToCategoryEnd();
    }

    this.responseManager.writeCookie();

    if(this.isResultPageRequired()) {
        this.hasResultListBeenDisplayed = true;
        return this.responseManager;
    }
    
    this.hasResultListBeenDisplayed = false;
    this.dropDefaultQuestions();
    return this.stream.next();
};

etk.SybhManager.prototype.atEnd = function() {
    if(this.isResultPageRequired()) {
        return false;
    }
    return this.stream.atEnd();
};

etk.SybhManager.prototype.isResultPageRequired = function() {
    if (this.stream.atEnd()){
        return true;        
    }
    return this.stream.atLastQuestionForCurrentCategory() && 
           this.currentCategory().showResultPage && 
           this.responseManager.allResults().length > 0 &&
           !this.hasResultListBeenDisplayed ;  
};

etk.SybhManager.prototype.currentCategory = function() {
    return this.stream.currentCategory();
};

etk.SybhManager.prototype.questionCount = function() {
    var questionCount = 0;
    for(var i=0; i < this.categories.length; i++) {
        questionCount += this.categories[i].questions.length;
    }
    return questionCount;
};

etk.SybhManager.prototype.toString = function(){
    return "SybhManager";
};

etk.SybhManager.prototype.progressPercentage = function(inQuestion){
//    var current = this.stream.current();
//    var current = this.currentQuestion;
    var allQuestions = this.allQuestions();
    var index = allQuestions.lastIndexOf(inQuestion);
    
    if (index == -1)
        index = this.lastIndex;
    else
        this.lastIndex = index;
    
    return Math.round(((index + 1)/allQuestions.length) * 100);
};

etk.SybhManager.prototype.allQuestions = function(){
    var results = [];
    for(var i=0; i < this.categories.length; i++) {
        var each = this.categories[i];
        results = results.concat(each.questions);
    }
    return results;
};

etk.SybhManager.prototype.dropDefaultQuestions = function(){
    if (this.stream.current().isBusinessTypeQuestion){
        var selectedBusinessTypeName = this.responseManager.getBusinessTypeResponseName();
        var defaultResponses = this.getDefaultResponses(selectedBusinessTypeName);
        this.processDefaultResults(defaultResponses);
    }
};

etk.SybhManager.prototype.getDefaultResponses = function(aName){
    var defaultResponses = [];
    for(var i=0; i < this.defaults.length; i++) {
        if (this.defaults[i].businessType == aName) {
            defaultResponses.push(this.defaults[i]);
        }
    }
    return defaultResponses;    
};


etk.SybhManager.prototype.processDefaultResults = function(defaultResponses){
    // collect default responses and drop questions from categories.

    for(var i=0; i < defaultResponses.length; i++) {
        var userResponse = new etk.UserResponse();
        var question = this.getQuestionForId(defaultResponses[i].id);
        userResponse.question = question;
        userResponse.response = defaultResponses[i].response;
        this.responseManager.addDefaultUserResponse(userResponse);
        // drop question
        this.dropQuestion(question);
    }
};

etk.SybhManager.prototype.dropQuestion = function(inQuestion){
    for(var i=0; i < this.categories.length; i++) {
        this.categories[i].dropQuestion(inQuestion);
    }
};

etk.SybhManager.prototype.getQuestionForId = function(inId){
    var allQuestions = this.allQuestions();
    for(var i=0; i < allQuestions.length; i++) {
        if(allQuestions[i].id == inId) {
            return allQuestions[i];
        }
    }
    return null;
};



var etk = window.etk || { };
etk.SybhStream = { };

etk.SybhStream = function(inSybhManager){
    this.source = inSybhManager;
    this.categoryStream = new etk.ReadStream(inSybhManager.categories);
    this.questionStream = null;
};

etk.SybhStream.prototype.next = function(){

    if ((this.questionStream === null) || this.questionStream.atEnd()){
        this.questionStream = new etk.ReadStream(this.categoryStream.next().questions);

    }
    // The questionStream may have no questions -- a category without questions.
    while (this.questionStream.atEnd() && !this.categoryStream.atEnd()) {
        this.questionStream = new etk.ReadStream(this.categoryStream.next().questions);
    } 
    return this.questionStream.next();
};

etk.SybhStream.prototype.back = function(){
    if (this.questionStream.atStart()){      
        this.questionStream = new etk.ReadStream(this.categoryStream.back().questions);
        this.questionStream.skipToEnd();
        return this.questionStream.current();
    }
    return this.questionStream.back();
};

etk.SybhStream.prototype.currentCategory = function() {
    return this.categoryStream.current();
};

etk.SybhStream.prototype.current = function() {
    return this.questionStream.current();
};

etk.SybhStream.prototype.atLastQuestionForCurrentCategory = function() {
    return this.questionStream !== null && this.questionStream.atEnd();
};

etk.SybhStream.prototype.atEnd = function(){
    if (this.atStart()){return false;}
    var allQuestions = this.source.allQuestions();
    return allQuestions.lastIndexOf(this.current()) == allQuestions.length - 1;
};  

etk.SybhStream.prototype.atStart = function(){
    return this.categoryStream.atStart() && (!this.questionStream === null || this.questionStream.atStart());
};  
etk.SybhStream.prototype.toString = function(){
    return "SybhStream";
};

etk.SybhStream.prototype.skipToCategoryEnd = function(){
    this.questionStream.skipToEnd();
};




var etk = window.etk || { };
etk.UserResponse = { };

etk.UserResponse = function(){
    this.question = {};
    this.response = null; //String eg Yes / No
};

etk.UserResponse.prototype.toString = function(){
    return "UserResponse";
};

etk.UserResponse.prototype.results = function(){
    return this.question.getResultsFor(this.response);
};

etk.UserResponse.prototype.isUserResponse = function(){
    return true;
};

etk.UserResponse.prototype.toHTML = function(){
    var html = "<tr>";
    html += "<td>" + this.question.text + "</td>";
    html += "<td>" + this.response + "</td>";
    html += "</tr>";
    return html;
};


var etk = window.etk || { };
etk.UserResponsePresenter = { };

etk.UserResponsePresenter = function(inContext) {
    this.init(inContext);
};

etk.UserResponsePresenter.prototype = new etk.Presenter();
etk.UserResponsePresenter.parent = etk.Presenter.prototype;

etk.UserResponsePresenter.prototype.toString = function(){
    return "UserResponsePresenter";
};

etk.UserResponsePresenter.prototype.show = function(userResponses, userResults, properties) {
    //etkLibPath should be defined when the code is called.
    var html  = '<html>\n';
    html += '<head>\n<title>Summary page</title>\n';
    html += '<link rel="stylesheet" media="screen,print" href="' + etkLibPath + 'etkPrintStyles.css" type="text/css"/>\n</head>\n';
    html += '<body>\n';
    html += '<img src="' + etkLibPath + 'sybh_logo.jpg" alt="Start your business here logo" width="400px" height="96px">\n';
    html += '<div id="summary">\n';
    html += '<h1 style="width: 400px">Answer summary</h1>\n';
    html += '<p>Print and bring this summary when you visit council or your business advisor.</p>'


    html += '<table>\n';
    html += '<tr>\n<td><b>Question</b></td>\n<td><b>You said</b></td>\n</tr>\n';
    
    for(var i=0; i < userResponses.length; i++) {
        html += userResponses[i].toHTML() + "\n";
    }
    
    html += '</table>\n</div>\n';
    
    if(userResults != null) {
        html += '<div id="results">';
        html += '<h1>Links that you require</h1>';
        for(var j=0; j< userResults.length; j++) {
            html += userResults[j].toDetailedHTML() + '\n';
        }
        html += '</div>';
    }
    if (properties){
        html += '<div id="properties">\n';
        html += '<p>This summary was produced from information provided by <b>' + properties.council + '</b>';
        html += ' and was last modified on ' + properties.dateModified.toLocaleDateString() +' </p>\n';
        html += '<table>';
        html += '<tr><td class="col-1">Council address</td><td>' + properties.councilAddress +'</td></tr>\n';
        html += '<tr><td class="col-1">Council url</td><td>' + properties.councilUrl +'</td></tr>\n';
        html += '<tr><td class="col-1">Council email</td><td>'+ properties.emailContact +'</td></tr>\n'; 
        html += '</table>'; 
        html += '</div>';
    }
    html += '<div id="footer">\n';
    html += '<p>DISCLAIMER</p>\n';
	html += '<p>While every effort will be made to ensure that the information provided is accurate and up to date, Council makes no warranty, representation or undertaking whether expressed or implied, nor does it assume any legal liability, whether direct or indirect, or responsibility for the accuracy, completeness, or usefulness of any information.</p>\n';
    html += '<p>Copyright &copy; 2007, Start your business here</p>\n';
    html += '<p>Start your business here was produced by REROC and Eternity Technologies</p>\n';
    html += '</div>';
    html += '</body>\n</html>\n';

    var summaryWindow = window.open('', 'summaryWindow');
    summaryWindow.document.open();
    summaryWindow.document.write(html);
    summaryWindow.document.close();    
};

var etk = window.etk || { };
etk.NullUserResponse = { };

etk.NullUserResponse = function(){
    this.response = null; 
};

etk.NullUserResponse.prototype.toString = function(){
    return "NullUserResponse";
};

etk.NullUserResponse.prototype.results = function(){
    return [];
};

etk.NullUserResponse.prototype.isUserResponse = function(){
    return false;
};

etk.NullUserResponse.prototype.toHTML = function(){
    
};


var etk = window.etk || { };
etk.DefaultResponse = { };

etk.DefaultResponse = function() {
    this.businessType = "";
    this.response = "";
    this.id = -1;
};

etk.DefaultResponse.prototype.toString = function(){
    return "DefaultResponse";
};


var etk = window.etk || { };
etk.Properties = { };

etk.Properties = function() {
    this.council = "";
    this.councilAddress = "";
    this.councilUrl = "";
    this.emailContact = "";
    this.dateModified = null;
}

etk.Properties.prototype.toString = function(){
    return "Properties";
}



/* Function to open new window to display disclaimer */
showDisclaimerWindow = function () {
	window.open(  etkLibPath +'disclaimer.html', "", "scrollbars=yes,height=500,width=500");
};


/*  Initial calls to load the page.
*/
var presenter;

function sybhRun(){
    var builder = new etk.QuestionTreeBuilder();

    builder.buildFromJson(jsonString);
    builder.jsonRoot.init();

    presenter = new etk.PagePresenter(builder.jsonRoot);
    presenter.refreshPageOnReturn();
    return presenter;
}

function etkStart() {
    presenter.show();
}

/* End of file */