/**** JS Version: 1.4.21 ****/
var curcontentindex=0;
var rotateTimer;
var messages=new Array();
var totalMessages;
var oper=1;
var loopCount=0;
function getElementByClass(classname)
{
	var inc=0;
	
	var alltags=document.all? document.all : document.getElementsByTagName("*");
	for (i=0; i<alltags.length; i++){
		if (alltags[i].className=="carouselcontent")
		{
			messages[inc++]=alltags[i];
		}
	}
	totalMessages = messages.length-1;

}
function rotatecontent()
{
	if(loopCount == totalMessages * 333)
	{
		pausecontent();
	}
	prevcontentindex = curcontentindex;
	curcontentindex=(curcontentindex<messages.length && curcontentindex>=0)? curcontentindex+oper : 0;
	if (curcontentindex == "-1") {
		prevcontentindex = 0;
		curcontentindex = totalMessages;
	} else if (curcontentindex == totalMessages + 1) {
		prevcontentindex = totalMessages;
		curcontentindex = 0;
	}

	messages[prevcontentindex].style.display="none"; //hide previous message
	messages[curcontentindex].style.display="block"; //show current message 
	
	//THIS IS WHERE WE NEED TO SET THE STYLE OF THE TABS
	
      var previousDiv = "carouseltab-" + (prevcontentindex+1);
      document.getElementById('carousel-current').id = previousDiv;
	
      var currentDiv = "carouseltab-" + (curcontentindex+1);
      document.getElementById(currentDiv).id = "carousel-current";

	loopCount++;
	
}
function nextcontent()
{
	pausecontent();
	oper = 1;
	rotatecontent();
}
function previouscontent()
{
	pausecontent();
	oper = -1;
	rotatecontent();
}
function pausecontent()
{
	clearInterval(rotateTimer);
}
function thisShowContent(index)
{      
        for (i=0; i<messages.length; i++)
	{
                if(i == index)
		{
			messages[i].style.display="block";
			//THIS IS WHERE WE NEED TO SET THE STYLE OF THE TAB THAT IS SELECTED
			//tabs[i]
                        // Change the carousel-current div to the carousel-X
                        var previousDiv = "carouseltab-" + (curcontentindex+1);
                        curcontentindex=i; // set this index to be the new current index
                        document.getElementById('carousel-current').id = previousDiv;
                        
                        // Change the clicked on tab to "carousel-current"
                        var divId = "carouseltab-" + (i+1);
                        document.getElementById(divId).id = "carousel-current";
		}	
		else
		{
			messages[i].style.display="none";
		}
	}
	pausecontent();
}
function initCarousel()
{
	if (document.getElementById("carousel-current")) {
		carouselRotation = carouselRotation * 1000;
		getElementByClass();
            rotateTimer = setInterval("rotatecontent()", carouselRotation);
	}
}

var PluckSiteControl = "1";


/*
Copyright (c) 2005 JSON.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The Software shall be used for Good, not Evil.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

/*
    The global object JSON contains two methods.

    JSON.stringify(value) takes a JavaScript value and produces a JSON text.
    The value must not be cyclical.

    JSON.parse(text) takes a JSON text and produces a JavaScript value. It will
    return false if there is an error.
*/
var JSON = function () {
    var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        s = {
            'boolean': function (x) {
                return String(x);
            },
            number: function (x) {
                return isFinite(x) ? String(x) : '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: function (x) {
                if (x) {
                    var a = [], b, f, i, l, v;
                    if (x instanceof Array) {
                        a[0] = '[';
                        l = x.length;
                        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] = ']';
                    } else if (x instanceof Object) {
                        a[0] = '{';
                        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] = '}';
                    } else {
                        return;
                    }
                    return a.join('');
                }
                return 'null';
            }
        };
    return {
        copyright: '(c)2005 JSON.org',
        license: 'http://www.crockford.com/JSON/license.html',
/*
    Stringify a JavaScript value, producing a JSON text.
*/
        stringify: function (v) {
            var f = s[typeof v];
            if (f) {
                v = f(v);
                if (typeof v == 'string') {
                    return v;
                }
            }
            return null;
        },
/*
    Parse a JSON text, producing a JavaScript value.
    It returns false if there is a syntax error.
*/
        eval: function (text) {
            try {
                return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
                        text.replace(/"(\\.|[^"\\])*"/g, ''))) &&
                    eval('(' + text + ')');
            } catch (e) {
                return false;
            }
        },

        parse: function (text) {
            var at = 0;
            var ch = ' ';

            function error(m) {
                throw {
                    name: 'JSONError',
                    message: m,
                    at: at - 1,
                    text: text
                };
            }

            function next() {
                ch = text.charAt(at);
                at += 1;
                return ch;
            }

            function white() {
                while (ch) {
                    if (ch <= ' ') {
                        next();
                    } else if (ch == '/') {
                        switch (next()) {
                            case '/':
                                while (next() && ch != '\n' && ch != '\r') {}
                                break;
                            case '*':
                                next();
                                for (;;) {
                                    if (ch) {
                                        if (ch == '*') {
                                            if (next() == '/') {
                                                next();
                                                break;
                                            }
                                        } else {
                                            next();
                                        }
                                    } else {
                                        error("Unterminated comment");
                                    }
                                }
                                break;
                            default:
                                error("Syntax error");
                        }
                    } else {
                        break;
                    }
                }
            }

            function string() {
                var i, s = '', t, u;

                if (ch == '"') {
    outer:          while (next()) {
                        if (ch == '"') {
                            next();
                            return s;
                        } else if (ch == '\\') {
                            switch (next()) {
                            case 'b':
                                s += '\b';
                                break;
                            case 'f':
                                s += '\f';
                                break;
                            case 'n':
                                s += '\n';
                                break;
                            case 'r':
                                s += '\r';
                                break;
                            case 't':
                                s += '\t';
                                break;
                            case 'u':
                                u = 0;
                                for (i = 0; i < 4; i += 1) {
                                    t = parseInt(next(), 16);
                                    if (!isFinite(t)) {
                                        break outer;
                                    }
                                    u = u * 16 + t;
                                }
                                s += String.fromCharCode(u);
                                break;
                            default:
                                s += ch;
                            }
                        } else {
                            s += ch;
                        }
                    }
                }
                error("Bad string");
            }

            function array() {
                var a = [];

                if (ch == '[') {
                    next();
                    white();
                    if (ch == ']') {
                        next();
                        return a;
                    }
                    while (ch) {
                        a.push(value());
                        white();
                        if (ch == ']') {
                            next();
                            return a;
                        } else if (ch != ',') {
                            break;
                        }
                        next();
                        white();
                    }
                }
                error("Bad array");
            }

            function object() {
                var k, o = {};

                if (ch == '{') {
                    next();
                    white();
                    if (ch == '}') {
                        next();
                        return o;
                    }
                    while (ch) {
                        k = string();
                        white();
                        if (ch != ':') {
                            break;
                        }
                        next();
                        o[k] = value();
                        white();
                        if (ch == '}') {
                            next();
                            return o;
                        } else if (ch != ',') {
                            break;
                        }
                        next();
                        white();
                    }
                }
                error("Bad object");
            }

            function number() {
                var n = '', v;
                if (ch == '-') {
                    n = '-';
                    next();
                }
                while (ch >= '0' && ch <= '9') {
                    n += ch;
                    next();
                }
                if (ch == '.') {
                    n += '.';
                    while (next() && ch >= '0' && ch <= '9') {
                        n += ch;
                    }
                }
                if (ch == 'e' || ch == 'E') {
                    n += 'e';
                    next();
                    if (ch == '-' || ch == '+') {
                        n += ch;
                        next();
                    }
                    while (ch >= '0' && ch <= '9') {
                        n += ch;
                        next();
                    }
                }
                v = +n;
                if (!isFinite(v)) {
                    ////error("Bad number");
                } else {
                    return v;
                }
            }

            function word() {
                switch (ch) {
                    case 't':
                        if (next() == 'r' && next() == 'u' && next() == 'e') {
                            next();
                            return true;
                        }
                        break;
                    case 'f':
                        if (next() == 'a' && next() == 'l' && next() == 's' &&
                                next() == 'e') {
                            next();
                            return false;
                        }
                        break;
                    case 'n':
                        if (next() == 'u' && next() == 'l' && next() == 'l') {
                            next();
                            return null;
                        }
                        break;
                }
                error("Syntax error");
            }

            function value() {
                white();
                switch (ch) {
                    case '{':
                        return object();
                    case '[':
                        return array();
                    case '"':
                        return string();
                    case '-':
                        return number();
                    default:
                        return ch >= '0' && ch <= '9' ? number() : word();
                }
            }

            return value();
        }
    };
}();

/*
Copyright (c) 2008, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.6.0
*/
if(typeof YAHOO=="undefined"||!YAHOO){var YAHOO={};}YAHOO.namespace=function(){var A=arguments,E=null,C,B,D;for(C=0;C<A.length;C=C+1){D=A[C].split(".");E=YAHOO;for(B=(D[0]=="YAHOO")?1:0;B<D.length;B=B+1){E[D[B]]=E[D[B]]||{};E=E[D[B]];}}return E;};YAHOO.log=function(D,A,C){var B=YAHOO.widget.Logger;if(B&&B.log){return B.log(D,A,C);}else{return false;}};YAHOO.register=function(A,E,D){var I=YAHOO.env.modules;if(!I[A]){I[A]={versions:[],builds:[]};}var B=I[A],H=D.version,G=D.build,F=YAHOO.env.listeners;B.name=A;B.version=H;B.build=G;B.versions.push(H);B.builds.push(G);B.mainClass=E;for(var C=0;C<F.length;C=C+1){F[C](B);}if(E){E.VERSION=H;E.BUILD=G;}else{YAHOO.log("mainClass is undefined for module "+A,"warn");}};YAHOO.env=YAHOO.env||{modules:[],listeners:[]};YAHOO.env.getVersion=function(A){return YAHOO.env.modules[A]||null;};YAHOO.env.ua=function(){var C={ie:0,opera:0,gecko:0,webkit:0,mobile:null,air:0};var B=navigator.userAgent,A;if((/KHTML/).test(B)){C.webkit=1;}A=B.match(/AppleWebKit\/([^\s]*)/);if(A&&A[1]){C.webkit=parseFloat(A[1]);if(/ Mobile\//.test(B)){C.mobile="Apple";}else{A=B.match(/NokiaN[^\/]*/);if(A){C.mobile=A[0];}}A=B.match(/AdobeAIR\/([^\s]*)/);if(A){C.air=A[0];}}if(!C.webkit){A=B.match(/Opera[\s\/]([^\s]*)/);if(A&&A[1]){C.opera=parseFloat(A[1]);A=B.match(/Opera Mini[^;]*/);if(A){C.mobile=A[0];}}else{A=B.match(/MSIE\s([^;]*)/);if(A&&A[1]){C.ie=parseFloat(A[1]);}else{A=B.match(/Gecko\/([^\s]*)/);if(A){C.gecko=1;A=B.match(/rv:([^\s\)]*)/);if(A&&A[1]){C.gecko=parseFloat(A[1]);}}}}}return C;}();(function(){YAHOO.namespace("util","widget","example");if("undefined"!==typeof YAHOO_config){var B=YAHOO_config.listener,A=YAHOO.env.listeners,D=true,C;if(B){for(C=0;C<A.length;C=C+1){if(A[C]==B){D=false;break;}}if(D){A.push(B);}}}})();YAHOO.lang=YAHOO.lang||{};(function(){var A=YAHOO.lang,C=["toString","valueOf"],B={isArray:function(D){if(D){return A.isNumber(D.length)&&A.isFunction(D.splice);}return false;},isBoolean:function(D){return typeof D==="boolean";},isFunction:function(D){return typeof D==="function";},isNull:function(D){return D===null;},isNumber:function(D){return typeof D==="number"&&isFinite(D);},isObject:function(D){return(D&&(typeof D==="object"||A.isFunction(D)))||false;},isString:function(D){return typeof D==="string";},isUndefined:function(D){return typeof D==="undefined";},_IEEnumFix:(YAHOO.env.ua.ie)?function(F,E){for(var D=0;D<C.length;D=D+1){var H=C[D],G=E[H];if(A.isFunction(G)&&G!=Object.prototype[H]){F[H]=G;}}}:function(){},extend:function(H,I,G){if(!I||!H){throw new Error("extend failed, please check that "+"all dependencies are included.");}var E=function(){};E.prototype=I.prototype;H.prototype=new E();H.prototype.constructor=H;H.superclass=I.prototype;if(I.prototype.constructor==Object.prototype.constructor){I.prototype.constructor=I;}if(G){for(var D in G){if(A.hasOwnProperty(G,D)){H.prototype[D]=G[D];}}A._IEEnumFix(H.prototype,G);}},augmentObject:function(H,G){if(!G||!H){throw new Error("Absorb failed, verify dependencies.");}var D=arguments,F,I,E=D[2];if(E&&E!==true){for(F=2;F<D.length;F=F+1){H[D[F]]=G[D[F]];}}else{for(I in G){if(E||!(I in H)){H[I]=G[I];}}A._IEEnumFix(H,G);}},augmentProto:function(G,F){if(!F||!G){throw new Error("Augment failed, verify dependencies.");}var D=[G.prototype,F.prototype];for(var E=2;E<arguments.length;E=E+1){D.push(arguments[E]);}A.augmentObject.apply(this,D);},dump:function(D,I){var F,H,K=[],L="{...}",E="f(){...}",J=", ",G=" => ";if(!A.isObject(D)){return D+"";}else{if(D instanceof Date||("nodeType" in D&&"tagName" in D)){return D;}else{if(A.isFunction(D)){return E;}}}I=(A.isNumber(I))?I:3;if(A.isArray(D)){K.push("[");for(F=0,H=D.length;F<H;F=F+1){if(A.isObject(D[F])){K.push((I>0)?A.dump(D[F],I-1):L);}else{K.push(D[F]);}K.push(J);}if(K.length>1){K.pop();}K.push("]");}else{K.push("{");for(F in D){if(A.hasOwnProperty(D,F)){K.push(F+G);if(A.isObject(D[F])){K.push((I>0)?A.dump(D[F],I-1):L);}else{K.push(D[F]);}K.push(J);}}if(K.length>1){K.pop();}K.push("}");}return K.join("");},substitute:function(S,E,L){var I,H,G,O,P,R,N=[],F,J="dump",M=" ",D="{",Q="}";for(;;){I=S.lastIndexOf(D);if(I<0){break;}H=S.indexOf(Q,I);if(I+1>=H){break;}F=S.substring(I+1,H);O=F;R=null;G=O.indexOf(M);if(G>-1){R=O.substring(G+1);O=O.substring(0,G);}P=E[O];if(L){P=L(O,P,R);}if(A.isObject(P)){if(A.isArray(P)){P=A.dump(P,parseInt(R,10));}else{R=R||"";var K=R.indexOf(J);if(K>-1){R=R.substring(4);}if(P.toString===Object.prototype.toString||K>-1){P=A.dump(P,parseInt(R,10));}else{P=P.toString();}}}else{if(!A.isString(P)&&!A.isNumber(P)){P="~-"+N.length+"-~";N[N.length]=F;}}S=S.substring(0,I)+P+S.substring(H+1);}for(I=N.length-1;I>=0;I=I-1){S=S.replace(new RegExp("~-"+I+"-~"),"{"+N[I]+"}","g");}return S;},trim:function(D){try{return D.replace(/^\s+|\s+$/g,"");}catch(E){return D;}},merge:function(){var G={},E=arguments;for(var F=0,D=E.length;F<D;F=F+1){A.augmentObject(G,E[F],true);}return G;},later:function(K,E,L,G,H){K=K||0;E=E||{};var F=L,J=G,I,D;if(A.isString(L)){F=E[L];}if(!F){throw new TypeError("method undefined");}if(!A.isArray(J)){J=[G];}I=function(){F.apply(E,J);};D=(H)?setInterval(I,K):setTimeout(I,K);return{interval:H,cancel:function(){if(this.interval){clearInterval(D);}else{clearTimeout(D);}}};},isValue:function(D){return(A.isObject(D)||A.isString(D)||A.isNumber(D)||A.isBoolean(D));}};A.hasOwnProperty=(Object.prototype.hasOwnProperty)?function(D,E){return D&&D.hasOwnProperty(E);}:function(D,E){return !A.isUndefined(D[E])&&D.constructor.prototype[E]!==D[E];};B.augmentObject(A,B,true);YAHOO.util.Lang=A;A.augment=A.augmentProto;YAHOO.augment=A.augmentProto;YAHOO.extend=A.extend;})();YAHOO.register("yahoo",YAHOO,{version:"2.6.0",build:"1321"});

/*
Copyright (c) 2008, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.net/yui/license.txt
version: 2.6.0
*/
YAHOO.lang.JSON=(function(){var l=YAHOO.lang,_UNICODE_EXCEPTIONS=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,_ESCAPES=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,_VALUES=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,_BRACKETS=/(?:^|:|,)(?:\s*\[)+/g,_INVALID=/^[\],:{}\s]*$/,_SPECIAL_CHARS=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,_CHARS={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};function _revive(data,reviver){var walk=function(o,key){var k,v,value=o[key];if(value&&typeof value==="object"){for(k in value){if(l.hasOwnProperty(value,k)){v=walk(value,k);if(v===undefined){delete value[k];}else{value[k]=v;}}}}return reviver.call(o,key,value);};return typeof reviver==="function"?walk({"":data},""):data;}function _char(c){if(!_CHARS[c]){_CHARS[c]="\\u"+("0000"+(+(c.charCodeAt(0))).toString(16)).slice(-4);}return _CHARS[c];}function _prepare(s){return s.replace(_UNICODE_EXCEPTIONS,_char);}function _isValid(str){return l.isString(str)&&_INVALID.test(str.replace(_ESCAPES,"@").replace(_VALUES,"]").replace(_BRACKETS,""));}function _string(s){return'"'+s.replace(_SPECIAL_CHARS,_char)+'"';}function _stringify(h,key,d,w,pstack){var o=typeof w==="function"?w.call(h,key,h[key]):h[key],i,len,j,k,v,isArray,a;if(o instanceof Date){o=l.JSON.dateToString(o);}else{if(o instanceof String||o instanceof Boolean||o instanceof Number){o=o.valueOf();}}switch(typeof o){case"string":return _string(o);case"number":return isFinite(o)?String(o):"null";case"boolean":return String(o);case"object":if(o===null){return"null";}for(i=pstack.length-1;i>=0;--i){if(pstack[i]===o){return"null";}}pstack[pstack.length]=o;a=[];isArray=l.isArray(o);if(d>0){if(isArray){for(i=o.length-1;i>=0;--i){a[i]=_stringify(o,i,d-1,w,pstack)||"null";}}else{j=0;if(l.isArray(w)){for(i=0,len=w.length;i<len;++i){k=w[i];v=_stringify(o,k,d-1,w,pstack);if(v){a[j++]=_string(k)+":"+v;}}}else{for(k in o){if(typeof k==="string"&&l.hasOwnProperty(o,k)){v=_stringify(o,k,d-1,w,pstack);if(v){a[j++]=_string(k)+":"+v;}}}}a.sort();}}pstack.pop();return isArray?"["+a.join(",")+"]":"{"+a.join(",")+"}";}return undefined;}return{isValid:function(s){return _isValid(_prepare(s));},parse:function(s,reviver){s=_prepare(s);if(_isValid(s)){return _revive(eval("("+s+")"),reviver);}throw new SyntaxError("parseJSON");},stringify:function(o,w,d){if(o!==undefined){if(l.isArray(w)){w=(function(a){var uniq=[],map={},v,i,j,len;for(i=0,j=0,len=a.length;i<len;++i){v=a[i];if(typeof v==="string"&&map[v]===undefined){uniq[(map[v]=j++)]=v;}}return uniq;})(w);}d=d>=0?d:1/0;return _stringify({"":o},"",d,w,[]);}return undefined;},dateToString:function(d){function _zeroPad(v){return v<10?"0"+v:v;}return d.getUTCFullYear()+"-"+_zeroPad(d.getUTCMonth()+1)+"-"+_zeroPad(d.getUTCDate())+"T"+_zeroPad(d.getUTCHours())+":"+_zeroPad(d.getUTCMinutes())+":"+_zeroPad(d.getUTCSeconds())+"Z";},stringToDate:function(str){if(/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/.test(str)){var d=new Date();d.setUTCFullYear(RegExp.$1,(RegExp.$2|0)-1,RegExp.$3);d.setUTCHours(RegExp.$4,RegExp.$5,RegExp.$6);return d;}return str;}};})();YAHOO.register("json",YAHOO.lang.JSON,{version:"2.6.0",build:"1321"});

/*  Prototype JavaScript framework, version 1.6.0
 *  (c) 2005-2007 Sam Stephenson
 *
 *  Prototype is freely distributable under the terms of an MIT-style license.
 *  For details, see the Prototype web site: http://www.prototypejs.org/
 *
 *--------------------------------------------------------------------------*/

var Prototype = {
  Version: '1.6.0',

  Browser: {
    IE:     !!(window.attachEvent && !window.opera),
    Opera:  !!window.opera,
    WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
    Gecko:  navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1,
    MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
  },

  BrowserFeatures: {
    XPath: !!document.evaluate,
    ElementExtensions: !!window.HTMLElement,
    SpecificElementExtensions:
      document.createElement('div').__proto__ &&
      document.createElement('div').__proto__ !==
        document.createElement('form').__proto__
  },

  ScriptFragment: '<script[^>]*>([\\S\\s]*?)<\/script>',
  JSONFilter: /^\/\*-secure-([\s\S]*)\*\/\s*$/,

  emptyFunction: function() { },
  K: function(x) { return x }
};

if (Prototype.Browser.MobileSafari)
  Prototype.BrowserFeatures.SpecificElementExtensions = false;

if (Prototype.Browser.WebKit)
  Prototype.BrowserFeatures.XPath = false;

/* Based on Alex Arnell's inheritance implementation. */
var Class = {
  create: function() {
    var parent = null, properties = $A(arguments);
    if (Object.isFunction(properties[0]))
      parent = properties.shift();

    function klass() {
      this.initialize.apply(this, arguments);
    }

    Object.extend(klass, Class.Methods);
    klass.superclass = parent;
    klass.subclasses = [];

    if (parent) {
      var subclass = function() { };
      subclass.prototype = parent.prototype;
      klass.prototype = new subclass;
      parent.subclasses.push(klass);
    }

    for (var i = 0; i < properties.length; i++)
      klass.addMethods(properties[i]);

    if (!klass.prototype.initialize)
      klass.prototype.initialize = Prototype.emptyFunction;

    klass.prototype.constructor = klass;

    return klass;
  }
};

Class.Methods = {
  addMethods: function(source) {
    var ancestor   = this.superclass && this.superclass.prototype;
    var properties = Object.keys(source);

    if (!Object.keys({ toString: true }).length)
      properties.push("toString", "valueOf");

    for (var i = 0, length = properties.length; i < length; i++) {
      var property = properties[i], value = source[property];
      if (ancestor && Object.isFunction(value) &&
          value.argumentNames().first() == "$super") {
        var method = value, value = Object.extend((function(m) {
          return function() { return ancestor[m].apply(this, arguments) };
        })(property).wrap(method), {
          valueOf:  function() { return method },
          toString: function() { return method.toString() }
        });
      }
      this.prototype[property] = value;
    }

    return this;
  }
};

var Abstract = { };

Object.extend = function(destination, source) {
  for (var property in source)
    destination[property] = source[property];
  return destination;
};

Object.extend(Object, {
  inspect: function(object) {
    try {
      if (object === undefined) return 'undefined';
      if (object === null) return 'null';
      return object.inspect ? object.inspect() : object.toString();
    } catch (e) {
      if (e instanceof RangeError) return '...';
      throw e;
    }
  },

  toJSON: function(object) {
    var type = typeof object;
    switch (type) {
      case 'undefined':
      case 'function':
      case 'unknown': return;
      case 'boolean': return object.toString();
    }

    if (object === null) return 'null';
    if (object.toJSON) return object.toJSON();
    if (Object.isElement(object)) return;

    var results = [];
    for (var property in object) {
      var value = Object.toJSON(object[property]);
      if (value !== undefined)
        results.push(property.toJSON() + ': ' + value);
    }

    return '{' + results.join(', ') + '}';
  },

  toQueryString: function(object) {
    return $H(object).toQueryString();
  },

  toHTML: function(object) {
    return object && object.toHTML ? object.toHTML() : String.interpret(object);
  },

  keys: function(object) {
    var keys = [];
    for (var property in object)
      keys.push(property);
    return keys;
  },

  values: function(object) {
    var values = [];
    for (var property in object)
      values.push(object[property]);
    return values;
  },

  clone: function(object) {
    return Object.extend({ }, object);
  },

  isElement: function(object) {
    return object && object.nodeType == 1;
  },

  isArray: function(object) {
    return object && object.constructor === Array;
  },

  isHash: function(object) {
    return object instanceof Hash;
  },

  isFunction: function(object) {
    return typeof object == "function";
  },

  isString: function(object) {
    return typeof object == "string";
  },

  isNumber: function(object) {
    return typeof object == "number";
  },

  isUndefined: function(object) {
    return typeof object == "undefined";
  }
});

Object.extend(Function.prototype, {
  argumentNames: function() {
    var names = this.toString().match(/^[\s\(]*function[^(]*\((.*?)\)/)[1].split(",").invoke("strip");
    return names.length == 1 && !names[0] ? [] : names;
  },

  bind: function() {
    if (arguments.length < 2 && arguments[0] === undefined) return this;
    var __method = this, args = $A(arguments), object = args.shift();
    return function() {
      return __method.apply(object, args.concat($A(arguments)));
    }
  },

  bindAsEventListener: function() {
    var __method = this, args = $A(arguments), object = args.shift();
    return function(event) {
      return __method.apply(object, [event || window.event].concat(args));
    }
  },

  curry: function() {
    if (!arguments.length) return this;
    var __method = this, args = $A(arguments);
    return function() {
      return __method.apply(this, args.concat($A(arguments)));
    }
  },

  delay: function() {
    var __method = this, args = $A(arguments), timeout = args.shift() * 1000;
    return window.setTimeout(function() {
      return __method.apply(__method, args);
    }, timeout);
  },

  wrap: function(wrapper) {
    var __method = this;
    return function() {
      return wrapper.apply(this, [__method.bind(this)].concat($A(arguments)));
    }
  },

  methodize: function() {
    if (this._methodized) return this._methodized;
    var __method = this;
    return this._methodized = function() {
      return __method.apply(null, [this].concat($A(arguments)));
    };
  }
});

Function.prototype.defer = Function.prototype.delay.curry(0.01);

Date.prototype.toJSON = function() {
  return '"' + this.getUTCFullYear() + '-' +
    (this.getUTCMonth() + 1).toPaddedString(2) + '-' +
    this.getUTCDate().toPaddedString(2) + 'T' +
    this.getUTCHours().toPaddedString(2) + ':' +
    this.getUTCMinutes().toPaddedString(2) + ':' +
    this.getUTCSeconds().toPaddedString(2) + 'Z"';
};

var Try = {
  these: function() {
    var returnValue;

    for (var i = 0, length = arguments.length; i < length; i++) {
      var lambda = arguments[i];
      try {
        returnValue = lambda();
        break;
      } catch (e) { }
    }

    return returnValue;
  }
};

RegExp.prototype.match = RegExp.prototype.test;

RegExp.escape = function(str) {
  return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
};

/*--------------------------------------------------------------------------*/

var PeriodicalExecuter = Class.create({
  initialize: function(callback, frequency) {
    this.callback = callback;
    this.frequency = frequency;
    this.currentlyExecuting = false;

    this.registerCallback();
  },

  registerCallback: function() {
    this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },

  execute: function() {
    this.callback(this);
  },

  stop: function() {
    if (!this.timer) return;
    clearInterval(this.timer);
    this.timer = null;
  },

  onTimerEvent: function() {
    if (!this.currentlyExecuting) {
      try {
        this.currentlyExecuting = true;
        this.execute();
      } finally {
        this.currentlyExecuting = false;
      }
    }
  }
});
Object.extend(String, {
  interpret: function(value) {
    return value == null ? '' : String(value);
  },
  specialChar: {
    '\b': '\\b',
    '\t': '\\t',
    '\n': '\\n',
    '\f': '\\f',
    '\r': '\\r',
    '\\': '\\\\'
  }
});

Object.extend(String.prototype, {
  gsub: function(pattern, replacement) {
    var result = '', source = this, match;
    replacement = arguments.callee.prepareReplacement(replacement);

    while (source.length > 0) {
      if (match = source.match(pattern)) {
        result += source.slice(0, match.index);
        result += String.interpret(replacement(match));
        source  = source.slice(match.index + match[0].length);
      } else {
        result += source, source = '';
      }
    }
    return result;
  },

  sub: function(pattern, replacement, count) {
    replacement = this.gsub.prepareReplacement(replacement);
    count = count === undefined ? 1 : count;

    return this.gsub(pattern, function(match) {
      if (--count < 0) return match[0];
      return replacement(match);
    });
  },

  scan: function(pattern, iterator) {
    this.gsub(pattern, iterator);
    return String(this);
  },

  truncate: function(length, truncation) {
    length = length || 30;
    truncation = truncation === undefined ? '...' : truncation;
    return this.length > length ?
      this.slice(0, length - truncation.length) + truncation : String(this);
  },

  strip: function() {
    return this.replace(/^\s+/, '').replace(/\s+$/, '');
  },

  stripTags: function() {
    return this.replace(/<\/?[^>]+>/gi, '');
  },

  stripScripts: function() {
    return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
  },

  extractScripts: function() {
    var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
    var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
    return (this.match(matchAll) || []).map(function(scriptTag) {
      return (scriptTag.match(matchOne) || ['', ''])[1];
    });
  },

  evalScripts: function() {
    return this.extractScripts().map(function(script) { return eval(script) });
  },

  escapeHTML: function() {
    var self = arguments.callee;
    self.text.data = this;
    return self.div.innerHTML;
  },

  unescapeHTML: function() {
    var div = new Element('div');
    div.innerHTML = this.stripTags();
    return div.childNodes[0] ? (div.childNodes.length > 1 ?
      $A(div.childNodes).inject('', function(memo, node) { return memo+node.nodeValue }) :
      div.childNodes[0].nodeValue) : '';
  },

  toQueryParams: function(separator) {
    var match = this.strip().match(/([^?#]*)(#.*)?$/);
    if (!match) return { };

    return match[1].split(separator || '&').inject({ }, function(hash, pair) {
      if ((pair = pair.split('='))[0]) {
        var key = decodeURIComponent(pair.shift());
        var value = pair.length > 1 ? pair.join('=') : pair[0];
        if (value != undefined) value = decodeURIComponent(value);

        if (key in hash) {
          if (!Object.isArray(hash[key])) hash[key] = [hash[key]];
          hash[key].push(value);
        }
        else hash[key] = value;
      }
      return hash;
    });
  },

  toArray: function() {
    return this.split('');
  },

  succ: function() {
    return this.slice(0, this.length - 1) +
      String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
  },

  times: function(count) {
    return count < 1 ? '' : new Array(count + 1).join(this);
  },

  camelize: function() {
    var parts = this.split('-'), len = parts.length;
    if (len == 1) return parts[0];

    var camelized = this.charAt(0) == '-'
      ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
      : parts[0];

    for (var i = 1; i < len; i++)
      camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);

    return camelized;
  },

  capitalize: function() {
    return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
  },

  underscore: function() {
    return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();
  },

  dasherize: function() {
    return this.gsub(/_/,'-');
  },

  inspect: function(useDoubleQuotes) {
    var escapedString = this.gsub(/[\x00-\x1f\\]/, function(match) {
      var character = String.specialChar[match[0]];
      return character ? character : '\\u00' + match[0].charCodeAt().toPaddedString(2, 16);
    });
    if (useDoubleQuotes) return '"' + escapedString.replace(/"/g, '\\"') + '"';
    return "'" + escapedString.replace(/'/g, '\\\'') + "'";
  },

  toJSON: function() {
    return this.inspect(true);
  },

  unfilterJSON: function(filter) {
    return this.sub(filter || Prototype.JSONFilter, '#{1}');
  },

  isJSON: function() {
    var str = this.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');
    return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
  },

  evalJSON: function(sanitize) {
    var json = this.unfilterJSON();
    try {
      if (!sanitize || json.isJSON()) return eval('(' + json + ')');
    } catch (e) { }
    throw new SyntaxError('Badly formed JSON string: ' + this.inspect());
  },

  include: function(pattern) {
    return this.indexOf(pattern) > -1;
  },

  startsWith: function(pattern) {
    return this.indexOf(pattern) === 0;
  },

  endsWith: function(pattern) {
    var d = this.length - pattern.length;
    return d >= 0 && this.lastIndexOf(pattern) === d;
  },

  empty: function() {
    return this == '';
  },

  blank: function() {
    return /^\s*$/.test(this);
  },

  interpolate: function(object, pattern) {
    return new Template(this, pattern).evaluate(object);
  }
});

if (Prototype.Browser.WebKit || Prototype.Browser.IE) Object.extend(String.prototype, {
  escapeHTML: function() {
    return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
  },
  unescapeHTML: function() {
    return this.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>');
  }
});

String.prototype.gsub.prepareReplacement = function(replacement) {
  if (Object.isFunction(replacement)) return replacement;
  var template = new Template(replacement);
  return function(match) { return template.evaluate(match) };
};

String.prototype.parseQuery = String.prototype.toQueryParams;

Object.extend(String.prototype.escapeHTML, {
  div:  document.createElement('div'),
  text: document.createTextNode('')
});

with (String.prototype.escapeHTML) div.appendChild(text);

var Template = Class.create({
  initialize: function(template, pattern) {
    this.template = template.toString();
    this.pattern = pattern || Template.Pattern;
  },

  evaluate: function(object) {
    if (Object.isFunction(object.toTemplateReplacements))
      object = object.toTemplateReplacements();

    return this.template.gsub(this.pattern, function(match) {
      if (object == null) return '';

      var before = match[1] || '';
      if (before == '\\') return match[2];

      var ctx = object, expr = match[3];
      var pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/, match = pattern.exec(expr);
      if (match == null) return before;

      while (match != null) {
        var comp = match[1].startsWith('[') ? match[2].gsub('\\\\]', ']') : match[1];
        ctx = ctx[comp];
        if (null == ctx || '' == match[3]) break;
        expr = expr.substring('[' == match[3] ? match[1].length : match[0].length);
        match = pattern.exec(expr);
      }

      return before + String.interpret(ctx);
    }.bind(this));
  }
});
Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;

var $break = { };

var Enumerable = {
  each: function(iterator, context) {
    var index = 0;
    iterator = iterator.bind(context);
    try {
      this._each(function(value) {
        iterator(value, index++);
      });
    } catch (e) {
      if (e != $break) throw e;
    }
    return this;
  },

  eachSlice: function(number, iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var index = -number, slices = [], array = this.toArray();
    while ((index += number) < array.length)
      slices.push(array.slice(index, index+number));
    return slices.collect(iterator, context);
  },

  all: function(iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var result = true;
    this.each(function(value, index) {
      result = result && !!iterator(value, index);
      if (!result) throw $break;
    });
    return result;
  },

  any: function(iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var result = false;
    this.each(function(value, index) {
      if (result = !!iterator(value, index))
        throw $break;
    });
    return result;
  },

  collect: function(iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var results = [];
    this.each(function(value, index) {
      results.push(iterator(value, index));
    });
    return results;
  },

  detect: function(iterator, context) {
    iterator = iterator.bind(context);
    var result;
    this.each(function(value, index) {
      if (iterator(value, index)) {
        result = value;
        throw $break;
      }
    });
    return result;
  },

  findAll: function(iterator, context) {
    iterator = iterator.bind(context);
    var results = [];
    this.each(function(value, index) {
      if (iterator(value, index))
        results.push(value);
    });
    return results;
  },

  grep: function(filter, iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var results = [];

    if (Object.isString(filter))
      filter = new RegExp(filter);

    this.each(function(value, index) {
      if (filter.match(value))
        results.push(iterator(value, index));
    });
    return results;
  },

  include: function(object) {
    if (Object.isFunction(this.indexOf))
      if (this.indexOf(object) != -1) return true;

    var found = false;
    this.each(function(value) {
      if (value == object) {
        found = true;
        throw $break;
      }
    });
    return found;
  },

  inGroupsOf: function(number, fillWith) {
    fillWith = fillWith === undefined ? null : fillWith;
    return this.eachSlice(number, function(slice) {
      while(slice.length < number) slice.push(fillWith);
      return slice;
    });
  },

  inject: function(memo, iterator, context) {
    iterator = iterator.bind(context);
    this.each(function(value, index) {
      memo = iterator(memo, value, index);
    });
    return memo;
  },

  invoke: function(method) {
    var args = $A(arguments).slice(1);
    return this.map(function(value) {
      return value[method].apply(value, args);
    });
  },

  max: function(iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var result;
    this.each(function(value, index) {
      value = iterator(value, index);
      if (result == undefined || value >= result)
        result = value;
    });
    return result;
  },

  min: function(iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var result;
    this.each(function(value, index) {
      value = iterator(value, index);
      if (result == undefined || value < result)
        result = value;
    });
    return result;
  },

  partition: function(iterator, context) {
    iterator = iterator ? iterator.bind(context) : Prototype.K;
    var trues = [], falses = [];
    this.each(function(value, index) {
      (iterator(value, index) ?
        trues : falses).push(value);
    });
    return [trues, falses];
  },

  pluck: function(property) {
    var results = [];
    this.each(function(value) {
      results.push(value[property]);
    });
    return results;
  },

  reject: function(iterator, context) {
    iterator = iterator.bind(context);
    var results = [];
    this.each(function(value, index) {
      if (!iterator(value, index))
        results.push(value);
    });
    return results;
  },

  sortBy: function(iterator, context) {
    iterator = iterator.bind(context);
    return this.map(function(value, index) {
      return {value: value, criteria: iterator(value, index)};
    }).sort(function(left, right) {
      var a = left.criteria, b = right.criteria;
      return a < b ? -1 : a > b ? 1 : 0;
    }).pluck('value');
  },

  toArray: function() {
    return this.map();
  },

  zip: function() {
    var iterator = Prototype.K, args = $A(arguments);
    if (Object.isFunction(args.last()))
      iterator = args.pop();

    var collections = [this].concat(args).map($A);
    return this.map(function(value, index) {
      return iterator(collections.pluck(index));
    });
  },

  size: function() {
    return this.toArray().length;
  },

  inspect: function() {
    return '#<Enumerable:' + this.toArray().inspect() + '>';
  }
};

Object.extend(Enumerable, {
  map:     Enumerable.collect,
  find:    Enumerable.detect,
  select:  Enumerable.findAll,
  filter:  Enumerable.findAll,
  member:  Enumerable.include,
  entries: Enumerable.toArray,
  every:   Enumerable.all,
  some:    Enumerable.any
});
function $A(iterable) {
  if (!iterable) return [];
  if (iterable.toArray) return iterable.toArray();
  var length = iterable.length, results = new Array(length);
  while (length--) results[length] = iterable[length];
  return results;
}

if (Prototype.Browser.WebKit) {
  function $A(iterable) {
    if (!iterable) return [];
    if (!(Object.isFunction(iterable) && iterable == '[object NodeList]') &&
        iterable.toArray) return iterable.toArray();
    var length = iterable.length, results = new Array(length);
    while (length--) results[length] = iterable[length];
    return results;
  }
}

Array.from = $A;

Object.extend(Array.prototype, Enumerable);

if (!Array.prototype._reverse) Array.prototype._reverse = Array.prototype.reverse;

Object.extend(Array.prototype, {
  _each: function(iterator) {
    for (var i = 0, length = this.length; i < length; i++)
      iterator(this[i]);
  },

  clear: function() {
    this.length = 0;
    return this;
  },

  first: function() {
    return this[0];
  },

  last: function() {
    return this[this.length - 1];
  },

  compact: function() {
    return this.select(function(value) {
      return value != null;
    });
  },

  flatten: function() {
    return this.inject([], function(array, value) {
      return array.concat(Object.isArray(value) ?
        value.flatten() : [value]);
    });
  },

  without: function() {
    var values = $A(arguments);
    return this.select(function(value) {
      return !values.include(value);
    });
  },

  reverse: function(inline) {
    return (inline !== false ? this : this.toArray())._reverse();
  },

  reduce: function() {
    return this.length > 1 ? this : this[0];
  },

  uniq: function(sorted) {
    return this.inject([], function(array, value, index) {
      if (0 == index || (sorted ? array.last() != value : !array.include(value)))
        array.push(value);
      return array;
    });
  },

  intersect: function(array) {
    return this.uniq().findAll(function(item) {
      return array.detect(function(value) { return item === value });
    });
  },

  clone: function() {
    return [].concat(this);
  },

  size: function() {
    return this.length;
  },

  inspect: function() {
    return '[' + this.map(Object.inspect).join(', ') + ']';
  },

  toJSON: function() {
    var results = [];
    this.each(function(object) {
      var value = Object.toJSON(object);
      if (value !== undefined) results.push(value);
    });
    return '[' + results.join(', ') + ']';
  }
});

// use native browser JS 1.6 implementation if available
if (Object.isFunction(Array.prototype.forEach))
  Array.prototype._each = Array.prototype.forEach;

if (!Array.prototype.indexOf) Array.prototype.indexOf = function(item, i) {
  i || (i = 0);
  var length = this.length;
  if (i < 0) i = length + i;
  for (; i < length; i++)
    if (this[i] === item) return i;
  return -1;
};

if (!Array.prototype.lastIndexOf) Array.prototype.lastIndexOf = function(item, i) {
  i = isNaN(i) ? this.length : (i < 0 ? this.length + i : i) + 1;
  var n = this.slice(0, i).reverse().indexOf(item);
  return (n < 0) ? n : i - n - 1;
};

Array.prototype.toArray = Array.prototype.clone;

function $w(string) {
  if (!Object.isString(string)) return [];
  string = string.strip();
  return string ? string.split(/\s+/) : [];
}

if (Prototype.Browser.Opera){
  Array.prototype.concat = function() {
    var array = [];
    for (var i = 0, length = this.length; i < length; i++) array.push(this[i]);
    for (var i = 0, length = arguments.length; i < length; i++) {
      if (Object.isArray(arguments[i])) {
        for (var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++)
          array.push(arguments[i][j]);
      } else {
        array.push(arguments[i]);
      }
    }
    return array;
  };
}
Object.extend(Number.prototype, {
  toColorPart: function() {
    return this.toPaddedString(2, 16);
  },

  succ: function() {
    return this + 1;
  },

  times: function(iterator) {
    $R(0, this, true).each(iterator);
    return this;
  },

  toPaddedString: function(length, radix) {
    var string = this.toString(radix || 10);
    return '0'.times(length - string.length) + string;
  },

  toJSON: function() {
    return isFinite(this) ? this.toString() : 'null';
  }
});

$w('abs round ceil floor').each(function(method){
  Number.prototype[method] = Math[method].methodize();
});
function $H(object) {
  return new Hash(object);
};

var Hash = Class.create(Enumerable, (function() {
  if (function() {
    var i = 0, Test = function(value) { this.key = value };
    Test.prototype.key = 'foo';
    for (var property in new Test('bar')) i++;
    return i > 1;
  }()) {
    function each(iterator) {
      var cache = [];
      for (var key in this._object) {
        var value = this._object[key];
        if (cache.include(key)) continue;
        cache.push(key);
        var pair = [key, value];
        pair.key = key;
        pair.value = value;
        iterator(pair);
      }
    }
  } else {
    function each(iterator) {
      for (var key in this._object) {
        var value = this._object[key], pair = [key, value];
        pair.key = key;
        pair.value = value;
        iterator(pair);
      }
    }
  }

  function toQueryPair(key, value) {
    if (Object.isUndefined(value)) return key;
    return key + '=' + encodeURIComponent(String.interpret(value));
  }

  return {
    initialize: function(object) {
      this._object = Object.isHash(object) ? object.toObject() : Object.clone(object);
    },

    _each: each,

    set: function(key, value) {
      return this._object[key] = value;
    },

    get: function(key) {
      return this._object[key];
    },

    unset: function(key) {
      var value = this._object[key];
      delete this._object[key];
      return value;
    },

    toObject: function() {
      return Object.clone(this._object);
    },

    keys: function() {
      return this.pluck('key');
    },

    values: function() {
      return this.pluck('value');
    },

    index: function(value) {
      var match = this.detect(function(pair) {
        return pair.value === value;
      });
      return match && match.key;
    },

    merge: function(object) {
      return this.clone().update(object);
    },

    update: function(object) {
      return new Hash(object).inject(this, function(result, pair) {
        result.set(pair.key, pair.value);
        return result;
      });
    },

    toQueryString: function() {
      return this.map(function(pair) {
        var key = encodeURIComponent(pair.key), values = pair.value;

        if (values && typeof values == 'object') {
          if (Object.isArray(values))
            return values.map(toQueryPair.curry(key)).join('&');
        }
        return toQueryPair(key, values);
      }).join('&');
    },

    inspect: function() {
      return '#<Hash:{' + this.map(function(pair) {
        return pair.map(Object.inspect).join(': ');
      }).join(', ') + '}>';
    },

    toJSON: function() {
      return Object.toJSON(this.toObject());
    },

    clone: function() {
      return new Hash(this);
    }
  }
})());

Hash.prototype.toTemplateReplacements = Hash.prototype.toObject;
Hash.from = $H;
var ObjectRange = Class.create(Enumerable, {
  initialize: function(start, end, exclusive) {
    this.start = start;
    this.end = end;
    this.exclusive = exclusive;
  },

  _each: function(iterator) {
    var value = this.start;
    while (this.include(value)) {
      iterator(value);
      value = value.succ();
    }
  },

  include: function(value) {
    if (value < this.start)
      return false;
    if (this.exclusive)
      return value < this.end;
    return value <= this.end;
  }
});

var $R = function(start, end, exclusive) {
  return new ObjectRange(start, end, exclusive);
};

var Ajax = {
  getTransport: function() {
    return Try.these(
      function() {return new XMLHttpRequest()},
      function() {return new ActiveXObject('Msxml2.XMLHTTP')},
      function() {return new ActiveXObject('Microsoft.XMLHTTP')}
    ) || false;
  },

  activeRequestCount: 0
};

Ajax.Responders = {
  responders: [],

  _each: function(iterator) {
    this.responders._each(iterator);
  },

  register: function(responder) {
    if (!this.include(responder))
      this.responders.push(responder);
  },

  unregister: function(responder) {
    this.responders = this.responders.without(responder);
  },

  dispatch: function(callback, request, transport, json) {
    this.each(function(responder) {
      if (Object.isFunction(responder[callback])) {
        try {
          responder[callback].apply(responder, [request, transport, json]);
        } catch (e) { }
      }
    });
  }
};

Object.extend(Ajax.Responders, Enumerable);

Ajax.Responders.register({
  onCreate:   function() { Ajax.activeRequestCount++ },
  onComplete: function() { Ajax.activeRequestCount-- }
});

Ajax.Base = Class.create({
  initialize: function(options) {
    this.options = {
      method:       'post',
      asynchronous: true,
      contentType:  'application/x-www-form-urlencoded',
      encoding:     'UTF-8',
      parameters:   '',
      evalJSON:     true,
      evalJS:       true
    };
    Object.extend(this.options, options || { });

    this.options.method = this.options.method.toLowerCase();
    if (Object.isString(this.options.parameters))
      this.options.parameters = this.options.parameters.toQueryParams();
  }
});

Ajax.Request = Class.create(Ajax.Base, {
  _complete: false,

  initialize: function($super, url, options) {
    $super(options);
    this.transport = Ajax.getTransport();
    this.request(url);
  },

  request: function(url) {
    this.url = url;
    this.method = this.options.method;
    var params = Object.clone(this.options.parameters);

    if (!['get', 'post'].include(this.method)) {
      // simulate other verbs over post
      params['_method'] = this.method;
      this.method = 'post';
    }

    this.parameters = params;

    if (params = Object.toQueryString(params)) {
      // when GET, append parameters to URL
      if (this.method == 'get')
        this.url += (this.url.include('?') ? '&' : '?') + params;
      else if (/Konqueror|Safari|KHTML/.test(navigator.userAgent))
        params += '&_=';
    }

    try {
      var response = new Ajax.Response(this);
      if (this.options.onCreate) this.options.onCreate(response);
      Ajax.Responders.dispatch('onCreate', this, response);

      this.transport.open(this.method.toUpperCase(), this.url,
        this.options.asynchronous);

      if (this.options.asynchronous) this.respondToReadyState.bind(this).defer(1);

      this.transport.onreadystatechange = this.onStateChange.bind(this);
      this.setRequestHeaders();

      this.body = this.method == 'post' ? (this.options.postBody || params) : null;
      this.transport.send(this.body);

      /* Force Firefox to handle ready state 4 for synchronous requests */
      if (!this.options.asynchronous && this.transport.overrideMimeType)
        this.onStateChange();

    }
    catch (e) {
      this.dispatchException(e);
    }
  },

  onStateChange: function() {
    var readyState = this.transport.readyState;
    if (readyState > 1 && !((readyState == 4) && this._complete))
      this.respondToReadyState(this.transport.readyState);
  },

  setRequestHeaders: function() {
    var headers = {
      'X-Requested-With': 'XMLHttpRequest',
      'X-Prototype-Version': Prototype.Version,
      'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
    };

    if (this.method == 'post') {
      headers['Content-type'] = this.options.contentType +
        (this.options.encoding ? '; charset=' + this.options.encoding : '');

      /* Force "Connection: close" for older Mozilla browsers to work
       * around a bug where XMLHttpRequest sends an incorrect
       * Content-length header. See Mozilla Bugzilla #246651.
       */
      if (this.transport.overrideMimeType &&
          (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
            headers['Connection'] = 'close';
    }

    // user-defined headers
    if (typeof this.options.requestHeaders == 'object') {
      var extras = this.options.requestHeaders;

      if (Object.isFunction(extras.push))
        for (var i = 0, length = extras.length; i < length; i += 2)
          headers[extras[i]] = extras[i+1];
      else
        $H(extras).each(function(pair) { headers[pair.key] = pair.value });
    }

    for (var name in headers)
      this.transport.setRequestHeader(name, headers[name]);
  },

  success: function() {
    var status = this.getStatus();
    return !status || (status >= 200 && status < 300);
  },

  getStatus: function() {
    try {
      return this.transport.status || 0;
    } catch (e) { return 0 }
  },

  respondToReadyState: function(readyState) {
    var state = Ajax.Request.Events[readyState], response = new Ajax.Response(this);

    if (state == 'Complete') {
      try {
        this._complete = true;
        (this.options['on' + response.status]
         || this.options['on' + (this.success() ? 'Success' : 'Failure')]
         || Prototype.emptyFunction)(response, response.headerJSON);
      } catch (e) {
        this.dispatchException(e);
      }

      var contentType = response.getHeader('Content-type');
      if (this.options.evalJS == 'force'
          || (this.options.evalJS && contentType
          && contentType.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i)))
        this.evalResponse();
    }

    try {
      (this.options['on' + state] || Prototype.emptyFunction)(response, response.headerJSON);
      Ajax.Responders.dispatch('on' + state, this, response, response.headerJSON);
    } catch (e) {
      this.dispatchException(e);
    }

    if (state == 'Complete') {
      // avoid memory leak in MSIE: clean up
      this.transport.onreadystatechange = Prototype.emptyFunction;
    }
  },

  getHeader: function(name) {
    try {
      return this.transport.getResponseHeader(name);
    } catch (e) { return null }
  },

  evalResponse: function() {
    try {
      return eval((this.transport.responseText || '').unfilterJSON());
    } catch (e) {
      this.dispatchException(e);
    }
  },

  dispatchException: function(exception) {
    (this.options.onException || Prototype.emptyFunction)(this, exception);
    Ajax.Responders.dispatch('onException', this, exception);
  }
});

Ajax.Request.Events =
  ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];

Ajax.Response = Class.create({
  initialize: function(request){
    this.request = request;
    var transport  = this.transport  = request.transport,
        readyState = this.readyState = transport.readyState;

    if((readyState > 2 && !Prototype.Browser.IE) || readyState == 4) {
      this.status       = this.getStatus();
      this.statusText   = this.getStatusText();
      this.responseText = String.interpret(transport.responseText);
      this.headerJSON   = this._getHeaderJSON();
    }

    if(readyState == 4) {
      var xml = transport.responseXML;
      this.responseXML  = xml === undefined ? null : xml;
      this.responseJSON = this._getResponseJSON();
    }
  },

  status:      0,
  statusText: '',

  getStatus: Ajax.Request.prototype.getStatus,

  getStatusText: function() {
    try {
      return this.transport.statusText || '';
    } catch (e) { return '' }
  },

  getHeader: Ajax.Request.prototype.getHeader,

  getAllHeaders: function() {
    try {
      return this.getAllResponseHeaders();
    } catch (e) { return null }
  },

  getResponseHeader: function(name) {
    return this.transport.getResponseHeader(name);
  },

  getAllResponseHeaders: function() {
    return this.transport.getAllResponseHeaders();
  },

  _getHeaderJSON: function() {
    var json = this.getHeader('X-JSON');
    if (!json) return null;
    json = decodeURIComponent(escape(json));
    try {
      return json.evalJSON(this.request.options.sanitizeJSON);
    } catch (e) {
      this.request.dispatchException(e);
    }
  },

  _getResponseJSON: function() {
    var options = this.request.options;
    if (!options.evalJSON || (options.evalJSON != 'force' &&
      !(this.getHeader('Content-type') || '').include('application/json')))
        return null;
    try {
      return this.transport.responseText.evalJSON(options.sanitizeJSON);
    } catch (e) {
      this.request.dispatchException(e);
    }
  }
});

Ajax.Updater = Class.create(Ajax.Request, {
  initialize: function($super, container, url, options) {
    this.container = {
      success: (container.success || container),
      failure: (container.failure || (container.success ? null : container))
    };

    options = options || { };
    var onComplete = options.onComplete;
    options.onComplete = (function(response, param) {
      this.updateContent(response.responseText);
      if (Object.isFunction(onComplete)) onComplete(response, param);
    }).bind(this);

    $super(url, options);
  },

  updateContent: function(responseText) {
    var receiver = this.container[this.success() ? 'success' : 'failure'],
        options = this.options;

    if (!options.evalScripts) responseText = responseText.stripScripts();

    if (receiver = $(receiver)) {
      if (options.insertion) {
        if (Object.isString(options.insertion)) {
          var insertion = { }; insertion[options.insertion] = responseText;
          receiver.insert(insertion);
        }
        else options.insertion(receiver, responseText);
      }
      else receiver.update(responseText);
    }

    if (this.success()) {
      if (this.onComplete) this.onComplete.bind(this).defer();
    }
  }
});

Ajax.PeriodicalUpdater = Class.create(Ajax.Base, {
  initialize: function($super, container, url, options) {
    $super(options);
    this.onComplete = this.options.onComplete;

    this.frequency = (this.options.frequency || 2);
    this.decay = (this.options.decay || 1);

    this.updater = { };
    this.container = container;
    this.url = url;

    this.start();
  },

  start: function() {
    this.options.onComplete = this.updateComplete.bind(this);
    this.onTimerEvent();
  },

  stop: function() {
    this.updater.options.onComplete = undefined;
    clearTimeout(this.timer);
    (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
  },

  updateComplete: function(response) {
    if (this.options.decay) {
      this.decay = (response.responseText == this.lastText ?
        this.decay * this.options.decay : 1);

      this.lastText = response.responseText;
    }
    this.timer = this.onTimerEvent.bind(this).delay(this.decay * this.frequency);
  },

  onTimerEvent: function() {
    this.updater = new Ajax.Updater(this.container, this.url, this.options);
  }
});
function $(element) {
  if (arguments.length > 1) {
    for (var i = 0, elements = [], length = arguments.length; i < length; i++)
      elements.push($(arguments[i]));
    return elements;
  }
  if (Object.isString(element))
    element = document.getElementById(element);
  return Element.extend(element);
}

if (Prototype.BrowserFeatures.XPath) {
  document._getElementsByXPath = function(expression, parentElement) {
    var results = [];
    var query = document.evaluate(expression, $(parentElement) || document,
      null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    for (var i = 0, length = query.snapshotLength; i < length; i++)
      results.push(Element.extend(query.snapshotItem(i)));
    return results;
  };
}

/*--------------------------------------------------------------------------*/

if (!window.Node) var Node = { };

if (!Node.ELEMENT_NODE) {
  // DOM level 2 ECMAScript Language Binding
  Object.extend(Node, {
    ELEMENT_NODE: 1,
    ATTRIBUTE_NODE: 2,
    TEXT_NODE: 3,
    CDATA_SECTION_NODE: 4,
    ENTITY_REFERENCE_NODE: 5,
    ENTITY_NODE: 6,
    PROCESSING_INSTRUCTION_NODE: 7,
    COMMENT_NODE: 8,
    DOCUMENT_NODE: 9,
    DOCUMENT_TYPE_NODE: 10,
    DOCUMENT_FRAGMENT_NODE: 11,
    NOTATION_NODE: 12
  });
}

(function() {
  var element = this.Element;
  this.Element = function(tagName, attributes) {
    attributes = attributes || { };
    tagName = tagName.toLowerCase();
    var cache = Element.cache;
    if (Prototype.Browser.IE && attributes.name) {
      tagName = '<' + tagName + ' name="' + attributes.name + '">';
      delete attributes.name;
      return Element.writeAttribute(document.createElement(tagName), attributes);
    }
    if (!cache[tagName]) cache[tagName] = Element.extend(document.createElement(tagName));
    return Element.writeAttribute(cache[tagName].cloneNode(false), attributes);
  };
  Object.extend(this.Element, element || { });
}).call(window);

Element.cache = { };

Element.Methods = {
  visible: function(element) {
    return $(element).style.display != 'none';
  },

  toggle: function(element) {
    element = $(element);
    Element[Element.visible(element) ? 'hide' : 'show'](element);
    return element;
  },

  hide: function(element) {
    $(element).style.display = 'none';
    return element;
  },

  show: function(element) {
    $(element).style.display = '';
    return element;
  },

  remove: function(element) {
    element = $(element);
    element.parentNode.removeChild(element);
    return element;
  },

  update: function(element, content) {
    element = $(element);
    if (content && content.toElement) content = content.toElement();
    if (Object.isElement(content)) return element.update().insert(content);
    content = Object.toHTML(content);
    element.innerHTML = content.stripScripts();
    content.evalScripts.bind(content).defer();
    return element;
  },

  replace: function(element, content) {
    element = $(element);
    if (content && content.toElement) content = content.toElement();
    else if (!Object.isElement(content)) {
      content = Object.toHTML(content);
      var range = element.ownerDocument.createRange();
      range.selectNode(element);
      content.evalScripts.bind(content).defer();
      content = range.createContextualFragment(content.stripScripts());
    }
    element.parentNode.replaceChild(content, element);
    return element;
  },

  insert: function(element, insertions) {
    element = $(element);

    if (Object.isString(insertions) || Object.isNumber(insertions) ||
        Object.isElement(insertions) || (insertions && (insertions.toElement || insertions.toHTML)))
          insertions = {bottom:insertions};

    var content, t, range;

    for (position in insertions) {
      content  = insertions[position];
      position = position.toLowerCase();
      t = Element._insertionTranslations[position];

      if (content && content.toElement) content = content.toElement();
      if (Object.isElement(content)) {
        t.insert(element, content);
        continue;
      }

      content = Object.toHTML(content);

      range = element.ownerDocument.createRange();
      t.initializeRange(element, range);
      t.insert(element, range.createContextualFragment(content.stripScripts()));

      content.evalScripts.bind(content).defer();
    }

    return element;
  },

  wrap: function(element, wrapper, attributes) {
    element = $(element);
    if (Object.isElement(wrapper))
      $(wrapper).writeAttribute(attributes || { });
    else if (Object.isString(wrapper)) wrapper = new Element(wrapper, attributes);
    else wrapper = new Element('div', wrapper);
    if (element.parentNode)
      element.parentNode.replaceChild(wrapper, element);
    wrapper.appendChild(element);
    return wrapper;
  },

  inspect: function(element) {
    element = $(element);
    var result = '<' + element.tagName.toLowerCase();
    $H({'id': 'id', 'className': 'class'}).each(function(pair) {
      var property = pair.first(), attribute = pair.last();
      var value = (element[property] || '').toString();
      if (value) result += ' ' + attribute + '=' + value.inspect(true);
    });
    return result + '>';
  },

  recursivelyCollect: function(element, property) {
    element = $(element);
    var elements = [];
    while (element = element[property])
      if (element.nodeType == 1)
        elements.push(Element.extend(element));
    return elements;
  },

  ancestors: function(element) {
    return $(element).recursivelyCollect('parentNode');
  },

  descendants: function(element) {
    return $A($(element).getElementsByTagName('*')).each(Element.extend);
  },

  firstDescendant: function(element) {
    element = $(element).firstChild;
    while (element && element.nodeType != 1) element = element.nextSibling;
    return $(element);
  },

  immediateDescendants: function(element) {
    if (!(element = $(element).firstChild)) return [];
    while (element && element.nodeType != 1) element = element.nextSibling;
    if (element) return [element].concat($(element).nextSiblings());
    return [];
  },

  previousSiblings: function(element) {
    return $(element).recursivelyCollect('previousSibling');
  },

  nextSiblings: function(element) {
    return $(element).recursivelyCollect('nextSibling');
  },

  siblings: function(element) {
    element = $(element);
    return element.previousSiblings().reverse().concat(element.nextSiblings());
  },

  match: function(element, selector) {
    if (Object.isString(selector))
      selector = new Selector(selector);
    return selector.match($(element));
  },

  up: function(element, expression, index) {
    element = $(element);
    if (arguments.length == 1) return $(element.parentNode);
    var ancestors = element.ancestors();
    return expression ? Selector.findElement(ancestors, expression, index) :
      ancestors[index || 0];
  },

  down: function(element, expression, index) {
    element = $(element);
    if (arguments.length == 1) return element.firstDescendant();
    var descendants = element.descendants();
    return expression ? Selector.findElement(descendants, expression, index) :
      descendants[index || 0];
  },

  previous: function(element, expression, index) {
    element = $(element);
    if (arguments.length == 1) return $(Selector.handlers.previousElementSibling(element));
    var previousSiblings = element.previousSiblings();
    return expression ? Selector.findElement(previousSiblings, expression, index) :
      previousSiblings[index || 0];
  },

  next: function(element, expression, index) {
    element = $(element);
    if (arguments.length == 1) return $(Selector.handlers.nextElementSibling(element));
    var nextSiblings = element.nextSiblings();
    return expression ? Selector.findElement(nextSiblings, expression, index) :
      nextSiblings[index || 0];
  },

  select: function() {
    var args = $A(arguments), element = $(args.shift());
    return Selector.findChildElements(element, args);
  },

  adjacent: function() {
    var args = $A(arguments), element = $(args.shift());
    return Selector.findChildElements(element.parentNode, args).without(element);
  },

  identify: function(element) {
    element = $(element);
    var id = element.readAttribute('id'), self = arguments.callee;
    if (id) return id;
    do { id = 'anonymous_element_' + self.counter++ } while ($(id));
    element.writeAttribute('id', id);
    return id;
  },

  readAttribute: function(element, name) {
    element = $(element);
    if (Prototype.Browser.IE) {
      var t = Element._attributeTranslations.read;
      if (t.values[name]) return t.values[name](element, name);
      if (t.names[name]) name = t.names[name];
      if (name.include(':')) {
        return (!element.attributes || !element.attributes[name]) ? null :
         element.attributes[name].value;
      }
    }
    return element.getAttribute(name);
  },

  writeAttribute: function(element, name, value) {
    element = $(element);
    var attributes = { }, t = Element._attributeTranslations.write;

    if (typeof name == 'object') attributes = name;
    else attributes[name] = value === undefined ? true : value;

    for (var attr in attributes) {
      var name = t.names[attr] || attr, value = attributes[attr];
      if (t.values[attr]) name = t.values[attr](element, value);
      if (value === false || value === null)
        element.removeAttribute(name);
      else if (value === true)
        element.setAttribute(name, name);
      else element.setAttribute(name, value);
    }
    return element;
  },

  getHeight: function(element) {
    return $(element).getDimensions().height;
  },

  getWidth: function(element) {
    return $(element).getDimensions().width;
  },

  classNames: function(element) {
    return new Element.ClassNames(element);
  },

  hasClassName: function(element, className) {
    if (!(element = $(element))) return;
    var elementClassName = element.className;
    return (elementClassName.length > 0 && (elementClassName == className ||
      new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName)));
  },

  addClassName: function(element, className) {
    if (!(element = $(element))) return;
    if (!element.hasClassName(className))
      element.className += (element.className ? ' ' : '') + className;
    return element;
  },

  removeClassName: function(element, className) {
    if (!(element = $(element))) return;
    element.className = element.className.replace(
      new RegExp("(^|\\s+)" + className + "(\\s+|$)"), ' ').strip();
    return element;
  },

  toggleClassName: function(element, className) {
    if (!(element = $(element))) return;
    return element[element.hasClassName(className) ?
      'removeClassName' : 'addClassName'](className);
  },

  // removes whitespace-only text node children
  cleanWhitespace: function(element) {
    element = $(element);
    var node = element.firstChild;
    while (node) {
      var nextNode = node.nextSibling;
      if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
        element.removeChild(node);
      node = nextNode;
    }
    return element;
  },

  empty: function(element) {
    return $(element).innerHTML.blank();
  },

  descendantOf: function(element, ancestor) {
    element = $(element), ancestor = $(ancestor);

    if (element.compareDocumentPosition)
      return (element.compareDocumentPosition(ancestor) & 8) === 8;

    if (element.sourceIndex && !Prototype.Browser.Opera) {
      var e = element.sourceIndex, a = ancestor.sourceIndex,
       nextAncestor = ancestor.nextSibling;
      if (!nextAncestor) {
        do { ancestor = ancestor.parentNode; }
        while (!(nextAncestor = ancestor.nextSibling) && ancestor.parentNode);
      }
      if (nextAncestor) return (e > a && e < nextAncestor.sourceIndex);
    }

    while (element = element.parentNode)
      if (element == ancestor) return true;
    return false;
  },

  scrollTo: function(element) {
    element = $(element);
    var pos = element.cumulativeOffset();
    window.scrollTo(pos[0], pos[1]);
    return element;
  },

  getStyle: function(element, style) {
    element = $(element);
    style = style == 'float' ? 'cssFloat' : style.camelize();
    var value = element.style[style];
    if (!value) {
      var css = document.defaultView.getComputedStyle(element, null);
      value = css ? css[style] : null;
    }
    if (style == 'opacity') return value ? parseFloat(value) : 1.0;
    return value == 'auto' ? null : value;
  },

  getOpacity: function(element) {
    return $(element).getStyle('opacity');
  },

  setStyle: function(element, styles) {
    element = $(element);
    var elementStyle = element.style, match;
    if (Object.isString(styles)) {
      element.style.cssText += ';' + styles;
      return styles.include('opacity') ?
        element.setOpacity(styles.match(/opacity:\s*(\d?\.?\d*)/)[1]) : element;
    }
    for (var property in styles)
      if (property == 'opacity') element.setOpacity(styles[property]);
      else
        elementStyle[(property == 'float' || property == 'cssFloat') ?
          (elementStyle.styleFloat === undefined ? 'cssFloat' : 'styleFloat') :
            property] = styles[property];

    return element;
  },

  setOpacity: function(element, value) {
    element = $(element);
    element.style.opacity = (value == 1 || value === '') ? '' :
      (value < 0.00001) ? 0 : value;
    return element;
  },

  getDimensions: function(element) {
    element = $(element);
    var display = $(element).getStyle('display');
    if (display != 'none' && display != null) // Safari bug
      return {width: element.offsetWidth, height: element.offsetHeight};

    // All *Width and *Height properties give 0 on elements with display none,
    // so enable the element temporarily
    var els = element.style;
    var originalVisibility = els.visibility;
    var originalPosition = els.position;
    var originalDisplay = els.display;
    els.visibility = 'hidden';
    els.position = 'absolute';
    els.display = 'block';
    var originalWidth = element.clientWidth;
    var originalHeight = element.clientHeight;
    els.display = originalDisplay;
    els.position = originalPosition;
    els.visibility = originalVisibility;
    return {width: originalWidth, height: originalHeight};
  },

  makePositioned: function(element) {
    element = $(element);
    var pos = Element.getStyle(element, 'position');
    if (pos == 'static' || !pos) {
      element._madePositioned = true;
      element.style.position = 'relative';
      // Opera returns the offset relative to the positioning context, when an
      // element is position relative but top and left have not been defined
      if (window.opera) {
        element.style.top = 0;
        element.style.left = 0;
      }
    }
    return element;
  },

  undoPositioned: function(element) {
    element = $(element);
    if (element._madePositioned) {
      element._madePositioned = undefined;
      element.style.position =
        element.style.top =
        element.style.left =
        element.style.bottom =
        element.style.right = '';
    }
    return element;
  },

  makeClipping: function(element) {
    element = $(element);
    if (element._overflow) return element;
    element._overflow = Element.getStyle(element, 'overflow') || 'auto';
    if (element._overflow !== 'hidden')
      element.style.overflow = 'hidden';
    return element;
  },

  undoClipping: function(element) {
    element = $(element);
    if (!element._overflow) return element;
    element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
    element._overflow = null;
    return element;
  },

  cumulativeOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
    } while (element);
    return Element._returnOffset(valueL, valueT);
  },

  positionedOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
      if (element) {
        if (element.tagName == 'BODY') break;
        var p = Element.getStyle(element, 'position');
        if (p == 'relative' || p == 'absolute') break;
      }
    } while (element);
    return Element._returnOffset(valueL, valueT);
  },

  absolutize: function(element) {
    element = $(element);
    if (element.getStyle('position') == 'absolute') return;
    // Position.prepare(); // To be done manually by Scripty when it needs it.

    var offsets = element.positionedOffset();
    var top     = offsets[1];
    var left    = offsets[0];
    var width   = element.clientWidth;
    var height  = element.clientHeight;

    element._originalLeft   = left - parseFloat(element.style.left  || 0);
    element._originalTop    = top  - parseFloat(element.style.top || 0);
    element._originalWidth  = element.style.width;
    element._originalHeight = element.style.height;

    element.style.position = 'absolute';
    element.style.top    = top + 'px';
    element.style.left   = left + 'px';
    element.style.width  = width + 'px';
    element.style.height = height + 'px';
    return element;
  },

  relativize: function(element) {
    element = $(element);
    if (element.getStyle('position') == 'relative') return;
    // Position.prepare(); // To be done manually by Scripty when it needs it.

    element.style.position = 'relative';
    var top  = parseFloat(element.style.top  || 0) - (element._originalTop || 0);
    var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);

    element.style.top    = top + 'px';
    element.style.left   = left + 'px';
    element.style.height = element._originalHeight;
    element.style.width  = element._originalWidth;
    return element;
  },

  cumulativeScrollOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.scrollTop  || 0;
      valueL += element.scrollLeft || 0;
      element = element.parentNode;
    } while (element);
    return Element._returnOffset(valueL, valueT);
  },

  getOffsetParent: function(element) {
    if (element.offsetParent) return $(element.offsetParent);
    if (element == document.body) return $(element);

    while ((element = element.parentNode) && element != document.body)
      if (Element.getStyle(element, 'position') != 'static')
        return $(element);

    return $(document.body);
  },

  viewportOffset: function(forElement) {
    var valueT = 0, valueL = 0;

    var element = forElement;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;

      // Safari fix
      if (element.offsetParent == document.body &&
        Element.getStyle(element, 'position') == 'absolute') break;

    } while (element = element.offsetParent);

    element = forElement;
    do {
      if (!Prototype.Browser.Opera || element.tagName == 'BODY') {
        valueT -= element.scrollTop  || 0;
        valueL -= element.scrollLeft || 0;
      }
    } while (element = element.parentNode);

    return Element._returnOffset(valueL, valueT);
  },

  clonePosition: function(element, source) {
    var options = Object.extend({
      setLeft:    true,
      setTop:     true,
      setWidth:   true,
      setHeight:  true,
      offsetTop:  0,
      offsetLeft: 0
    }, arguments[2] || { });

    // find page position of source
    source = $(source);
    var p = source.viewportOffset();

    // find coordinate system to use
    element = $(element);
    var delta = [0, 0];
    var parent = null;
    // delta [0,0] will do fine with position: fixed elements,
    // position:absolute needs offsetParent deltas
    if (Element.getStyle(element, 'position') == 'absolute') {
      parent = element.getOffsetParent();
      delta = parent.viewportOffset();
    }

    // correct by body offsets (fixes Safari)
    if (parent == document.body) {
      delta[0] -= document.body.offsetLeft;
      delta[1] -= document.body.offsetTop;
    }

    // set position
    if (options.setLeft)   element.style.left  = (p[0] - delta[0] + options.offsetLeft) + 'px';
    if (options.setTop)    element.style.top   = (p[1] - delta[1] + options.offsetTop) + 'px';
    if (options.setWidth)  element.style.width = source.offsetWidth + 'px';
    if (options.setHeight) element.style.height = source.offsetHeight + 'px';
    return element;
  }
};

Element.Methods.identify.counter = 1;

Object.extend(Element.Methods, {
  getElementsBySelector: Element.Methods.select,
  childElements: Element.Methods.immediateDescendants
});

Element._attributeTranslations = {
  write: {
    names: {
      className: 'class',
      htmlFor:   'for'
    },
    values: { }
  }
};


if (!document.createRange || Prototype.Browser.Opera) {
  Element.Methods.insert = function(element, insertions) {
    element = $(element);

    if (Object.isString(insertions) || Object.isNumber(insertions) ||
        Object.isElement(insertions) || (insertions && (insertions.toElement || insertions.toHTML)))
          insertions = { bottom: insertions };

    var t = Element._insertionTranslations, content, position, pos, tagName;

    for (position in insertions) {
      content  = insertions[position];
      position = position.toLowerCase();
      pos      = t[position];

      if (content && content.toElement) content = content.toElement();
      if (Object.isElement(content)) {
        pos.insert(element, content);
        continue;
      }

      content = Object.toHTML(content);
      tagName = ((position == 'before' || position == 'after')
        ? element.parentNode : element).tagName.toUpperCase();

      if (t.tags[tagName]) {
        var fragments = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
        if (position == 'top' || position == 'after') fragments.reverse();
        fragments.each(pos.insert.curry(element));
      }
      else element.insertAdjacentHTML(pos.adjacency, content.stripScripts());

      content.evalScripts.bind(content).defer();
    }

    return element;
  };
}

if (Prototype.Browser.Opera) {
  Element.Methods._getStyle = Element.Methods.getStyle;
  Element.Methods.getStyle = function(element, style) {
    switch(style) {
      case 'left':
      case 'top':
      case 'right':
      case 'bottom':
        if (Element._getStyle(element, 'position') == 'static') return null;
      default: return Element._getStyle(element, style);
    }
  };
  Element.Methods._readAttribute = Element.Methods.readAttribute;
  Element.Methods.readAttribute = function(element, attribute) {
    if (attribute == 'title') return element.title;
    return Element._readAttribute(element, attribute);
  };
}

else if (Prototype.Browser.IE) {
  $w('positionedOffset getOffsetParent viewportOffset').each(function(method) {
    Element.Methods[method] = Element.Methods[method].wrap(
      function(proceed, element) {
        element = $(element);
        var position = element.getStyle('position');
        if (position != 'static') return proceed(element);
        element.setStyle({ position: 'relative' });
        var value = proceed(element);
        element.setStyle({ position: position });
        return value;
      }
    );
  });

  Element.Methods.getStyle = function(element, style) {
    element = $(element);
    style = (style == 'float' || style == 'cssFloat') ? 'styleFloat' : style.camelize();
    var value = element.style[style];
    if (!value && element.currentStyle) value = element.currentStyle[style];

    if (style == 'opacity') {
      if (value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
        if (value[1]) return parseFloat(value[1]) / 100;
      return 1.0;
    }

    if (value == 'auto') {
      if ((style == 'width' || style == 'height') && (element.getStyle('display') != 'none'))
        return element['offset' + style.capitalize()] + 'px';
      return null;
    }
    return value;
  };

  Element.Methods.setOpacity = function(element, value) {
    function stripAlpha(filter){
      return filter.replace(/alpha\([^\)]*\)/gi,'');
    }
    element = $(element);
    var currentStyle = element.currentStyle;
    if ((currentStyle && !currentStyle.hasLayout) ||
      (!currentStyle && element.style.zoom == 'normal'))
        element.style.zoom = 1;

    var filter = element.getStyle('filter'), style = element.style;
    if (value == 1 || value === '') {
      (filter = stripAlpha(filter)) ?
        style.filter = filter : style.removeAttribute('filter');
      return element;
    } else if (value < 0.00001) value = 0;
    style.filter = stripAlpha(filter) +
      'alpha(opacity=' + (value * 100) + ')';
    return element;
  };

  Element._attributeTranslations = {
    read: {
      names: {
        'class': 'className',
        'for':   'htmlFor'
      },
      values: {
        _getAttr: function(element, attribute) {
          return element.getAttribute(attribute, 2);
        },
        _getAttrNode: function(element, attribute) {
          var node = element.getAttributeNode(attribute);
          return node ? node.value : "";
        },
        _getEv: function(element, attribute) {
          var attribute = element.getAttribute(attribute);
          return attribute ? attribute.toString().slice(23, -2) : null;
        },
        _flag: function(element, attribute) {
          return $(element).hasAttribute(attribute) ? attribute : null;
        },
        style: function(element) {
          return element.style.cssText.toLowerCase();
        },
        title: function(element) {
          return element.title;
        }
      }
    }
  };

  Element._attributeTranslations.write = {
    names: Object.clone(Element._attributeTranslations.read.names),
    values: {
      checked: function(element, value) {
        element.checked = !!value;
      },

      style: function(element, value) {
        element.style.cssText = value ? value : '';
      }
    }
  };

  Element._attributeTranslations.has = {};

  $w('colSpan rowSpan vAlign dateTime accessKey tabIndex ' +
      'encType maxLength readOnly longDesc').each(function(attr) {
    Element._attributeTranslations.write.names[attr.toLowerCase()] = attr;
    Element._attributeTranslations.has[attr.toLowerCase()] = attr;
  });

  (function(v) {
    Object.extend(v, {
      href:        v._getAttr,
      src:         v._getAttr,
      type:        v._getAttr,
      action:      v._getAttrNode,
      disabled:    v._flag,
      checked:     v._flag,
      readonly:    v._flag,
      multiple:    v._flag,
      onload:      v._getEv,
      onunload:    v._getEv,
      onclick:     v._getEv,
      ondblclick:  v._getEv,
      onmousedown: v._getEv,
      onmouseup:   v._getEv,
      onmouseover: v._getEv,
      onmousemove: v._getEv,
      onmouseout:  v._getEv,
      onfocus:     v._getEv,
      onblur:      v._getEv,
      onkeypress:  v._getEv,
      onkeydown:   v._getEv,
      onkeyup:     v._getEv,
      onsubmit:    v._getEv,
      onreset:     v._getEv,
      onselect:    v._getEv,
      onchange:    v._getEv
    });
  })(Element._attributeTranslations.read.values);
}

else if (Prototype.Browser.Gecko && /rv:1\.8\.0/.test(navigator.userAgent)) {
  Element.Methods.setOpacity = function(element, value) {
    element = $(element);
    element.style.opacity = (value == 1) ? 0.999999 :
      (value === '') ? '' : (value < 0.00001) ? 0 : value;
    return element;
  };
}

else if (Prototype.Browser.WebKit) {
  Element.Methods.setOpacity = function(element, value) {
    element = $(element);
    element.style.opacity = (value == 1 || value === '') ? '' :
      (value < 0.00001) ? 0 : value;

    if (value == 1)
      if(element.tagName == 'IMG' && element.width) {
        element.width++; element.width--;
      } else try {
        var n = document.createTextNode(' ');
        element.appendChild(n);
        element.removeChild(n);
      } catch (e) { }

    return element;
  };

  // Safari returns margins on body which is incorrect if the child is absolutely
  // positioned.  For performance reasons, redefine Position.cumulativeOffset for
  // KHTML/WebKit only.
  Element.Methods.cumulativeOffset = function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      if (element.offsetParent == document.body)
        if (Element.getStyle(element, 'position') == 'absolute') break;

      element = element.offsetParent;
    } while (element);

    return Element._returnOffset(valueL, valueT);
  };
}

if (Prototype.Browser.IE || Prototype.Browser.Opera) {
  // IE and Opera are missing .innerHTML support for TABLE-related and SELECT elements
  Element.Methods.update = function(element, content) {
    element = $(element);

    if (content && content.toElement) content = content.toElement();
    if (Object.isElement(content)) return element.update().insert(content);

    content = Object.toHTML(content);
    var tagName = element.tagName.toUpperCase();

    if (tagName in Element._insertionTranslations.tags) {
      $A(element.childNodes).each(function(node) { element.removeChild(node) });
      Element._getContentFromAnonymousElement(tagName, content.stripScripts())
        .each(function(node) { element.appendChild(node) });
    }
    else element.innerHTML = content.stripScripts();

    content.evalScripts.bind(content).defer();
    return element;
  };
}

if (document.createElement('div').outerHTML) {
  Element.Methods.replace = function(element, content) {
    element = $(element);

    if (content && content.toElement) content = content.toElement();
    if (Object.isElement(content)) {
      element.parentNode.replaceChild(content, element);
      return element;
    }

    content = Object.toHTML(content);
    var parent = element.parentNode, tagName = parent.tagName.toUpperCase();

    if (Element._insertionTranslations.tags[tagName]) {
      var nextSibling = element.next();
      var fragments = Element._getContentFromAnonymousElement(tagName, content.stripScripts());
      parent.removeChild(element);
      if (nextSibling)
        fragments.each(function(node) { parent.insertBefore(node, nextSibling) });
      else
        fragments.each(function(node) { parent.appendChild(node) });
    }
    else element.outerHTML = content.stripScripts();

    content.evalScripts.bind(content).defer();
    return element;
  };
}

Element._returnOffset = function(l, t) {
  var result = [l, t];
  result.left = l;
  result.top = t;
  return result;
};

Element._getContentFromAnonymousElement = function(tagName, html) {
  var div = new Element('div'), t = Element._insertionTranslations.tags[tagName];
  div.innerHTML = t[0] + html + t[1];
  t[2].times(function() { div = div.firstChild });
  return $A(div.childNodes);
};

Element._insertionTranslations = {
  before: {
    adjacency: 'beforeBegin',
    insert: function(element, node) {
      element.parentNode.insertBefore(node, element);
    },
    initializeRange: function(element, range) {
      range.setStartBefore(element);
    }
  },
  top: {
    adjacency: 'afterBegin',
    insert: function(element, node) {
      element.insertBefore(node, element.firstChild);
    },
    initializeRange: function(element, range) {
      range.selectNodeContents(element);
      range.collapse(true);
    }
  },
  bottom: {
    adjacency: 'beforeEnd',
    insert: function(element, node) {
      element.appendChild(node);
    }
  },
  after: {
    adjacency: 'afterEnd',
    insert: function(element, node) {
      element.parentNode.insertBefore(node, element.nextSibling);
    },
    initializeRange: function(element, range) {
      range.setStartAfter(element);
    }
  },
  tags: {
    TABLE:  ['<table>',                '</table>',                   1],
    TBODY:  ['<table><tbody>',         '</tbody></table>',           2],
    TR:     ['<table><tbody><tr>',     '</tr></tbody></table>',      3],
    TD:     ['<table><tbody><tr><td>', '</td></tr></tbody></table>', 4],
    SELECT: ['<select>',               '</select>',                  1]
  }
};

(function() {
  this.bottom.initializeRange = this.top.initializeRange;
  Object.extend(this.tags, {
    THEAD: this.tags.TBODY,
    TFOOT: this.tags.TBODY,
    TH:    this.tags.TD
  });
}).call(Element._insertionTranslations);

Element.Methods.Simulated = {
  hasAttribute: function(element, attribute) {
    attribute = Element._attributeTranslations.has[attribute] || attribute;
    var node = $(element).getAttributeNode(attribute);
    return node && node.specified;
  }
};

Element.Methods.ByTag = { };

Object.extend(Element, Element.Methods);

if (!Prototype.BrowserFeatures.ElementExtensions &&
    document.createElement('div').__proto__) {
  window.HTMLElement = { };
  window.HTMLElement.prototype = document.createElement('div').__proto__;
  Prototype.BrowserFeatures.ElementExtensions = true;
}

Element.extend = (function() {
  if (Prototype.BrowserFeatures.SpecificElementExtensions)
    return Prototype.K;

  var Methods = { }, ByTag = Element.Methods.ByTag;

  var extend = Object.extend(function(element) {
    if (!element || element._extendedByPrototype ||
        element.nodeType != 1 || element == window) return element;

    var methods = Object.clone(Methods),
      tagName = element.tagName, property, value;

    // extend methods for specific tags
    if (ByTag[tagName]) Object.extend(methods, ByTag[tagName]);

    for (property in methods) {
      value = methods[property];
      if (Object.isFunction(value) && !(property in element))
        element[property] = value.methodize();
    }

    element._extendedByPrototype = Prototype.emptyFunction;
    return element;

  }, {
    refresh: function() {
      // extend methods for all tags (Safari doesn't need this)
      if (!Prototype.BrowserFeatures.ElementExtensions) {
        Object.extend(Methods, Element.Methods);
        Object.extend(Methods, Element.Methods.Simulated);
      }
    }
  });

  extend.refresh();
  return extend;
})();

Element.hasAttribute = function(element, attribute) {
  if (element.hasAttribute) return element.hasAttribute(attribute);
  return Element.Methods.Simulated.hasAttribute(element, attribute);
};

Element.addMethods = function(methods) {
  var F = Prototype.BrowserFeatures, T = Element.Methods.ByTag;

  if (!methods) {
    Object.extend(Form, Form.Methods);
    Object.extend(Form.Element, Form.Element.Methods);
    Object.extend(Element.Methods.ByTag, {
      "FORM":     Object.clone(Form.Methods),
      "INPUT":    Object.clone(Form.Element.Methods),
      "SELECT":   Object.clone(Form.Element.Methods),
      "TEXTAREA": Object.clone(Form.Element.Methods)
    });
  }

  if (arguments.length == 2) {
    var tagName = methods;
    methods = arguments[1];
  }

  if (!tagName) Object.extend(Element.Methods, methods || { });
  else {
    if (Object.isArray(tagName)) tagName.each(extend);
    else extend(tagName);
  }

  function extend(tagName) {
    tagName = tagName.toUpperCase();
    if (!Element.Methods.ByTag[tagName])
      Element.Methods.ByTag[tagName] = { };
    Object.extend(Element.Methods.ByTag[tagName], methods);
  }

  function copy(methods, destination, onlyIfAbsent) {
    onlyIfAbsent = onlyIfAbsent || false;
    for (var property in methods) {
      var value = methods[property];
      if (!Object.isFunction(value)) continue;
      if (!onlyIfAbsent || !(property in destination))
        destination[property] = value.methodize();
    }
  }

  function findDOMClass(tagName) {
    var klass;
    var trans = {
      "OPTGROUP": "OptGroup", "TEXTAREA": "TextArea", "P": "Paragraph",
      "FIELDSET": "FieldSet", "UL": "UList", "OL": "OList", "DL": "DList",
      "DIR": "Directory", "H1": "Heading", "H2": "Heading", "H3": "Heading",
      "H4": "Heading", "H5": "Heading", "H6": "Heading", "Q": "Quote",
      "INS": "Mod", "DEL": "Mod", "A": "Anchor", "IMG": "Image", "CAPTION":
      "TableCaption", "COL": "TableCol", "COLGROUP": "TableCol", "THEAD":
      "TableSection", "TFOOT": "TableSection", "TBODY": "TableSection", "TR":
      "TableRow", "TH": "TableCell", "TD": "TableCell", "FRAMESET":
      "FrameSet", "IFRAME": "IFrame"
    };
    if (trans[tagName]) klass = 'HTML' + trans[tagName] + 'Element';
    if (window[klass]) return window[klass];
    klass = 'HTML' + tagName + 'Element';
    if (window[klass]) return window[klass];
    klass = 'HTML' + tagName.capitalize() + 'Element';
    if (window[klass]) return window[klass];

    window[klass] = { };
    window[klass].prototype = document.createElement(tagName).__proto__;
    return window[klass];
  }

  if (F.ElementExtensions) {
    copy(Element.Methods, HTMLElement.prototype);
    copy(Element.Methods.Simulated, HTMLElement.prototype, true);
  }

  if (F.SpecificElementExtensions) {
    for (var tag in Element.Methods.ByTag) {
      var klass = findDOMClass(tag);
      if (Object.isUndefined(klass)) continue;
      copy(T[tag], klass.prototype);
    }
  }

  Object.extend(Element, Element.Methods);
  delete Element.ByTag;

  if (Element.extend.refresh) Element.extend.refresh();
  Element.cache = { };
};

document.viewport = {
  getDimensions: function() {
    var dimensions = { };
    $w('width height').each(function(d) {
      var D = d.capitalize();
      dimensions[d] = self['inner' + D] ||
       (document.documentElement['client' + D] || document.body['client' + D]);
    });
    return dimensions;
  },

  getWidth: function() {
    return this.getDimensions().width;
  },

  getHeight: function() {
    return this.getDimensions().height;
  },

  getScrollOffsets: function() {
    return Element._returnOffset(
      window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft,
      window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop);
  }
};
/* Portions of the Selector class are derived from Jack Slocum’s DomQuery,
 * part of YUI-Ext version 0.40, distributed under the terms of an MIT-style
 * license.  Please see http://www.yui-ext.com/ for more information. */

var Selector = Class.create({
  initialize: function(expression) {
    this.expression = expression.strip();
    this.compileMatcher();
  },

  compileMatcher: function() {
    // Selectors with namespaced attributes can't use the XPath version
    if (Prototype.BrowserFeatures.XPath && !(/(\[[\w-]*?:|:checked)/).test(this.expression))
      return this.compileXPathMatcher();

    var e = this.expression, ps = Selector.patterns, h = Selector.handlers,
        c = Selector.criteria, le, p, m;

    if (Selector._cache[e]) {
      this.matcher = Selector._cache[e];
      return;
    }

    this.matcher = ["this.matcher = function(root) {",
                    "var r = root, h = Selector.handlers, c = false, n;"];

    while (e && le != e && (/\S/).test(e)) {
      le = e;
      for (var i in ps) {
        p = ps[i];
        if (m = e.match(p)) {
          this.matcher.push(Object.isFunction(c[i]) ? c[i](m) :
    	      new Template(c[i]).evaluate(m));
          e = e.replace(m[0], '');
          break;
        }
      }
    }

    this.matcher.push("return h.unique(n);\n}");
    eval(this.matcher.join('\n'));
    Selector._cache[this.expression] = this.matcher;
  },

  compileXPathMatcher: function() {
    var e = this.expression, ps = Selector.patterns,
        x = Selector.xpath, le, m;

    if (Selector._cache[e]) {
      this.xpath = Selector._cache[e]; return;
    }

    this.matcher = ['.//*'];
    while (e && le != e && (/\S/).test(e)) {
      le = e;
      for (var i in ps) {
        if (m = e.match(ps[i])) {
          this.matcher.push(Object.isFunction(x[i]) ? x[i](m) :
            new Template(x[i]).evaluate(m));
          e = e.replace(m[0], '');
          break;
        }
      }
    }

    this.xpath = this.matcher.join('');
    Selector._cache[this.expression] = this.xpath;
  },

  findElements: function(root) {
    root = root || document;
    if (this.xpath) return document._getElementsByXPath(this.xpath, root);
    return this.matcher(root);
  },

  match: function(element) {
    this.tokens = [];

    var e = this.expression, ps = Selector.patterns, as = Selector.assertions;
    var le, p, m;

    while (e && le !== e && (/\S/).test(e)) {
      le = e;
      for (var i in ps) {
        p = ps[i];
        if (m = e.match(p)) {
          // use the Selector.assertions methods unless the selector
          // is too complex.
          if (as[i]) {
            this.tokens.push([i, Object.clone(m)]);
            e = e.replace(m[0], '');
          } else {
            // reluctantly do a document-wide search
            // and look for a match in the array
            return this.findElements(document).include(element);
          }
        }
      }
    }

    var match = true, name, matches;
    for (var i = 0, token; token = this.tokens[i]; i++) {
      name = token[0], matches = token[1];
      if (!Selector.assertions[name](element, matches)) {
        match = false; break;
      }
    }

    return match;
  },

  toString: function() {
    return this.expression;
  },

  inspect: function() {
    return "#<Selector:" + this.expression.inspect() + ">";
  }
});

Object.extend(Selector, {
  _cache: { },

  xpath: {
    descendant:   "//*",
    child:        "/*",
    adjacent:     "/following-sibling::*[1]",
    laterSibling: '/following-sibling::*',
    tagName:      function(m) {
      if (m[1] == '*') return '';
      return "[local-name()='" + m[1].toLowerCase() +
             "' or local-name()='" + m[1].toUpperCase() + "']";
    },
    className:    "[contains(concat(' ', @class, ' '), ' #{1} ')]",
    id:           "[@id='#{1}']",
    attrPresence: "[@#{1}]",
    attr: function(m) {
      m[3] = m[5] || m[6];
      return new Template(Selector.xpath.operators[m[2]]).evaluate(m);
    },
    pseudo: function(m) {
      var h = Selector.xpath.pseudos[m[1]];
      if (!h) return '';
      if (Object.isFunction(h)) return h(m);
      return new Template(Selector.xpath.pseudos[m[1]]).evaluate(m);
    },
    operators: {
      '=':  "[@#{1}='#{3}']",
      '!=': "[@#{1}!='#{3}']",
      '^=': "[starts-with(@#{1}, '#{3}')]",
      '$=': "[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']",
      '*=': "[contains(@#{1}, '#{3}')]",
      '~=': "[contains(concat(' ', @#{1}, ' '), ' #{3} ')]",
      '|=': "[contains(concat('-', @#{1}, '-'), '-#{3}-')]"
    },
    pseudos: {
      'first-child': '[not(preceding-sibling::*)]',
      'last-child':  '[not(following-sibling::*)]',
      'only-child':  '[not(preceding-sibling::* or following-sibling::*)]',
      'empty':       "[count(*) = 0 and (count(text()) = 0 or translate(text(), ' \t\r\n', '') = '')]",
      'checked':     "[@checked]",
      'disabled':    "[@disabled]",
      'enabled':     "[not(@disabled)]",
      'not': function(m) {
        var e = m[6], p = Selector.patterns,
            x = Selector.xpath, le, m, v;

        var exclusion = [];
        while (e && le != e && (/\S/).test(e)) {
          le = e;
          for (var i in p) {
            if (m = e.match(p[i])) {
              v = Object.isFunction(x[i]) ? x[i](m) : new Template(x[i]).evaluate(m);
              exclusion.push("(" + v.substring(1, v.length - 1) + ")");
              e = e.replace(m[0], '');
              break;
            }
          }
        }
        return "[not(" + exclusion.join(" and ") + ")]";
      },
      'nth-child':      function(m) {
        return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ", m);
      },
      'nth-last-child': function(m) {
        return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ", m);
      },
      'nth-of-type':    function(m) {
        return Selector.xpath.pseudos.nth("position() ", m);
      },
      'nth-last-of-type': function(m) {
        return Selector.xpath.pseudos.nth("(last() + 1 - position()) ", m);
      },
      'first-of-type':  function(m) {
        m[6] = "1"; return Selector.xpath.pseudos['nth-of-type'](m);
      },
      'last-of-type':   function(m) {
        m[6] = "1"; return Selector.xpath.pseudos['nth-last-of-type'](m);
      },
      'only-of-type':   function(m) {
        var p = Selector.xpath.pseudos; return p['first-of-type'](m) + p['last-of-type'](m);
      },
      nth: function(fragment, m) {
        var mm, formula = m[6], predicate;
        if (formula == 'even') formula = '2n+0';
        if (formula == 'odd')  formula = '2n+1';
        if (mm = formula.match(/^(\d+)$/)) // digit only
          return '[' + fragment + "= " + mm[1] + ']';
        if (mm = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
          if (mm[1] == "-") mm[1] = -1;
          var a = mm[1] ? Number(mm[1]) : 1;
          var b = mm[2] ? Number(mm[2]) : 0;
          predicate = "[((#{fragment} - #{b}) mod #{a} = 0) and " +
          "((#{fragment} - #{b}) div #{a} >= 0)]";
          return new Template(predicate).evaluate({
            fragment: fragment, a: a, b: b });
        }
      }
    }
  },

  criteria: {
    tagName:      'n = h.tagName(n, r, "#{1}", c);   c = false;',
    className:    'n = h.className(n, r, "#{1}", c); c = false;',
    id:           'n = h.id(n, r, "#{1}", c);        c = false;',
    attrPresence: 'n = h.attrPresence(n, r, "#{1}"); c = false;',
    attr: function(m) {
      m[3] = (m[5] || m[6]);
      return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}"); c = false;').evaluate(m);
    },
    pseudo: function(m) {
      if (m[6]) m[6] = m[6].replace(/"/g, '\\"');
      return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(m);
    },
    descendant:   'c = "descendant";',
    child:        'c = "child";',
    adjacent:     'c = "adjacent";',
    laterSibling: 'c = "laterSibling";'
  },

  patterns: {
    // combinators must be listed first
    // (and descendant needs to be last combinator)
    laterSibling: /^\s*~\s*/,
    child:        /^\s*>\s*/,
    adjacent:     /^\s*\+\s*/,
    descendant:   /^\s/,

    // selectors follow
    tagName:      /^\s*(\*|[\w\-]+)(\b|$)?/,
    id:           /^#([\w\-\*]+)(\b|$)/,
    className:    /^\.([\w\-\*]+)(\b|$)/,
    pseudo:       /^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|(?=\s)|(?=:))/,
    attrPresence: /^\[([\w]+)\]/,
    attr:         /\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\4]*?)\4|([^'"][^\]]*?)))?\]/
  },

  // for Selector.match and Element#match
  assertions: {
    tagName: function(element, matches) {
      return matches[1].toUpperCase() == element.tagName.toUpperCase();
    },

    className: function(element, matches) {
      return Element.hasClassName(element, matches[1]);
    },

    id: function(element, matches) {
      return element.id === matches[1];
    },

    attrPresence: function(element, matches) {
      return Element.hasAttribute(element, matches[1]);
    },

    attr: function(element, matches) {
      var nodeValue = Element.readAttribute(element, matches[1]);
      return Selector.operators[matches[2]](nodeValue, matches[3]);
    }
  },

  handlers: {
    // UTILITY FUNCTIONS
    // joins two collections
    concat: function(a, b) {
      for (var i = 0, node; node = b[i]; i++)
        a.push(node);
      return a;
    },

    // marks an array of nodes for counting
    mark: function(nodes) {
      for (var i = 0, node; node = nodes[i]; i++)
        node._counted = true;
      return nodes;
    },

    unmark: function(nodes) {
      for (var i = 0, node; node = nodes[i]; i++)
        node._counted = undefined;
      return nodes;
    },

    // mark each child node with its position (for nth calls)
    // "ofType" flag indicates whether we're indexing for nth-of-type
    // rather than nth-child
    index: function(parentNode, reverse, ofType) {
      parentNode._counted = true;
      if (reverse) {
        for (var nodes = parentNode.childNodes, i = nodes.length - 1, j = 1; i >= 0; i--) {
          var node = nodes[i];
          if (node.nodeType == 1 && (!ofType || node._counted)) node.nodeIndex = j++;
        }
      } else {
        for (var i = 0, j = 1, nodes = parentNode.childNodes; node = nodes[i]; i++)
          if (node.nodeType == 1 && (!ofType || node._counted)) node.nodeIndex = j++;
      }
    },

    // filters out duplicates and extends all nodes
    unique: function(nodes) {
      if (nodes.length == 0) return nodes;
      var results = [], n;
      for (var i = 0, l = nodes.length; i < l; i++)
        if (!(n = nodes[i])._counted) {
          n._counted = true;
          results.push(Element.extend(n));
        }
      return Selector.handlers.unmark(results);
    },

    // COMBINATOR FUNCTIONS
    descendant: function(nodes) {
      var h = Selector.handlers;
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        h.concat(results, node.getElementsByTagName('*'));
      return results;
    },

    child: function(nodes) {
      var h = Selector.handlers;
      for (var i = 0, results = [], node; node = nodes[i]; i++) {
        for (var j = 0, children = [], child; child = node.childNodes[j]; j++)
          if (child.nodeType == 1 && child.tagName != '!') results.push(child);
      }
      return results;
    },

    adjacent: function(nodes) {
      for (var i = 0, results = [], node; node = nodes[i]; i++) {
        var next = this.nextElementSibling(node);
        if (next) results.push(next);
      }
      return results;
    },

    laterSibling: function(nodes) {
      var h = Selector.handlers;
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        h.concat(results, Element.nextSiblings(node));
      return results;
    },

    nextElementSibling: function(node) {
      while (node = node.nextSibling)
	      if (node.nodeType == 1) return node;
      return null;
    },

    previousElementSibling: function(node) {
      while (node = node.previousSibling)
        if (node.nodeType == 1) return node;
      return null;
    },

    // TOKEN FUNCTIONS
    tagName: function(nodes, root, tagName, combinator) {
      tagName = tagName.toUpperCase();
      var results = [], h = Selector.handlers;
      if (nodes) {
        if (combinator) {
          // fastlane for ordinary descendant combinators
          if (combinator == "descendant") {
            for (var i = 0, node; node = nodes[i]; i++)
              h.concat(results, node.getElementsByTagName(tagName));
            return results;
          } else nodes = this[combinator](nodes);
          if (tagName == "*") return nodes;
        }
        for (var i = 0, node; node = nodes[i]; i++)
          if (node.tagName.toUpperCase() == tagName) results.push(node);
        return results;
      } else return root.getElementsByTagName(tagName);
    },

    id: function(nodes, root, id, combinator) {
      var targetNode = $(id), h = Selector.handlers;
      if (!targetNode) return [];
      if (!nodes && root == document) return [targetNode];
      if (nodes) {
        if (combinator) {
          if (combinator == 'child') {
            for (var i = 0, node; node = nodes[i]; i++)
              if (targetNode.parentNode == node) return [targetNode];
          } else if (combinator == 'descendant') {
            for (var i = 0, node; node = nodes[i]; i++)
              if (Element.descendantOf(targetNode, node)) return [targetNode];
          } else if (combinator == 'adjacent') {
            for (var i = 0, node; node = nodes[i]; i++)
              if (Selector.handlers.previousElementSibling(targetNode) == node)
                return [targetNode];
          } else nodes = h[combinator](nodes);
        }
        for (var i = 0, node; node = nodes[i]; i++)
          if (node == targetNode) return [targetNode];
        return [];
      }
      return (targetNode && Element.descendantOf(targetNode, root)) ? [targetNode] : [];
    },

    className: function(nodes, root, className, combinator) {
      if (nodes && combinator) nodes = this[combinator](nodes);
      return Selector.handlers.byClassName(nodes, root, className);
    },

    byClassName: function(nodes, root, className) {
      if (!nodes) nodes = Selector.handlers.descendant([root]);
      var needle = ' ' + className + ' ';
      for (var i = 0, results = [], node, nodeClassName; node = nodes[i]; i++) {
        nodeClassName = node.className;
        if (nodeClassName.length == 0) continue;
        if (nodeClassName == className || (' ' + nodeClassName + ' ').include(needle))
          results.push(node);
      }
      return results;
    },

    attrPresence: function(nodes, root, attr) {
      if (!nodes) nodes = root.getElementsByTagName("*");
      var results = [];
      for (var i = 0, node; node = nodes[i]; i++)
        if (Element.hasAttribute(node, attr)) results.push(node);
      return results;
    },

    attr: function(nodes, root, attr, value, operator) {
      if (!nodes) nodes = root.getElementsByTagName("*");
      var handler = Selector.operators[operator], results = [];
      for (var i = 0, node; node = nodes[i]; i++) {
        var nodeValue = Element.readAttribute(node, attr);
        if (nodeValue === null) continue;
        if (handler(nodeValue, value)) results.push(node);
      }
      return results;
    },

    pseudo: function(nodes, name, value, root, combinator) {
      if (nodes && combinator) nodes = this[combinator](nodes);
      if (!nodes) nodes = root.getElementsByTagName("*");
      return Selector.pseudos[name](nodes, value, root);
    }
  },

  pseudos: {
    'first-child': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++) {
        if (Selector.handlers.previousElementSibling(node)) continue;
          results.push(node);
      }
      return results;
    },
    'last-child': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++) {
        if (Selector.handlers.nextElementSibling(node)) continue;
          results.push(node);
      }
      return results;
    },
    'only-child': function(nodes, value, root) {
      var h = Selector.handlers;
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        if (!h.previousElementSibling(node) && !h.nextElementSibling(node))
          results.push(node);
      return results;
    },
    'nth-child':        function(nodes, formula, root) {
      return Selector.pseudos.nth(nodes, formula, root);
    },
    'nth-last-child':   function(nodes, formula, root) {
      return Selector.pseudos.nth(nodes, formula, root, true);
    },
    'nth-of-type':      function(nodes, formula, root) {
      return Selector.pseudos.nth(nodes, formula, root, false, true);
    },
    'nth-last-of-type': function(nodes, formula, root) {
      return Selector.pseudos.nth(nodes, formula, root, true, true);
    },
    'first-of-type':    function(nodes, formula, root) {
      return Selector.pseudos.nth(nodes, "1", root, false, true);
    },
    'last-of-type':     function(nodes, formula, root) {
      return Selector.pseudos.nth(nodes, "1", root, true, true);
    },
    'only-of-type':     function(nodes, formula, root) {
      var p = Selector.pseudos;
      return p['last-of-type'](p['first-of-type'](nodes, formula, root), formula, root);
    },

    // handles the an+b logic
    getIndices: function(a, b, total) {
      if (a == 0) return b > 0 ? [b] : [];
      return $R(1, total).inject([], function(memo, i) {
        if (0 == (i - b) % a && (i - b) / a >= 0) memo.push(i);
        return memo;
      });
    },

    // handles nth(-last)-child, nth(-last)-of-type, and (first|last)-of-type
    nth: function(nodes, formula, root, reverse, ofType) {
      if (nodes.length == 0) return [];
      if (formula == 'even') formula = '2n+0';
      if (formula == 'odd')  formula = '2n+1';
      var h = Selector.handlers, results = [], indexed = [], m;
      h.mark(nodes);
      for (var i = 0, node; node = nodes[i]; i++) {
        if (!node.parentNode._counted) {
          h.index(node.parentNode, reverse, ofType);
          indexed.push(node.parentNode);
        }
      }
      if (formula.match(/^\d+$/)) { // just a number
        formula = Number(formula);
        for (var i = 0, node; node = nodes[i]; i++)
          if (node.nodeIndex == formula) results.push(node);
      } else if (m = formula.match(/^(-?\d*)?n(([+-])(\d+))?/)) { // an+b
        if (m[1] == "-") m[1] = -1;
        var a = m[1] ? Number(m[1]) : 1;
        var b = m[2] ? Number(m[2]) : 0;
        var indices = Selector.pseudos.getIndices(a, b, nodes.length);
        for (var i = 0, node, l = indices.length; node = nodes[i]; i++) {
          for (var j = 0; j < l; j++)
            if (node.nodeIndex == indices[j]) results.push(node);
        }
      }
      h.unmark(nodes);
      h.unmark(indexed);
      return results;
    },

    'empty': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++) {
        // IE treats comments as element nodes
        if (node.tagName == '!' || (node.firstChild && !node.innerHTML.match(/^\s*$/))) continue;
        results.push(node);
      }
      return results;
    },

    'not': function(nodes, selector, root) {
      var h = Selector.handlers, selectorType, m;
      var exclusions = new Selector(selector).findElements(root);
      h.mark(exclusions);
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        if (!node._counted) results.push(node);
      h.unmark(exclusions);
      return results;
    },

    'enabled': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        if (!node.disabled) results.push(node);
      return results;
    },

    'disabled': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        if (node.disabled) results.push(node);
      return results;
    },

    'checked': function(nodes, value, root) {
      for (var i = 0, results = [], node; node = nodes[i]; i++)
        if (node.checked) results.push(node);
      return results;
    }
  },

  operators: {
    '=':  function(nv, v) { return nv == v; },
    '!=': function(nv, v) { return nv != v; },
    '^=': function(nv, v) { return nv.startsWith(v); },
    '$=': function(nv, v) { return nv.endsWith(v); },
    '*=': function(nv, v) { return nv.include(v); },
    '~=': function(nv, v) { return (' ' + nv + ' ').include(' ' + v + ' '); },
    '|=': function(nv, v) { return ('-' + nv.toUpperCase() + '-').include('-' + v.toUpperCase() + '-'); }
  },

  matchElements: function(elements, expression) {
    var matches = new Selector(expression).findElements(), h = Selector.handlers;
    h.mark(matches);
    for (var i = 0, results = [], element; element = elements[i]; i++)
      if (element._counted) results.push(element);
    h.unmark(matches);
    return results;
  },

  findElement: function(elements, expression, index) {
    if (Object.isNumber(expression)) {
      index = expression; expression = false;
    }
    return Selector.matchElements(elements, expression || '*')[index || 0];
  },

  findChildElements: function(element, expressions) {
    var exprs = expressions.join(','), expressions = [];
    exprs.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/, function(m) {
      expressions.push(m[1].strip());
    });
    var results = [], h = Selector.handlers;
    for (var i = 0, l = expressions.length, selector; i < l; i++) {
      selector = new Selector(expressions[i].strip());
      h.concat(results, selector.findElements(element));
    }
    return (l > 1) ? h.unique(results) : results;
  }
});

function $$() {
  return Selector.findChildElements(document, $A(arguments));
}
var Form = {
  reset: function(form) {
    $(form).reset();
    return form;
  },

  serializeElements: function(elements, options) {
    if (typeof options != 'object') options = { hash: !!options };
    else if (options.hash === undefined) options.hash = true;
    var key, value, submitted = false, submit = options.submit;

    var data = elements.inject({ }, function(result, element) {
      if (!element.disabled && element.name) {
        key = element.name; value = $(element).getValue();
        if (value != null && (element.type != 'submit' || (!submitted &&
            submit !== false && (!submit || key == submit) && (submitted = true)))) {
          if (key in result) {
            // a key is already present; construct an array of values
            if (!Object.isArray(result[key])) result[key] = [result[key]];
            result[key].push(value);
          }
          else result[key] = value;
        }
      }
      return result;
    });

    return options.hash ? data : Object.toQueryString(data);
  }
};

Form.Methods = {
  serialize: function(form, options) {
    return Form.serializeElements(Form.getElements(form), options);
  },

  getElements: function(form) {
    return $A($(form).getElementsByTagName('*')).inject([],
      function(elements, child) {
        if (Form.Element.Serializers[child.tagName.toLowerCase()])
          elements.push(Element.extend(child));
        return elements;
      }
    );
  },

  getInputs: function(form, typeName, name) {
    form = $(form);
    var inputs = form.getElementsByTagName('input');

    if (!typeName && !name) return $A(inputs).map(Element.extend);

    for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) {
      var input = inputs[i];
      if ((typeName && input.type != typeName) || (name && input.name != name))
        continue;
      matchingInputs.push(Element.extend(input));
    }

    return matchingInputs;
  },

  disable: function(form) {
    form = $(form);
    Form.getElements(form).invoke('disable');
    return form;
  },

  enable: function(form) {
    form = $(form);
    Form.getElements(form).invoke('enable');
    return form;
  },

  findFirstElement: function(form) {
    var elements = $(form).getElements().findAll(function(element) {
      return 'hidden' != element.type && !element.disabled;
    });
    var firstByIndex = elements.findAll(function(element) {
      return element.hasAttribute('tabIndex') && element.tabIndex >= 0;
    }).sortBy(function(element) { return element.tabIndex }).first();

    return firstByIndex ? firstByIndex : elements.find(function(element) {
      return ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
    });
  },

  focusFirstElement: function(form) {
    form = $(form);
    form.findFirstElement().activate();
    return form;
  },

  request: function(form, options) {
    form = $(form), options = Object.clone(options || { });

    var params = options.parameters, action = form.readAttribute('action') || '';
    if (action.blank()) action = window.location.href;
    options.parameters = form.serialize(true);

    if (params) {
      if (Object.isString(params)) params = params.toQueryParams();
      Object.extend(options.parameters, params);
    }

    if (form.hasAttribute('method') && !options.method)
      options.method = form.method;

    return new Ajax.Request(action, options);
  }
};

/*--------------------------------------------------------------------------*/

Form.Element = {
  focus: function(element) {
    $(element).focus();
    return element;
  },

  select: function(element) {
    $(element).select();
    return element;
  }
};

Form.Element.Methods = {
  serialize: function(element) {
    element = $(element);
    if (!element.disabled && element.name) {
      var value = element.getValue();
      if (value != undefined) {
        var pair = { };
        pair[element.name] = value;
        return Object.toQueryString(pair);
      }
    }
    return '';
  },

  getValue: function(element) {
    element = $(element);
    var method = element.tagName.toLowerCase();
    return Form.Element.Serializers[method](element);
  },

  setValue: function(element, value) {
    element = $(element);
    var method = element.tagName.toLowerCase();
    Form.Element.Serializers[method](element, value);
    return element;
  },

  clear: function(element) {
    $(element).value = '';
    return element;
  },

  present: function(element) {
    return $(element).value != '';
  },

  activate: function(element) {
    element = $(element);
    try {
      element.focus();
      if (element.select && (element.tagName.toLowerCase() != 'input' ||
          !['button', 'reset', 'submit'].include(element.type)))
        element.select();
    } catch (e) { }
    return element;
  },

  disable: function(element) {
    element = $(element);
    element.blur();
    element.disabled = true;
    return element;
  },

  enable: function(element) {
    element = $(element);
    element.disabled = false;
    return element;
  }
};

/*--------------------------------------------------------------------------*/

var Field = Form.Element;
var $F = Form.Element.Methods.getValue;

/*--------------------------------------------------------------------------*/

Form.Element.Serializers = {
  input: function(element, value) {
    switch (element.type.toLowerCase()) {
      case 'checkbox':
      case 'radio':
        return Form.Element.Serializers.inputSelector(element, value);
      default:
        return Form.Element.Serializers.textarea(element, value);
    }
  },

  inputSelector: function(element, value) {
    if (value === undefined) return element.checked ? element.value : null;
    else element.checked = !!value;
  },

  textarea: function(element, value) {
    if (value === undefined) return element.value;
    else element.value = value;
  },

  select: function(element, index) {
    if (index === undefined)
      return this[element.type == 'select-one' ?
        'selectOne' : 'selectMany'](element);
    else {
      var opt, value, single = !Object.isArray(index);
      for (var i = 0, length = element.length; i < length; i++) {
        opt = element.options[i];
        value = this.optionValue(opt);
        if (single) {
          if (value == index) {
            opt.selected = true;
            return;
          }
        }
        else opt.selected = index.include(value);
      }
    }
  },

  selectOne: function(element) {
    var index = element.selectedIndex;
    return index >= 0 ? this.optionValue(element.options[index]) : null;
  },

  selectMany: function(element) {
    var values, length = element.length;
    if (!length) return null;

    for (var i = 0, values = []; i < length; i++) {
      var opt = element.options[i];
      if (opt.selected) values.push(this.optionValue(opt));
    }
    return values;
  },

  optionValue: function(opt) {
    // extend element because hasAttribute may not be native
    return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text;
  }
};

/*--------------------------------------------------------------------------*/

Abstract.TimedObserver = Class.create(PeriodicalExecuter, {
  initialize: function($super, element, frequency, callback) {
    $super(callback, frequency);
    this.element   = $(element);
    this.lastValue = this.getValue();
  },

  execute: function() {
    var value = this.getValue();
    if (Object.isString(this.lastValue) && Object.isString(value) ?
        this.lastValue != value : String(this.lastValue) != String(value)) {
      this.callback(this.element, value);
      this.lastValue = value;
    }
  }
});

Form.Element.Observer = Class.create(Abstract.TimedObserver, {
  getValue: function() {
    return Form.Element.getValue(this.element);
  }
});

Form.Observer = Class.create(Abstract.TimedObserver, {
  getValue: function() {
    return Form.serialize(this.element);
  }
});

/*--------------------------------------------------------------------------*/

Abstract.EventObserver = Class.create({
  initialize: function(element, callback) {
    this.element  = $(element);
    this.callback = callback;

    this.lastValue = this.getValue();
    if (this.element.tagName.toLowerCase() == 'form')
      this.registerFormCallbacks();
    else
      this.registerCallback(this.element);
  },

  onElementEvent: function() {
    var value = this.getValue();
    if (this.lastValue != value) {
      this.callback(this.element, value);
      this.lastValue = value;
    }
  },

  registerFormCallbacks: function() {
    Form.getElements(this.element).each(this.registerCallback, this);
  },

  registerCallback: function(element) {
    if (element.type) {
      switch (element.type.toLowerCase()) {
        case 'checkbox':
        case 'radio':
          Event.observe(element, 'click', this.onElementEvent.bind(this));
          break;
        default:
          Event.observe(element, 'change', this.onElementEvent.bind(this));
          break;
      }
    }
  }
});

Form.Element.EventObserver = Class.create(Abstract.EventObserver, {
  getValue: function() {
    return Form.Element.getValue(this.element);
  }
});

Form.EventObserver = Class.create(Abstract.EventObserver, {
  getValue: function() {
    return Form.serialize(this.element);
  }
});
if (!window.Event) var Event = { };

Object.extend(Event, {
  KEY_BACKSPACE: 8,
  KEY_TAB:       9,
  KEY_RETURN:   13,
  KEY_ESC:      27,
  KEY_LEFT:     37,
  KEY_UP:       38,
  KEY_RIGHT:    39,
  KEY_DOWN:     40,
  KEY_DELETE:   46,
  KEY_HOME:     36,
  KEY_END:      35,
  KEY_PAGEUP:   33,
  KEY_PAGEDOWN: 34,
  KEY_INSERT:   45,

  cache: { },

  relatedTarget: function(event) {
    var element;
    switch(event.type) {
      case 'mouseover': element = event.fromElement; break;
      case 'mouseout':  element = event.toElement;   break;
      default: return null;
    }
    return Element.extend(element);
  }
});

Event.Methods = (function() {
  var isButton;

  if (Prototype.Browser.IE) {
    var buttonMap = { 0: 1, 1: 4, 2: 2 };
    isButton = function(event, code) {
      return event.button == buttonMap[code];
    };

  } else if (Prototype.Browser.WebKit) {
    isButton = function(event, code) {
      switch (code) {
        case 0: return event.which == 1 && !event.metaKey;
        case 1: return event.which == 1 && event.metaKey;
        default: return false;
      }
    };

  } else {
    isButton = function(event, code) {
      return event.which ? (event.which === code + 1) : (event.button === code);
    };
  }

  return {
    isLeftClick:   function(event) { return isButton(event, 0) },
    isMiddleClick: function(event) { return isButton(event, 1) },
    isRightClick:  function(event) { return isButton(event, 2) },

    element: function(event) {
      var node = Event.extend(event).target;
      return Element.extend(node.nodeType == Node.TEXT_NODE ? node.parentNode : node);
    },

    findElement: function(event, expression) {
      var element = Event.element(event);
      return element.match(expression) ? element : element.up(expression);
    },

    pointer: function(event) {
      return {
        x: event.pageX || (event.clientX +
          (document.documentElement.scrollLeft || document.body.scrollLeft)),
        y: event.pageY || (event.clientY +
          (document.documentElement.scrollTop || document.body.scrollTop))
      };
    },

    pointerX: function(event) { return Event.pointer(event).x },
    pointerY: function(event) { return Event.pointer(event).y },

    stop: function(event) {
      Event.extend(event);
      event.preventDefault();
      event.stopPropagation();
      event.stopped = true;
    }
  };
})();

Event.extend = (function() {
  var methods = Object.keys(Event.Methods).inject({ }, function(m, name) {
    m[name] = Event.Methods[name].methodize();
    return m;
  });

  if (Prototype.Browser.IE) {
    Object.extend(methods, {
      stopPropagation: function() { this.cancelBubble = true },
      preventDefault:  function() { this.returnValue = false },
      inspect: function() { return "[object Event]" }
    });

    return function(event) {
      if (!event) return false;
      if (event._extendedByPrototype) return event;

      event._extendedByPrototype = Prototype.emptyFunction;
      var pointer = Event.pointer(event);
      Object.extend(event, {
        target: event.srcElement,
        relatedTarget: Event.relatedTarget(event),
        pageX:  pointer.x,
        pageY:  pointer.y
      });
      return Object.extend(event, methods);
    };

  } else {
    Event.prototype = Event.prototype || document.createEvent("HTMLEvents").__proto__;
    Object.extend(Event.prototype, methods);
    return Prototype.K;
  }
})();

Object.extend(Event, (function() {
  var cache = Event.cache;

  function getEventID(element) {
    if (element._eventID) return element._eventID;
    arguments.callee.id = arguments.callee.id || 1;
    return element._eventID = ++arguments.callee.id;
  }

  function getDOMEventName(eventName) {
    if (eventName && eventName.include(':')) return "dataavailable";
    return eventName;
  }

  function getCacheForID(id) {
    return cache[id] = cache[id] || { };
  }

  function getWrappersForEventName(id, eventName) {
    var c = getCacheForID(id);
    return c[eventName] = c[eventName] || [];
  }

  function createWrapper(element, eventName, handler) {
    var id = getEventID(element);
    var c = getWrappersForEventName(id, eventName);
    if (c.pluck("handler").include(handler)) return false;

    var wrapper = function(event) {
      if (!Event || !Event.extend ||
        (event.eventName && event.eventName != eventName))
          return false;

      Event.extend(event);
      handler.call(element, event)
    };

    wrapper.handler = handler;
    c.push(wrapper);
    return wrapper;
  }

  function findWrapper(id, eventName, handler) {
    var c = getWrappersForEventName(id, eventName);
    return c.find(function(wrapper) { return wrapper.handler == handler });
  }

  function destroyWrapper(id, eventName, handler) {
    var c = getCacheForID(id);
    if (!c[eventName]) return false;
    c[eventName] = c[eventName].without(findWrapper(id, eventName, handler));
  }

  function destroyCache() {
    for (var id in cache)
      for (var eventName in cache[id])
        cache[id][eventName] = null;
  }

  if (window.attachEvent) {
    window.attachEvent("onunload", destroyCache);
  }

  return {
    observe: function(element, eventName, handler) {
      element = $(element);
      var name = getDOMEventName(eventName);

      var wrapper = createWrapper(element, eventName, handler);
      if (!wrapper) return element;

      if (element.addEventListener) {
        element.addEventListener(name, wrapper, false);
      } else {
        element.attachEvent("on" + name, wrapper);
      }

      return element;
    },

    stopObserving: function(element, eventName, handler) {
      element = $(element);
      var id = getEventID(element), name = getDOMEventName(eventName);

      if (!handler && eventName) {
        getWrappersForEventName(id, eventName).each(function(wrapper) {
          element.stopObserving(eventName, wrapper.handler);
        });
        return element;

      } else if (!eventName) {
        Object.keys(getCacheForID(id)).each(function(eventName) {
          element.stopObserving(eventName);
        });
        return element;
      }

      var wrapper = findWrapper(id, eventName, handler);
      if (!wrapper) return element;

      if (element.removeEventListener) {
        element.removeEventListener(name, wrapper, false);
      } else {
        element.detachEvent("on" + name, wrapper);
      }

      destroyWrapper(id, eventName, handler);

      return element;
    },

    fire: function(element, eventName, memo) {
      element = $(element);
      if (element == document && document.createEvent && !element.dispatchEvent)
        element = document.documentElement;

      if (document.createEvent) {
        var event = document.createEvent("HTMLEvents");
        event.initEvent("dataavailable", true, true);
      } else {
        var event = document.createEventObject();
        event.eventType = "ondataavailable";
      }

      event.eventName = eventName;
      event.memo = memo || { };

      if (document.createEvent) {
        element.dispatchEvent(event);
      } else {
        element.fireEvent(event.eventType, event);
      }

      return event;
    }
  };
})());

Object.extend(Event, Event.Methods);

Element.addMethods({
  fire:          Event.fire,
  observe:       Event.observe,
  stopObserving: Event.stopObserving
});

Object.extend(document, {
  fire:          Element.Methods.fire.methodize(),
  observe:       Element.Methods.observe.methodize(),
  stopObserving: Element.Methods.stopObserving.methodize()
});

(function() {
  /* Support for the DOMContentLoaded event is based on work by Dan Webb,
     Matthias Miller, Dean Edwards and John Resig. */

  var timer, fired = false;

  function fireContentLoadedEvent() {
    if (fired) return;
    if (timer) window.clearInterval(timer);
    document.fire("dom:loaded");
    fired = true;
  }

  if (document.addEventListener) {
    if (Prototype.Browser.WebKit) {
      timer = window.setInterval(function() {
        if (/loaded|complete/.test(document.readyState))
          fireContentLoadedEvent();
      }, 0);

      Event.observe(window, "load", fireContentLoadedEvent);

    } else {
      document.addEventListener("DOMContentLoaded",
        fireContentLoadedEvent, false);
    }

  } else {
    document.write("<script id=__onDOMContentLoaded defer src=//:><\/script>");
    $("__onDOMContentLoaded").onreadystatechange = function() {
      if (this.readyState == "complete") {
        this.onreadystatechange = null;
        fireContentLoadedEvent();
      }
    };
  }
})();
/*------------------------------- DEPRECATED -------------------------------*/

Hash.toQueryString = Object.toQueryString;

var Toggle = { display: Element.toggle };

Element.Methods.childOf = Element.Methods.descendantOf;

var Insertion = {
  Before: function(element, content) {
    return Element.insert(element, {before:content});
  },

  Top: function(element, content) {
    return Element.insert(element, {top:content});
  },

  Bottom: function(element, content) {
    return Element.insert(element, {bottom:content});
  },

  After: function(element, content) {
    return Element.insert(element, {after:content});
  }
};

var $continue = new Error('"throw $continue" is deprecated, use "return" instead');

// This should be moved to script.aculo.us; notice the deprecated methods
// further below, that map to the newer Element methods.
var Position = {
  // set to true if needed, warning: firefox performance problems
  // NOT neeeded for page scrolling, only if draggable contained in
  // scrollable elements
  includeScrollOffsets: false,

  // must be called before calling withinIncludingScrolloffset, every time the
  // page is scrolled
  prepare: function() {
    this.deltaX =  window.pageXOffset
                || document.documentElement.scrollLeft
                || document.body.scrollLeft
                || 0;
    this.deltaY =  window.pageYOffset
                || document.documentElement.scrollTop
                || document.body.scrollTop
                || 0;
  },

  // caches x/y coordinate pair to use with overlap
  within: function(element, x, y) {
    if (this.includeScrollOffsets)
      return this.withinIncludingScrolloffsets(element, x, y);
    this.xcomp = x;
    this.ycomp = y;
    this.offset = Element.cumulativeOffset(element);

    return (y >= this.offset[1] &&
            y <  this.offset[1] + element.offsetHeight &&
            x >= this.offset[0] &&
            x <  this.offset[0] + element.offsetWidth);
  },

  withinIncludingScrolloffsets: function(element, x, y) {
    var offsetcache = Element.cumulativeScrollOffset(element);

    this.xcomp = x + offsetcache[0] - this.deltaX;
    this.ycomp = y + offsetcache[1] - this.deltaY;
    this.offset = Element.cumulativeOffset(element);

    return (this.ycomp >= this.offset[1] &&
            this.ycomp <  this.offset[1] + element.offsetHeight &&
            this.xcomp >= this.offset[0] &&
            this.xcomp <  this.offset[0] + element.offsetWidth);
  },

  // within must be called directly before
  overlap: function(mode, element) {
    if (!mode) return 0;
    if (mode == 'vertical')
      return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
        element.offsetHeight;
    if (mode == 'horizontal')
      return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
        element.offsetWidth;
  },

  // Deprecation layer -- use newer Element methods now (1.5.2).

  cumulativeOffset: Element.Methods.cumulativeOffset,

  positionedOffset: Element.Methods.positionedOffset,

  absolutize: function(element) {
    Position.prepare();
    return Element.absolutize(element);
  },

  relativize: function(element) {
    Position.prepare();
    return Element.relativize(element);
  },

  realOffset: Element.Methods.cumulativeScrollOffset,

  offsetParent: Element.Methods.getOffsetParent,

  page: Element.Methods.viewportOffset,

  clone: function(source, target, options) {
    options = options || { };
    return Element.clonePosition(target, source, options);
  }
};

/*--------------------------------------------------------------------------*/

if (!document.getElementsByClassName) document.getElementsByClassName = function(instanceMethods){
  function iter(name) {
    return name.blank() ? null : "[contains(concat(' ', @class, ' '), ' " + name + " ')]";
  }

  instanceMethods.getElementsByClassName = Prototype.BrowserFeatures.XPath ?
  function(element, className) {
    className = className.toString().strip();
    var cond = /\s/.test(className) ? $w(className).map(iter).join('') : iter(className);
    return cond ? document._getElementsByXPath('.//*' + cond, element) : [];
  } : function(element, className) {
    className = className.toString().strip();
    var elements = [], classNames = (/\s/.test(className) ? $w(className) : null);
    if (!classNames && !className) return elements;

    var nodes = $(element).getElementsByTagName('*');
    className = ' ' + className + ' ';

    for (var i = 0, child, cn; child = nodes[i]; i++) {
      if (child.className && (cn = ' ' + child.className + ' ') && (cn.include(className) ||
          (classNames && classNames.all(function(name) {
            return !name.toString().blank() && cn.include(' ' + name + ' ');
          }))))
        elements.push(Element.extend(child));
    }
    return elements;
  };

  return function(className, parentElement) {
    return $(parentElement || document.body).getElementsByClassName(className);
  };
}(Element.Methods);

/*--------------------------------------------------------------------------*/

Element.ClassNames = Class.create();
Element.ClassNames.prototype = {
  initialize: function(element) {
    this.element = $(element);
  },

  _each: function(iterator) {
    this.element.className.split(/\s+/).select(function(name) {
      return name.length > 0;
    })._each(iterator);
  },

  set: function(className) {
    this.element.className = className;
  },

  add: function(classNameToAdd) {
    if (this.include(classNameToAdd)) return;
    this.set($A(this).concat(classNameToAdd).join(' '));
  },

  remove: function(classNameToRemove) {
    if (!this.include(classNameToRemove)) return;
    this.set($A(this).without(classNameToRemove).join(' '));
  },

  toString: function() {
    return $A(this).join(' ');
  }
};

Object.extend(Element.ClassNames.prototype, Enumerable);

/*--------------------------------------------------------------------------*/

Element.addMethods();

document.iframeLoaders = {};

iframe = function() { this.initialize.apply(this, arguments); };
iframe.prototype = {
	initialize: function(form, options,count){
		if (!options) options = {};
		this.form = form;
		this.uniqueId = count;
		document.iframeLoaders[this.uniqueId] = this;
		var url = form.action + '?jsonRequest=' + escape(form.elements[0].value); // change form submit to string; similar to changing form method to get
		var firstSlash = url.indexOf("/", url.indexOf("//")+2);
		this.transport = this.getTransport((firstSlash > 0) ? url.substring(0, firstSlash) : "");
		this.onComplete = options.onComplete || null;
		this.update = this.$(options.update) || null;
		this.updateMultiple = options.multiple || false;
		if (((navigator.vendor && (navigator.vendor.indexOf('Apple')) > -1) || window.opera) // safari and opera only
     && (/\/Direct\/Process(\?|$)/.test(form.action)) && form.elements && (form.elements.length == 1)) { // only change calls that contain 1 element and whose actions end with /Direct/Process
			var doc = this.transport.contentWindow || this.transport.contentDocument; // retrieve the document of the iframe
			if (url.length < 80000) { // allow fallback to normal submission (80k is the max length for urls in safari)
				if (doc.document) // make sure we have the document and not the window
					doc = doc.document;
				
				try { // if this fails, fallback to normal submission
					doc.location.replace(url); // use location.replace to overwrite elements in history 
					return;
				} catch (e) { };
			}
		}
		form.target= 'frame_'+this.uniqueId;
		form.setAttribute("target", 'frame_'+this.uniqueId); // in case the other one fails.
		form.submit();
	},

	onStateChange: function() {
		this.transport = this.$('frame_'+this.uniqueId);
		try {	 var doc = this.transport.contentDocument.body.innerHTML; this.transport.contentDocument.close(); }	// For NS6
		catch (e){ 
			try{ var doc = this.transport.contentWindow.document.body.innerHTML; this.transport.contentWindow.document.close(); } // For IE5.5 and IE6
			 catch (e){
				 try { var doc = this.transport.document.body.innerHTML; this.transport.document.body.close(); } // for IE5
					catch (e) {
						try	{ var doc = window.frames['frame_'+this.uniqueId].document.body.innerText; } // for really nasty browsers
						catch (e) { //alert(e); 
						} // forget it.
				 }
			}
		}
		this.transport.responseText = doc;
		if (this.onComplete) setTimeout(this.bind(function(){this.onComplete(this.transport);}, this), 10);
		if (this.update) setTimeout(this.bind(function(){this.update.innerHTML = this.transport.responseText;}, this), 10);
		if (this.updateMultiple){ setTimeout(this.bind(function(){ // JSON support!
				try	{ var hasscript = false; eval("var inputObject = "+this.transport.responseText);	// we're expecting a JSON object, eval it to inputObject
					for (var i in inputObject) { if (i == 'script') { hasscript = true; } // check if we passed some javascript along too
						else {if ( elm = this.$(i)) { elm.innerHTML = inputObject[i]; } else { 
						//alert("element "+i+" not found!"); 
						} } // if it's not script, update the corresponding div
					} if (hasscript) eval(inputObject['script']); // some on-the-fly-javascript exchanging support too
				} catch (e) { //alert('There was an error processing: '+this.transport.responseText); 
				} // in case of an error					
			}, this), 10);
		}	
	},

	getTransport: function(baseUrl) {
		var divElm = document.createElement('DIV'), frame;
		divElm.setAttribute('style', 'width: 0; height: 0; margin: 0; padding: 0; visibility: hidden; overflow: hidden');
		if (navigator.userAgent.indexOf('MSIE') > 0 && navigator.userAgent.indexOf('Opera') == -1) {// switch to the crappy solution for IE
			divElm.style.width = 0;
			divElm.style.height = 0;
			divElm.style.margin = 0;
			divElm.style.padding = 0;
			divElm.style.visibility = 'hidden';
			divElm.style.overflow = 'hidden';
			divElm.innerHTML = '<iframe name=\"frame_'+this.uniqueId+'\" id=\"frame_'+this.uniqueId+'\" src=\"' + baseUrl + '/ver1.0/Content/blank.html\" onload=\"setTimeout(function(){document.iframeLoaders['+this.uniqueId+'].onStateChange()},20);"></iframe>';
		} else {
			frame = document.createElement("iframe");
			frame.setAttribute("name", "frame_"+this.uniqueId);
			frame.setAttribute("id", "frame_"+this.uniqueId);
			frame.addEventListener("load", this.bind(function(){ this.onStateChange(); }, this), false);
			divElm.appendChild(frame);
		}
    (RequestBatch.container || document.body).appendChild(divElm);
		return frame;
	},
  
  bind: function(functionObject, referenceObject) {
    return function() {
      return functionObject.apply(referenceObject, arguments);
    }
  },
  
  '$': function(id) {
    return document.getElementById(id);
  }
};


if (typeof(RequestBatch) === 'undefined') {
    RequestBatch = function() {
      this.initialize.apply(this, arguments);
    };
    // for unique id
    var counter = 0;

    // how many requests are still pending?
    var pendingRequests = 0;

    function DirectAccessErrorHandler(msg,ex){
    //alert(msg);
    }
    (function() {

        function buildJsonpUrl(serverUrl, jsonString, callbackName) {
            var separator = serverUrl.indexOf('?') == -1 ? "?" : "&";
            // use Jsonp endpoint instead of Process
            serverUrl = serverUrl.replace('/Process', '/Jsonp');
            return serverUrl + separator + "r="
			+ encodeURIComponent(jsonString)
			+ '&cb=' + callbackName
			+ '&rnd=' + Math.floor(Math.random() * 10000);
        }

        function useJsonp(serverUrl, jsonString, callbackName) {
            // use Jsonp endpoint instead of Process
            serverUrl = buildJsonpUrl(serverUrl, jsonString, callbackName);
            var isIE = /*@cc_on!@*/false;
            if ((isIE && serverUrl.length < 2083) || (!isIE && serverUrl.length < 4000)) {
                return serverUrl;
            }
            return false;
        }

        // the core object to request batches
        RequestBatch.prototype = {
            initialize: function() {
                this.UniqueId = counter++;
                this.Requests = new Array()
            },

            HasTemplate: function() {
                return typeof (this["Template"]) != "undefined";
            },

            AddToRequest: function(requestThis) {
                this.Requests[this.Requests.length] = requestThis;
            },

            BeginRequest: function(serverUrl, callback) {
                pendingRequests++;

                if (!RequestBatch.callbacks) {
                    RequestBatch.callbacks = {};
                }

                // the cc_on comment below is important.. if you remove it, it will change the processing of the script
                // see http://msdn.microsoft.com/en-us/library/8ka90k2e(VS.85).aspx for details of conditional compilation
                var jsonString = YAHOO.lang.JSON.stringify(this), ie = /*@cc_on!@*/false;
                if (ie && !RequestBatch.container) { // forcibly take this route only for ie
                    var body = document.body, div;
                    RequestBatch.container = div = body.insertBefore(document.createElement('div'), body.firstChild);
                    div.style.height = div.style.width = div.style.margin = div.style.padding = 0;
                    div.style.visibility = div.style.overflow = 'hidden';
                    div.style.display = 'none';
                }
                // generate our callback function that will call their callback function via closure semantics
                var daapiCallbackName = 'daapiCallback' + this.UniqueId;
                var thisRequest = this;
                if (jsonpServerUrl = useJsonp(serverUrl, jsonString, 'RequestBatch.callbacks.' + daapiCallbackName)) {
                    // insert script node with callback function = daapiCallbackName
                    var jsonpScriptNode = document.createElement('script');
                    jsonpScriptNode.type = "text/javascript";
                    jsonpScriptNode.src = jsonpServerUrl;
                    var headElem = document.getElementsByTagName('head')[0];
                    RequestBatch.callbacks[daapiCallbackName] = (function(userCallback, headElem, scriptNode) {
                        return function(responses) {
                            if (thisRequest.HasTemplate()) {
                                userCallback(responses);
                            } else {
                                // clean up after ourselves
                                userCallback(responses.ResponseBatch);
                                userCallback = headElem = scriptNode = null;
                            }
                        }
                    })(callback, headElem, jsonpScriptNode);
                    headElem.appendChild(jsonpScriptNode);
                }
                else {
                    var form = generateForm(this.UniqueId, serverUrl, jsonString);
                    new iframe(form, { onComplete: function(request) { processResponse(callback, request, thisRequest.HasTemplate()); } }, this.UniqueId);
                }
                // in case they reuse the requestbatch
                this.UniqueId = counter++;
            }
        };
    })();
}

function generateForm(formId, serverUrl, inputVal) {
    // create the form
	var form = document.createElement("form");
	form.acceptCharset = "UTF-8";
	form.name = "f" + formId;
	form.id = "f" + formId;
	form.action = serverUrl;

	// create the input element on the form
	var inputElem = document.createElement("input");
	inputElem.name = "jsonRequest";
	inputElem.type = "hidden";
	inputElem.value = inputVal;
	form.appendChild(inputElem);

	// Firefox has a behavior on refresh that displays a popup confirming that is it reloading a form.
	// We work around this by attempting to perform a get action if the size is below a threshold, else
	// we will run as a post
	form.method = "post";
    if(navigator.userAgent.toLowerCase().indexOf('firefox') != -1) {
        var separator = serverUrl.indexOf('?') == -1 ? "?" : "&";
        var fullRequestURL = serverUrl + separator + "jsonRequest="+ escape(inputVal);
        if (fullRequestURL.length < 4000) {
            // we plan to perform a get, so we need to parse the sid out of the url and place it
            // inside the form
            var sidPos = serverUrl.indexOf('sid=');
            if (sidPos != -1) {
                var endPos = serverUrl.indexOf('&', sidPos);
                var sid = serverUrl.substring(sidPos + 'sid='.length, endPos == -1 ? serverUrl.length : endPos);
	            var sidInputElem = document.createElement("input");
	            sidInputElem.name = "sid";
	            sidInputElem.type = "hidden";
	            sidInputElem.value = sid;
	            form.appendChild(sidInputElem);
	            // remove the sid from the url
	            form.action = serverUrl.substring(0, sidPos-1);
            }
            form.method = "get";
        }
    }

	(RequestBatch.container || document.body).appendChild(form);
	return form;
}

function processResponse(callback, request, isTemplated)
{
    pendingRequests--;
    try {
        if (isTemplated) {
            callback(request.ResponseText);
        } else {
            var jsonResponse = unescape(request.responseText);
            jsonResponse = jsonResponse.replace(/\\\>/g, ">");
            var responseObject = YAHOO.lang.JSON.parse(jsonResponse);
            try {
                callback(responseObject.ResponseBatch);
            } catch (e) {
                DirectAccessErrorHandler("exception during client callback", e);
            }
        }
    } catch (e) {
        DirectAccessErrorHandler("exception during processResponse", e);
    }
}

function getPendingRequestCount()
{
    return pendingRequests;
}



// ------------------------------------------------------------------------------------
// This file contains all the request type objects for the SiteLife JSON Direct API.
// Create instances of these objects, place them in a RequestBatch, and send them off.
// ------------------------------------------------------------------------------------

(function() { // wrapped in a function to keep the Class variable out of the global scope
    var Class = function() {
        return function() {
            this.initialize.apply(this, arguments);
        }
    };
    // Identify a user
    UserKey = Class();
    UserKey.prototype = {
        initialize: function(key) {
            var data = new Object();
            data.Key = key;
            this.UserKey = data;
        }
    };
    // Identify a comment
    CommentKey = Class();
    CommentKey.prototype = {
        initialize: function(key) {
            var data = new Object();
            data.Key = key;
            this.CommentKey = data;
        }
    };
    // Identify an article
    ArticleKey = Class();
    ArticleKey.prototype = {
        initialize: function(key) {
            var data = new Object();
            data.Key = key;
            this.ArticleKey = data;
        }
    };

    // Identify a persona message
    PersonaMessageKey = Class();
    PersonaMessageKey.prototype = {
        initialize: function(key) {
            var data = new Object();
            data.Key = key;
            this.PersonaMessageKey = data;
        }
    };

    // Identify a review
    ReviewKey = Class();
    ReviewKey.prototype = {
        initialize: function(key) {
            var data = new Object();
            data.Key = key;
            this.ReviewKey = data;
        }
    };

    // Identify a gallery
    GalleryKey = Class();
    GalleryKey.prototype = {
        initialize: function(key) {
            var data = new Object();
            data.Key = key;
            this.GalleryKey = data;
        }
    };

    // Identify a photo
    PhotoKey = Class();
    PhotoKey.prototype = {
        initialize: function(key) {
            var data = new Object();
            data.Key = key;
            this.PhotoKey = data;
        }
    };

    // Identify a video
    VideoKey = Class();
    VideoKey.prototype = {
        initialize: function(key) {
            var data = new Object();
            data.Key = key;
            this.VideoKey = data;
        }
    };

    // Identify a blog with this blog key
    BlogKey = Class();
    BlogKey.prototype = {
        initialize: function(key) {
            var data = new Object();
            data.Key = key;
            this.BlogKey = data;
        }
    };

    // Identify a blog post with this blog post key
    BlogPostKey = Class();
    BlogPostKey.prototype = {
        initialize: function(key) {
            var data = new Object();
            data.Key = key;
            this.BlogPostKey = data;
        }
    };

    // Identify a custom item with this CustomItemKey
    CustomItemKey = Class();
    CustomItemKey.prototype = {
        initialize: function(key) {
            var data = new Object();
            data.Key = key;
            this.CustomItemKey = data;
        }
    };

    // Identify a custom collection with this CustomCollectionKey
    CustomCollectionKey = Class();
    CustomCollectionKey.prototype = {
        initialize: function(key) {
            var data = new Object();
            data.Key = key;
            this.CustomCollectionKey = data;
        }
    };


    // Identify a Forum Category
    ForumCategoryKey = Class();
    ForumCategoryKey.prototype = {
        initialize: function(key) {
            var data = new Object();
            data.Key = key;
            this.ForumCategoryKey = data;
        }
    };

    // Identify a Forum
    ForumKey = Class();
    ForumKey.prototype = {
        initialize: function(key) {
            var data = new Object();
            data.Key = key;
            this.ForumKey = data;
        }
    };

    // Identify a forum discussion with this DiscussionKey
    DiscussionKey = Class();
    DiscussionKey.prototype = {
        initialize: function(key) {
            var data = new Object();
            data.Key = key;
            this.DiscussionKey = data;
        }
    };

    // Identify a Forum Post
    ForumPostKey = Class();
    ForumPostKey.prototype = {
        initialize: function(key) {
            var data = new Object();
            data.Key = key;
            this.ForumPostKey = data;
        }
    };

    // Identify an Event
    EventKey = Class();
    EventKey.prototype = {
        initialize: function(key) {
            var data = new Object();
            data.Key = key;
            this.EventKey = data;
        }
    };

    // Identify an Event
    EventSetKey = Class();
    EventSetKey.prototype = {
        initialize: function(key) {
            var data = new Object();
            data.Key = key;
            this.EventSetKey = data;
        }
    };

    // Identify a Community Group
    CommunityGroupKey = Class();
    CommunityGroupKey.prototype = {
        initialize: function(key) {
            var data = new Object();
            data.Key = key;
            this.CommunityGroupKey = data;
        }
    };

    // Identify a CommunityGroup Membership
    CommunityGroupMembershipKey = Class();
    CommunityGroupMembershipKey.prototype = {
        initialize: function(communityGroupKey, userKey) {
            var data = new Object();
            data.CommunityGroupKey = communityGroupKey;
            data.UserKey = userKey;
            this.CommunityGroupMembershipKey = data;
        }
    };


    // Identify a CommunityGroup Invitation
    CommunityGroupInvitationKey = Class();
    CommunityGroupInvitationKey.prototype = {
        initialize: function(communityGroupKey, userKey) {
            var data = new Object();
            data.CommunityGroupKey = communityGroupKey;
            data.UserKey = userKey;
            this.CommunityGroupInvitationKey = data;
        }
    };

    // Identify a CommunityGroup Registrant
    CommunityGroupRegistrantKey = Class();
    CommunityGroupRegistrantKey.prototype = {
        initialize: function(communityGroupKey, userKey) {
            var data = new Object();
            data.CommunityGroupKey = communityGroupKey;
            data.UserKey = userKey;
            this.CommunityGroupRegistrantKey = data;
        }
    };

    // Identify a CommunityGroup Banned User
    CommunityGroupBannedUserKey = Class();
    CommunityGroupBannedUserKey.prototype = {
        initialize: function(communityGroupKey, userKey) {
            var data = new Object();
            data.CommunityGroupKey = communityGroupKey;
            data.UserKey = userKey;
            this.CommunityGroupBannedUserKey = data;
        }
    };

    PollKey = Class();
    PollKey.prototype = {
        initialize: function(pollKey) {
            var data = new Object();
            data.Key = pollKey;
            this.PollKey = data;
        }
    }

    // Points/Badging
    BadgeFamilyKey = Class();
    BadgeFamilyKey.prototype = {
        initialize: function(badgeFamilyKey) {
            var data = new Object();
            data.Key = badgeFamilyKey;
            this.BadgeFamilyKey = data;
        }
    }

    LeaderboardKey = Class();
    LeaderboardKey.prototype = {
        initialize: function(leaderboardKey) {
            var data = new Object();
            data.Key = leaderboardKey;
            this.LeaderboardKey = data;
        }
    }

    // Wrapper to request a comment page
    CommentPage = Class();
    CommentPage.prototype = {
        initialize: function(articleKey, numberPerPage, onPage, sort, findCommentKey) {
            var data = new Object();
            data.ArticleKey = articleKey;
            data.NumberPerPage = numberPerPage;
            data.OnPage = onPage;
            data.Sort = sort;
            data.FindCommentKey = findCommentKey;
            this.CommentPage = data;
        }
    };

    // Wrapper to request a persona message page
    PersonaMessagePage = Class();
    PersonaMessagePage.prototype = {
        initialize: function(userKey, numberPerPage, onPage, sort) {
            var data = new Object();
            data.UserKey = userKey;
            data.NumberPerPage = numberPerPage;
            data.OnPage = onPage;
            data.Sort = sort;
            this.PersonaMessagePage = data;
        }
    };

    // Wrapper to request a review page
    ReviewPage = Class();
    ReviewPage.prototype = {
        initialize: function(articleKey, numberPerPage, onPage, sort) {
            var data = new Object();
            data.ArticleKey = articleKey;
            data.NumberPerPage = numberPerPage;
            data.OnPage = onPage;
            data.Sort = sort;
            this.ReviewPage = data;
        }
    };

    // wrapper to request a page of reviews by user
    UserReviewPage = Class();
    UserReviewPage.prototype = {
        initialize: function(userKey, numberPerPage, onPage, sort) {
            var data = new Object();
            data.UserKey = userKey;
            data.NumberPerPage = numberPerPage;
            data.OnPage = onPage;
            data.Sort = sort;
            this.UserReviewPage = data;
        }
    };

    // Wrapper of types a gallery can contain
    MediaType = Class();
    MediaType.prototype = {
        initialize: function(name) {
            var data = new Object();
            data.Name = name;
            this.MediaType = data;
        }
    };
    // Wrapper to request a page of public galleries
    PublicGalleryPage = Class();
    PublicGalleryPage.prototype = {
        initialize: function(numberPerPage, onPage, mediaType) {
            var data = new Object();
            data.NumberPerPage = numberPerPage;
            data.OnPage = onPage;
            data.MediaType = mediaType;
            this.PublicGalleryPage = data;
        }
    };
    // Wrapper to request a page of user galleries
    UserGalleryPage = Class();
    UserGalleryPage.prototype = {
        initialize: function(userKey, numberPerPage, onPage, mediaType) {
            var data = new Object();
            data.UserKey = userKey;
            data.NumberPerPage = numberPerPage;
            data.OnPage = onPage;
            data.MediaType = mediaType;
            this.UserGalleryPage = data;
        }
    };
    // Wrapper to request a page of photos
    PhotoPage = Class();
    PhotoPage.prototype = {
        initialize: function(galleryKey, numberPerPage, onPage, sort) {
            var data = new Object();
            data.GalleryKey = galleryKey;
            data.NumberPerPage = numberPerPage;
            data.OnPage = onPage;
            data.Sort = sort;
            this.PhotoPage = data;
        }
    };
    // Wrapper to request a page of videos
    VideoPage = Class();
    VideoPage.prototype = {
        initialize: function(galleryKey, numberPerPage, onPage, sort) {
            var data = new Object();
            data.GalleryKey = galleryKey;
            data.NumberPerPage = numberPerPage;
            data.OnPage = onPage;
            data.Sort = sort;
            this.VideoPage = data;
        }
    };
    // Wrapper to request a comment action
    CommentAction = Class();
    CommentAction.prototype = {
        initialize: function(commentOnKey, onPageUrl, onPageTitle, commentBody) {
            var data = new Object();
            data.CommentOnKey = commentOnKey;
            data.OnPageUrl = onPageUrl;
            data.OnPageTitle = onPageTitle;
            data.CommentBody = commentBody;
            this.CommentAction = data;
        }
    };
    // Wrapper to request a review action
    ReviewAction = Class();
    ReviewAction.prototype = {
        initialize: function(reviewOnThisKey, onPageUrl, onPageTitle,
                        reviewTitle, reviewRating, reviewBody, reviewPros, reviewCons) {
            var data = new Object();
            data.ReviewOnKey = reviewOnThisKey;
            data.OnPageUrl = onPageUrl;
            data.OnPageTitle = onPageTitle;
            data.ReviewTitle = reviewTitle;
            data.ReviewRating = reviewRating;
            data.ReviewBody = reviewBody;
            data.ReviewPros = reviewPros;
            data.ReviewCons = reviewCons;
            this.ReviewAction = data;
        }
    };
    // Wrapper to request a recommend action
    RecommendAction = Class();
    RecommendAction.prototype = {
        initialize: function(recommendThisKey, articleTitle) {
            var data = new Object();
            data.RecommendThisKey = recommendThisKey;
            if (articleTitle) {
                data.OnPageTitle = articleTitle;
            }

            this.RecommendAction = data;
        }
    };
    // Wrapper to request a rate action
    RateAction = Class();
    RateAction.prototype = {
        initialize: function(rateThisKey, rating, multiRate) {
            var data = new Object();
            data.RateThisKey = rateThisKey;
            data.Rating = rating;
            if (typeof (multiRate) != "undefined") {
                data.MultiRate = multiRate;
            }
            this.RateAction = data;
        }
    };

    // Permanently delete a gallery, video or photo
    DeleteContentAction = Class();
    DeleteContentAction.prototype = {
        initialize: function(deleteThisContent) {
            var data = new Object();
            data.DeleteThisContent = deleteThisContent;
            this.DeleteContentAction = data;
        }
    };

    // Email from the SiteLife system
    EmailContentAction = Class();
    EmailContentAction.prototype = {
        initialize: function(toAddress, subject, body) {
            var data = new Object();
            data.ToAddress = toAddress;
            data.Subject = subject;
            data.Body = body;
            this.EmailContentAction = data;
        }
    };

    // Email from the SiteLife system with user key as target
    EmailContentWithUserIDAction = Class();
    EmailContentWithUserIDAction.prototype = {
        initialize: function(toUserKey, subject, body) {
            var data = new Object();
            data.UserKey = toUserKey;
            data.Subject = subject;
            data.Body = body;
            this.EmailContentWithUserIDAction = data;
        }
    };

    // Wrapper to request a report abuse action
    ReportAbuseAction = Class();
    ReportAbuseAction.prototype = {
        initialize: function(reportThisKey, abuseReason, abuseDescription) {
            var data = new Object();
            data.ReportThisKey = reportThisKey;
            data.AbuseReason = abuseReason;
            data.AbuseDescription = abuseDescription;
            this.ReportAbuseAction = data;
        }
    };
    // Category used for discovery
    Category = Class();
    Category.prototype = {
        initialize: function(name) {
            var data = new Object();
            data.Name = name;
            this.Category = data;
        }
    };
    // Section used for discovery
    Section = Class();
    Section.prototype = {
        initialize: function(name) {
            var data = new Object();
            data.Name = name;
            this.Section = data;
        }
    };
    // Update or create an article
    UpdateArticleAction = Class();
    UpdateArticleAction.prototype = {
        initialize: function(updateArticle, onPageUrl, onPageTitle, section, categories) {
            var data = new Object();
            data.UpdateArticle = updateArticle;
            data.OnPageUrl = onPageUrl;
            data.OnPageTitle = onPageTitle;
            data.Section = section;
            data.Categories = categories;
            this.UpdateArticleAction = data;
        }
    };
    // Update or create a gallery
    UpdateGalleryAction = Class();
    UpdateGalleryAction.prototype = {
        initialize: function(updateGallery, galleryType, mediaType, title, description, tags, section, galleryPromo) {
            var data = new Object();
            data.UpdateGallery = updateGallery;
            data.GalleryType = galleryType;
            data.MediaType = mediaType;
            data.Title = title;
            data.Description = description;
            data.Tags = tags;
            data.Section = section;
            data.GalleryPromo = galleryPromo;
            this.UpdateGalleryAction = data;
        }
    };
    // Update or create a photo
    UpdatePhotoAction = Class();
    UpdatePhotoAction.prototype = {
        initialize: function(updatePhoto, title, description, tags, section) {
            var data = new Object();
            data.UpdatePhoto = updatePhoto;
            data.Title = title;
            data.Description = description;
            data.Tags = tags;
            data.Section = section;
            this.UpdatePhotoAction = data;
        }
    };
    // Update or create a video
    UpdateVideoAction = Class();
    UpdateVideoAction.prototype = {
        initialize: function(updateVideo, title, description, tags, section) {
            var data = new Object();
            data.UpdateVideo = updateVideo;
            data.Title = title;
            data.Description = description;
            data.Tags = tags;
            data.Section = section;
            this.UpdateVideoAction = data;
        }
    };
    //
    GalleryType = Class();
    GalleryType.prototype = {
        initialize: function(name) {
            var data = new Object();
            data.Name = name;
            this.GalleryType = data;
        }
    };
    // GalleryPromo used for setting promotional text for public galleries
    GalleryPromo = Class();
    GalleryPromo.prototype = {
        initialize: function(title, body, photoKey) {
            var data = new Object();
            data.Title = title;
            data.Body = body;
            data.PhotoKey = photoKey;
            this.GalleryPromo = data;
        }
    };
    // UserTier used for discovery
    UserTier = Class();
    UserTier.prototype = {
        initialize: function(name) {
            var data = new Object();
            data.Name = name;
            this.UserTier = data;
        }
    };
    // MembershipTier used for community groups
    MembershipTier = Class();
    MembershipTier.prototype = {
        initialize: function(name) {
            var data = new Object();
            data.Name = name;
            this.MembershipTier = data;
        }
    };
    // Activity used for discovery
    Activity = Class();
    Activity.prototype = {
        initialize: function(name) {
            var data = new Object();
            data.Name = name;
            this.Activity = data;
        }
    };
    // Discovery on articles
    DiscoverArticlesAction = Class();
    DiscoverArticlesAction.prototype = {
        initialize: function(searchSections, searchCategories, limitToContributors, activity, age, maximumNumberOfDiscoveries) {
            var data = new Object();
            data.SearchSections = searchSections;
            data.SearchCategories = searchCategories;
            data.LimitToContributors = limitToContributors;
            data.Activity = activity;
            data.Age = age;
            data.MaximumNumberOfDiscoveries = maximumNumberOfDiscoveries;

            this.DiscoverArticlesAction = data;
        }
    };

    // Action used to add a friend
    AddFriendAction = Class();
    AddFriendAction.prototype = {
        initialize: function(friendUserKey) {
            var data = new Object();
            data.FriendUserKey = friendUserKey;
            this.AddFriendAction = data;
        }
    };

    // Action used to add a message
    AddPersonaMessageAction = Class();
    AddPersonaMessageAction.prototype = {
        initialize: function(toUserKey, body) {
            var data = new Object();
            data.ToUserKey = toUserKey;
            data.Body = body;
            this.AddPersonaMessageAction = data;
        }
    };

    // Action used to remove a message
    RemovePersonaMessageAction = Class();
    RemovePersonaMessageAction.prototype = {
        initialize: function(personaMessageKey) {
            var data = new Object();
            data.PersonaMessageKey = personaMessageKey;
            this.RemovePersonaMessageAction = data;
        }
    };

    // Action used to approve a friend
    ApproveFriendAction = Class();
    ApproveFriendAction.prototype = {
        initialize: function(friendUserKey, isApproved) {
            var data = new Object();
            data.FriendUserKey = friendUserKey;
            data.IsApproved = isApproved;
            this.ApproveFriendAction = data;
        }
    };

    // Action used to remove a friend
    RemoveFriendAction = Class();
    RemoveFriendAction.prototype = {
        initialize: function(friendUserKey) {
            var data = new Object();
            data.FriendUserKey = friendUserKey;
            this.RemoveFriendAction = data;
        }
    };

    // Action used to add an enemy
    AddEnemyAction = Class();
    AddEnemyAction.prototype = {
        initialize: function(enemyUserKey) {
            var data = new Object();
            data.EnemyUserKey = enemyUserKey;
            this.AddEnemyAction = data;
        }
    };

    // Action used to remove an enemy
    RemoveEnemyAction = Class();
    RemoveEnemyAction.prototype = {
        initialize: function(enemyUserKey) {
            var data = new Object();
            data.EnemyUserKey = enemyUserKey;
            this.RemoveEnemyAction = data;
        }
    };

    // Wrapper to request a friend page
    FriendPage = Class();
    FriendPage.prototype = {
        initialize: function(userKey, numberPerPage, onPage, isPendingList, filterKey, filterValue) {
            var data = new Object();
            data.UserKey = userKey;
            data.NumberPerPage = numberPerPage;
            data.OnPage = onPage;
            data.IsPendingList = isPendingList;
            data.FilterKey = filterKey;
            data.FilterValue = filterValue;
            this.FriendPage = data;
        }
    };

    // Wrapper to request if a given user key is a friend of the user specified by the second parameter
    // if the userKey parameter is not specified, the currently logged-in user is used
    IsFriend = Class();
    IsFriend.prototype = {
        initialize: function(friendUserKey, userKey) {
            var data = new Object();
            data.FriendUserKey = friendUserKey;
            data.UserKey = userKey;
            this.IsFriend = data;
        }
    };

    // Wrapper to request a friend page
    EnemyPage = Class();
    EnemyPage.prototype = {
        initialize: function(userKey, numberPerPage, onPage, sort) {
            var data = new Object();
            data.UserKey = userKey;
            data.NumberPerPage = numberPerPage;
            data.OnPage = onPage;
            data.Sort = sort;
            this.EnemyPage = data;
        }
    };

    // Discovery on content
    DiscoverContentAction = Class();
    DiscoverContentAction.prototype = {
        initialize: function(searchSections, searchCategories, limitToContributors, activity, contentType, age, maximumNumberOfDiscoveries, filterBySiteOfOrigin, parentKeys) {
            var data = new Object();
            data.SearchSections = searchSections;
            data.SearchCategories = searchCategories;
            data.LimitToContributors = limitToContributors;
            data.Activity = activity;
            data.ContentType = contentType;
            data.Age = age;
            data.MaximumNumberOfDiscoveries = maximumNumberOfDiscoveries;
            data.FilterBySiteOfOrigin = filterBySiteOfOrigin;
            if (parentKeys) {
                data.ParentKeys = parentKeys;
            }
            this.DiscoverContentAction = data;
        }
    };

    // Content type for discovery
    ContentType = Class();
    ContentType.prototype = {
        initialize: function(name) {
            var data = new Object();
            data.Name = name;
            this.ContentType = data;
        }
    };

    UpdateUserProfileAction = Class();
    UpdateUserProfileAction.prototype = {
        initialize: function(userKey,
                            aboutMe,
                            location,
                            signature,
                            dateOfBirth,
                            sex,
                            personaPrivacyMode,
                            commentsTabVisible,
                            photosTabVisible,
                            messagesOpenToEveryone,
                            isEmailNotificationsEnabled,
                            selectedStyleId,
                            customAnswers,
                            extendedProfile) {

            var data = new Object();
            data.UserKey = userKey;
            data.AboutMe = aboutMe;
            data.Location = location;
            data.Signature = signature;
            data.DateOfBirth = dateOfBirth;
            data.Sex = sex;
            data.PersonaPrivacyMode = personaPrivacyMode;
            data.CommentsTabVisible = commentsTabVisible;
            data.PhotosTabVisible = photosTabVisible;
            data.MessagesOpenToEveryone = messagesOpenToEveryone;
            data.IsEmailNotificationsEnabled = isEmailNotificationsEnabled;
            data.SelectedStyleId = selectedStyleId;
            data.CustomAnswers = customAnswers;
            data.ExtendedProfile = extendedProfile;
            this.UpdateUserProfileAction = data;
        }
    };

    UpdateUserBlockedSettingAction = Class();
    UpdateUserBlockedSettingAction.prototype = {
        initialize: function(userKey, isBlocked) {
            var data = new Object;
            data.UserKey = userKey;
            data.IsBlocked = isBlocked;
            this.UpdateUserBlockedSettingAction = data;
        }
    };

    SearchAction = Class();
    SearchAction.prototype = {
        initialize: function(searchType, searchString, numberPerPage, onPage) {
            var data = new Object();
            data.SearchType = searchType;
            data.SearchString = searchString;
            data.NumberPerPage = numberPerPage;
            data.OnPage = onPage;
            this.SearchAction = data;
        }
    };

    // Wrapper to request a watch item page
    WatchItemPage = Class();
    WatchItemPage.prototype = {
        initialize: function(userKey, numberPerPage, onPage) {
            var data = new Object();
            data.UserKey = userKey;
            data.NumberPerPage = numberPerPage;
            data.OnPage = onPage;
            this.WatchItemPage = data;
        }
    };

    // Wrapper to add a watch item
    AddWatchItemAction = Class();
    AddWatchItemAction.prototype = {
        initialize: function(userKey, watchTargetKey, title, url) {
            var data = new Object();
            data.UserKey = userKey;
            data.WatchTargetKey = watchTargetKey;
            data.WatchItemTitle = title;
            data.WatchItemUrl = url;
            this.AddWatchItemAction = data;
        }
    };

    // Wrapper to delete a watch item
    DeleteWatchItemAction = Class();
    DeleteWatchItemAction.prototype = {
        initialize: function(userKey, watchTargetKey) {
            var data = new Object();
            data.UserKey = userKey;
            data.WatchTargetKey = watchTargetKey;
            this.DeleteWatchItemAction = data;
        }
    };

    // Wrapper to request a blog post page
    BlogPostPage = Class();
    BlogPostPage.prototype = {
        initialize: function(blogKey, numberPerPage, onPage, sort, blogPostState, restrictToOwner, includeFuturePosts) {
            var data = new Object();
            data.BlogKey = blogKey;
            data.NumberPerPage = numberPerPage;
            data.OnPage = onPage;
            data.Sort = sort;
            data.BlogPostState = blogPostState;
            if ((typeof (restrictToOwner) == 'undefined') || (restrictToOwner == null)) {
                // Default to false for backwards compatibility
                restrictToOwner = false;
            }
            data.RestrictToOwner = restrictToOwner.toString();
            if ((typeof (includeFuturePosts) == 'undefined') || (includeFuturePosts == null)) {
                // Default to false for backwards compatibility
                includeFuturePosts = false;
            }
            data.IncludeFuturePosts = includeFuturePosts.toString();
            this.BlogPostPage = data;
        }
    };

    // Wrapper to request a blog post page by Tag
    BlogPostsByTagPage = Class();
    BlogPostsByTagPage.prototype = {
        initialize: function(blogKey, tag, numberPerPage, onPage, sort) {
            var data = new Object();
            data.BlogKey = blogKey;
            data.Tag = tag;
            data.NumberPerPage = numberPerPage;
            data.OnPage = onPage;
            data.Sort = sort;
            this.BlogPostsByTagPage = data;
        }
    };


    // Wrapper to request a blog post archive count
    BlogPostArchiveCount = Class();
    BlogPostArchiveCount.prototype = {
        initialize: function(blogKey) {
            var data = new Object();
            data.BlogKey = blogKey;
            this.BlogPostArchiveCount = data;
        }
    };


    // Wrapper to request a blog post archive content page
    BlogPostArchiveContentPage = Class();
    BlogPostArchiveContentPage.prototype = {
        initialize: function(blogKey, month, numberPerPage, onPage, sort) {
            var data = new Object();
            data.BlogKey = blogKey;
            data.Month = month;
            data.NumberPerPage = numberPerPage;
            data.OnPage = onPage;
            data.Sort = sort;
            this.BlogPostArchiveContentPage = data;
        }
    };


    // Wrapper to request a user comment page
    UserCommentPage = Class();
    UserCommentPage.prototype = {
        initialize: function(userKey, numberPerPage, onPage, sort, commentsOnly) {
            var data = new Object();
            data.UserKey = userKey;
            data.NumberPerPage = numberPerPage;
            data.OnPage = onPage;
            data.Sort = sort;
            data.CommentsOnly = commentsOnly;
            this.UserCommentPage = data;
        }
    };


    // Wrapper to request blog tag
    RecentBlogTag = Class();
    RecentBlogTag.prototype = {
        initialize: function(blogKey) {
            var data = new Object();
            data.BlogKey = blogKey;
            this.RecentBlogTag = data;
        }
    };


    // Wrapper to request recent user photo page
    RecentUserPhotoPage = Class();
    RecentUserPhotoPage.prototype = {
        initialize: function(userKey, numberPerPage, onPage) {
            var data = new Object();
            data.UserKey = userKey;
            data.NumberPerPage = numberPerPage;
            data.OnPage = onPage;
            this.RecentUserPhotoPage = data;
        }
    };

    // Wrapper to request recent user video page
    RecentUserVideoPage = Class();
    RecentUserVideoPage.prototype = {
        initialize: function(userKey, numberPerPage, onPage) {
            var data = new Object();
            data.UserKey = userKey;
            data.NumberPerPage = numberPerPage;
            data.OnPage = onPage;
            this.RecentUserVideoPage = data;
        }
    };


    // Wrapper to request recent public gallery page
    RecentPublicGalleryPage = Class();
    RecentPublicGalleryPage.prototype = {
        initialize: function(userKey, numberPerPage, onPage) {
            var data = new Object();
            data.UserKey = userKey;
            data.NumberPerPage = numberPerPage;
            data.OnPage = onPage;
            this.RecentPublicGalleryPage = data;
        }
    };


    // Wrapper to request recent user activity page
    RecentUserActivity = Class();
    RecentUserActivity.prototype = {
        initialize: function(userKey) {
            var data = new Object();
            data.UserKey = userKey;
            this.RecentUserActivity = data;
        }
    };


    // Wrapper to request page of user media submission counts
    UserMediaSubmissionsCountPage = Class();
    UserMediaSubmissionsCountPage.prototype = {
        initialize: function(userKey, mediaType, numberPerPage, onPage) {
            var data = new Object();
            data.UserKey = userKey;
            data.MediaType = mediaType;
            data.NumberPerPage = numberPerPage;
            data.OnPage = onPage;
            this.UserMediaSubmissionsCountPage = data;
        }
    };


    // Wrapper to request recent forum discussion page
    RecentForumDiscussionPage = Class();
    RecentForumDiscussionPage.prototype = {
        initialize: function(userKey, numberPerPage, onPage) {
            var data = new Object();
            data.UserKey = userKey;
            data.NumberPerPage = numberPerPage;
            data.OnPage = onPage;
            this.RecentForumDiscussionPage = data;
        }
    };


    // Wrapper to request user group forum page
    UserGroupForumPage = Class();
    UserGroupForumPage.prototype = {
        initialize: function(userKey, numberPerPage, onPage, sort) {
            var data = new Object();
            data.UserKey = userKey;
            data.NumberPerPage = numberPerPage;
            data.OnPage = onPage;
            data.Sort = sort;
            this.UserGroupForumPage = data;
        }
    };

    // The blogRollEntry used in UpdateBlogAction
    BlogRollEntry = Class();
    BlogRollEntry.prototype = {
        initialize: function(name, url) {
            var data = new Object();
            data.Name = name;
            data.Url = url;
            this.BlogRollEntry = data;
        }
    };

    // Bookmark used in UpdateCommunityGroupAction
    Bookmark = Class();
    Bookmark.prototype = {
        initialize: function(title, link) {
            var data = new Object();
            data.Title = title;
            data.Link = link;
            this.Bookmark = data;
        }
    };

    // CommunityGroupVisibility used in UpdateCommunityGroupAction
    CommunityGroupVisibility = Class();
    CommunityGroupVisibility.prototype = {
        initialize: function(name) {
            var data = new Object();
            data.Name = name;
            this.CommunityGroupVisibility = data;
        }
    };

    // Update or create a blog
    UpdateBlogAction = Class();
    UpdateBlogAction.prototype = {
        initialize: function(updateBlog, title, tagline, blogRollEntries, blogType) {
            var data = new Object();
            data.BlogKey = updateBlog;
            data.Title = title;
            data.Tagline = tagline;
            data.BlogRollEntries = blogRollEntries;
            data.BlogType = blogType;
            this.UpdateBlogAction = data;
        }
    };

    // Update or create a blog post, key can be either a post key (update case)
    // or a blog key (create case)
    UpdateBlogPostAction = Class();
    UpdateBlogPostAction.prototype = {
        initialize: function(key, title, body, tags, publishDate, published) {
            var data = new Object();
            data.TargetThis = key;
            data.Title = title;
            data.Body = body;
            data.Tags = tags;
            data.Date = publishDate;
            data.Published = published;
            this.UpdateBlogPostAction = data;
        }
    };

    // Identify a forum discussion with this DiscussionKey
    DiscussionKey = Class();
    DiscussionKey.prototype = {
        initialize: function(key) {
            var data = new Object();
            data.Key = key;
            this.DiscussionKey = data;
        }
    };

    // Identify a custom item with this CustomItemKey
    CustomItemKey = Class();
    CustomItemKey.prototype = {
        initialize: function(key) {
            var data = new Object();
            data.Key = key;
            this.CustomItemKey = data;
        }
    };

    // Identify a custom collection with this CustomCollectionKey
    CustomCollectionKey = Class();
    CustomCollectionKey.prototype = {
        initialize: function(key) {
            var data = new Object();
            data.Key = key;
            this.CustomCollectionKey = data;
        }
    };

    // Update or create a custom item in storage
    UpdateCustomItemAction = Class();
    UpdateCustomItemAction.prototype = {
        initialize: function(customItemKey, name, mimeType, displayText, content, includeInRecentActivity) {
            var data = new Object();
            data.CustomItemKey = customItemKey;
            data.Name = name;
            data.MimeType = mimeType;
            data.DisplayText = displayText;
            data.Content = content;
            if ((typeof (includeInRecentActivity) == 'undefined') || (includeInRecentActivity == null)) {
                // Default to true for backwards compatibility
                includeInRecentActivity = true;
            }
            data.IncludeInRecentActivity = includeInRecentActivity
            this.UpdateCustomItemAction = data;
        }
    };

    // Add a new custom collection to storage
    AddCustomCollectionAction = Class();
    AddCustomCollectionAction.prototype = {
        initialize: function(customCollectionKey, customCollectionName) {
            var data = new Object();
            data.CustomCollectionKey = customCollectionKey;
            data.CustomCollectionName = customCollectionName;
            this.AddCustomCollectionAction = data;
        }
    };

    // Insert an item into a custom collection
    InsertIntoCollectionAction = Class();
    InsertIntoCollectionAction.prototype = {
        initialize: function(customCollectionKey, insertThisKey, position) {
            var data = new Object();
            data.CustomCollectionKey = customCollectionKey;
            data.InsertThisKey = insertThisKey;
            data.Position = position;
            this.InsertIntoCollectionAction = data;
        }
    };

    // Remove an item from a custom collection (position can be null to specify to remove all occurrences of item)
    RemoveFromCollectionAction = Class();
    RemoveFromCollectionAction.prototype = {
        initialize: function(customCollectionKey, removeThisKey, position) {
            var data = new Object();
            data.CustomCollectionKey = customCollectionKey;
            data.RemoveThisKey = removeThisKey;
            data.Position = position;
            this.RemoveFromCollectionAction = data;
        }
    };

    // Get a page of items out of a custom collection
    CustomCollectionPage = Class();
    CustomCollectionPage.prototype = {
        initialize: function(customCollectionKey, numberPerPage, onPage, sort) {
            var data = new Object();
            data.CustomCollectionKey = customCollectionKey;
            data.NumberPerPage = numberPerPage;
            data.OnPage = onPage;
            data.Sort = sort;
            this.CustomCollectionPage = data;
        }
    };


    // Get a page of items out of a custom collection
    EditorMessageRequest = Class();
    EditorMessageRequest.prototype = {
        initialize: function() {
            this.EditorMessageRequest = new Object();
        }
    };

    // Retrieve a user's tags for the given content type
    UserTags = Class();
    UserTags.prototype = {
        initialize: function(userKey, contentType) {
            var data = new Object();
            data.UserKey = userKey;
            data.ContentType = contentType;
            this.UserTags = data;
        }
    };


    // Get an item's ContentPolicy
    GetContentPolicyAction = Class();
    GetContentPolicyAction.prototype = {
        initialize: function(targetKey, userTier, action) {
            var data = new Object();
            data.TargetKey = targetKey;
            data.UserTier = userTier;
            data.ContentPolicyActionType = action;
            this.GetContentPolicyAction = data;
        }
    }

    // Set an item's ContentPolicy
    SetContentPolicyAction = Class();
    SetContentPolicyAction.prototype = {
        initialize: function(targetKey, userTier, action, policy) {
            var data = new Object();
            data.TargetKey = targetKey;
            data.UserTier = userTier;
            data.ContentPolicyActionType = action;
            data.ContentPolicy = policy;
            this.SetContentPolicyAction = data;
        }
    }

    ContentPolicy = Class();
    ContentPolicy.prototype = {
        initialize: function(name) {
            var data = new Object();
            data.Name = name;
            this.ContentPolicy = data;
        }
    };

    ContentPolicyActionType = Class();
    ContentPolicyActionType.prototype = {
        initialize: function(name) {
            var data = new Object();
            data.Name = name;
            this.ContentPolicyActionType = data;
        }
    };

    // Updates a Forum's meta data
    UpdateForumAction = Class();
    UpdateForumAction.prototype = {
        initialize: function(forumKey, title, description) {
            var data = new Object();
            data.ForumKey = forumKey;
            data.Title = title;
            data.Description = description;
            this.UpdateForumAction = data;
        }
    };

    //Adds/Updates a Forum Discussion's meta data. If the key is a ForumKey, it will be added as a new Discussion.
    //If the key is a ForumDiscussionKey, the existing forum discussion will be updated.
    UpdateForumDiscussionAction = Class();
    UpdateForumDiscussionAction.prototype = {
        initialize: function(key, title, body, isQuestion, isPoll, section, categories) {
            var data = new Object();
            data.TargetThis = key;
            data.Title = title;
            data.Body = body;
            data.IsQuestion = typeof (isQuestion) == 'string' ? isQuestion : (isQuestion ? "true" : "false");
            data.IsPoll = typeof (isPoll) == 'string' ? isPoll : (isPoll ? "true" : "false");
            if (typeof (section) != "undefined") {
                data.Section = section;
            }
            if (typeof (categories) != "undefined") {
                data.Categories = categories;
            }
            this.UpdateForumDiscussionAction = data;
        }
    };

    //Adds/Updates a Forum Post's meta data. If the key is a ForumDiscussionKey, it will be added as a new Post.
    //If the key is a ForumPostKey, the existing forum post will be updated.
    UpdateForumPostAction = Class();
    UpdateForumPostAction.prototype = {
        initialize: function(key, title, body, isQuestion) {
            var data = new Object();
            data.TargetThis = key;
            data.Title = title;
            data.Body = body;
            data.IsQuestion = isQuestion;
            this.UpdateForumPostAction = data;
        }
    };

    //Updates a Forum Discussion's Sticky flag
    ForumToggleDiscussionStickyAction = Class();
    ForumToggleDiscussionStickyAction.prototype = {
        initialize: function(discussionKey) {
            var data = new Object();
            data.DiscussionKey = discussionKey;
            this.ForumToggleDiscussionStickyAction = data;
        }
    };

    //Opens/Closes a Forum Discussion
    ForumToggleDiscussionClosedAction = Class();
    ForumToggleDiscussionClosedAction.prototype = {
        initialize: function(discussionKey) {
            var data = new Object();
            data.DiscussionKey = discussionKey;
            this.ForumToggleDiscussionClosedAction = data;
        }
    };

    //Retrieves a paginated list of Discussions for a particular Forum
    ForumDiscussionsPage = Class();
    ForumDiscussionsPage.prototype = {
        initialize: function(forumKey, numberPerPage, oneBasedOnPage, sort) {
            var data = new Object();
            data.ForumKey = forumKey;
            data.NumberPerPage = numberPerPage;
            data.OnPage = oneBasedOnPage;
            data.Sort = sort;
            this.ForumDiscussionsPage = data;
        }
    };

    //Retrieves a paginated list of Posts for a particular Forum
    ForumPostsPage = Class();
    ForumPostsPage.prototype = {
        initialize: function(forumDiscussionKey, numberPerPage, oneBasedOnPage, sort, findPostKey) {
            var data = new Object();
            data.DiscussionKey = forumDiscussionKey;
            data.NumberPerPage = numberPerPage;
            data.OnPage = oneBasedOnPage;
            data.Sort = sort;
            data.FindPostKey = findPostKey;
            this.ForumPostsPage = data;
        }
    };

    //Retrieves a paginated list of forums for a particular category
    ForumCategoriesPage = Class();
    ForumCategoriesPage.prototype = {
        initialize: function(numberPerPage, oneBasedOnPage) {
            var data = new Object();
            data.NumberPerPage = numberPerPage;
            data.OnPage = oneBasedOnPage;
            this.ForumCategoriesPage = data;
        }
    };

    //Retrieves a paginated list of forums for a particular category
    ForumsPage = Class();
    ForumsPage.prototype = {
        initialize: function(categoryKey, numberPerPage, oneBasedOnPage, sort) {
            var data = new Object();
            data.ForumCategoryKey = categoryKey;
            data.NumberPerPage = numberPerPage;
            data.OnPage = oneBasedOnPage;
            data.Sort = sort;
            this.ForumsPage = data;
        }
    };

    ForumSearchAction = Class();
    ForumSearchAction.prototype = {
        initialize: function(searchKey, searchString, numberPerPage, onPage) {
            var data = new Object();
            data.TargetThis = searchKey;
            data.SearchString = searchString;
            data.NumberPerPage = numberPerPage;
            data.OnPage = onPage;
            this.ForumSearchAction = data;
        }
    };

    // Retrieves a paginated list of community groups
    CommunityGroupPage = Class();
    CommunityGroupPage.prototype = {
        initialize: function(numberPerPage, oneBasedOnPage, sort, section) {
            var data = new Object();
            data.NumberPerPage = numberPerPage;
            data.OnPage = oneBasedOnPage;
            data.Sort = sort;
            if ((typeof (section) == 'undefined') || (section == null)) {
                // Default section to All
                section = new Section("All");
            }
            data.Section = section;
            this.CommunityGroupPage = data;
        }
    };

    // Retrieves a paginated list of community groups
    CommunityGroupMembership = Class();
    CommunityGroupMembership.prototype = {
        initialize: function(groupKey, userKey) {
            var data = new Object();
            data.CommunityGroupKey = groupKey;
            data.UserKey = userKey;
            this.CommunityGroupMembership = data;
        }
    };


    // Retrieves a paginated list of community groups
    CommunityGroupMembershipPage = Class();
    CommunityGroupMembershipPage.prototype = {
        initialize: function(key, numberPerPage, oneBasedOnPage, sort, membershipFilter) {
            var data = new Object();
            data.Key = key;
            data.NumberPerPage = numberPerPage;
            data.OnPage = oneBasedOnPage;
            data.Sort = sort;
            data.MembershipFilter = membershipFilter;
            this.CommunityGroupMembershipPage = data;
        }
    };

    // Retrieves a paginated list of registrants
    CommunityGroupRegistrantPage = Class();
    CommunityGroupRegistrantPage.prototype = {
        initialize: function(key, numberPerPage, oneBasedOnPage, sort) {
            var data = new Object();
            data.CommunityGroupKey = key;
            data.NumberPerPage = numberPerPage;
            data.OnPage = oneBasedOnPage;
            data.Sort = sort;
            this.CommunityGroupRegistrantPage = data;
        }
    };

    // Retrieves a paginated list of banned users
    CommunityGroupBannedUserPage = Class();
    CommunityGroupBannedUserPage.prototype = {
        initialize: function(key, numberPerPage, oneBasedOnPage, sort) {
            var data = new Object();
            data.CommunityGroupKey = key;
            data.NumberPerPage = numberPerPage;
            data.OnPage = oneBasedOnPage;
            data.Sort = sort;
            this.CommunityGroupBannedUserPage = data;
        }
    };

    // Retrieves a paginated list of invited users
    CommunityGroupInvitedUserPage = Class();
    CommunityGroupInvitedUserPage.prototype = {
        initialize: function(key, numberPerPage, oneBasedOnPage, sort) {
            var data = new Object();
            data.CommunityGroupKey = key;
            data.NumberPerPage = numberPerPage;
            data.OnPage = oneBasedOnPage;
            data.Sort = sort;
            this.CommunityGroupInvitedUserPage = data;
        }
    };



    // Creates a new or updates an existing community group
    UpdateCommunityGroupAction = Class();
    UpdateCommunityGroupAction.prototype = {
        initialize: function(key, title, description, categories, visibility, bookmarks, section, photoKey) {
            var data = new Object();
            data.CommunityGroupKey = key;
            data.Title = title;
            data.Description = description;
            data.Categories = categories;
            data.Visibility = visibility,
        data.Bookmarks = bookmarks;
            data.Section = section;
            data.PhotoKey = photoKey;
            this.UpdateCommunityGroupAction = data;
        }
    };

    // Updates an existing commnity group's bookmarks
    UpdateCommunityGroupBookmarksAction = Class();
    UpdateCommunityGroupBookmarksAction.prototype = {
        initialize: function(key, bookmarks) {
            var data = new Object();
            data.CommunityGroupKey = key;
            data.Bookmarks = bookmarks;
            this.UpdateCommunityGroupBookmarksAction = data;
        }
    };

    // Creates or updates a user's membership in a group, with options to ban the user from the group.
    UpdateCommunityGroupMembershipAction = Class();
    UpdateCommunityGroupMembershipAction.prototype = {
        initialize: function(communityGroupKey, userKey, membershipTier, isBanned, banMessage) {
            var data = new Object();
            data.CommunityGroupKey = communityGroupKey;
            data.UserKey = userKey;
            data.MembershipTier = membershipTier;
            data.IsBanned = isBanned;
            data.BanMessage = banMessage;
            this.UpdateCommunityGroupMembershipAction = data;
        }
    };

    // Enables a user to request membership in a community group or an admin to invite a non-member.
    RequestCommunityGroupMembershipAction = Class();
    RequestCommunityGroupMembershipAction.prototype = {
        initialize: function(communityGroupKey, userKey, message) {
            var data = new Object();
            data.CommunityGroupKey = communityGroupKey;
            data.UserKey = userKey;
            data.Message = message;
            this.RequestCommunityGroupMembershipAction = data;
        }
    };

    //Retrieves a paginated list of Events for a particular EventSetKey
    EventsPage = Class();
    EventsPage.prototype = {
        initialize: function(eventSetKey, startDate, endDate, numberPerPage, oneBasedOnPage, sort) {
            var data = new Object();
            data.EventSetKey = eventSetKey;
            data.StartDate = startDate;
            data.EndDate = endDate;
            data.NumberPerPage = numberPerPage;
            data.OnPage = oneBasedOnPage;
            data.Sort = sort;
            this.EventsPage = data;
        }
    };

    // Update or creates an Event, key can be either an EventKey (update case)
    // or an EventSetKey (create case)
    UpdateEventAction = Class();
    UpdateEventAction.prototype = {
        initialize: function(key, title, description, location, bookmarkName, bookmarkUrl, startDate, endDate, utcOffset) {
            var data = new Object();
            data.TargetThis = key;
            data.Title = title;
            data.Description = description;
            data.Location = location;
            data.BookmarkName = bookmarkName;
            data.BookmarkUrl = bookmarkUrl;
            data.StartDate = startDate;
            data.EndDate = endDate;
            data.UtcOffset = utcOffset;
            this.UpdateEventAction = data;
        }
    };


    // Retrieve a paginated list of recent group activities
    RecentMiniFeedActivity = Class();
    RecentMiniFeedActivity.prototype = {
        initialize: function(communityGroupKey, onPage, numberPerPage) {
            var data = new Object();
            data.CommunityGroupKey = communityGroupKey;
            data.OnPage = onPage;
            data.NumberPerPage = numberPerPage
            this.RecentMiniFeedActivity = data;
        }
    }

    //Retrieve a list of Most Active Users in a CommunityGroup
    CommunityGroupMostActiveMembers = Class();
    CommunityGroupMostActiveMembers.prototype = {
        initialize: function(communityGroupKey, age, maximumNumberOfMembers) {
            var data = new Object();
            data.CommunityGroupKey = communityGroupKey;
            data.Age = age;
            data.MaximumNumberOfMembers = maximumNumberOfMembers
            this.CommunityGroupMostActiveMembers = data;
        }
    }

    // perform a search for content within a specific community group
    CommunityGroupSearchAction = Class();
    CommunityGroupSearchAction.prototype = {
        initialize: function(communityGroupKey, searchType, searchString, numberPerPage, onPage) {
            var data = new Object();
            data.CommunityGroupKey = communityGroupKey;
            data.SearchType = searchType;
            data.SearchString = searchString;
            data.OnPage = onPage;
            data.NumberPerPage = numberPerPage;
            this.CommunityGroupSearchAction = data;
        }
    }

    // perform a search for content within a specific community group
    RequestDeleteCommunityGroupAction = Class();
    RequestDeleteCommunityGroupAction.prototype = {
        initialize: function(communityGroupKey, deleteReason) {
            var data = new Object();
            data.CommunityGroupKey = communityGroupKey;
            data.DeleteReason = deleteReason;
            this.RequestDeleteCommunityGroupAction = data;
        }
    }

    CommunityGroupRecentForumDiscussions = Class();
    CommunityGroupRecentForumDiscussions.prototype = {
        initialize: function(communityGroupKey, age, maximumNumberOfDiscussions) {
            var data = new Object();
            data.CommunityGroupKey = communityGroupKey;
            data.Age = age;
            data.MaximumNumberOfDiscussions = maximumNumberOfDiscussions;
            this.CommunityGroupRecentForumDiscussions = data;
        }
    }


    SystemTimeInfo = Class();
    SystemTimeInfo.prototype = {
        initialize: function() {
            var data = new Object();
            this.SystemTimeInfo = data;
        }
    }

    PrivateMessageFolderList = Class();
    PrivateMessageFolderList.prototype = {
        initialize: function() {
            var data = new Object();
            this.PrivateMessageFolderList = data;
        }
    }


    PrivateMessage = Class();
    PrivateMessage.prototype = {
        initialize: function(folderID, messageID) {
            var data = new Object();
            data.FolderID = folderID;
            data.MessageID = messageID;
            this.PrivateMessage = data;
        }
    }

    PrivateMessagePage = Class();
    PrivateMessagePage.prototype = {
        initialize: function(folderID, numberPerPage, onPage, messageReadState) {
            var data = new Object();
            data.FolderID = folderID;
            data.NumberPerPage = numberPerPage;
            data.OnPage = onPage;
            data.MessageReadState = messageReadState;
            this.PrivateMessagePage = data;
        }
    }

    PrivateMessageSendAction = Class();
    PrivateMessageSendAction.prototype = {
        initialize: function(subject, body, recipientList) {
            var data = new Object();
            data.Subject = subject;
            data.Body = body;
            data.RecipientList = recipientList;
            this.PrivateMessageSendAction = data;
        }
    }

    PrivateMessageMoveMessageAction = Class();
    PrivateMessageMoveMessageAction.prototype = {
        initialize: function(sourceFolderID, destinationFolderID, messageIDList) {
            var data = new Object();
            data.SourceFolderID = sourceFolderID;
            data.DestinationFolderID = destinationFolderID;
            data.MessageIDList = messageIDList;
            this.PrivateMessageMoveMessageAction = data;
        }
    }

    PrivateMessageDeleteMessageAction = Class();
    PrivateMessageDeleteMessageAction.prototype = {
        initialize: function(sourceFolderID, messageIDList) {
            var data = new Object();
            data.SourceFolderID = sourceFolderID;
            data.MessageIDList = messageIDList;
            this.PrivateMessageDeleteMessageAction = data;
        }
    }

    PrivateMessageEmptyTrashAction = Class();
    PrivateMessageEmptyTrashAction.prototype = {
        initialize: function() {
            var data = new Object();
            this.PrivateMessageEmptyTrashAction = data;
        }
    }


    PrivateMessageCreateFolderAction = Class();
    PrivateMessageCreateFolderAction.prototype = {
        initialize: function() {
            var data = new Object();
            data.FolderID = "Inbox";
            this.PrivateMessageCreateFolderAction = data;
        }
    }

    FirstUnreadPost = Class();
    FirstUnreadPost.prototype = {
        initialize: function(discussionKey, numberPerPage, sort) {
            var data = new Object();
            data.DiscussionKey = discussionKey;
            data.NumberPerPage = numberPerPage;
            data.Sort = sort;
            this.FirstUnreadPost = data;
        }
    }

    LatestPost = Class();
    LatestPost.prototype = {
        initialize: function(discussionKey, numberPerPage, sort) {
            var data = new Object();
            data.DiscussionKey = discussionKey;
            data.NumberPerPage = numberPerPage;
            data.Sort = sort;
            this.LatestPost = data;
        }
    }

    UpdateDiscussionLastReadAction = Class();
    UpdateDiscussionLastReadAction.prototype = {
        initialize: function(discussionKey, postKey, forceUpdate) {
            var data = new Object();
            data.DiscussionKey = discussionKey;
            if (postKey) {
                data.ForumPostKey = postKey;
            }
            if (forceUpdate) {
                data.ForceUpdate = true;
            }
            else {
                data.ForceUpdate = false;
            }
            this.UpdateDiscussionLastReadAction = data;
        }
    }

    UpdateForumAllReadAction = Class();
    UpdateForumAllReadAction.prototype = {
        initialize: function(forumKey) {
            var data = new Object();
            data.ForumKey = forumKey;
            this.UpdateForumAllReadAction = data;
        }
    }

    UpdateCategoryAllReadAction = Class();
    UpdateCategoryAllReadAction.prototype = {
        initialize: function(categoryKey) {
            var data = new Object();
            data.ForumCategoryKey = categoryKey;
            this.UpdateCategoryAllReadAction = data;
        }
    }

    UpdateExternalUserIdAction = Class();
    UpdateExternalUserIdAction.prototype = {
        initialize: function(externalSiteName, externalSiteUserId, forUser) {
            var data = new Object();
            data.ExternalSiteName = externalSiteName;
            data.ExternalSiteUserId = externalSiteUserId;
            data.ForUser = forUser;
            this.UpdateExternalUserIdAction = data;
        }
    }

    UpdateSubscriptionAction = Class();
    UpdateSubscriptionAction.prototype = {
        initialize: function(discussionKey, subscribe) {
            var data = new Object();
            data.DiscussionKey = discussionKey;
            data.Subscribe = subscribe;
            this.UpdateSubscriptionAction = data;
        }
    }

    UpdatePollAction = Class();
    UpdatePollAction.prototype = {
        initialize: function(pollOnKey, question, answers) {
            var data = new Object();
            data.PollOnKey = pollOnKey;
            data.Question = question;
            data.Answers = answers;
            this.UpdatePollAction = data;
        }
    }

    TogglePollIsClosedAction = Class();
    TogglePollIsClosedAction.prototype = {
        initialize: function(pollKey) {
            var data = new Object();
            data.ToggleThisPoll = pollKey;
            this.TogglePollIsClosedAction = data;
        }
    }

    PostPollAnswerAction = Class();
    PostPollAnswerAction.prototype = {
        initialize: function(pollToAnswer, indexOfAnswer) {
            var data = new Object();
            data.PollToAnswer = pollToAnswer;
            data.IndexOfAnswer = indexOfAnswer;
            this.PostPollAnswerAction = data;
        }
    }

    PollPage = Class();
    PollPage.prototype = {
        initialize: function(pollOnKey, numberPerPage, onPage, sort) {
            var data = new Object();
            data.PollOnKey = pollOnKey;
            data.NumberPerPage = numberPerPage;
            data.OnPage = onPage;
            data.Sort = sort;
            this.PollPage = data;
        }
    }

    CheckFilteredWords = Class();
    CheckFilteredWords.prototype = {
        initialize: function(keyValueDictionary) { // key is the string ID, value is the string to be checked - formatted like { "key1":"string1", "key2":"string2" }.
            var data = new Object();
            data.WordDictionary = keyValueDictionary;
            this.CheckFilteredWords = data;
        }
    }

    //Points&Badging
    AwardPointsAction = Class();
    AwardPointsAction.prototype = {
        initialize: function(userKey, points, currencyType) {
            var data = new Object();
            data.UserKey = userKey;
            data.Points = points;
            data.CurrencyType = currencyType;
            this.AwardPointsAction = data;
        }
    }

    BadgeFamily = Class();
    BadgeFamily.prototype = {
        initialize: function(badgeFamilyKey) {
            var data = new Object();
            data.BadgeFamilyKey = badgeFamilyKey;
            this.BadgeFamily = data;
        }
    }

    BadgeFamilies = Class();
    BadgeFamilies.prototype = {
        initialize: function() {
            var data = new Object();
            this.BadgeFamilies = data;
        }
    }

    BadgingEventAction = Class();
    BadgingEventAction.prototype = {
        initialize: function(activityName, activityTags, userTags) {
            var data = new Object();
            data.ActivityName = activityName;
            data.ActivityTags = activityTags
            data.UserTags = userTags;
            this.BadgingEventAction = data;
        }
    }

    GrantBadgeAction = Class();
    GrantBadgeAction.prototype = {
        initialize: function(userKey, badgeFamilyKey, badgeKey) {
            var data = new Object();
            data.UserKey = userKey;
            data.BadgeFamilyKey = badgeFamilyKey
            data.BadgeKey = badgeKey;
            this.GrantBadgeAction = data;
        }
    }

    Leaderboard = Class();
    Leaderboard.prototype = {
        initialize: function(leaderboardKey) {
            var data = new Object();
            data.LeaderboardKey = leaderboardKey;
            this.Leaderboard = data;
        }
    }

    Leaderboards = Class();
    Leaderboards.prototype = {
        initialize: function() {
            var data = new Object();
            this.Leaderboards = data;
        }
    }

    LeaderboardRankingsPage = Class();
    LeaderboardRankingsPage.prototype = {
        initialize: function(leaderboardKey, oneBasedOnPage) {
            var data = new Object();
            data.LeaderboardKey = leaderboardKey;
            data.OnPage = oneBasedOnPage;
            this.LeaderboardRankingsPage = data;
        }
    }

    RevokeBadgeAction = Class();
    RevokeBadgeAction.prototype = {
        initialize: function(userKey, badgeFamilyKey, badgeKey) {
            var data = new Object();
            data.UserKey = userKey;
            data.BadgeFamilyKey = badgeFamilyKey
            data.BadgeKey = badgeKey;
            this.RevokeBadgeAction = data;
        }
    }

    PointsAndBadgingRuleValidationAction = Class();
    PointsAndBadgingRuleValidationAction.prototype = {
        initialize: function(rules) {
            var data = new Object();
            data.Rules = rules;
            this.PointsAndBadgingRuleValidationAction = data;
        }
    }

    AbuseItemPage = Class();
    AbuseItemPage.prototype = {
        initialize: function(numberPerPage, onPage, section, maxReportsPerItem) {
            var data = new Object();
            data.NumberPerPage = numberPerPage;
            data.OnPage = onPage;
            data.Section = section;
            data.MaxReportsPerItem = maxReportsPerItem;
            this.AbuseItemPage = data;
        }
    }

    AbuseItem = Class();
    AbuseItem.prototype = {
        initialize: function(targetKey) {
            var data = new Object();
            data.TargetKey = targetKey;
            this.AbuseItem = data;
        }
    }

    ClearAbuseAction = Class();
    ClearAbuseAction.prototype = {
        initialize: function(targetKey) {
            var data = new Object();
            data.TargetKey = targetKey;
            this.ClearAbuseAction = data;
        }
    }

    SetCommentBlockingStateAction = Class();
    SetCommentBlockingStateAction.prototype = {
        initialize: function(commentKey, blockingState) {
            var data = new Object();
            data.CommentKey = commentKey;
            data.CommentBlockingState = blockingState;
            this.SetCommentBlockingStateAction = data;
        }
    }
    //Community feed
    RecentActivityRequest = Class();
    RecentActivityRequest.prototype = {
        initialize: function(activityForTypes, count) {
            var data = new Object();
            data.ActivityForTypes = activityForTypes;
            data.Count = count;
            this.RecentActivityRequest = data;
        }
    }

    // updates the flag on individual content as to
    // whether or not the content will be included in
    // discovery results
    UpdateDiscoveryFilterFlagOnContentAction = Class();
    UpdateDiscoveryFilterFlagOnContentAction.prototype = {
        initialize: function(content, excludeContentFlag) {
            var data = new Object();
            data.DiscoveryFilterFlagExcludeThisContent = content;
            data.ExcludeContentFlag = excludeContentFlag;
            this.UpdateDiscoveryFilterFlagOnContentAction = data;
        }
    };

    SendTwitterMessageAction = Class();
    SendTwitterMessageAction.prototype = {
    	initialize: function(message, url, template){
    		var data = new Object();
    		data.Message = message;
    		data.Url = url;
    		data.Template = template;
    		this.SendTwitterMessageAction = data;
    	}
    }

    UserTwitterStatus = Class();
    UserTwitterStatus.prototype = {
    	initialize: function(userKey){
    		var data = new Object();
    		data.UserKey = userKey;
    		this.UserTwitterStatus = data;
    	}
    }


    UserTwitterFriends = Class();
    UserTwitterFriends.prototype = {
    	initialize: function(numberPerPage, onPage){
    		var data = new Object();
    		data.NumberPerPage = numberPerPage;
    		data.OnPage = onPage;
    		this.UserTwitterFriends = data;
    	}
    }

    UserExtendedPrefs = Class();
    UserExtendedPrefs.prototype = {
    	initialize: function(userKey){
    		var data = new Object();
    		data.UserKey = userKey;
    		this.UserExtendedPrefs = data;
    	}
    }

    UpdateUserExtendedPrefAction = Class();
    UpdateUserExtendedPrefAction.prototype = {
    	initialize: function(name, value){
    		var data = new Object();
    		data.PrefName = name;
    		data.PrefValue = value;
    		this.UpdateUserExtendedPrefAction = data;
    	}
    }

})();


/*
    Gannett - Sitelife Integration JavaScript API 

    This script if responsible communicating with USAToday and SiteLife servers, 
    to deliver custom SiteLife widgets.  These widgets include:
        - User Avatar
        - Comments (Comment form and paginated comment list)
        - Review Widget (Review form and paginated review List)
        - Article Reaction Count Control
        - Article Recommend Control
        - Article Discovery Controls

    Dependancies:
        - SiteLife Direct Access API
            - prototype
            - scriptaculous

    References to integrated technologies: 
        - SiteLife DAAPI    http://sitelifestage.usatoday.com/api/index.htm         
        - AJAX              http://en.wikipedia.org/wiki/Ajax_%28programming%29
        - AHAH              http://microformats.org/wiki/rest/ahah        
        - Pork iFrames      http://www.schizofreend.nl/Pork.Iframe/
        - JSON Transforms   http://goessner.net/articles/jsont/
        - Prototype         http://www.prototypejs.org/
        - Scriptaculous     http://wiki.script.aculo.us/scriptaculous/
 
   Created: 1/10/07 by Josh West of Amentra, Inc for USAToday.com
    Modified: 4/04/2007 by Kevin Meredith and Sophak Phou of Amentra, Inc for GMTI.
        - Added functionality specifically for GMTI purposes
        - Removed USAToday specific functionality.
    Modified: 4/20/2007 by Kevin Meredith
        - Added contentURL to getArticleLink function
        - Added comment/recommend count to Discovery Actions
        - Added decodeURI() function to Discovery Actions title
   Modified: 07/17/2007 by Sophak Phou
            - Added function to populate dynamic html tags load onto page after initial onload function(DynamicArticleControls)
 Modified 3/3/2008 by SSS
	 - Added maximum comment character count to be dynamic
	 - Added sort order for article commnets
Modified 5/01/2008
	Added user friendly error message if, user enters space in comment box.                            
	Added a fix to clear the avatar variable to fix issue with wrong avatar on article pages & persona page occasionally.                       
	Added implementation to handle the time offset for Hawaii/Guam sites's comments.        
	Added new Reply-To and "New post" feature to article comments and also a new Full comments article page where user can view just comments.                                 
	Fixed a bug where sort option shows up if the article has only recommends and not comments. 
Modified 5/28/2008
	Added a feature to display the remaining number of characters
	Changed the pagination links on articlecomments to execute the full page refresh. 
	Page will also refresh whenever user submits the comments or changes the sort order. 
Modified 6/30/2008
	Added monitoring function to check avalaibility and rendring issues of daapi calls 
Modified 9/8/2008 by SSS
	Removed extra pluck batch call
	Fixed bug in UpdateArticleAction function
	Added Article authors id to batch call
	Added pagination link at top for full comment page 
Modified 9/25/2008 SSS
	Updated all the relative URL to fix issue with URL rewrite.
Modified 10/09/2008 SSS
	Added new function getDiscoveryTabcontent to support the frontpage tab module
	Updated the ArticleControls function.
Modified 03/27/2009 SSS
	Commented the unnecessary condition inside requestbatch function
	modifed the code to support the AT cookie expire function
Modified 05/08/2009 YT
	Added new function to support Comment Pre Moderation.
Modified 10/12/2009 SSS
	Added the code to scrub the HTML out of comment
 */
var gsl = {
    
    /*************************************************************************/
    /* Site Configurations ***************************************************/
    enabled: true,
    sitelifeApiUrl: "",
    personaHrefEnabled: true,
    personaHrefURL: "",
    commentCountHrefEnabled: true,
    reviewCountHrefEnabled: true,
    recommendCountHrefEnabled: true,
	reportabuseposx:"",
	reportabuseposy:"",
	fullcommentpage:0,
	totalnocomments:0,
	resized:false,
	params:"",
    /* Default Configuration *************************************************/
    /*************************************************************************/
    linkLblUrl: new Array(),
    linkUrl: new Array(),
    linkUIDEnabled: new Array(),
    personaHref:" ",
    personaUserKey:" ",
	dynElement:null,
	wilDaapiWork:"true",
	plkIframeId:99,
	initDaapiReq:"http://sitelife."+ document.domain +"/ver1.0/Content/images/no-user-image.gif",
	pluckSigninPage:"/apps/pbcs.dll/section?category=Pluck_signin",	
    // Page Configuration Settings (modify on individual pages -or- in environment config)
    exceptionLogging: false,    // on/off - log gsl exceptions    
    apiLogging: false,          // on/off - log sitelife calls
    widgetLogging: false,       // on/off - log interactions with custom sitelife widgets
    Debug: 1,                   // on/off - if debugDiv exists display debugging info
    _updateArticle: false,      // DO NOT MODIFY!
    _keyUsed: false,
    IsOdd:1,
	plkreplycomment:"",
    /*************************************************************************/
    /* Fronts Controls *******************************************************/
    // Fronts Controls Environment Configuration
    requestsPerBatch: 10,
    
    // Fronts Controls Page Configuration
    discoveryAge: "12",    // number of days for discovery widgets
    
    /*************************************************************************/
    /* GMTI SiteLife Library Initialization **********************************/

    initialSetup: function(userID) {
        try {
		    if(this.enabled==true) {
				this.checkDaapiAvailable();
				if (this.wilDaapiWork=="true"){
	        		 if($("gslComments")) {
						//check is user is recaching the page
						var checkURL = window.location.href.toLowerCase();
						if((checkURL.indexOf("cmsedit") > 0 || checkURL.indexOf("cmsstage") > 0 || checkURL.indexOf("cmsqa") > 0) && checkURL.indexOf("nocache=1") > 0)
							{
							var SetContentPolicy = "";
							//if so, check CommentPreModeration value
							if(typeof(CommentPreModeration) != undefined && CommentPreModeration == 'checked')
								{
								SetContentPolicy = "ApprovalRequired";
								} else {
										SetContentPolicy = "Allowed";
										}
							gsl.CommentPreModeration(SetContentPolicy);
							}
						this.Comments(); 
					}
					 else if($("gslReviews")) {   this.Reviews();   } 
					//if(typeof(contentID) != "undefined") { this.AddThisArticle(); }
	                if(gsl.ArticleControls) { gsl.ArticleControls(); }  // Scans page for Article Controls
				}
				else
					document.getElementById("IE6Error").style.display ="block"; 
            }   
        } catch(e) {
            this.showException("initialSetup", e);
        }
    },
	//Make a Call to Set Comment Policy for that article
	CommentPreModeration: function(SetContentPolicy) {
			var rb= new RequestBatch();
			var setPolicyRequest = new SetContentPolicyAction(new ArticleKey(contentID), new UserTier("Standard"), new ContentPolicyActionType("Comment"), new ContentPolicy(SetContentPolicy));
            rb.AddToRequest(setPolicyRequest);
            //rb.BeginRequest(serverUrl, OnSetComplete);
			this.sitelifeRequest(rb, "Set Comments Policy", this.OnSetComplete); 
	},
	//Dislpay what Pluck returns back
	OnSetComplete: function(ReturnedJSON) {
		//Don't do anything in the Call back function for now.
    },


  _templates: {'comments': {'loaded': false}, 'reviews': {'loaded': false}},
    _avatarOverride: false,
    _updateArticle: false,
    
    /*************************************************************************/
    /* SiteLife User *********************************************************/
    
    getUserPhotoLink: function(pid, photo) {
        if(pid != "anonymous"){
            var personaHtml= "<img src='" + photo + "' alt='User Image'/>"; 
            gsl.personaHref = photo;
            if(gsl.personaHrefEnabled){
                var personaHtmlHref = "<a href='" + gsl.sitedomain+gsl.personaHrefURL + '&U=' + pid + "'>" +personaHtml+ "</a>";
                personaHtml = personaHtmlHref;
            }
            return personaHtml;
        }
        else return "";
    },

    getUserPersona: function(pid) {
        return gsl.sitedomain + gsl.personaHrefURL + '&U=' + pid;
    },
    
    
    getUserHandle: function() {
        var cookie = GDN.Cookie.Get("at");
		return gsl.TempGetnamevalue(cookie,"a");
    },
    
    getUserHandleLink: function(pid, handle,aboutme,age,location,sex) {
        var personaHref= this.getUserPersona(pid);
      
	  var handleHtml= "<a href='" + gsl.sitedomain+gsl.personaHrefURL + "&U=" + pid + "'><b>" + handle + "</b></a>"; 
        return handleHtml;       
    },
    
    getUserPid: function() {
       return GDN.Cookies.Pluck.GetValue("UserId");
    },
    
    getUserMsgsLink: function(msgs) {
        var msgLink = "<a href='" + this.personaUrl + "?plckPersonaPage=PersonaMessages'>" + msgs + " messages</a>";
        return msgLink;
    },

   /*************************************************************************/
    /* Report Abuse - ra *****************************************************/
    
    getReportAbuseLink: function(type, key, reported) {
        var raHtml= "";
        
        if (reported==true) {
            raHtml += "<span id='gslReportAbuse:" + type + ":" + key + "' class='gslAbuseReported'>Reported</span>"; 
        } else {    
            raHtml += "<span id='gslReportAbuse:" + type + ":" + key + "' class='gslReportAbuseLink'>";    
            raHtml += "<a href='#none' onclick=\"javascript:gsl.ReportAbuse(event, '" + type + "', '" + key + "'); return false;\">Report Abuse</a>";			
            raHtml += "</span>"; 
        }
        return raHtml;    
    },
	
	getReplyToLink: function(key) {
	var replyhtml= "<a class='reply' href='javascript:gsl.addquote(\""+key+"\")';>Reply to this Post</a>";
	return replyhtml;
	},
	
	ReportAbuse: function(evt, type, key) {
      this._showDivAtMouse(evt, "gslReportAbuseForm");
        $("gslReportAbuseType").value= type;
        $("gslReportAbuseKey").value= key;
    },
    
    reportAbuseSubmit: function() {
        var key= $("gslReportAbuseKey").value;
        var type= $("gslReportAbuseType").value;
        var text= $("gslReportAbuseCommentText").value;
        var reason= $("gslReportAbuseReason").value;
       this.reportAbuseClose();

        var cntKey= null;
        if (type == 'comment') {
            cntKey= new CommentKey(key);
        } else if (type == 'article') {
            cntKey= new ArticleKey(key);
        } else if (type == 'review') {
            cntKey= new ReviewKey(key);
        } else if (type == 'photo') {
            cntKey= new PhotoKey(key);
			//gpg.pgAbuseArray[$("gsl_pg_currentno").value]= true;
			if (typeof(gpg.localMasterPGArray)!='undefined')
			gpg.localMasterPGArray[gpg.globalpgpageno][$("gsl_pg_currentno").value].CurrentUserHasReportedAbuse = "true";
		}		

        var raReq= new RequestBatch();	 
        raReq.AddToRequest(new ReportAbuseAction(cntKey, reason, text)); 
        this.sitelifeRequest(raReq, "SubmitReportAbuse", this._reportAbuseCallback);
        
        var raLink= $("gslReportAbuse:"+type+":"+key);
        if(raLink) raLink.innerHTML= this.getReportAbuseLink(type, key, true);   
    },
    
    _reportAbuseCallback: function(res) {
        if(res.Messages.length > 0 && res.Messages[0].Message=="ok") {
        } else {
            alert("Report Abuse Failed: " + res.Messages[0].Message);
        }
    },
    
    reportAbuseClose: function() {
        this._hideDiv("gslReportAbuseForm");
        $("gslReportAbuseKey").value= "";
        $("gslReportAbuseType").value= "";
        $("gslReportAbuseCommentText").value= "";
        $("gslReportAbuseReason").value= "Obscenity or vulgarity";       
    },   
        

  /*************************************************************************/
    /* Comments - com ********************************************************/
    
    Comments: function() {
        // expects <div id="gslComments"></div> to exist on page
        // <div id="gslCountControl"> and <div id="gslRecommendControl"> optional
        
        // Load Comment Templates
		 gsl._templates.comments['loaded']= true;
      
		  if(gsl.reactionsClosed==false) {
            gsl.updateReactionFormHead('comment');
        }
		 gsl.getReactions('comment');  
		
    },
          
    /*************************************************************************/
    /* Reviews - rev *********************************************************/    

    Reviews: function() {
        // expects <div id="gslReviews"></div> to exist on page
        // <div id="gslCountControl"> and <div id="gslRecommendControl"> optional
        
        // Load Review Templates
        gsl._templates.reviews['loaded']= true; 
               if(gsl.reactionsClosed==false) {
         
            gsl.updateReactionFormHead('review');
        }  
		gsl.getReactions('review'); 		
    },
    
    getReviewCountControl: function(count, link) {
        var revCntCtl="";
        revCntCtl= "<span class='gslReviewsLink'><a href='" + link + "' alt='Go to reviews'><span class='gslReviewsLabel'>Reviews</span><span class='gslReviewsCount'>" + gsl.niceNumber(count) + "</span></a></span>";        
        return revCntCtl;        
    },
    
    getRatingControl: function(rating, enabled) {
        var ratCtl= "";      
        if(enabled==true && this._templates.reviews['loaded']==true) {
            ratCtl= this._templates.reviews['ratingControl'];           
        } else {
            ratCtl = "<img alt='' src='" + this.ratingStarsUrl + "null_zero.jpg' border='0' />";
            ratCtl += "<img alt='' src='" + this._getRatingImageUrl('0') + "' border='0'>";
        }       
        return ratCtl;
    },
 
    getRatingImage: function(rating) {
        var ratHtml= "<img alt='' src='" + this._getRatingImageUrl(rating) + "' border='0'>";
        return ratHtml;  
    },
    
    _getRatingImageUrl: function(rating) {
        var starsUrl = "";
        var ratNum = parseInt(Math.round(rating));
        switch(ratNum) {
            case 1: starsUrl = this.ratingStarsUrl + "00.jpg"; break;
            case 2: starsUrl = this.ratingStarsUrl + "05.jpg"; break;
            case 3: starsUrl = this.ratingStarsUrl + "10.jpg"; break;
            case 4: starsUrl = this.ratingStarsUrl + "15.jpg"; break;
            case 5: starsUrl = this.ratingStarsUrl + "20.jpg"; break;
            case 6: starsUrl = this.ratingStarsUrl + "25.jpg"; break;
            case 7: starsUrl = this.ratingStarsUrl + "30.jpg"; break;
            case 8: starsUrl = this.ratingStarsUrl + "35.jpg"; break;
            case 9: starsUrl = this.ratingStarsUrl + "40.jpg"; break;
            default: starsUrl = this.ratingStarsUrl + "00.jpg"; break; 
        }
        return starsUrl;
    },

    _fillRatingStar: function(ratingStars, ratingField, rating) {
        var ratStars= $(ratingStars);
        var ratField= $(ratingField);
        
        var oldRating= parseInt(ratField.value,10);
        var newRating= rating;
        
        if (newRating < 1 && oldRating >= newRating) { newRating = oldRating};
        
        if (newRating >=1 && newRating <= 9) {
            ratStars.src = this._getRatingImageUrl(newRating);
        } else {
            ratStars.src = this._getRatingImageUrl('0');
        }
    },
    
    _setRating: function(ratingField, rating) {
        var ratField= $(ratingField);
        ratField.value= rating;
    },
	
	addquote:function(key) {
	var content;
	if(key){
		var author = $("author_"+key).value;
		content = $("body_"+key).value;
		gsl.plkreplycomment = content;
	}
	var form_id = "gslComFormBody";
	var form_el = $(form_id);
	if(content){
		author = author.replace(/.+<b>([^<]+)<\/b>.+/i, "$1");
		content = "[QUOTE]"+content+"[/QUOTE]\n";
		$('gslQuoteAuthor').value = "<span class='author'>"+author+"</span>";
		form_el.value = content;
	} else {
		form_el.value = "";
	}
	var frmEl = $("gslComFormBody");
		if (!frmEl.disabled){
			frmEl.scrollTo();
			frmEl.focus();
			gsl.char_count(frmEl);
		}
	},

    /*************************************************************************/
    /* Reactions - aka Comments and Reviews Common Logic *********************/
   
    getReactions: function(type, page) {
   
		gsl.params = new String(window.location.href.toString().replace(/^[^\?]+\?/,"")).toQueryParams();
		if (typeof(gsl.params["pluckarticleid"]) != 'undefined' ){
			$("pluckarticleid").style.display ="block";
			$("pluckarticleid").innerHTML = "Pluck Article ID = " + contentID;
			}
			if (gsl.fullcommentpage)
					window["contentID"] = gsl.params["key"];
		if (typeof(gsl.params["page"])!='undefined') gsl.params["page"] = gsl.params["page"].replace("#pluckcomments","");
		page = gsl.params["page"] || 1;
		if (typeof(gsl.params["s"])=='undefined') gsl.params["s"]=$('gslSortOrder').value ;
	
		this.commentSortOrder = ((gsl.params["s"] == "a") ? "TimeStampAscending" : "TimeStampDescending");
		//After 1.2.4 please delete or change the follwoing first if condition 
		if (typeof($("gslCharCount"))!='undefined' || gsl.fullcommentpage){
			if(this.commentSortOrder=="TimeStampAscending") {
				$('gslSortOrder').value = "a";
			} else {
				$('gslSortOrder').value = "d";
			}
		}
		else
			$('gslSortOrder').value = this.commentSortOrder;
		
		if(typeof($("gslCharCount"))!='undefined') $("gslCharCount").innerHTML = gsl.commentMaxChars;
		this.commentSortOrder = ((this.commentSortOrder=="") ? "TimeStampDescending" : this.commentSortOrder);
        var articleKey= this.getArticleKey();
        
        var rb= new RequestBatch();
         
        if (type=='comment') {
            rb.AddToRequest(new CommentPage(new ArticleKey(articleKey),gsl.requestsperBatch,page,this.commentSortOrder));
        } else if (type=='review') {
            rb.AddToRequest(new ReviewPage(new ArticleKey(articleKey),gsl.requestsperBatch,page,this.reviewSortOrder));
        } else {
            this.showException("getReactions: type not specified");
        }
       
        rb.AddToRequest(new ArticleKey(articleKey));
		if(typeof(contentAutID)!= 'undefined' && contentAutID != "") 
			rb.AddToRequest(new UserKey(contentAutID));
        this.sitelifeRequest(rb, "LoadReactions", this._getReactionsCallback);   
    },
    
    _getReactionsCallback: function(resBatch) {
        var rPage= null;
        var rList= null;
        var rType= null;
        var article= null;
        var i= 0;
        for ( i=0; i<resBatch.Responses.length; i++) {
            var res = resBatch.Responses[i];           
            if (res.CommentPage != null) {
                rPage= res.CommentPage;
                rList= res.CommentPage.Comments;
                rType= 'comment';   
             } else if (res.ReviewPage != null) {
                rPage= res.ReviewPage;
                rList= res.ReviewPage.Reviews;
                rType= 'review';        
            } else if (res.Article != null ) {
                article= res.Article;
			
				if (res.Article.Comments.NumberOfComments > 1 && (typeof($("gslsort"))!='undefined' && $("gslsort")!=''))
				$("gslsort").style.display ="block";	
				if (gsl.fullcommentpage){
					window["contentURL"] = article.PageUrl;
					window["contentTitle"] =article.PageTitle;
					var titleLink = document.createElement("a");
					titleLink.setAttribute("href", article.PageUrl);
					titleLink.innerHTML = article.PageTitle;
					$("gslTitleName").innerHTML = "for <span></span>";
					var el = $("gslTitleName").getElementsByTagName("span")[0];
					el.appendChild(titleLink);	
				}
				gsl.totalnocomments= parseInt(res.Article.Comments.NumberOfComments);
				
				// var bylinedivs= document.getElementsByClassName("ratingbyline");
				// for(i=0; i<bylinedivs.length; i++) {
				// var bylinediv = bylinedivs[0];
				
            
			 } else if (res.User != null ) {
					if (typeof($("gslshowAuthImg"))!='undefined' ) {
					var authdiv = $("gslshowAuthImg");
					var authdivtext = "";
					authdivtext = "<a href=\"/apps/pbcs.dll/section?category=pluckpersona&U="+res.User.UserKey.Key +"\" alt='Go to Author persona'>";
					authdivtext +="<img src=\""+res.User.AvatarPhotoUrl+"\" alt=\"Author Image\">";
					authdivtext +="<\/img><\/a>";
					authdiv.innerHTML = authdivtext;
					
				}
				}
        }
        // save reponses page for debugging purposes (javascript:alert(gsl.responses.toJSONString().replace(/:{/g, ":\n{").replace(/},/g, "},\n"));)
        if (resBatch.Responses) { gsl.responses = resBatch.Responses; }        
            
        // set UpdateArticleAction flag if article has not been updated yet
        //if(!article || (article && (!article.Section || article.Categories.length==0))) {      
         //   gsl._updateArticle= true;
       // }
		
		 gsl._updateArticle = gsl._compareArticleInfo(article);
		if (gsl._updateArticle && gsl.updateOnLoad) {
                    var rb = new RequestBatch();
                    gsl.sitelifeRequest(rb, "UpdateArticle", gsl._upArtCB);
			}
        if(rPage) {                     // populate summary
            if (rType=='comment') {
                var comCnt= (typeof(gslComCountOffset)!='undefined' && gslComCountOffset!='')? gslComCountOffset : 0; 
                comCnt= parseInt(comCnt) + parseInt(rPage.NumberOfComments)
				
            } else if (rType=='review') {
                var smryHtml= "<div class='gslRevSmry'><span class='gslRevSmryCount'>Reviews: (" + gsl.niceNumber(rPage.NumberOfReviews) + ")</span>";
                if (gsl.ratingsEnabled==true)
                    smryHtml += "<span class='gslRevSmryRating'>Average Rating: <span class='gslRevSmryRatingStars'>" + gsl.getRatingImage(rPage.AverageReviewRating) + "</span></span></div>";
                
                $("gslReactionSummary").innerHTML= smryHtml;
            } 
        }
    
        if(rList) {                     // populate coment/review list
            var rListHtml= "";
            for (i=0; i<rList.length; i++) {
                rListHtml += gsl._getReactionHtml( rType, rList[i] );
            } 
            $("gslReactionList").innerHTML= rListHtml;
		}
        
        if(rPage){    			// populate pagination control
		//After 1.2.4 please delete or change the follwoing first if condition 
			if (typeof($("gslCharCount"))=='undefined' && gsl.fullcommentpage)
				 $("gslPagination2").innerHTML= gsl.getPaginationControl(rType, rPage);
			 else
			 {
				if (gsl.fullcommentpage && $("gslPagination_Top")!=null)
					$("gslPagination_Top").innerHTML= gsl.getPaginationControl(rType, rPage);
				$("gslPagination").innerHTML= gsl.getPaginationControl(rType, rPage);
			}
		}
        // var cntCtl= $("gslCommentsCount");
        // if (cntCtl) {        // populate comment/review count control
            // if (rType=='comment') {
				//cntCtl.innerHTML="";
                // var comCnt= (typeof(gslComCountOffset)!='undefined' && gslComCountOffset!='')? gslComCountOffset : 0; 
                // if (article) { 
                    // comCnt= parseInt(comCnt) + parseInt(article.Comments.NumberOfComments) 
                // } 				
				// cntCtl.innerHTML ="("+comCnt+")";
            // } else if (rType=='review') {  
                // var revCnt=0;
                // if (article) {
                    // revCnt= article.Reviews.NumberOfReviews;
                // }    
                // cntCtl.innerHTML= gsl.getReviewCountControl(revCnt, "#gslPageReturn"); // output review count control
            // }
        // } 
		// else
		// {
			 if (rType=='comment') {
				//cntCtl.innerHTML="";
                var comCnt= (typeof(gslComCountOffset)!='undefined' && gslComCountOffset!='')? gslComCountOffset : 0; 
				  if(rPage){   
				   comCnt= parseInt(comCnt) + parseInt(rPage.NumberOfComments) 
				   } else if (article) { 
                    comCnt= parseInt(comCnt) + parseInt(article.Comments.NumberOfComments) 
                } 
				var articlekey = gsl.getArticleKey();
				if (typeof($("gslCtl-article|comments|"+articlekey))!='undefined' && $("gslCtl-article|comments|"+articlekey) != null){
					var bylinecontrolcomment = $("gslCtl-article|comments|"+articlekey);
					bylinecontrolcomment.innerHTML = gsl.getCommentCountControl(parseInt(rPage.NumberOfComments),"");
				} else if (comCnt == "1"){					
					if(comCtl=$('gslCtl|comments|'+articlekey))
						comCtl.innerHTML="";
					comCtl.innerHTML= gsl.getCommentCountControl(comCnt, "#gslPageReturn"); // output comment count control
				}
				if (typeof($("gslCtl-article|recommends|"+articlekey))!='undefined' && $("gslCtl-article|recommends|"+articlekey) !=null){
					var recCtl=$('gslCtl-article|recommends|'+articlekey);
		            var recCount=0; 
		            var recd=false;
		            if (article && article.Recommendations ) {
		                recCount=parseInt(article.Recommendations.NumberOfRecommendations);
		                recd= (article.Recommendations.CurrentUserHasRecommended=="True")? true : false;
		            }
		            recCtl.innerHTML= gsl.getRecommendCountControl('articles',articlekey, recCount, recd);
				}
			}
		//}
		// This section is obsolete ..need to test it and take it out in future release. 2/20/2009-SSS
		if (typeof($("gslRecommendControl"))!='undefined' && $("gslRecommendControl") !=null){
	        var recCtl= $("gslRecommendControl");
	        if (recCtl) {        // populate content control
	            var recd=false;
	            var recCnt=0;
	            var artKey= gsl.getArticleKey();
	            if (article) {
	                recd= (article.Recommendations && article.Recommendations.CurrentUserHasRecommended=='True')? true: false;
	                recCnt= article.Recommendations.NumberOfRecommendations;
	                artKey= article.ArticleKey.Key;
	            }
	            
	            recCtl.innerHTML= gsl.getRecommendCountControl('article', artKey, recCnt, recd); 
	        }
		}
    },    

    _getReactionHtml: function(type, reaction) {
        var reacHtml= "";
		var IsBlockedUserloggedin = false;
		var classalt ="";
		
		if(GDN.Cookie.Exists("at") && gsl.getUserPid() == reaction.Author.UserKey.Key)
			IsBlockedUserloggedin =true;
			
		if (reaction.AbuseReportCount < gsl.MaxNumberofAbuse){
		
		    if(reaction.Author.IsBlocked!="True" || IsBlockedUserloggedin){
			    
		        var authorKey= reaction.Author.UserKey.Key;
		            var recd= (reaction.CurrentUserHasRecommended=="True")? true: false;
		            var rptd= (reaction.CurrentUserHasReportedAbuse=="True")? true: false;
		            var staffMark= (reaction.Author.UserTier=="Editor" || reaction.Author.UserTier=="Staff")? gsl.SiteStaffText : "";
		            var recNum= reaction.NumberOfRecommendations;
					var sitetimezone = 	((typeof(gsl.TimeZonewords) != "undefined") && (typeof(gsl.TimeZoneoffset) != "undefined"))? gsl.TimeZonewords:"";
		            recNum= (!recNum)? '0': recNum;
					
		        if (type=='comment') {
				 var comKey= reaction.CommentKey.Key;
				var reportabusetext = (reaction.Author.UserTier=="Editor" || reaction.Author.UserTier=="Staff")?"":this.getReportAbuseLink('comment',comKey,rptd);
		           
		            if (gsl.IsOdd == 1) {
						classalt="odd";
						gsl.IsOdd = 0;
						}
						else{
						classalt="even";
						gsl.IsOdd = 1;
						}
		            var commentData= {
		                'authorIcon': this.getUserPhotoLink(authorKey, reaction.Author.AvatarPhotoUrl),
		                'authorHandle': this.getUserHandleLink(authorKey, reaction.Author.DisplayName,reaction.Author.AboutMe,reaction.Author.Age,reaction.Author.Location,reaction.Author.Sex),
		                'commentTimestamp': this.niceDate(reaction.PostedAtTime)+" "+sitetimezone,
		                'commentBody': reaction.CommentBody,
		                'commentKey': comKey,
		                'recommendLink': this.getRecommendCountControl('comments',comKey,recNum,recd),
						
		                'reportAbuseLink': reportabusetext,
		                'staffMark': staffMark,
		                'siteofOrigin':reaction.SiteOfOrigin,
						'alt':classalt,
						'authorNameHandle':reaction.Author.DisplayName,
						'replylink':this.getReplyToLink(comKey),
						'newpostLink':'<a class="newpost" href="javascript:gsl.addquote(null);">New post</a>'
		            };
		           
		            try {       
		                reacHtml= this._transform(commentData, $("comment").innerHTML);
		            } catch(e) {
		                this.showException("_getReactionHtml() comment transform" , e);
		            } 
		            
		        } else if (type=='review') {
		            var revKey= reaction.ReviewKey.Key;
		            var rating= "";
		            if (this.ratingsEnabled==true)
		                rating= this.getRatingImage(reaction.ReviewRating);
		            
		            var reviewData= {
		                'authorIcon': this.getUserPhotoLink(authorKey, reaction.Author.AvatarPhotoUrl),
		                'authorHandle': this.getUserHandleLink(authorKey, reaction.Author.DisplayName),
		                'reviewTimestamp': this.niceDate(reaction.PostedAtTime),
		                'reviewTitle': reaction.ReviewTitle,
		                'reviewRating': rating,
		                'reviewBody': reaction.ReviewBody,
		                'reviewKey': revKey,
		                'recommendLink': this.getRecommendCountControl('review',revKey,recNum,recd),
		                'reportAbuseLink': this.getReportAbuseLink('review',revKey,rptd),
		                'staffMark': staffMark
		            };
		          
		            try {       
		                reacHtml= this._transform(reviewData, $("review").innerHTML);
		            } catch(e) {
		                this.showException("_getReactionHtml() review transform" , e);
		            }       
		        }
			}	
		}
	//	}
        return reacHtml;  
    },
 
    updateReactionFormHead: function(type, signOut) {
        if ( this.reactionsClosed==false && (this._templates.comments['loaded']==true || this._templates.reviews['loaded']==true )) {
            
            var reacFormHead= $("gslReactionFormHead");
            if(reacFormHead) {
                var headHtml= ""; 
               if (!GDN.Cookie.Exists("at")) {
                    // no transform necessary for logged out template
					 if (type=='comment') {
                    $("headLoggedIn").style.display = "none";
                    $("headLoggedOut").style.display ="block";
					}
					else if (type=='review') {
					$("headLoggedIn").style.display = "none";
                    $("headLoggedOut").style.display ="block";
					}
                           
                } else {
                   // Currently we dont need to get userinfo at login header section
                   // var uHandleLink= this.getUserHandleLink(this.getUserPid(), this.getUserHandle());
                   // var headerData= { 'userHandleLink':uHandleLink };
                    var headerTemplate= "";
                    if (type=='comment') {
                        $("headLoggedIn").style.display = "block";
                        $("headLoggedOut").style.display ="none";
						 headerTemplate= document.getElementById("headLoggedIn").innerHTML;
                    } else if (type=='review') {
                        $("headLoggedIn").style.display = "block";
                        $("headLoggedOut").style.display ="none";
						 headerTemplate= document.getElementById("headLoggedIn").innerHTML;
                    } 
                    
                    try {
						
						var maxcharacters={'maxchars':gsl.commentMaxChars};
                        headHtml= this._transform(maxcharacters, headerTemplate);
                    } catch (e) {
                        this.showException("updateReactionFormHead() head transform" , e);
                    }         
                } 
                document.getElementById("headLoggedIn").innerHTML= headHtml;
            }        
            
            if (type=='comment') {
                var comBody= $("gslComFormBody");
                var comBtn= $("gslComFormSubmit");
                if(comBody && comBtn) {
                    if (!GDN.Cookie.Exists("at")) {     
                        comBody.disabled = true;
                        comBody.value="";  
                        comBtn.disabled = true;                                     
                    } else {
                        comBody.disabled = false; 
						comBody.value=""; 
                        comBtn.disabled = false; 
                    }
                }           
            } else if (type=='review') {
                var revTitle= $("gslRevFormTitle");
                var revRating= $("gslRevFormRatingControl");
                var revBody= $("gslRevFormBody");
                var revBtn= $("gslRevFormSubmit");
                if(revTitle && revRating && revBody && revBtn) {
                    if (!GDN.Cookie.Exists("at")) {      
                        revTitle.disabled= true; 
                        revTitle.value="";
                        if (this.ratingsEnabled==true) {
                            revRating.innerHTML= this.getRatingControl(0, false);
                        } else {
                            revRating.innerHTML="";
                        }
                        revBody.disabled= true; 
                        revBody.value="";
                        revBtn.disabled= true;                                                             
                    } else {
                        revTitle.disabled= false; 
                        if (this.ratingsEnabled==true) {
                            revRating.innerHTML= this.getRatingControl(0, true); 
                        } else {
                            revRating.innerHTML="";
                        }
                        revBody.disabled= false; 
                        revBtn.disabled= false; 
                    }
                }
            } 
            
            // Reset Error block in form
            var errorNode=$("gslFormError");
            if (errorNode) errorNode.innerHTML="";             

            
        } 
    },    
    
    getPaginationControl: function(type, page) {
        var reacCount= (type=='comment')? page.NumberOfComments: page.NumberOfReviews;
        var plusMinus= this.paginationLinks;
        var pageControl= "";	
		var new_url = "";

		//After 1.2.4 please delete or change the follwoing first if condition 
		if (typeof($("gslCharCount"))=='undefined' && !gsl.fullcommentpage){
		var tempsortselected = "";
		if(gsl.params["s"]=="TimeStampAscending") {
				tempsortselected = "a";
			} else {
				tempsortselected = "d";
			}
		new_url= (gsl.fullcommentpage)? "/apps/pbcs.dll/section?Category=pluckcomments&key="+gsl.params["key"]+"&s="+tempsortselected+"&page=":contentURL+"&s="+tempsortselected+"&page=";
        }
		else
		new_url= (gsl.fullcommentpage)? "/apps/pbcs.dll/section?Category=pluckcomments&key="+gsl.params["key"]+"&s="+gsl.params["s"]+"&page=":contentURL+"&s="+gsl.params["s"]+"&page=";
		
		        if (reacCount > gsl.requestsperBatch) {
            var pageDiv = parseInt(reacCount)/gsl.requestsperBatch;
            if (pageDiv > parseInt(pageDiv)) {
                pageDiv += 1;
            }
            pageDiv = parseInt(pageDiv);

            var ll, ul;
            var rPoP = page.OnPage;
            var pnp = rPoP-1;
            
            if (rPoP != 1) {
            pageControl += " <a href=\""+new_url+"#pluckcomments\" alt='Go to first page'>First</a> ";
			pageControl += " <a href=\""+new_url+pnp.toString()+"#pluckcomments\" alt='Go to previous page'><<</a> ";

            }
            ll = rPoP - plusMinus;
            ul = parseInt(rPoP) + plusMinus;

            if (ll < 1) {
                ll =1;
            } 
            if (ul>pageDiv) {
                ul = pageDiv;
            }
            
            for (var i=ll; i<=ul; i++)
            {
                if (rPoP != i) {
                    pageControl += " <a href=\""+new_url+i.toString()+"#pluckcomments\">" + i + "</a> ";
                } else pageControl += " " + i + " ";
            }
            pnp = pnp+2;
            if (rPoP != pageDiv) {
          	pageControl += " <a href=\""+new_url+pnp.toString()+"#pluckcomments\" alt='Go to next page'>>></a> ";
			pageControl += " <a href=\""+new_url+pageDiv.toString()+"#pluckcomments\" alt='Go to last page'>Last</a>";            
            }
			if(typeof($("gslfullpagecomment"))!='undefined' && $("gslfullpagecomment")!='' && !gsl.fullcommentpage){
			pageControl += "<div class='gslfullpage' style='display:none'>"+
				"<a class='button clear' href='javascript:gsl.redirectToCommentPage();'>"+
				"Full page view"+
				"</a> <em>See more comments per page and quote other replies</em>"+
				"</div>";
			}
        } 
        
        return pageControl;
    },
	
    submitReaction: function() {
        var type= $("gslReactionType").value;
        var tmpl= ""; 
        var body= "";
        var bwfBody= "";
        var max= 0;
        var err= $("gslFormError"); 
        err.innerHTML= "";
        var emptyFlag= false;
        
         if (type=='comment') {
            tmpl= this._templates.comments;
            body= $("gslComFormBody").value; 
            bwfBody= body; 
            max= this.commentMaxChars;
            
            if (body.length==0 || !this.hasWhiteSpace(body)) {
                err.innerHTML= $('missingInputError').innerHTML;
                setTimeout("$('gslComFormBody').focus()", 1); 
                return false;
            }
			if (this.checkBodyLength(body, max)==false) {
				var data= {'maxchars':max};
				err.innerHTML= this._transform(data, $('entryTooLongError').innerHTML);
				return false;
			}
				var el = $("gslComFormBody");
				if (el.value.indexOf("[QUOTE]") != -1 || el.value.indexOf("[\QUOTE]") != -1 ){
					return_str = el.value.sub(/\[QUOTE\](.*)\[\/QUOTE\]/, "");
					return_str = return_str.replace(/<(.|\n)*?>/g, ""); 	
					return_str = "<p class='replyingto'>Replying to "+ $('gslQuoteAuthor').value + ":</p>" +
								  "<blockquote>" + gsl.plkreplycomment + "</blockquote>" + return_str;
					
				} else {
					return_str = el.value.replace(/<(.|\n)*?>/g, ""); 		
				}
				el.value =return_str;
		} else if (type=='review') {
            tmpl= this._templates.reviews;
            var revTitle= $("gslRevFormTitle").value;
            var revRating= (ratNode= $("gslRevFormRating"))? ratNode.value : 0;
            body= $("gslRevFormBody").value;
            bwfBody= body + " " + revTitle;
            max= this.reviewMaxChars;
            emptyFlag= (body.length==0 || revTitle.length==0)? true: false;
            
            if (body.length==0 || revTitle.length==0) {
				err.innerHTML= $('missingInputError').innerHTML;
                if (revTitle.length==0) { setTimeout("$('gslRevFormTitle').focus()", 1); }
                else if (body.length==0) { setTimeout("$('gslRevFormBody').focus()", 1); }
                return false;
            }
        }
        
       
			
            this._submitReactionToSiteLife();
        
       
          
    },
	
	hasWhiteSpace:function (s){
     reWhiteSpace = new RegExp(/^\s+$/);

     // Check for white space
     if (reWhiteSpace.test(s)) {
         
          return false;
     }
	return true;
	},
	
	redirectToCommentPage:function (){
	
		if (gsl.totalnocomments>gsl.requestsperBatch){
			var base_url = "/apps/pbcs.dll/section?Category=pluckcomments&key="+gsl.getArticleKey();
			var dir = gsl.commentSortOrder;
			if(dir == "TimeStampAscending"){
				base_url += "&s=a";
			} else {
				base_url += "&s=d";
			}
			window.location.href = base_url;
		}
		else
			window.location.href = "#pluckcomments";
	},
 	
    _submitReactionToSiteLife: function() {
        var type= $("gslReactionType").value;
        var title= document.title;
        var articleKey= this.getArticleKey();    
        var articleLink= this.getArticleLink(document.location.toString().split('#')[0]+"#gslPageReturn");
        var rb= new RequestBatch();

        if (type=='comment') { 
            var comBody= $("gslComFormBody").value;
			comBody= this.return2br(comBody);
            rb.AddToRequest(new CommentAction(new ArticleKey(articleKey), articleLink, title, comBody));
			
			//Add another request to check if User is Standard
			var userKey = new UserKey(gsl.getUserPid()); 
			rb.AddToRequest(userKey);
   
            $("gslComFormBody").value= "";
            
        } else if (type=='review') {
            var revTitle= $("gslRevFormTitle").value;
            var revRating= (this.ratingsEnabled==true)? $("gslRevFormRating").value : 0;
            var revBody= $("gslRevFormBody").value;
            rb.AddToRequest(new ReviewAction(new ArticleKey(articleKey), articleLink, title, revTitle, revRating, revBody, null, null));
            
            $("gslRevFormTitle").value = "";
            $("gslRevFormBody").value = "";
            if (this.ratingsEnabled==true) {
                this._setRating('gslRevFormRating', 1);
                this._fillRatingStar('gslRevFormStars', 'gslRevFormRating', -1);  
            }
        }
        
        this.sitelifeRequest(rb, "SubmitReaction", this._submitReactionToSiteLifeCallback);   
    },
    
    _submitReactionToSiteLifeCallback: function(res) {
        var type= $("gslReactionType").value;
        
        for (var i=0; i<res.Messages.length; i++) {
            var msg = res.Messages[i];
            if (msg.Message != "ok") {
				if (msg.Message.indexOf("User not allowed to execute command")!= -1) {
					msg.Message = "We are sorry, your session has been expired, you will be redirected to sign in page";
					window.location.href = gsl.pluckSigninPage + "&destination=" +encodeURIComponent(location.href);
				}
					$("gslFormError").innerHTML = msg.Message;
			        gsl.showException("_submitReactionToSiteLifeCallback" + msg.Message);
            } else {
                    var reacCount =  gsl.totalnocomments;
					var curPage = parseInt(gsl.params["page"] || 1);
					var pageDiv = Math.ceil(reacCount / gsl.requestsperBatch);
					var desc = ((gsl.params["s"] == "a") ? false : true);
					var npage;
					var response= res.Responses[i];
					var resUserTier = response.User.UserTier;
					if(desc && curPage>1){
						npage = 1;
					} else if(!desc && curPage<pageDiv){
						npage = pageDiv;
					}	
					if(npage){	
						var new_url = (gsl.fullcommentpage)? "/apps/pbcs.dll/section?Category=pluckcomments&key="+gsl.params["key"]+"&s="+gsl.params["s"]+"&page=":contentURL+"&s="+gsl.params["s"]+"&page=";
						window.location.href = new_url + npage.toString();
					} else {
						//Display message if Comments are premoderated
						if(typeof(CommentPreModeration) != 'undefined' && CommentPreModeration == 'checked' && resUserTier == 'Standard'){
							var err= $("gslFormError");
							if($("gslFormPreModeration")){err.innerHTML = $("gslFormPreModeration").innerHTML;}
						} else {
						//Otherwise refresh the page to get comment from pluck and show it in the page
						window.location.reload();
						}
					}
                }
				
        }
    },
    	
    checkBodyLength: function(body, max) {
        if (body.length <= max) { 
            return true;
        } else {
            return false;
        }
    },    
    //Convert carrage returns - line feeds to HTML <br />
	return2br:function (dataStr) {
        return dataStr.replace(/(\r\n|[\r\n])/g, "<br />");
    },
    /*************************************************************************/
    /* Article - art *********************************************************/ 
    
    getArticleKey: function() {   
    /* need to know where they have their articleKey */ 
        var id = (typeof(contentID)!='undefined') ? contentID : null;
        if (id == null) {gsl.showDebug("No contentID found.  Returned null");}
        return id;
    },


    getArticleTitle: function() {
        // if gsl.contentTitle is not set, then parse it out of the browser title bar
        var title= contentTitle || "";
        if(title == ""){
            title= document.title;   // Will need to strip off what ever comes in as the title
            title= title.split('#')[0];  
        }                   // strip off any #anchor/fragment
        return title;
    },

	getArticleLink: function(artId) {
        var linkURL = (typeof(contentURL) != 'undefined') ? contentURL : document.location.toString().split('#')[0];
        return linkURL;
    },
          
    // Using the 'section' discovery variable for content type (story, blog, photo, etc)   
    getArticleSection: function() {
        return new Section(this.getArticleKey().split(".")[3]);  
    },     
       
    // Using 'categories' discovery array for listing which news sections the article appears in 
    getArticleCats: function(cats) {
        if(!cats) {
            var sArtKey = gsl.getArticleKey().split(".");
            cats = new Array();
            for (x=4; x<sArtKey.length; x++) {
                cats[x-4] = sArtKey[x];
            }
        } else {
            cats= (cats && cats!='')? cats.split(".") : new Array();
        }
        var categories= new Array();            // SiteLife Category object array
        for (i=0; i<cats.length; i++) {
            categories[i]= new Category(cats[i]);
        }
        return categories;
    }, 

    _compareArticleInfo: function(article) {
        // Call UpdateArticleAction if no article info
        if(!article || (article && (!article.Section || article.Categories.length==0))) {
           return true;
        }   
        
        // Call UpdateArticleAction if section has changed
        var sec= this.getArticleSection();  
        if ( article && (article.Section && sec.Section && (article.Section.Name.toLowerCase() != sec.Section.Name))) {
            return true;
        }
        
        // Call UpdateArticleAction if categories have changed
        var cats= this.getArticleCats();  
        if ( article && article.Categories && article.Categories.length > 0) { 
            
            if (article.Categories.length != cats.length) {
                return true;
            }
            
            var i=0;
            for (i=0; i<article.Categories.length; i++) {
                if(cats[i].Category.Name.toLowerCase() != article.Categories[i].Name) {
                    return true;
                }  
            }
        } 
		 if ((typeof(contentTitle) != "undefined") && article && article.PageTitle && (article.Categories.length > 0)) { 
            if (article.PageTitle != contentTitle) {
                return true;
            }
        } 
		 if ((typeof(contentURL) != "undefined") && article && article.PageTitle && (article.Categories.length > 0)) { 
            if (article.PageUrl != contentURL) {
                return true;
            }
        } 
	   
        return false;       
    },
       
    /*************************************************************************/
    /* Comments - com ********************************************************/
       
    getCommentCountControl: function(count, link) {
        var comCntCtl="";
        var strCount= gsl.niceNumber(count);
        var strLabel= gsl.commentLbl || "Comments";
        if (count==0) {
            strCount= "0";
            strLabel= gsl.NocommentLbl || "Comment";
        }
        comCntCtl+= "<span class='gslCommentsLink'>";
        if(gsl.commentCountHrefEnabled)
            comCntCtl+= "<a href='"+link+"' title='Go to comments' alt='Go to comments'>";
			
        comCntCtl+= "<span class='gslCommentsLabel'>"+strLabel+"</span>";
		if (count!=0){
        comCntCtl+= "<span id='gslCommentsCount' class='gslCommentsCount'>("+strCount+")</span>";
		}
        if(gsl.commentCountHrefEnabled)
            comCntCtl+= "</a>";
        comCntCtl+= "</span>";
        
        return comCntCtl;        
    },
                 
    /*************************************************************************/
    /* Reviews - rev *********************************************************/ 
       
    getReviewCountControl: function(count, link) {    
        var revCntCtl="";
        var strCount= gsl.niceNumber(count);
        var strLabel= gsl.reviewLbl || "Reviews";
        if (count==0) {
            strCount= "0";
            strLabel= gsl.reviewLbl || "Review";
        } 
        revCntCtl+= "<span class='gslReviewsLink'>";
        if(gsl.reviewCountHrefEnabled)
            revCntCtl+= "<a href='"+link+"' title='Go to reviews' alt='Go to reviews'>";
        revCntCtl+= "<span class='gslReviewsLabel'>"+strLabel+"</span>";
        revCntCtl+= "<span class='gslReviewsCount'>("+strCount+")</span>";
        if(gsl.reviewCountHrefEnabled)
            revCntCtl+= "</a>";
        revCntCtl+= "</span>";                     
        
        return revCntCtl;        
    },
    
    /*************************************************************************/
    /* Recommend - rec *******************************************************/ 
    
    getRecommendCountControl: function(type, key, recCount, recommended) {
        var recHtml= "";

        if (key==null || key.split('.')[0]=="") {
            recHtml += "<span class='gslDisabledRecommendLink'>";
            recHtml += "<span class='gslRecommendLabel'>"+gsl.recommendLbl+"</span>";
            recHtml += "<span class='gslDisabledRecommendCount'>(0)</span>";
            recHtml += "</span>";    
        } else {
            if (recommended==true) {
                recHtml += "<span class='gslRecommended'>";
                recHtml += "<span class='gslRecommendLabel'>"+gsl.recommendedLbl+"</span>";
                recHtml += "<span class='gslRecommendedCount'>(" + gsl.niceNumber(recCount) + ")</span>";
                recHtml += "</span>";            
            } else {  
                var strCount= gsl.niceNumber(recCount);             
                if (recCount==0) {
                    strCount= "0";
                }
                recHtml += "<span id='gslRecommend:" + type + ":" + key + "'>"; 
				recHtml += "<span class='gslRecommendLink'>";
                if(gsl.recommendCountHrefEnabled)
                    recHtml += "<a href=\"javascript:void(\'Recommend\')\" title='Recommend this article' alt='Recommend this article' onclick=\"gsl.Recommend('" + type + "','" + key + "','" + recCount + "');\">";
                recHtml += "<span class='gslRecommendLabel'>"+gsl.recommendLbl+"</span>";
                if (recCount==0){
				recHtml += "<span class='gslRecommendCount'></span>";
				} else {
                recHtml += "<span class='gslRecommendCount'>(" + strCount + ")</span>";
				}
                if(gsl.recommendCountHrefEnabled)
                    recHtml += "</a>";
                recHtml += "</span>";      
                recHtml += "</span>";
            }
        }
        return recHtml;
    },
   
    Recommend: function(type, key, recCount) {        
        var recKey= null;
        if (type=='comments') {
            recKey= new CommentKey(key);
        } else if (type=='reviews') {
            recKey= new ReviewKey(key);
        } else if (type=='articles') {
            recKey= new ArticleKey(key);
        } else if (type=='photo') {
            recKey= new PhotoKey(key);
			if(typeof(gpg)!='undefined'){
			gpg.localMasterPGArray[gpg.globalpgpageno][$("gsl_pg_currentno").value].CurrentUserHasRecommended = "True";
			gpg.localMasterPGArray[gpg.globalpgpageno][$("gsl_pg_currentno").value].NumberOfRecommendations = parseInt(gpg.localMasterPGArray[gpg.globalpgpageno][$("gsl_pg_currentno").value].NumberOfRecommendations) +1;
			}
		} else if (type=='saxophoto') {
            recKey= new ArticleKey(key);
			if(typeof(gpg)!='undefined'){
			gpg.localMasterPGArray[gpg.globalpgpageno][$("gsl_pg_currentno").value].CurrentUserHasRecommended = "True";
			gpg.localMasterPGArray[gpg.globalpgpageno][$("gsl_pg_currentno").value].NumberOfRecommendations = parseInt(gpg.localMasterPGArray[gpg.globalpgpageno][$("gsl_pg_currentno").value].NumberOfRecommendations) +1;
			}
        }		
        
        var rb= new RequestBatch();	 
        rb.AddToRequest(new RecommendAction(recKey)); 
        this.sitelifeRequest(rb, "SubmitRecommend", this._recommendCallback);
        
        var recLink= $("gslRecommend:"+type+":"+key);
        if(recLink) {
            var num= parseInt(recCount,10);
            num += 1;
            recLink.innerHTML= this.getRecommendCountControl(type, key, num, true);
        }
    },
    
    _recommendCallback: function(res) {
        if(res.Messages.length > 0 && res.Messages[0].Message=="ok") {
            gsl.showDebug("Recommend Successful");  
        } else {
            gsl.showDebug("Recommend Failed: " + res.Messages[0].Message);
        }   
        
        // save responses page for debugging purposes (javascript:alert(gsl.lastRecommendRes.toJSONString().replace(/:{/g, ":\n{").replace(/},/g, "},\n"));)
        if (gsl.Debug && res.Responses) { gsl.lastRecommendRes= res.Responses; } 

    },
    
    setSortOrder:function(){
		var sortCtrlselected = $("gslSortOrder").options[$("gslSortOrder").selectedIndex].value;
		// After 1.2.4 release please delete following condition 
		if (typeof($("gslCharCount"))=='undefined' && !gsl.fullcommentpage){
			if (sortCtrlselected == "TimeStampAscending")
				sortCtrlselected = "a";
			else
				sortCtrlselected = "d";
		}
		var new_url = (gsl.fullcommentpage)? "/apps/pbcs.dll/section?Category=pluckcomments&key="+gsl.params["key"]+"&s="+sortCtrlselected:contentURL + "&s=" + sortCtrlselected;
		window.location.href = new_url;
	}, 
              
    /*************************************************************************/
    /* AJAX Transport Functions **********************************************/
   
    sitelifeRequest: function(slBatch, action, callback) {

        // Add UpdateArticleAction to batch, if update article flag is set then 
        if (this._updateArticle==true) {
	        var articleKey= this.getArticleKey();
            var articleLink= this.getArticleLink();
            var title= this.getArticleTitle();
            var section= this.getArticleSection();
            var cats= this.getArticleCats();
            slBatch.AddToRequest(new UpdateArticleAction(new ArticleKey(articleKey), articleLink, title, section,cats));
            gsl.showDebug("Updating Article:"+articleKey+" title:"+title+" URL:"+articleLink+" section:"+section+" cats:"+cats);
        }
	  
        this.logSiteLife("gslRequest:"+action);
        var This= this;
        var callbackWrap= function(response) {
            try {
	            gsl.logSiteLife("gslResponse:"+action);
                callback(response);
            } catch(e) {
                gsl.showException("SL Request Callback Wrapper", e);
            }
        };     
        try {    
            slBatch.BeginRequest(this.sitelifeApiUrl, callbackWrap); 
        } catch(e) {
            this.showException("SL Request", e);
        }
    },
    
    isSitelifeAvailable: function() {
        // check for the existence of a sitelife class 
        if(typeof(DiscoverArticlesAction)!='undefined') {
            return true;
        } else {
            return false;
        }    
    },
    
    logSiteLife: function(msg) {         
        gsl.showDebug(msg);
    },
    
    /*************************************************************************/
    /* Utility Functions *****************************************************/
    
     _mouseX: function(evt) {
        if (evt.pageX) return evt.pageX;
        else if (evt.clientX)
            return evt.clientX + (document.documentElement.scrollLeft ?
            document.documentElement.scrollLeft :
            document.body.scrollLeft);
        else return null;
    },
    
    _mouseY: function(evt) {
        if (evt.pageY) return evt.pageY;
        else if (evt.clientY)
            return evt.clientY + (document.documentElement.scrollTop ?
            document.documentElement.scrollTop :
            document.body.scrollTop);
        else return null;
    },
    
    _hideDiv: function(id){
        document.getElementById(id).style.display = "none";
    },
    
    _showDivAtMouse: function(evt, id) {
        posx = this._mouseX(evt) - 170;
        posy = this._mouseY(evt);
        document.getElementById(id).style.left = posx + "px";
        document.getElementById(id).style.top = posy + "px";
        document.getElementById(id).style.display = "block";
    },
  
    niceNumber: function(num) {
        num= num.toString();
        if(num.length<=3) {
            return (num=="")? "0" : num;
        } else {
            var niceNum= "";
            try {
                if(mod=(num.length%3)) {
                    niceNum= num.substr(0, mod)+",";
                }                
                for(i=0; i<=(num.length/3)-1; i++) {
                    if(i!=0) { niceNum= niceNum + ","; }
                    niceNum= niceNum + num.substr((3*i)+mod, 3);
                }
            } catch(e) {
                return num;
            }     
            return niceNum;
        }
    },
     
    /*************************************************************************/
    /* Debugging Functions ***************************************************/
    
    showDebug: function(debugtext) {
        if (this.Debug==1) {
            if($("debug"))
            {
                if(($("debug")).innerHTML == "")
                    ($("debug")).innerHTML += "<br /><br />DEBUG LOG<br />==========<br />";
                datestamp = new Date();
                ($("debug")).innerHTML += datestamp.toLocaleTimeString() +": "+ debugtext + "<br>";
            }
        }
    },
    
    showException: function(location, ex) {
        var msg= " ";
        if(ex && ex.name && ex.message) {
            msg= "Javascript Exception in " + location + ": " + ex.name + " - " + ex.message;
        } else {
            msg= "Error in " + location + " - " + ex;
        }
        this.showDebug(msg);
        
    },

    /*************************************************************************/
    /* Article Functions - art ***********************************************/ 
	 AddThisArticle: function(){
        var rb= new RequestBatch();
        rb.AddToRequest(new ArticleKey(gsl.getArticleKey()));
        try{
            gsl.sitelifeRequest(rb, "Add this article", this._loadATACallback);
        } catch(e) {
            this.showException("SL Request", e);
        }
    },
    
    _loadATACallback: function(result) {
        for (var i=0; i<result.Responses.length; i++) {
            var res= result.Responses[i];
            if(res.Article != null) { 
                gsl._updateArticle = gsl._compareArticleInfo(res.Article);
                if (gsl._updateArticle && gsl.updateOnLoad) {
                    var rb = new RequestBatch();
                    gsl.sitelifeRequest(rb, "UpdateArticle", gsl._upArtCB);
                }
            }
        }
    },
	
	DynamicArticleControls: function(elementID) {
	    if (elementID){
	        gsl.dynElement = $(elementID);
	        if(gsl.ArticleControls) { gsl.ArticleControls(); }
	        gsl.dynElement = null;
	    } else return;
	},
		
    ArticleControls: function() {   
        // 1. Find set of HTML elements with class "gslArticleControl" on the page. 
		    var artCtls= document.getElementsByClassName("gslArticleControl");
	       this._processDiscoveryForAll(artCtls);
    }, 

	getDiscoveryTabContent:function() {
	//  Get All the divs present on the frontpage tab module for discovery action 
		 var artClassCtls= document.getElementsByClassName("gslArticleControlTab");
		 var combinedArtCtls = new Array();
		 var count=0;
		  if (artClassCtls.length > 0) {
		   gsl.discoveryAge= $("gslDiscoveryAge").value;
			for(inc=0; inc<artClassCtls.length; inc++) {
				var artCtlsTab = artClassCtls[inc].getElementsByClassName("gslArticleControl");
				//Concat the all the arrays present on the tab so that thier will be only one pluck call 
				for(cntarr=0; cntarr<artCtlsTab.length; cntarr++) {
						combinedArtCtls[count] = artCtlsTab[cntarr];
						count++;
						}
			}
			//Call the existing discvoery function to process the discovery action.
			this._processDiscoveryForAll(combinedArtCtls);
		}
	},

	_processDiscoveryForAll: function(artCtls) {
        // 1. Parse out Article or Discovery Widget info from the HTML element's id
        // 2. Build batch(es) of Article and Discovery requests
        // 
        // Article Controls:
        //      <div id="gslCtl|[ControlType]|[ArticleKey]" class="gslArticleControl"></div>
        //      Ex: <div id="gslCtl|comments|123456789.story" class="gslArticleControl"></div>
        // Article control element id breakdown - 
        //      gslCtl | [control type] | [article id]
        //      [ControlType] = comments, reviews, or recommend
        //      [ArticleId] = unique id of article (not containing a pipe |)
        // 
        // Discovery Widgets:
        //     <div id="gslCtl|[ControlType]|[Activity]|[Section]|[Categories]|[Index]" class="gslArticleControl"></div>
        //     Ex: <div id="gslCtl|discovery|Recent|story|money.life" class="gslArticleControl"></div>
        // Discovery widget element id breakdown -
        //     gslCtl | [ControlType] | [Activity] | [Section] | [Categories] | [Index]
        //     [ControlType]= discovery
        //     [Activity]   = Recent, Commented, Reviews, or Recommended
        //     [Section]    = article type - story, blog, etc.
        //     [Categories] = period deliminated article sections - news, money, travel, money.life, news.sports, etc.
        //     [Index]      = Index of discovery widget (valid index is 1 through 10 per discovery search)

	  if (artCtls.length > 0) {
	            var controls= new Array();
	            var i=0;
	            
	            var reqBatch;  
	            var ctlCount=0;
	            for(i=0; i<artCtls.length; i++) {
	                
	                // 2. Parse out Article or Discovery Widget info from the HTML element's id
	                var ctlIda= artCtls[i].id.split("|");   //split control id attribute by pipe delimiter
	                
	                var cid;
	                var type="";
	                // Will need to find gslCtl in all templates and switch to new name, gslCtl
	                if (ctlIda[0]=='gslCtl' && ctlIda.length==3) { 
	                    cid= ctlIda[2];
	                    type= ctlIda[1];    // count or recommend
	                } else if (ctlIda[0]=='gslCtl' && ctlIda.length==6) {
	                    cid= ctlIda[2]+ctlIda[3]+ctlIda[4]; //activity + section + categories;
	                    type= ctlIda[1];    // discovery
	               } else {
	                    this.showDebug("Malformed gslArticleControl Id (1)");
	                }
	                
	                // if the article id "<articleNum>.<articleType>" is blank then 
	                // clear the contents of the control and skip adding it to batch 
	                if(cid.split(".")[0]=="") {
	                    try {
	                        // clear node contents
	                        if (artCtls[i]) { artCtls[i].innerHTML= ""; }
	                    } catch(e) { }
	                    this.showException("Empty Article Id"); // log the issue in omniture
	                    continue;   // skip the rest of the loop
	                }            
	                
	                // 3. Build batch(es) of Article and Discovery requests 
	                if(!controls[cid]) {                 
	                    controls[cid]=cid;
	                    ctlCount += 1;
	                    
						//if(cid!=contentID) {
		                    if(!reqBatch) {
		                        reqBatch= new RequestBatch(); 
		                    }
		                    if (type=="comments" || type=="reviews" || type=="recommends" || type=="ratings" ) { 
		                        this.showDebug("adding article control to batch: " + type + " cid:"+ cid);   
		                        reqBatch.AddToRequest(new ArticleKey(cid));  
		                    } else if (type=="discovery") {
		                        var activity= ctlIda[2];
		                        var section= ctlIda[3];
		                        var categories= ctlIda[4];
		                        var contribs= new Array(new UserTier("All"));
		                        var maxIndex= this._findDiscoveryMaxIndex(activity, section, categories);
		                        this.showDebug("adding discovery control to batch: " + type + " cid:"+ cid);   
								reqBatch.AddToRequest(new DiscoverArticlesAction(new Array(new Section(section)), this.getArticleCats(categories), contribs, new Activity(activity), this.discoveryAge, maxIndex));    
		                    } else {
		                        this.showDebug("Malformed gslArticleControl Id (2) - type: " + type + " cid: "+cid);
		                    }
		                                 
		                    if(ctlCount!=1 && (ctlCount%this.requestsPerBatch)==0) {
		                        this.sitelifeRequest(reqBatch, "LoadArticleCtls", this._ArticleControlsCallback);     
		                        reqBatch = null;
		                    }
						//}
	                }
	            }
	            
	            if(ctlCount > 0 && (ctlCount%this.requestsPerBatch)!=0 && !gsl.ie6Error) {
	                this.sitelifeRequest(reqBatch, "LoadArticleCtls", this._ArticleControlsCallback); 
	            }
	        }
	},
	
    _findDiscoveryMaxIndex: function(activity, section, categories) {
        // find max disovery widget index
        var j=1;
        for(j=1; j<=10; j++) {
            var discElem= $('gslCtl|discovery|'+activity+'|'+section+'|'+categories+'|'+j);
            if(!discElem) {
                return j-1;
            }
        }   
        return 10; 
    },

    _ArticleControlsCallback: function(result) {
        var j=0;
        var k=0;
        // Process Controls Successfully Retrieved
        for ( j=0; j<result.Responses.length; j++) {
            if (result.Responses[j].Article) {
                
                // Process Article Control
                var article= result.Responses[j].Article;
                gsl._processArticleControl(article.ArticleKey.Key, article);
                
            } else if (result.Responses[j].DiscoverArticlesAction) {
            
                // Process Discovery Widget
                var disovAction= result.Responses[j].DiscoverArticlesAction;
                var discArts= result.Responses[j].DiscoverArticlesAction.DiscoveredArticles;
                var k=0;
                for ( k=0; k<discArts.length; k++) {
                    var discov= discArts[k]; 
                    if (discov) {
                        gsl._processDiscoveryControl(discov, k+1, disovAction.SearchSections, disovAction.SearchCategories, disovAction.Activity.Name);
                    }
                }                
            } 
        } 
        
        // Process ArticlesKeys That Were Not Found
        for ( j=0; j<result.Messages.length; j++) {
            // When ArticleKey is not found, this is returned as a message
            // "Unable to find data on request:[ArticleRequest] ArticleKey = [RequestedArticleKey]; Key = [RequestedArticleKey]"
            var msg="";
            article= {}; // clear out article
            // If the msg is the unable to find message
            if( (msg=result.Messages[j].Message) && msg.substr(0,14)=="Unable to find") {
                // get the article key
                var key="";
                try {
                    // No article record -> Populate article control anyway
                    key= msg.split("= [")[1].split("];")[0];
                    gsl._processArticleControl(key, article);
                    
                } catch(e) {
                    gsl.showException("Unable to extract ArticleKey from batch", e);
                    continue;
                }
            }
        }  
        if (gsl.Debug && result.Responses) { gsl.lastArtCtlRes= result.Responses; }     
    },

    _processArticleControl: function(key, article) {
        // Populate all controls that coorespond to the SiteLife article object <acticle>    
        this.showDebug("processing article control - key: "+key);    
        var revCtl;
        if (revCtl=$('gslCtl|reviews|'+key)) {
            var revCnt= (article.Reviews)? article.Reviews.NumberOfReviews : 0;    // get review count 
            var revLink="";
            if (typeof(gslReviewLinks)!='undefined') {
                revLink= (link=gslReviewLinks[key])? link: gsl.getArticleLink(key);
                revLink += "#gslPageReturn";
            } else {
                revLink= gsl.getArticleLink(key) + "#gslPageReturn";
            }        
            revCtl.innerHTML= gsl.getReviewCountControl(revCnt, revLink); 
        }
        //#gslPageReturn is the anchor to link to on the page
        var comCtl;
        if (comCtl=$('gslCtl|comments|'+key)) {
            var comLink="";   
            var comCnt= (article.Comments)? article.Comments.NumberOfComments : 0;    // get comment count                  
            if (typeof(gslComCountOffset)!='undefined') {
                comCnt = parseInt(comCnt) + parseInt((offset=gslComCountOffset[key])? offset: 0); // add offset to review count (typepad legacy support)
            }
            if (typeof(gslCommentLinks)!='undefined') {
                comLink= (link=gslCommentLinks[key])? link: gsl.getArticleLink(key);
                comLink += "#gslPageReturn";
            } else {
                comLink= gsl.getArticleLink(key) + "#gslPageReturn";
            }
            comCtl.innerHTML= gsl.getCommentCountControl(comCnt, comLink);                     
        }
        
        var recCtl;
        if (recCtl=$('gslCtl|recommends|'+key)) {
            var recCount=0; 
            var recd=false;
            if (article.Recommendations) {
                recCount= article.Recommendations.NumberOfRecommendations;
                recd= (article.Recommendations.CurrentUserHasRecommended=="True")? true : false;
            }
            recCtl.innerHTML= gsl.getRecommendCountControl('articles', key, recCount, recd);
        }
        

    },

    _processDiscoveryControl: function(article, index, sections, categories, activity) {
        // Populate the discovery widget
        var strSections= this._getNameValues(sections);
        var strCats= this._getNameValues(categories);
        
        this.showDebug("processing article: "+article.ArticleKey.Key+" index: "+index+" sections: "+strSections+" cats: "+categories+" activity: "+activity);
        
        var ctlNode= $('gslCtl|discovery|'+activity+'|'+strSections+'|'+strCats+'|'+index);
        if (ctlNode) {
            var key= article.ArticleKey.Key;
            var title= (article.PageTitle)? article.PageTitle : activity+' '+strSections+' '+strCats;
            var link= (article.PageUrl)? article.PageUrl : this.getArticleLink(key);
             if (activity == "Commented") 
                var number = article.Comments.NumberOfComments;
            else if (activity == "Rated")
                var number = article.Ratings.NumberOfRatings;
            else if (activity == "Recommended")
                var number = article.Recommendations.NumberOfRecommendations;
            else if (activity == "Reviewed")
                var number = article.Reviews.NumberOfReviews;
            else 
                var number = null;
            ctlNode.innerHTML= this.getDiscoveryLinkControl( index, title, link, activity, number);

        }
    },

    _getNameValues: function(arr, delim) {
        var valArray= new Array();
        var i=0;
        for (i=0; i<arr.length; i++) {
            valArray[i]= arr[i].Name;
        }
        return valArray.join(delim);
    },

    getDiscoveryLinkControl: function(index, title, href, type, count) {
        var discCtl="";
      
        discCtl+= "<span class='gslDiscoveryControl'>";
        //discCtl+= " <span class='gslDiscoveryIndex'>"+index+".</span>";
        discCtl+= " <span class='gslDiscoveryLink'>";
        discCtl+= "  <span class='gslDiscovery" + type + "'>";
        discCtl+= "   <a href='"+href+"' title='Go to article' alt='Go to article'>"+unescape(title)+"</a>";
        if (count != null) {discCtl+= "    <span class='gslDiscoveryCount'>("+count+")</span>";}
        discCtl+= "  </span>";
        discCtl+= "  <div class='gslDiscoverySeparator'></div>";
        discCtl+= " </span>";
        discCtl+= "</span>";
        
        return discCtl;  
    },
    
    /*************************************************************************/
    /* SiteLife Thumbnail Functions ******************************************/
    
	checkDaapiAvailable: function(){
	var getpk1cookie = GDN.Cookies.Session.GetValue("pk1");
	if (typeof(getpk1cookie) == "undefined" || getpk1cookie == null )
		gsl.checkpluckconnectivity();
	else
		this.wilDaapiWork = getpk1cookie;
	},
	
	checkpluckconnectivity:function() {
		 var form = this._generateForm(this.plkIframeId,gsl.initDaapiReq, "");
		 try {
		 this._iframeinitialize(form,"",this.plkIframeId);
		 document.body.removeChild(document.body.lastChild);
		  document.body.removeChild(document.body.lastChild);
		 GDN.Cookies.Session.SetValue("pk1",escape(this.wilDaapiWork));
		 }
		 catch (e) {
		 this.wilDaapiWork = "false";
		 GDN.Cookies.Session.SetValue("pk1",escape(this.wilDaapiWork));
		 document.body.removeChild(document.body.lastChild);
		  document.body.removeChild(document.body.lastChild);
		 }
   },
   
	_iframeinitialize: function(form, options,count){
		if (!options) options = {};
		this.form = form;
		document.iframeLoaders[count] = this;
		this.transport = this._getTransport();
		if (((navigator.vendor && (navigator.vendor.indexOf('Apple')) > -1) || window.opera) // safari and opera only
     && (/\/Direct\/Process(\?|$)/.test(form.action)) && form.elements && (form.elements.length == 1)) { // only change calls that contain 1 element and whose actions end with /Direct/Process
			var url = form.action + '?jsonRequest=' + escape(form.elements[0].value), // change form submit to string; similar to changing form method to get
					doc = this.transport.contentWindow || this.transport.contentDocument; // retrieve the document of the iframe
			if (url.length < 80000) { // allow fallback to normal submission (80k is the max length for urls in safari)
				if (doc.document) // make sure we have the document and not the window
					doc = doc.document;
				try { // if this fails, fallback to normal submission
					doc.location.replace(url); // use location.replace to overwrite elements in history 
					return;
				} catch (e) { };
			}
		}
		form.target= 'frame_'+this.plkIframeId;
		form.setAttribute("target", 'frame_'+this.plkIframeId); // in case the other one fails.
		form.submit();
	},

	_getTransport: function() {
		var divElm = document.createElement('DIV'), frame;
		divElm.setAttribute('style', 'width: 0; height: 0; margin: 0; padding: 0; visibility: hidden; overflow: hidden');
		if (navigator.userAgent.indexOf('MSIE') > 0 && navigator.userAgent.indexOf('Opera') == -1) {// switch to the crappy solution for IE
			divElm.style.width = 0;
			divElm.style.height = 0;
			divElm.style.margin = 0;
			divElm.style.padding = 0;
			divElm.style.visibility = 'hidden';
			divElm.style.overflow = 'hidden';
			divElm.innerHTML = '<iframe name=\"frame_'+this.plkIframeId+'\" id=\"frame_'+this.plkIframeId+'\" src=\"about:blank\" onload=\""></iframe>';
		} else {
			frame = document.createElement("iframe");
			frame.setAttribute("name", "frame_"+this.plkIframeId);
			frame.setAttribute("id", "frame_"+this.plkIframeId);
			divElm.appendChild(frame);
		}
		document.body.appendChild(divElm);
		return frame;
	},
	
	_generateForm:function (formId, serverUrl, inputVal) {
	    // create the form
		var form = document.createElement("form");
		form.acceptCharset = "UTF-8";
		form.name = "f" + formId;
		form.id = "f" + formId;
		form.action = serverUrl;
		// Firefox has a behavior on refresh that displays a popup confirming that is it reloading a form.
		// We work around this by attempting to perform a get action if the size is below a threshold, else
		// we will run as a post
		form.method = "post";
	    if(navigator.userAgent.toLowerCase().indexOf('firefox') != -1) {
		    var fullRequestURL = serverUrl;
	        if (fullRequestURL.length < 15000) {
	            // we plan to perform a get, so we need to parse the sid out of the url and place it
	            // inside the form
	            var sidPos = serverUrl.indexOf('sid=');
	            if (sidPos != -1) {
	                var endPos = serverUrl.indexOf('&', sidPos);
	                var sid = serverUrl.substring(sidPos + 'sid='.length, endPos == -1 ? serverUrl.length : endPos);
		            var sidInputElem = document.createElement("input");
		            sidInputElem.name = "sid";
		            sidInputElem.type = "hidden";
		            sidInputElem.value = sid;
		            form.appendChild(sidInputElem);
		            // remove the sid from the url
		            form.action = serverUrl.substring(0, sidPos-1);
	            }
	            form.method = "get";
	        }
	    }		
		// append the form to the document body
		// users must be cautious of when they call this due to a bug in IE
		// see http://support.microsoft.com/kb/927917 for details
		document.body.appendChild(form);
		return form;
	}, 

	getUserAvatarAddress: function(){
		gsl.personaHref= null;
		 if(this.enabled==true) {
		 this._updateArticle=false;
	        var rb= new RequestBatch();
	        rb.AddToRequest(new UserKey());
	        try{
	            gsl.sitelifeRequest(rb, "LoadAvatarAddress", this._loadUAACallback);
	        } catch(e) {
	            this.showException("SL Request", e);
	        }
		 }
    },
    
    _loadUAACallback: function(result)
    {
	
        for (var i=0; i<result.Responses.length; i++) {
            var res= result.Responses[i];
            if (res.User != null) {
                var user=res.User;
                gsl.personaUserKey = user.UserKey.Key;
                gsl.personaHref = user.AvatarPhotoUrl;
            }
        }
    },

    _upArtCB: function(response) {
        if (response.Messages[0].Message != "ok") 
            showDebug("SiteLife Error: "+response.Messages[0].Message);
    },

    populateAvatar: function(pid, photo) {
        if($("gslAvtPhoto"))
           $("gslAvtPhoto").innerHTML = gsl.getUserPhotoLink(pid, photo);
    }, 
  
   _transform: function(data, template) {
        var self = data;
        var rules = { "self" : unescape(template) };
  
        var T = {
          output: false,
          init: function() {
             for (var rule in rules)
                if (rule.substr(0,4) != "self")
                   rules["self."+rule] = rules[rule];
             return this;
          },
          apply: function(expr) {
             var trf = function(s){ return s.replace(/{([A-Za-z0-9_\$\.\[\]\'@\(\)]+)}/g,
                                      function($0,$1){return T.processArg($1, expr);})},
                 x = expr.replace(/\[[0-9]+\]/g, "[*]"), res;
             if (x in rules) {
                if (typeof(rules[x]) == "string")
                   res = trf(rules[x]);
                else if (typeof(rules[x]) == "function")
                   res = trf(rules[x](eval(expr)).toString());
             }
             else
                res = T.eval(expr);
             return res;
          },
          processArg: function(arg, parentExpr) {
             var expand = function(a,e){return (e=a.replace(/^\$/,e)).substr(0,4)!="self" ? ("self."+e) : e; },
                 res = "";
             T.output = true;
             if (arg.charAt(0) == "@")
                res = eval(arg.replace(/@([A-za-z0-9_]+)\(([A-Za-z0-9_\$\.\[\]\']+)\)/,
                                       function($0,$1,$2){return "rules['self."+$1+"']("+expand($2,parentExpr)+")";}));
             else if (arg != "$")
                res = T.apply(expand(arg, parentExpr));
             else
                res = T.eval(parentExpr);
             T.output = false;
             return res;
          },
          eval: function(expr) {
             var v = eval(expr), res = "";
             if (typeof(v) != "undefined") {
                if (v instanceof Array) {
                   for (var i=0; i<v.length; i++)
                      if (typeof(v[i]) != "undefined")
                         res += T.apply(expr+"["+i+"]");
                }
                else if (typeof(v) == "object") {
                   for (var m in v)
                      if (typeof(v[m]) != "undefined")
                         res += T.apply(expr+"."+m);
                }
                else if (T.output)
                   res += v;
             }
             return res;
          }
        };
        
        try {
            return T.init().apply("self");    
        } catch(e) {
            this.showException("_transform()" , e);
            return " ";
        }
    },
    
    
    
        niceDate: function(date){
        var retDate= date;
        if( typeof(niceDate)=='undefined') {
			if(typeof(gsl.TimeZoneoffset) != "undefined" && gsl.TimeZoneoffset !="" )
				retDate= this.convertTimeZone(date);
			else
				retDate= date;
        } else {
            try {
				if(typeof(gsl.TimeZoneoffset) != "undefined" && gsl.TimeZoneoffset !="")
					retDate=this.convertTimeZone(date);
				else
					retDate= niceDate(date);
            } catch(e) {
                retDate= date;  
            }
        }
        return retDate;
    },
	
	convertTimeZone:function(pkdate){
	try{    
    var datetimeobjs =  pkdate.split(" ");
	var dateobjs = datetimeobjs[0].split("/");
	var ampm = "";
	var plucktime = new Date();
	var parseformat = gsl_dateFormat.i18n.monthNames[dateobjs[0]-1]+ ", " + dateobjs[1] + " " + dateobjs[2] +" " + datetimeobjs[1] +" " + datetimeobjs[2];
	plucktime.setTime(Date.parse(parseformat));
	plucktime.setTime(plucktime.getTime() + gsl.TimeZoneoffset * 3600000 );
	var dtformat= gsl_dateFormat(plucktime, "mm/dd/yyyy h:MM:ss tt");
	 
	} catch(e) {
            this.showException("convertTimeZone", e);
        }
		return dtformat;
	},
	
	TempGetnamevalue:function (query,queryname){
		keypairs = new Object();
		  numKP = 1;
		    // Local vars used to store and keep track of name/value pairs
		    // as we parse them back into a usable form.
		  while (query.indexOf('&') > -1) {
		    keypairs[numKP] = query.substring(0,query.indexOf('&'));
		    query = query.substring((query.indexOf('&')) + 1);
		    numKP++;
		      // Split the query string at each '&', storing the left-hand side
		      // of the split in a new keypairs[] holder, and chopping the query
		      // so that it gets the value of the right-hand string.
		  }
		  keypairs[numKP] = query;
		    for (i in keypairs) {
		    keyName = keypairs[i].substring(0,keypairs[i].indexOf('='));
		      // Left of '=' is name.
		    keyValue = keypairs[i].substring((keypairs[i].indexOf('=')) + 1);
		      // Right of '=' is value.
			
			  if (keyName == queryname){
			  return keyValue;
			  }
		    while (keyValue.indexOf('+') > -1) {
		      keyValue = keyValue.substring(0,keyValue.indexOf('+')) + ' ' + keyValue.substring(keyValue.indexOf('+') + 1);
		        // Replace each '+' in data string with a space.
		    }
		 keyValue = unescape(keyValue);
			
		}
	},
	
	char_count:function (el) {
	try{   
		if (typeof($("gslCharCount"))!='undefined'){
			remain = gsl.commentMaxChars - el.value.length; 
			$('gslCharCount').innerHTML = remain;
			if(remain==0) 
				alert("No characters remaining.");
			 else if(remain < 500 && gsl.resized == false) {
				$('gslComFormBody').setStyle({height: "170px"});
				gsl.resized = true;
			}
		  }
		} catch(e) {
			this.showException("Character count function", e);
        }
	}
	
    
};
/*
	Date Format 1.1
	(c) 2007 Steven Levithan <stevenlevithan.com>
	MIT license
	With code by Scott Trenda (Z and o flags, and enhanced brevity)
*/

/*** dateFormat
	Accepts a date, a mask, or a date and a mask.
	Returns a formatted version of the given date.
	The date defaults to the current date/time.
	The mask defaults ``"ddd mmm d yyyy HH:MM:ss"``.
*/
var gsl_dateFormat = function () {
	var	token        = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloZ]|"[^"]*"|'[^']*'/g,
		timezone     = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (value, length) {
			value = String(value);
			length = parseInt(length) || 2;
			while (value.length < length)
				value = "0" + value;
			return value;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask) {
		// Treat the first argument as a mask if it doesn't contain any numbers
		if (
			arguments.length == 1 &&
			(typeof date == "string" || date instanceof String) &&
			!/\d/.test(date)
		) {
			mask = date;
			date = undefined;
		}

		date = date ? new Date(date) : new Date();
		if (isNaN(date))
			throw "invalid date";

		var dF = gsl_dateFormat;
		mask   = String(dF.masks[mask] || mask || dF.masks["default"]);

		var	d = date.getDate(),
			D = date.getDay(),
			m = date.getMonth(),
			y = date.getFullYear(),
			H = date.getHours(),
			M = date.getMinutes(),
			s = date.getSeconds(),
			L = date.getMilliseconds(),
			o = date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "a.m." : "p.m.",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4)
			};

		return mask.replace(token, function ($0) {
			return ($0 in flags) ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
gsl_dateFormat.masks = {
	"default":       "ddd mmm d yyyy HH:MM:ss",
	shortDate:       "m/d/yy",
	mediumDate:      "mmm d, yyyy",
	longDate:        "mmmm d, yyyy",
	fullDate:        "dddd, mmmm d, yyyy",
	shortTime:       "h:MM TT",
	mediumTime:      "h:MM:ss TT",
	longTime:        "h:MM:ss TT Z",
	isoDate:         "yyyy-mm-dd",
	isoTime:         "HH:MM:ss",
	isoDateTime:     "yyyy-mm-dd'T'HH:MM:ss",
	isoFullDateTime: "yyyy-mm-dd'T'HH:MM:ss.lo"
};

// Internationalization strings
gsl_dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask) {
	return gsl_dateFormat(this, mask);
};


gsl.sitedomain="http:/"+"/www.sheboyganpress.com";
gsl.personaHrefURL="/apps/pbcs.dll/section?category=pluckpersona";
gsl.enabled=true;                      // Option to enable or disable all of SiteLife DAAPI widgets (Enabled by DEFAULT).
gsl.sitelifeApiUrl="http:/"+"/sitelife.sheboyganpress.com/ver1.0/Direct/Process?sid=sitelife.sheboyganpress.com";  // The SiteLife DAAPI URL.
gsl.personaHrefEnabled=true;     // Option to enable the user thumbnail photo as a link. (Requires personaHrefURL if enabled).
gsl.commentCountHrefEnabled=false;     // Option to enable the comment count as a link
gsl.reviewCountHrefEnabled=false;      // Option to enable the review count as a link
gsl.recommendCountHrefEnabled=false;    // Option to enable the recomment count as a link
gsl.updateOnLoad=true;                // Option to allow update article information on page load
gsl.commentLbl=" Read Comments"; // Label of the Comment Count
gsl.NocommentLbl=" Post a Comment"; // Label of the Zero Comment Count
gsl.reviewLbl="Read Reviews";          // Label of the Review Count
gsl.recommendLbl=" Recommend";
gsl.recommendedLbl=" Recommended";
gsl.commentMaxChars=1000;
gsl.commentSortOrder="TimeStampDescending";
gsl.reviewMaxChars= 1000;
gsl.reviewSortOrder="TimeStampDescending";
gsl.reactionsClosed=false;
gsl.paginationLinks=4;
gsl.requestsperBatch=10; //Maximum value 10 , best prctice not to reduce less than 10 
gsl.MaxNumberofAbuse=3; //Maximum number of abuse report count i.e. if it exceeds that comment wont be shown on page. 
gsl.SiteStaffText="sheboyganpress.com Staff";


/*
******************************************************************************
       File: GCIONSettings.js
  Copyright: Copyright (c) 2008, Gannett Inc. All rights reserved.
******************************************************************************
*/

/* ==================================================================== */
/* Defines common global settings                                       */
/* ==================================================================== */

var gdn_language = "eng";
var gdn_timeout  = 20;
var gdn_coppaage = 13;

/* ==================================================================== */
/* Defines global settings for user authentication                      */
/* ==================================================================== */

var gdn_enable_auth_by_division        = true;
var gdn_enable_third_party_by_division = true;

/* ==================================================================== */
/* Defines global settings for user registration                        */
/* ==================================================================== */

var gdn_enable_reg_by_division  = true;
var gdn_sessions                = 2;
var gdn_page_views              = 3;
var gdn_days                    = 30;
var gdn_occupation_required     = false;
var gdn_enable_bt               = true;

/* ==================================================================== */
/* Defines supported Web browsers                                       */
/* ==================================================================== */

var gdn_browsers = [];
gdn_browsers[0]  = "Explorer|>=|6.0|Windows";
gdn_browsers[1]  = "Firefox|>=|1.0|Windows";
gdn_browsers[2]  = "Firefox|>=|1.0|Mac";
gdn_browsers[3]  = "Safari|>=|1.0|Mac";

var gdn_ext_ex = []; var gdn_local_ex = []; var gdn_msgs = [1]; gdn_msgs["eng"] = []; gdn_msgs["eng"]["CancelExec"] = "Canceling your membership..."; gdn_msgs["eng"]["CancelFailed"] = "We were unable to cancel your membership"; gdn_msgs["eng"]["CancelTimeout"] = "We were unable to cancel your membership. Please try again later."; gdn_msgs["eng"]["ChangeActDupEmail"] = "The email address you entered is already in use"; gdn_msgs["eng"]["ChangeActDupUser"] = "The screen name you entered is already in use"; gdn_msgs["eng"]["ChangeActExec"] = "Updating your account..."; gdn_msgs["eng"]["ChangeActFailed"] = "We were unable to update your account"; gdn_msgs["eng"]["ChangeActTimeout"] = "We were unable to update your account. Please try again later."; gdn_msgs["eng"]["ChangePwdExec"] = "Changing your password..."; gdn_msgs["eng"]["ChangePwdFailed"] = "We were unable to change your password"; gdn_msgs["eng"]["ChangePwdInvalid"] = "Your old password is invalid"; gdn_msgs["eng"]["ChangePwdTimeout"] = "We were unable to change your password. Please try again later."; gdn_msgs["eng"]["ChangeUsrDupUser"] = "The screen name you entered is already in use"; gdn_msgs["eng"]["ChangeUsrExec"] = "Updating your account..."; gdn_msgs["eng"]["ChangeUsrFailed"] = "We were unable to update your account"; gdn_msgs["eng"]["ChangeUsrTimeout"] = "We were unable to update your account. Please try again later."; gdn_msgs["eng"]["ConfirmActivated"] = "Your account has already been activated"; gdn_msgs["eng"]["ConfirmExec"] = "Sending your confirmation email..."; gdn_msgs["eng"]["ConfirmInvalid"] = "The email address you entered is invalid"; gdn_msgs["eng"]["ConfirmTimeout"] = "We were unable to send your confirmation email. Please try again later."; gdn_msgs["eng"]["ForgotPwdExec"] = "Retrieving your password..."; gdn_msgs["eng"]["ForgotPwdInvalid"] = "The email address you entered is invalid"; gdn_msgs["eng"]["ForgotPwdTimeout"] = "We were unable to retrieve your password. Please try again later."; gdn_msgs["eng"]["LoginExec"] = "Loading..."; gdn_msgs["eng"]["LoginFailed"] = "Invalid email or password"; gdn_msgs["eng"]["LoginLockedOut"] = "Your account is locked out. Please try again in 10 minutes."; gdn_msgs["eng"]["LoginNoCookies"] = "Cookies must be enabled to log in"; gdn_msgs["eng"]["LoginTimeout"] = "Unable to log you in"; gdn_msgs["eng"]["LoginUnavailable"] = "Your {0} is currently unavailable. Please manually enter your information and click the Become a Member button to sign up now."; gdn_msgs["eng"]["NletterExec"] = "Updating your newsletter subscriptions..."; gdn_msgs["eng"]["NletterFailed"] = "Your newsletter subscriptions could not be updated"; gdn_msgs["eng"]["NletterNone"] = "No newsletters were found"; gdn_msgs["eng"]["NletterSaved"] = "Your newsletter subscriptions updated successfully"; gdn_msgs["eng"]["NletterTimeout"] = "We were unable to update your newsletter subscriptions. Please try again later."; gdn_msgs["eng"]["RegDupEmail"] = "The email address you entered is already in use"; gdn_msgs["eng"]["RegDupUser"] = "The screen name you entered is already in use"; gdn_msgs["eng"]["RegExec"] = "Registering your account..."; gdn_msgs["eng"]["RegFailed"] = "We were unable to complete your registration"; gdn_msgs["eng"]["RegTimeout"] = "We were unable to register your account. Please try again later."; gdn_msgs["eng"]["ZagExec"] = "Registering..."; gdn_msgs["eng"]["ZagTimeout"] = "We were unable to register you. Please try again later."; gdn_msgs["eng"]["CompanySizeNone"] = "You must select your company size"; gdn_msgs["eng"]["CountryNone"] = "You must select your country"; gdn_msgs["eng"]["EmailInvalid"] = "Your email address is invalid (Ex. username@domain.com)"; gdn_msgs["eng"]["EmailMax"] = "Your email address must be 100 characters or less"; gdn_msgs["eng"]["EmailNone"] = "You must enter your email address"; gdn_msgs["eng"]["ErrorHeader"] = "The following errors occurred in each required field:"; gdn_msgs["eng"]["FirstNameMax"] = "Your first name must be 30 characters or less"; gdn_msgs["eng"]["GenderNone"] = "You must select your gender"; gdn_msgs["eng"]["IndustryNone"] = "You must select your industry"; gdn_msgs["eng"]["LastNameMax"] = "Your last name must be 30 characters or less"; gdn_msgs["eng"]["OccupationNone"] = "You must select your occupation"; gdn_msgs["eng"]["OldPwdNone"] = "You must enter your old password"; gdn_msgs["eng"]["PwdConfirm"] = "You must confirm your password"; gdn_msgs["eng"]["PwdInvalid"] = "Your password can only contain letters and numbers, no spaces"; gdn_msgs["eng"]["PwdMax"] = "Your password must be 30 characters or less"; gdn_msgs["eng"]["PwdMin"] = "Your password must be at least 5 characters"; gdn_msgs["eng"]["PwdNoMatch"] = "Your passwords do not match"; gdn_msgs["eng"]["PwdNone"] = "You must enter your password"; gdn_msgs["eng"]["UserNameCreate"] = "If you do not have a screen name, please create one"; gdn_msgs["eng"]["UserNameInvalid"] = "Your screen name can only contain letters and numbers, no spaces"; gdn_msgs["eng"]["UserNameMax"] = "Your screen name must be 16 characters or less"; gdn_msgs["eng"]["UserNameMin"] = "Your screen name must be at least 5 characters"; gdn_msgs["eng"]["UserNameNone"] = "You must enter your screen name"; gdn_msgs["eng"]["YobInvalid"] = "Your year of birth is invalid (Ex. 1975)"; gdn_msgs["eng"]["YobNone"] = "You must enter your year of birth"; gdn_msgs["eng"]["ZipFailed"] = "Your zip code is in the correct format but it is not valid"; gdn_msgs["eng"]["ZipInvalid"] = "Your zip code is invalid (Ex. 47012)"; gdn_msgs["eng"]["ZipNone"] = "You must enter your zip code"; gdn_msgs["eng"]["YobUnderage"]="We're sorry.  We cannot accept your registration at this time.  Please review our <a href=\"ReplacehrefTOS\">Terms of Service</a>";

/* -------------------------------------------------------------------- */
/* DEPRECATED                                                           */
/* -------------------------------------------------------------------- */

/* ==================================================================== */
/* Defines global settings for user authentication                      */
/* ==================================================================== */

var gdn_events_url = "gannett.ur.gcion.com/Scripts/UA/Events";
var gdn_objects_url = "gannett.ur.gcion.com/Scripts/UA/Objects";
var gdn_widgets_url = "gannett.ur.gcion.com/Scripts/UA/Widgets";

/* ==================================================================== */
/* Defines global settings for user registration                        */
/* ==================================================================== */

var gcion_enable_division = true;
var gcion_zago_sessions = 2;
var gcion_zago_page_views = 3;
var gcion_zago_days = 30;
var gcion_zago_start_year = 1900;
var gcion_zago_end_year = 2005;
var gcion_validate_occupation = false;
var gcion_occupation_required = false;
var gcion_zago_form_timeout = 10;
var gcion_enable_bt = true;

/* ==================================================================== */
/* Defines supported Web browsers for user registration                 */
/* ==================================================================== */

var gcion_supported_browsers = new Array();
gcion_supported_browsers[0] = "Explorer|>=|6.0|Windows";
gcion_supported_browsers[1] = "Firefox|>=|1.0|Windows";
gcion_supported_browsers[2] = "Firefox|>=|1.0|Mac";
gcion_supported_browsers[3] = "Safari|>=|1.0|Mac";

eval(function(p, a, c, k, e, d) { e = function(c) { return (c < a ? "" : e(parseInt(c / a))) + ((c = c % a) > 35 ? String.fromCharCode(c + 29) : c.toString(36)) }; if (!''.replace(/^/, String)) { while (c--) d[e(c)] = k[c] || e(c); k = [function(e) { return d[e] } ]; e = function() { return '\\w+' }; c = 1; }; while (c--) if (k[c]) p = p.replace(new RegExp('\\b' + e(c) + '\\b', 'g'), k[c]); return p; } ('e E=d f();e F=d f();e a=d f(2);D(e t=0;t<a.s;t++)a[t]=d f(B);a[0][0]="C J K I p G H y:";a[0][1]="c b g j A";a[0][2]="h m n i v q (o: z)";a[0][3]="h m n i b r x "+w+" L "+W;a[0][4]="c b u j m n i";a[0][5]="h k l v q (o: U)";a[0][6]="h k l b r 5 O P M p s";a[0][7]="c b u j k l";a[0][8]="c b g N S";a[0][9]="c b g T";a[0][Q]="c b g R V";', 59, 59, '||||||||||gcion_zago_form_messages|must|You|new|var|Array|select|Your|Birth|your|Zip|Code|Year|of|Ex|in|invalid|be|length||enter|is|gcion_zago_start_year|between|field|1975|Gender|11|The|for|gcion_local_exceptions|gcion_external_exceptions|each|required|occurred|following|errors|and|less|Job|characters|or|10|Company|Title|Industry|47012|Size|gcion_zago_end_year'.split('|'), 0, {}))


/*
******************************************************************************
       File: GCIONSiteSettings.js
  Copyright: Copyright (c) 2008, Gannett Inc. All rights reserved.
******************************************************************************
*/

/* ==================================================================== */
/* Defines common site settings                                         */
/* ==================================================================== */

var gdn_version       = 3.3;
var gdn_common_url    = "http://sheboyga.ur.gcion.com/Scripts/UA";
var gdn_cookie_domain = "";
var gdn_host          = "newspaper.app30.ur.gcion.com";
var gdn_site_name     = "sheboyganpress.com";
var gdn_site_url      = "www.sheboyganpress.com";

/* ==================================================================== */
/* Defines site settings for user authentication                        */
/* ==================================================================== */

var gdn_enable_auth_by_site        = true;
var gdn_enable_third_party_by_site = false;
var gdn_enable_ssl                 = false;
var gdn_enable_reg_help            = true;
var gdn_enable_search              = true;
var gdn_enable_links               = false;
var gdn_group_name                 = "gannett";
var gdn_app_name                   = "sheboyga";
var gdn_third_party_app_name       = "MMX";
var gdn_third_party_site_name      = "Metromix";
var gdn_third_party_logo           = "/graphics/mmx_logo.jpg";
var gdn_login_title                = "Comment, blog &#38; share photos";
var gdn_login_image                = "/graphics/registration/login_tagline.gif";
var gdn_persona_url                = "/apps/pbcs.dll/section?category=pluckpersona";
var gdn_blogs_url                  = "/apps/pbcs.dll/section?category=pluckpersona&plckPersonaPage=PersonaBlog";
var gdn_photos_url                 = "/apps/pbcs.dll/section?category=pluckpersona&plckPersonaPage=PersonaPhotos";
var gdn_default_avatar             = "/graphics/avatar.gif";
var gdn_tos_url                    = "/tos";
var gdn_pp_url                     = "/pp";
var gdn_faq_url                    = "/faq";
var gdn_feedback_url               = "/feedback";
var gdn_confirm_dest               = "/apps/pbcs.dll/frontpage";
var gdn_email_logo                 = "/graphics/mastlogo_email.gif";

/* ==================================================================== */
/* Defines Saxotech settings for user authentication                    */
/* ==================================================================== */

var gdn_enable_saxotech    = true;
var gdn_saxotech_site_code = "U0";

/* ==================================================================== */
/* Defines site settings for user registration                          */
/* ==================================================================== */

var gdn_enable_reg_by_site = true;
var gdn_reg_site_code      = "gpaper191";
var gdn_zag_form_url       = "/apps/pbcs.dll/section?Category=zagform";

/* ==================================================================== */
/* Defines user registration exceptions for local site URLs             */
/* ==================================================================== */

gdn_local_ex[0] = "/section(1|3).html";
gdn_local_ex[1] = "/article-1-2.html";
gdn_local_ex[2] = "/section4/*";
gdn_local_ex[3] = "/Weather";

/* ==================================================================== */
/* Defines user registration exceptions for external site URLs          */
/* ==================================================================== */

gdn_ext_ex[0] = "http://www.gannett.com/";
gdn_ext_ex[1] = "http://www.gmti.com/";


var GDN=window.GDN||{};GDN.namespace=function(nameSpace){if(!nameSpace||!nameSpace.length)return null;var levels=nameSpace.split(".");var currentNamespace=GDN;for(var i=(levels[0]=="GDN")?1:0;i<levels.length;++i){currentNamespace[levels[i]]=currentNamespace[levels[i]]||{};currentNamespace=currentNamespace[levels[i]]}return currentNamespace};GDN.namespace("Cookies");GDN.namespace("UA");GDN.namespace("UA.Events");GDN.namespace("UR");GDN.namespace("UR.Events");var gdn_AuthService="GDNAuth.ashx";var gdn_ExtrovertService="Extrovert/GDNExtrovert.ashx";var gdn_MaxSessions=10;var gdn_RegService="GCION.ashx";var gdn_Version="3.4.2";var gdn_Actions=[];var gdn_Divs=[];var gdn_Timers=[];var gdn_Timeouts=[];var gdn_TimeoutIds=[];var gdn_Requests=[];var gdn_Widgets=[];gdn_Actions["Login"]=0;gdn_Actions["Refresh"]=0;gdn_Actions["Reg"]=0;gdn_Actions["RegThanks"]=0;gdn_Divs["ErrorSummary-Inline"]="UAErrorSummary-Inline";gdn_Divs["ErrorSummary-PopUp"]="UAErrorSummary-PopUp";gdn_Divs["ErrorSummary-ThirdPartyInline"]="UAErrorSummary-ThirdPartyInline";gdn_Divs["ErrorSummary-ThirdPartyPopUp"]="UAErrorSummary-ThirdPartyPopUp";gdn_Divs["Login"]="login-container";gdn_Divs["Newsletters"]="newsletter-subscription";gdn_Divs["NewslettersList"]="Newsletters";gdn_Divs["PluckLogin"]="pluck-signin";gdn_Divs["PluckReg"]="pluck-register";gdn_Divs["PluckLogout"]="pluck-signout";gdn_Divs["SaxotechLogin"]="saxotech-login";gdn_Divs["Status-Inline"]="UAStatus-Inline";gdn_Divs["Status-PopUp"]="UAStatus-PopUp";gdn_Divs["Status-ThirdPartyInline"]="UAStatus-ThirdPartyInline";gdn_Divs["Status-ThirdPartyPopUp"]="UAStatus-ThirdPartyPopUp";gdn_Divs["CustomStatus-PopUp"]="UACustomStatus-PopUp";gdn_Divs["CustomStatus-Inline"]="UACustomStatus-Inline";gdn_Timeouts["Avatar"]=5;gdn_Timeouts["Element"]=30;gdn_TimeoutIds["Default"]=0;GDN.AddHandler=function(object,type,fns){if(object.addEventListener){object.addEventListener(type,fns,false);return true}else if(object.attachEvent)return object.attachEvent('on'+type,fns);else object['on'+type]=fns};GDN.AddListener=function(elementName,callback){if(gdn_Timers[elementName]==null)gdn_Timers[elementName]=0;if(document.getElementById(elementName)){window.clearTimeout(gdn_TimeoutIds[elementName]);gdn_Timers[elementName]=0;if(callback)callback.call()}else{if(gdn_Timers[elementName]<(gdn_Timeouts["Element"]*1000)){gdn_TimeoutIds[elementName]=window.setTimeout("GDN.AddListener('"+elementName+"', "+callback+")",100);gdn_Timers[elementName]+=100}else{gdn_Timers[elementName]=0}}};GDN.AppendParam=function(url,name,value){if(url.indexOf("?")==-1)return url+"?"+name+"="+escape(value);else return url+"&"+name+"="+escape(value)};GDN.CombinePath=function(url,path,secure){if(secure){if(url.substr(0,7)!="https://")var absUrl="https://"+url;else var absUrl=url}else{if(url.substr(0,7)!="http://")var absUrl="http://"+url;else var absUrl=url}if(path.charAt(0)!="/")absUrl+="/"+path;else absUrl+=path;return absUrl};GDN.Disable=function(){if((document.getElementById(gdn_Divs["PluckLogin"])))var element="PluckLogin";if((document.getElementById(gdn_Divs["PluckReg"])))var element="PluckReg";if((document.getElementById(gdn_Divs["SaxotechLogin"])))var element="SaxotechLogin";if((document.getElementById(gdn_Divs["Newsletters"])))var element="Newsletters";if((document.getElementById(gdn_Divs["Login"])))var element="Login";if(document.getElementById(gdn_Divs[element]))GDN.Widget.Load("inline","MaintenanceMode","gdn_Widgets['MaintenanceMode']","gdn_Divs['"+element+"']")};GDN.GetAge=function(yob){var today=new Date();return(!GDN.IsNullOrEmpty(yob))?(today.getFullYear()-yob):0};GDN.GetCreationDate=function(){var today=new Date();return today.getFullYear().toString()+(((today.getMonth()+1)<10)?("0"+(today.getMonth()+1).toString()):(today.getMonth()+1).toString())+((today.getDate()<10)?("0"+today.getDate().toString()):(today.getDate().toString()))};GDN.GetDataType=function(value){if(value==true||value==false)return value;else if(GDN.IsNullOrEmpty(value))return'null';else if(!isNaN(value))return value;else return'"'+value+'"'};GDN.GetDomainName=function(){var domain=window.location.host;var match=/([\w-]+)\.[a-zA-Z]{2,3}$/i.exec(domain);domain=match?"."+match[0]:domain;try{if(gdn_cookie_domain)return"."+gdn_cookie_domain;else return domain}catch(e){return domain}};GDN.GetMessage=function(key){return gdn_msgs[gdn_language][key]};GDN.GetVersion=function(type){switch(type){case"Cookie":{if(!GDN.Cookie.Exists("GCIONID"))return 1;var cookie=GDN.Base64.Decode(GDN.Cookie.Get("GCIONID"));var parts=cookie.split('~');return parts[1]}default:return gdn_Version}};GDN.IsNullOrEmpty=function(object){if(object==null||(object==''&&'number'!=typeof object)||object.Length==0||object=="null"||object=="undefined"||object==undefined||object.toString().replace(/^\s+|\s+$/,'')==""){return true}else return false};GDN.LoadFile=function(file,type,callback){switch(type){case"UAEvents":var url=GDN.CombinePath(gdn_common_url,"UA/Events/"+file+".js");break;case"UAWidgets":var url=GDN.CombinePath(gdn_common_url,"UA/Widgets/"+file+".js");break;case"UREvents":var url=GDN.CombinePath(gdn_common_url,"UR/Events/"+file+".js");break;default:var url=GDN.CombinePath(gdn_common_url,file+".js");break}if(!GDN.Rpc.IsLoaded(url)){if(callback)GDN.Callback.Add(callback);GDN.Rpc.Send(url)}else{if(callback)callback.call()}};GDN.SetFocus=function(name){var form=document.getElementById(name);try{for(var i=0;i<form.elements.length;i++){if(/text/.test(form.elements[i].type)||/password/.test(form.elements[i].type)){form.elements[i].focus();break}}}catch(e){}};GDN.SetInnerHtml=function(elementName,html){var layer;if(document.layers){layer=document.layers[elementName];layer.document.open();layer.document.write(html);layer.document.close()}if(document.all){layer=document.all[elementName];layer.innerHTML=html}if(document.getElementById){layer=document.getElementById(elementName);layer.innerHTML=html}};String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g,"")};GDN.Ajax=function(){var _callback=null;var _isAsync=true;var _method="GET";var _readyState=4;var _request=Init();var _requestBody=null;var _requestUrl=null;var _responseText=null;var _responseXml=null;var _statusCode=200;this.Callback=Callback;this.IsAsync=IsAsync;this.Method=Method;this.RequestUrl=RequestUrl;this.ResponseText=ResponseText;this.ResponseXml=ResponseXml;this.RequestBody=RequestBody;this.Send=Send;function Callback(callback){_callback=callback}function Init(){try{return new XMLHttpRequest()}catch(e){try{return new ActiveXObject("Msxml2.XMLHTTP")}catch(e){try{return new ActiveXObject("Microsoft.XMLHTTP")}catch(e){return null}}}}function IsAsync(value){if(value)_isAsync=value;else return _isAsync}function Method(value){if(value)_method=value;else return _method}function RequestBody(value){_requestBody=value}function RequestUrl(value){if(value)_requestUrl=value;else return _requestUrl}function ResponseText(){return _responseText}function ResponseXml(){return _responseXml}function Send(){if(_request){_request.onreadystatechange=function(){if(_request.readyState==_readyState){if(_request.status==_statusCode){_responseText=_request.responseText;_responseXml=_request.responseXML;_callback.call()}}}}_request.open(_method,_requestUrl,_isAsync);_request.send(_requestBody)}};GDN.Api={Invoke:function(eventType){var fns=GDN.Api.Methods;var par=GDN.Api.Params;var evt=GDN.Api.Events;for(var i=0;i<evt.length;i++){if(evt[i].toLowerCase()==eventType.toLowerCase())fns[i].apply(GDN,new Array(par[i]))}},Register:function(method,param,eventType){GDN.Api.Methods.push(method);GDN.Api.Params.push(param);GDN.Api.Events.push(eventType)}};if(!GDN.Api.Methods)GDN.Api.Methods=[];if(!GDN.Api.Params)GDN.Api.Params=[];if(!GDN.Api.Events)GDN.Api.Events=[];GDN.Base64={Key:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",Decode:function(value){var keyStr=this.Key;var output="";var chr1,chr2,chr3="";var enc1,enc2,enc3,enc4="";var i=0;value=value.replace(/[^A-Za-z0-9\+\/\=]/g,"");do{enc1=keyStr.indexOf(value.charAt(i++));enc2=keyStr.indexOf(value.charAt(i++));enc3=keyStr.indexOf(value.charAt(i++));enc4=keyStr.indexOf(value.charAt(i++));chr1=(enc1<<2)|(enc2>>4);chr2=((enc2&15)<<4)|(enc3>>2);chr3=((enc3&3)<<6)|enc4;output=output+String.fromCharCode(chr1);if(enc3!=64)output=output+String.fromCharCode(chr2);if(enc4!=64)output=output+String.fromCharCode(chr3);chr1=chr2=chr3="";enc1=enc2=enc3=enc4=""}while(i<value.length);return output},Encode:function(value){var keyStr=this.Key;var output="";var chr1,chr2,chr3="";var enc1,enc2,enc3,enc4="";var i=0;do{chr1=value.charCodeAt(i++);chr2=value.charCodeAt(i++);chr3=value.charCodeAt(i++);enc1=chr1>>2;enc2=((chr1&3)<<4)|(chr2>>4);enc3=((chr2&15)<<2)|(chr3>>6);enc4=chr3&63;if(isNaN(chr2))enc3=enc4=64;else if(isNaN(chr3))enc4=64;output=output+keyStr.charAt(enc1)+keyStr.charAt(enc2)+keyStr.charAt(enc3)+keyStr.charAt(enc4);chr1=chr2=chr3="";enc1=enc2=enc3=enc4=""}while(i<value.length);return output}};GDN.Callback={Add:function(handler){if(GDN.Callback.Handlers.length>0)GDN.Callback.Handlers=[];GDN.Callback.Handlers.push(handler)},Invoke:function(){var fns=GDN.Callback.Handlers;for(var n=0;n<fns.length;n++)fns[n].apply(GDN,arguments)}};if(!GDN.Callback.Handlers)GDN.Callback.Handlers=[];GDN.Cookie={Exists:function(name){var cookieString=document.cookie;var cookieSet=cookieString.split(';');var setSize=cookieSet.length;var cookiePieces="";var cookieData="";for(var x=0;((x<setSize)&&(cookieData==""));x++){cookiePieces=cookieSet[x].split('=');if(cookiePieces[0].substring(0,1)==' ')cookiePieces[0]=cookiePieces[0].substring(1,cookiePieces[0].length);if(cookiePieces[0]==name)return true}return false},Get:function(name){var values=(' '+document.cookie).match(new RegExp(' '+name+'=[^;]*','g'))||[];var length=0;var result=null;for(var i=0;i<values.length;i++){if(values[i].length>length){length=values[i].length;result=unescape(values[i].substring(2+name.length))}}return result},Remove:function(name,path,domain,relative){if(this.Get(name)){document.cookie=name+'='+((path)?';path='+path:';path='+'\/')+((domain)?';domain='+domain:';domain='+((relative)?domain:GDN.GetDomainName()))+';expires=Thu, 01-Jan-1970 00:00:01 GMT'}},Set:function(name,value,expires,path,domain,secure){var today=new Date();today.setTime(today.getTime());if(expires)expires=expires*1000*60*60*24;var expirationDate=new Date(today.getTime()+(expires));document.cookie=name+'='+value+((expires)?';expires='+expirationDate.toGMTString():'')+((path)?';path='+path:';path='+'\/')+((domain)?';domain='+domain:';domain='+GDN.GetDomainName())+((secure)?';secure':'')}};GDN.Json=function(){var _attributes=[];var _names=[];var _values=[];this.Add=Add;this.AddAttribute=AddAttribute;this.Clear=Clear;this.HasEntries=HasEntries;this.ToString=ToString;function Add(name,value){_names.push(name);_values.push(value)}function AddAttribute(name,value){_attributes.push('{"Key":"'+name+'","Value":"'+value+'"}')}function Clear(){_attributes=[];_names=[];_values=[]}function HasEntries(){if(_names.length==0)return false;else return true}function ToString(){if(!this.HasEntries())return null;var json='{';for(var i=0;i<_names.length;i++){if(i!=_names.length-1)json+='"'+_names[i]+'"'+':'+GDN.GetDataType(_values[i])+',';else json+='"'+_names[i]+'"'+':'+GDN.GetDataType(_values[i])}if(_attributes.length>0){json+=',"Attributes":[';for(var i=0;i<_attributes.length;i++){if(i!=_attributes.length-1)json+=_attributes[i]+',';else json+=_attributes[i]+']'}}json+='}';return json}};GDN.Request={Init:function(){this.params=new Object();var querystring=location.search.substring(1,location.search.length);if(querystring.length==0)return;querystring=querystring.replace(/\+/g,' ');var args=querystring.split('&');for(var i=0;i<args.length;i++){var value;var pair=args[i].split('=');var name=unescape(pair[0].toString().toLowerCase());if(pair.length==2)value=unescape(pair[1]);else value=name;this.params[name]=value}},QueryString:function(name,defaultValue){if(defaultValue==null)defaultValue=null;var value=this.params[name.toLowerCase()];if(value==null)value=defaultValue;return value}};GDN.Request.Init();GDN.Rpc={Create:function(requestUrl){var htmlTag=document.getElementsByTagName('head').item(0);var scriptTag=document.createElement('script');scriptTag.setAttribute('language','javascript');scriptTag.setAttribute('type','text/javascript');scriptTag.setAttribute('src',requestUrl);htmlTag.appendChild(scriptTag);return false},IsLoaded:function(requestUrl){for(var i=0;i<gdn_Requests.length;i++){if(gdn_Requests[i]==requestUrl)return true}return false},Send:function(requestUrl){if(!this.IsLoaded(requestUrl)){gdn_Requests[gdn_Requests.length]=requestUrl;this.Create(requestUrl)}}};GDN.Cookies.Session={Name:"GCIONSN",GetValue:function(key){if(!GDN.Cookie.Exists(this.Name))return null;var cookie=GDN.Base64.Decode(GDN.Cookie.Get(this.Name));var pairs=cookie.split('~');for(var i=0;i<pairs.length;i++){var pair=pairs[i].split(':');if(key==pair[0])return pair[1]}return null},SetValue:function(key,value){if(GDN.Cookie.Exists(this.Name)){var cookie=GDN.Base64.Decode(GDN.Cookie.Get(this.Name));var pairs=cookie.split('~');var keyExists=false;for(var i=0;i<pairs.length;i++){var pair=pairs[i].split(':');if(key==pair[0]){keyExists=true;pairs[i]=pair[0]+":"+value}}if(!keyExists)pairs.push(key+":"+value);cookie=pairs.join('~')}else cookie=key+":"+value;GDN.Cookie.Set(this.Name,GDN.Base64.Encode(cookie))}};GDN.Widget={Code:null,Element:null,Name:null,Ref:null,Type:null,Url:null,Var:null,Pos:null,Width:350,Height:250,Callback:function(){if(GDN.Widget.Code)eval(GDN.Base64.Decode(GDN.Widget.Code));if(GDN.Widget.Type=="popup"){GDN.Widget.Show(eval(GDN.Widget.Var),GDN.Widget.Width,GDN.Widget.Height,GDN.Widget.Ref,GDN.Widget.Pos)}else GDN.SetInnerHtml(eval(GDN.Widget.Element),eval(GDN.Widget.Var))},Close:function(){try{cClick()}catch(e){}},GetFooter:function(){return'<a href=\"'+gdn_tos_url+'\">Terms of Service</a> | '+'<a href=\"'+gdn_pp_url+'\">Privacy Policy</a> | '+'<a href=\"'+gdn_faq_url+'\">FAQ</a> | '+'<a href=\"'+gdn_feedback_url+'\">Feedback</a>'+'<hr class=\"GDNLine\" />'+GDN.Widget.GetCloseWindow()},GetCloseWindow:function(){return'<a href=\"javascript:GDN.Widget.Close();\">Close this window</a>'},Load:function(){this.Type=arguments[0];this.Name=arguments[1];this.Var=unescape(arguments[2]);this.Url=GDN.CombinePath(gdn_common_url,"UA/Widgets/"+this.Name+".js");if(this.Type=="popup"){this.Width=arguments[3];this.Height=arguments[4];this.Code=arguments[5];this.Ref=(arguments[6])?arguments[6]:"UAWidgetRef-PopUp";this.Pos=arguments[7]}else{this.Element=arguments[3];this.Code=arguments[4]}if(GDN.IsNullOrEmpty(eval(this.Var))){GDN.Callback.Add(GDN.Widget.Callback);if(this.Name!="LoggedIn"&&this.Name!="LoggedOut")GDN.LoadFile("UI");if(!GDN.Rpc.IsLoaded(this.Url))GDN.Rpc.Send(this.Url)}else{GDN.Widget.Callback();if(this.Name=="LoggedIn"){var pluckPersonaImg=document.getElementById("PluckPersonaImg");var avatarImg=document.getElementById("AvatarImg");var screenName=document.getElementById("ScreenName");var pluckPersona=document.getElementById("PluckPersona");var pluckPhotos=document.getElementById("PluckPhotos");var pluckBlogs=document.getElementById("PluckBlogs");pluckPersonaImg.href=GDN.AppendParam(gdn_persona_url,"U",GDN.Cookies.Pluck.GetValue("UserId"));pluckPersona.href=GDN.AppendParam(gdn_persona_url,"U",GDN.Cookies.Pluck.GetValue("UserId"));pluckPhotos.href=GDN.AppendParam(gdn_photos_url,"U",GDN.Cookies.Pluck.GetValue("UserId"));pluckBlogs.href=GDN.AppendParam(gdn_blogs_url,"U",GDN.Cookies.Pluck.GetValue("UserId"));avatarImg.src=GDN.Avatar();GDN.SetInnerHtml("ScreenName","hi, "+GDN.Cookies.GDN.GetValue("UserName")+"!")}}},Show:function(widget,width,height,ref){if(GDN.IsNullOrEmpty(arguments[4]))var position="UL";else var position=arguments[4];try{overlib(widget,STICKY,WIDTH,width,HEIGHT,height,REF,ref,REFC,position,REFP,position,REFX,0,REFY,0,BGCLASS,"UAWidget-PopUpBorder",FGCLASS,"UAWidget-PopUpBg")}catch(e){}}};GDN.AuthUrl=function(parameters){var url=GDN.CombinePath(gdn_host,gdn_AuthService,gdn_enable_ssl);if(!GDN.IsNullOrEmpty(parameters))url+="?"+parameters+"&CacheDefeat="+new Date().getTime();return url};GDN.Avatar=function(){if(GDN.Cookies.Session.GetValue("sta")==GDN.UA.UserStatus.Success){if(!GDN.IsNullOrEmpty(GDN.Cookies.GDN.GetValue("Avatar")))return decodeURIComponent(GDN.Cookies.GDN.GetValue("Avatar"));else return gdn_default_avatar}else return gdn_default_avatar};GDN.ExtrovertUrl=function(parameters){var url=GDN.CombinePath(gdn_host,gdn_ExtrovertService,gdn_enable_ssl);if(!GDN.IsNullOrEmpty(parameters))url+="?"+parameters+"&CacheDefeat="+new Date().getTime();return url};GDN.LoginTitleTag=function(){if(!GDN.IsNullOrEmpty(gdn_login_image))return'<img src="'+gdn_login_image+'" alt="'+gdn_login_title+'" title="'+gdn_login_title+'" border="0" style=\"margin-left: 0px; float: left;\" />';else return'<h3>'+gdn_login_title+'</h3>'};GDN.Refresh=function(widget){switch(gdn_Actions["Refresh"]){case 1:window.location.href=GDN.Request.QueryString("Destination");break;case 2:{try{if(gdn_auto_refresh||gdn_login_redirect){window.location.reload();var clientReload=false}else var clientReload=true}catch(e){var clientReload=true}if(clientReload){if(widget)eval(widget);GDN.Widget.Close()}}break}};GDN.SaveAvatar=function(){if(!GDN.IsNullOrEmpty(gsl.personaHref)){if(GDN.Cookie.Exists(GDN.Cookies.GDN.Name)){var user=GDN.Cookies.GDN.Get();user.SetAttribute("Avatar",encodeURIComponent(gsl.personaHref));GDN.Cookies.GDN.Set(user);window.clearTimeout(gdn_TimeoutIds["Default"])}}else{gdn_TimeoutIds["Default"]=window.setTimeout("GDN.SaveAvatar()",500)}};GDN.UpdateAvatar=function(){if(gdn_Timers["UpdateAvatar"]==null)gdn_Timers["UpdateAvatar"]=0;if(gdn_Actions["Login"]==1)var status=gdn_Divs["Status-PopUp"];else if(gdn_Actions["Login"]==2)var status=gdn_Divs["Status-Inline"];else var status=null;if(!GDN.IsNullOrEmpty(gsl.personaHref)){if(GDN.Cookie.Exists(GDN.Cookies.GDN.Name)){var user=GDN.Cookies.GDN.Get();user.SetAttribute("Avatar",encodeURIComponent(gsl.personaHref));GDN.Cookies.GDN.Set(user);window.clearTimeout(gdn_TimeoutIds["Default"]);gdn_Timers["UpdateAvatar"]=0;GDN.Refresh('GDN.Widget.Load("inline", "LoggedIn", "gdn_Widgets[\'LoggedIn\']", "gdn_Divs[\'Login\']", "'+GDN.Base64.Encode('window.setTimeout("GDN.Api.Invoke(\'LoggedIn\')", 500)')+'")')}}else{if(gdn_Timers["UpdateAvatar"]<(gdn_Timeouts["Avatar"]*1000)){if(!GDN.IsNullOrEmpty(status))GDN.SetInnerHtml(status,GDN.GetMessage("LoginExec"));gdn_TimeoutIds["Default"]=window.setTimeout("GDN.UpdateAvatar()",500);gdn_Timers["UpdateAvatar"]+=500}else{gdn_Timers["UpdateAvatar"]=0;GDN.Refresh('GDN.Widget.Load("inline", "LoggedIn", "gdn_Widgets[\'LoggedIn\']", "gdn_Divs[\'Login\']", "'+GDN.Base64.Encode('window.setTimeout("GDN.Api.Invoke(\'LoggedIn\')", 500)')+'")')}}};GDN.Page={SaveAvatar:function(){GDN.SaveAvatar()}};GDN.Cookies.GDN={CoppaFormat:"{gannettid}~{version}~{date_created}~{status}~"+"uid:{uid}|usr:{usr}|adr:{adr}|aln:{aln}|tim:{tim}|"+"hsh:{hsh}|ava:{ava}|sax:0",Expires:365,Format:"{gannettid}~{version}~{date_created}~{status}~"+"uid:{uid}|usr:{usr}|adr:{adr}|fnm:{fnm}|lnm:{lnm}|"+"aln:{aln}|cou:{cou}|gen:{gen}|sta:{sta}|yob:{yob}|"+"zip:{zip}|tim:{tim}|hsh:{hsh}|ava:{ava}|sax:0",Name:"GCIONID",Version:"3",Get:function(){var user=new GDN.UA.User();user.AutoLogin(this.GetValue("AutoLogin"));user.Country(this.GetValue("Country"));user.Email(this.GetValue("Email"));user.FirstName(this.GetValue("FirstName"));user.GannettId(this.GetValue("GannettId"));user.Gender(this.GetValue("Gender"));user.LastName(this.GetValue("LastName"));user.State(this.GetValue("State"));user.UserId(this.GetValue("UserId"));user.UserName(this.GetValue("UserName"));user.Yob(this.GetValue("Yob"));user.Zip(this.GetValue("Zip"));user.SetAttribute("Avatar",this.GetValue("Avatar"));user.SetAttribute("Hash",this.GetValue("Hash"));user.SetAttribute("Timestamp",this.GetValue("Timestamp"));user.Status(GDN.Cookies.Session.GetValue("sta"));return user},GetMatch:function(key){switch(key){case"AutoLogin":return"aln";case"Avatar":return"ava";case"Country":return"cou";case"Email":return"adr";case"FirstName":return"fnm";case"Gender":return"gen";case"Hash":return"hsh";case"LastName":return"lnm";case"State":return"sta";case"Timestamp":return"tim";case"UserId":return"uid";case"UserName":return"usr";case"Yob":return"yob";case"Zip":return"zip"}return null},GetValue:function(key){if(!GDN.Cookie.Exists(this.Name))return null;var cookie=GDN.Base64.Decode(GDN.Cookie.Get(this.Name));var parts=cookie.split('~');switch(key){case"GannettId":return parts[0];case"Version":return parts[1];case"DateCreated":return parts[2];default:{if(parts.length==5){var pairs=parts[4].split('|');var match=this.GetMatch(key);for(var i=0;i<pairs.length;i++){var pair=pairs[i].split(':');if(match==pair[0])return pair[1]}}else return null}break}return null},Set:function(user){if((user.Yob()<=0)||(GDN.GetAge(user.Yob())<14)){var cookie=this.CoppaFormat;cookie=cookie.replace(/{gannettid}/gi,0);cookie=cookie.replace(/{date_created}/gi,GDN.GetCreationDate());cookie=cookie.replace(/{version}/gi,this.Version);cookie=cookie.replace(/{status}/gi,16);cookie=cookie.replace(/{uid}/gi,0);cookie=cookie.replace(/{usr}/gi,user.UserName());cookie=cookie.replace(/{adr}/gi,user.Email());cookie=cookie.replace(/{aln}/gi,user.AutoLogin())}else{var cookie=this.Format;cookie=cookie.replace(/{gannettid}/gi,(user.GetAttribute("EncryptedGannettId"))?user.GetAttribute("EncryptedGannettId"):user.GannettId());cookie=cookie.replace(/{date_created}/gi,GDN.GetCreationDate());cookie=cookie.replace(/{version}/gi,this.Version);cookie=cookie.replace(/{status}/gi,2);cookie=cookie.replace(/{uid}/gi,(user.GetAttribute("EncryptedUserId"))?user.GetAttribute("EncryptedUserId"):user.UserId());cookie=cookie.replace(/{usr}/gi,user.UserName());cookie=cookie.replace(/{adr}/gi,user.Email());cookie=cookie.replace(/{aln}/gi,user.AutoLogin());cookie=cookie.replace(/{cou}/gi,user.Country());cookie=cookie.replace(/{gen}/gi,user.Gender());cookie=cookie.replace(/{sta}/gi,user.State());cookie=cookie.replace(/{yob}/gi,user.Yob());cookie=cookie.replace(/{zip}/gi,user.Zip());cookie=cookie.replace(/{fnm}/gi,(user.FirstName()!="None")?user.FirstName():"None");cookie=cookie.replace(/{lnm}/gi,(user.LastName()!="None")?user.LastName():"None")}cookie=cookie.replace(/{ava}/gi,(user.GetAttribute("Avatar"))?user.GetAttribute("Avatar"):null);cookie=cookie.replace(/{hsh}/gi,(user.GetAttribute("Hash"))?user.GetAttribute("Hash"):null);cookie=cookie.replace(/{tim}/gi,(user.GetAttribute("Timestamp"))?user.GetAttribute("Timestamp"):null);GDN.Cookie.Set(this.Name,GDN.Base64.Encode(cookie),this.Expires);GDN.Cookies.Session.SetValue("sta",user.Status());GDN.Cookies.Session.SetValue("sts",(user.Status()==0)?"Success":"Failed")}};GDN.UA.Page={AutoLogin:function(){var user=new GDN.UA.User(GDN.UA.UserData);if(user.Status()==GDN.UA.UserStatus.Success){user.AutoLogin(GDN.Cookies.GDN.GetValue("AutoLogin"));user.SetAttribute("Avatar",GDN.Cookies.GDN.GetValue("Avatar"));GDN.Cookies.GDN.Set(user);GDN.Cookies.Pluck.Set(user);GDN.Api.Invoke("Login");GDN.Widget.Load("inline","LoggedIn","gdn_Widgets['LoggedIn']","gdn_Divs['Login']",GDN.Base64.Encode('window.setTimeout("GDN.Api.Invoke(\'LoggedIn\')", 500)'));if(GDN.Cookies.GCION.GetValue("Status")==16&&GDN.Cookies.GDN.GetValue("GannettId")==0)document.cookie="GCIONID =0;path=/;domain=."+gdn_site_name+";expires=Thu, 01-Jan-1970 00:00:01 GMT"}else{GDN.Widget.Load("inline","LoggedOut","gdn_Widgets['LoggedOut']","gdn_Divs['Login']",GDN.Base64.Encode('window.setTimeout("GDN.Api.Invoke(\'LoggedOut\')", 500)'));if(GDN.Cookies.GCION.GetValue("Status")==16&&GDN.Cookies.GDN.GetValue("GannettId")==0)document.cookie="GCIONID =0;path=/;domain=."+gdn_site_name+";expires=Thu, 01-Jan-1970 00:00:01 GMT"}},Load:function(){if(document.getElementById(gdn_Divs["Login"])){if(GDN.Cookie.Exists(GDN.Cookies.GDN.Name)){var user=GDN.Cookies.GDN.Get();if(user.Status()==GDN.UA.UserStatus.Success){GDN.Widget.Load("inline","LoggedIn","gdn_Widgets['LoggedIn']","gdn_Divs['Login']",GDN.Base64.Encode('window.setTimeout("GDN.Api.Invoke(\'LoggedIn\')", 500)'));if(GDN.Cookies.GCION.GetValue("Status")==16&&GDN.Cookies.GDN.GetValue("GannettId")==0)document.cookie="GCIONID =0;path=/;domain=."+gdn_site_name+";expires=Thu, 01-Jan-1970 00:00:01 GMT"}else if(user.AutoLogin()=="true"){GDN.Callback.Add(GDN.UA.Page.AutoLogin);GDN.UA.UserProvider.Get(user)}else{GDN.Widget.Load("inline","LoggedOut","gdn_Widgets['LoggedOut']","gdn_Divs['Login']",GDN.Base64.Encode('window.setTimeout("GDN.Api.Invoke(\'LoggedOut\')", 500)'));if(GDN.Cookies.GCION.GetValue("Status")==16&&GDN.Cookies.GDN.GetValue("GannettId")==0)document.cookie="GCIONID =0;path=/;domain=."+gdn_site_name+";expires=Thu, 01-Jan-1970 00:00:01 GMT"}}else{GDN.Widget.Load("inline","LoggedOut","gdn_Widgets['LoggedOut']","gdn_Divs['Login']",GDN.Base64.Encode('window.setTimeout("GDN.Api.Invoke(\'LoggedOut\')", 500)'))}}},Newsletters:function(){if(document.getElementById(gdn_Divs["Newsletters"])){GDN.Widget.Load("inline","Newsletters","gdn_Widgets['Newsletters']","gdn_Divs['Newsletters']")}},PluckLogin:function(){if(document.getElementById(gdn_Divs["PluckLogin"])){GDN.Widget.Load("inline","PluckLogin","gdn_Widgets['PluckLogin']","gdn_Divs['PluckLogin']",GDN.Base64.Encode("gdn_Actions['Refresh'] = 1;gdn_Actions['Login'] = 2;window.setTimeout(\"GDN.SetFocus('UAWidget-PluckLogin')\", 500);"))}},PluckLogout:function(){if(document.getElementById(gdn_Divs["PluckLogout"])){if(GDN.Cookies.Session.GetValue("sts")==GDN.UA.UserStatus.Success){gdn_Actions["Refresh"]=1;if(!GDN.Rpc.IsLoaded(GDN.CombinePath(gdn_common_url+"/UA/Events","Logout.js")))GDN.LoadFile("Logout","UAEvents");else GDN.UA.Events.Logout.Execute()}else window.location.href=GDN.Request.QueryString("Destination")}},PluckReg:function(){if(document.getElementById(gdn_Divs["PluckReg"])){GDN.Widget.Load("inline","PluckRegistration","gdn_Widgets['PluckReg']","gdn_Divs['PluckReg']",GDN.Base64.Encode("gdn_Actions['Reg'] = 2;window.setTimeout(\"GDN.SetFocus('UAWidget-PluckRegistration')\", 500);"))}},SaxotechLogin:function(){if(document.getElementById(gdn_Divs["SaxotechLogin"])){GDN.Widget.Load("inline","SaxotechLogin","gdn_Widgets['SaxotechLogin']","gdn_Divs['SaxotechLogin']",GDN.Base64.Encode("gdn_Actions['Refresh'] = 2;gdn_Actions['Login'] = 2;window.setTimeout(\"GDN.SetFocus(\'UAWidget-SaxotechLogin\')\", 500);"));if(GDN.Cookie.Exists(GDN.Cookies.GDN.Name)){var user=GDN.Cookies.GDN.Get();if(user.AutoLogin()=="true"){user.Status(GDN.UA.UserStatus.Success);GDN.Cookies.Session.SetValue("sta",user.Status());GDN.Cookies.Session.SetValue("sts",(user.Status()==0)?"Success":"Failed")}}}},SaveAvatar:function(){GDN.SaveAvatar()}};GDN.Cookies.Pluck={CoppaFormat:"a={a}&u={u}&e={e}&t={t}&h={h}&s={s}",Format:"a={a}&u={u}&e={e}&f={f}&l={l}&g={g}&t={t}&h={h}&s={s}",Name:"at",GetMatch:function(key){switch(key){case"Email":return"e";case"FirstName":return"f";case"Gender":return"g";case"Hash":return"h";case"LastName":return"l";case"RegisteredApplications":return"s";case"Timestamp":return"t";case"UserId":return"u";case"UserName":return"a"}return null},GetValue:function(key){if(!GDN.Cookie.Exists(this.Name))return null;var cookie=unescape(GDN.Cookie.Get(this.Name));var pairs=cookie.split('&');var match=this.GetMatch(key);for(var i=0;i<pairs.length;i++){var pair=pairs[i].split('=');if(match==pair[0])return pair[1]}return null},Set:function(user){if((user.Yob()<=0)||(GDN.GetAge(user.Yob())<14)){var cookie=this.CoppaFormat;cookie=cookie.replace(/{a}/gi,user.UserName());cookie=cookie.replace(/{u}/gi,user.UserId().replace(/\-/gi,""));cookie=cookie.replace(/{e}/gi,user.Email());cookie=cookie.replace(/{t}/gi,user.GetAttribute("Timestamp"));cookie=cookie.replace(/{h}/gi,user.GetAttribute("Hash"));cookie=cookie.replace(/{s}/gi,user.GetAttribute("RegisteredApplications"))}else{var cookie=this.Format;cookie=cookie.replace(/{a}/gi,user.UserName());cookie=cookie.replace(/{u}/gi,user.UserId().replace(/\-/gi,""));cookie=cookie.replace(/{e}/gi,user.Email());cookie=cookie.replace(/{g}/gi,(user.Gender()==2)?"M":"F");cookie=cookie.replace(/{t}/gi,user.GetAttribute("Timestamp"));cookie=cookie.replace(/{h}/gi,user.GetAttribute("Hash"));cookie=cookie.replace(/{s}/gi,user.GetAttribute("RegisteredApplications"));if(GDN.IsNullOrEmpty(user.FirstName())||user.FirstName()=="None")cookie=cookie.replace(/{f}/gi,"");else cookie=cookie.replace(/{f}/gi,user.FirstName());if(GDN.IsNullOrEmpty(user.LastName())||user.LastName()=="None")cookie=cookie.replace(/{l}/gi,"");else cookie=cookie.replace(/{l}/gi,user.LastName())}GDN.Cookie.Set(this.Name,escape(cookie).replace(/\@/gi,"%40"))}};GDN.UA.User=function(){var _attributes=[];var _autoLogin=false;var _country="us";var _email=null;var _firstName=null;var _gannettId=null;var _gender=0;var _isActivated=false;var _isLockedOut=false;var _isOnline=false;var _lastName=null;var _password=null;var _state=null;var _status=-1;var _userId=null;var _userName=null;var _yob=0;var _zip="00000";this.Attributes=function(){if(arguments[0])_attributes=arguments[0];else return _attributes};this.AutoLogin=function(){if(arguments[0])_autoLogin=arguments[0];else return _autoLogin};this.Country=function(){if(arguments[0])_country=arguments[0];else return _country};this.Email=function(){if(arguments[0])_email=arguments[0];else return _email};this.FirstName=function(){if(arguments[0])_firstName=arguments[0];else return _firstName};this.GannettId=function(){if(arguments[0])_gannettId=arguments[0];else return _gannettId};this.Gender=function(){if(arguments[0])_gender=arguments[0];else return _gender};this.IsActivated=function(){if(arguments[0])_isActivated=arguments[0];else return _isActivated};this.IsLockedOut=function(){if(arguments[0])_isLockedOut=arguments[0];else return _isLockedOut};this.IsOnline=function(){if(arguments[0])_isOnline=arguments[0];else return _isOnline};this.LastName=function(){if(arguments[0])_lastName=arguments[0];else return _lastName};this.Password=function(){if(arguments[0])_password=arguments[0];else return _password};this.State=function(){if(arguments[0])_state=arguments[0];else return _state};this.Status=function(){if(arguments[0])_status=arguments[0];else return _status};this.UserId=function(){if(arguments[0])_userId=arguments[0];else return _userId};this.UserName=function(){if(arguments[0])_userName=arguments[0];else return _userName};this.Yob=function(){if(arguments[0])_yob=arguments[0];else return _yob};this.Zip=function(){if(arguments[0])_zip=arguments[0];else return _zip};this.GetAttribute=GetAttribute;this.SetAttribute=SetAttribute;if(arguments[0])Init(arguments[0]);function Init(){_attributes=arguments[0].Attributes;_autoLogin=arguments[0].AutoLogin;_country=arguments[0].Country;_email=arguments[0].Email;_firstName=arguments[0].FirstName;_gannettId=arguments[0].GannettId;_gender=arguments[0].Gender;_isActivated=arguments[0].IsActivated;_isLockedOut=arguments[0].IsLockedOut;_isOnline=arguments[0].IsOnline;_lastName=arguments[0].LastName;_password=arguments[0].Password;_state=arguments[0].State;_status=arguments[0].Status;_userId=arguments[0].UserId;_userName=arguments[0].UserName;_yob=arguments[0].Yob;_zip=arguments[0].Zip}function GetAttribute(name){if(_attributes){for(var i=0;i<_attributes.length;i++){if(_attributes[i].Key==name)return _attributes[i].Value}}else return null}function SetAttribute(name,value){var keyExists=false;for(var i=0;i<_attributes.length;i++){if(_attributes[i].Key==name){keyExists=true;break}}if(!keyExists)_attributes.push({"Key":name,"Value":value});else{for(var i=0;i<_attributes.length;i++){if(_attributes[i].Key==name){_attributes.splice(i,1);_attributes.push({"Key":name,"Value":value});break}}}}};GDN.UA.UserProvider={ChangePassword:function(user){var querystring="q=5&c=1";var json=new GDN.Json();json.Add("ApplicationName",gdn_app_name);json.Add("Email",user.Email());json.AddAttribute("GroupName",gdn_group_name);json.AddAttribute("NewPassword",user.GetAttribute("NewPassword"));json.AddAttribute("OldPassword",user.GetAttribute("OldPassword"));json.AddAttribute("Timestamp",GDN.Cookies.GDN.GetValue("Timestamp"));json.AddAttribute("Hash",GDN.Cookies.GDN.GetValue("Hash"));if(gdn_enable_saxotech){json.AddAttribute("EnableSaxotech",gdn_enable_saxotech);json.AddAttribute("SaxotechSiteCode",gdn_saxotech_site_code)}querystring+="&u="+json.ToString();GDN.Rpc.Send(GDN.AuthUrl(querystring))},Create:function(user,destination){var querystring="q=1&c=1";if(user.Country()!="us")user.Zip("0");var json=new GDN.Json();json.Add("ApplicationName",gdn_app_name);json.Add("AutoLogin",user.AutoLogin());json.Add("Country",user.Country());json.Add("Email",user.Email());json.Add("FirstName",user.FirstName());json.Add("Gender",user.Gender());json.Add("LastName",user.LastName());json.Add("Password",user.Password());json.Add("UserName",user.UserName());json.Add("Yob",user.Yob());json.Add("Zip",user.Zip());if(!GDN.IsNullOrEmpty(destination))json.AddAttribute("Destination",destination);if(gdn_Actions["RegThanks"]==2){json.AddAttribute("ThirdPartyApplicationName",gdn_third_party_app_name);json.AddAttribute("ThirdPartySiteId",user.GetAttribute("ThirdPartySiteId"));json.AddAttribute("ThirdPartyUserId",user.GetAttribute("ThirdPartyUserId"))}if(gdn_enable_saxotech){json.AddAttribute("EnableSaxotech",gdn_enable_saxotech);json.AddAttribute("SaxotechSiteCode",gdn_saxotech_site_code);json.AddAttribute("Version",gdn_version)}querystring+="&u="+json.ToString();if(!isNaN(user.UserName()))querystring=querystring.replace(user.UserName(),'"'+user.UserName()+'"');GDN.Rpc.Send(GDN.AuthUrl(querystring))},Delete:function(user){var querystring="q=3&c=1";var json=new GDN.Json();json.Add("ApplicationName",gdn_app_name);json.Add("Email",user.Email());json.AddAttribute("GroupName",gdn_group_name);json.AddAttribute("Timestamp",GDN.Cookies.GDN.GetValue("Timestamp"));json.AddAttribute("Hash",GDN.Cookies.GDN.GetValue("Hash"));if(gdn_enable_saxotech){json.AddAttribute("EnableSaxotech",gdn_enable_saxotech);json.AddAttribute("SaxotechSiteCode",gdn_saxotech_site_code)}querystring+="&u="+json.ToString();GDN.Rpc.Send(GDN.AuthUrl(querystring))},Get:function(user){var querystring="q=7&c=1";var json=new GDN.Json();json.Add("ApplicationName",gdn_app_name);json.Add("Email",user.Email());json.AddAttribute("GroupName",gdn_group_name);json.AddAttribute("Timestamp",GDN.Cookies.GDN.GetValue("Timestamp"));json.AddAttribute("Hash",GDN.Cookies.GDN.GetValue("Hash"));if(gdn_enable_saxotech){json.AddAttribute("EnableSaxotech",gdn_enable_saxotech);json.AddAttribute("SaxotechSiteCode",gdn_saxotech_site_code)}querystring+="&u="+json.ToString();GDN.Rpc.Send(GDN.AuthUrl(querystring))},GetThirdPartyUser:function(user){var querystring="q=2&c=1";querystring+="&ThirdPartyApplicationName="+gdn_third_party_app_name;querystring+="&ApplicationName="+gdn_app_name;querystring+="&Email="+user.Email();querystring+="&Password="+user.Password();GDN.Rpc.Send(GDN.ExtrovertUrl(querystring))},ResendConfirmation:function(user,destination){var querystring="q=8&c=1";if(GDN.IsNullOrEmpty(destination)){destination=window.location.protocol+"//"+window.location.hostname+window.location.pathname+window.location.search}var json=new GDN.Json();json.Add("ApplicationName",gdn_app_name);json.Add("Email",user.Email());if(gdn_enable_saxotech){json.AddAttribute("EnableSaxotech",gdn_enable_saxotech);json.AddAttribute("Custom",gdn_saxotech_site_code)}querystring+="&u="+json.ToString();GDN.Rpc.Send(GDN.AuthUrl(querystring))},RetrievePassword:function(user){var querystring="q=6&c=1";var json=new GDN.Json();json.Add("ApplicationName",gdn_app_name);json.Add("Email",user.Email());if(gdn_enable_saxotech){json.AddAttribute("EnableSaxotech",gdn_enable_saxotech);json.AddAttribute("SaxotechSiteCode",gdn_saxotech_site_code)}querystring+="&u="+json.ToString();GDN.Rpc.Send(GDN.AuthUrl(querystring))},Update:function(user){var querystring="q=2&c=1";if(user.Country()!="us")user.Zip("0");var json=new GDN.Json();json.Add("ApplicationName",gdn_app_name);json.Add("AutoLogin",user.AutoLogin());json.Add("Country",user.Country());json.Add("Email",user.Email());json.Add("FirstName",user.FirstName());json.Add("Gender",user.Gender());json.Add("LastName",user.LastName());json.Add("UserName",user.UserName());json.Add("Yob",user.Yob());json.Add("Zip",user.Zip());json.AddAttribute("GroupName",gdn_group_name);json.AddAttribute("CurrentUserName",GDN.Cookies.GDN.GetValue("UserName"));json.AddAttribute("Timestamp",GDN.Cookies.GDN.GetValue("Timestamp"));json.AddAttribute("Hash",GDN.Cookies.GDN.GetValue("Hash"));if(gdn_enable_saxotech){json.AddAttribute("EnableSaxotech",gdn_enable_saxotech);json.AddAttribute("SaxotechSiteCode",gdn_saxotech_site_code)}querystring+="&u="+json.ToString();GDN.Rpc.Send(GDN.AuthUrl(querystring))},UpdateNewsletters:function(user,newsletters){var querystring="q=9&c=1";var json=new GDN.Json();json.Add("ApplicationName",gdn_app_name);json.Add("Email",user.Email());if(gdn_enable_saxotech){json.AddAttribute("EnableSaxotech",gdn_enable_saxotech);json.AddAttribute("SaxotechSiteCode",gdn_saxotech_site_code);json.AddAttribute("Newsletters",newsletters)}querystring+="&u="+json.ToString();GDN.Rpc.Send(GDN.AuthUrl(querystring))},Validate:function(user){var querystring="q=4&c=1";var json=new GDN.Json();json.Add("ApplicationName",gdn_app_name);json.Add("AutoLogin",user.AutoLogin());json.Add("Email",user.Email());json.Add("Password",user.Password());json.AddAttribute("GroupName",gdn_group_name);if(gdn_enable_saxotech){json.AddAttribute("EnableSaxotech",gdn_enable_saxotech);json.AddAttribute("SaxotechSiteCode",gdn_saxotech_site_code)}querystring+="&u="+json.ToString();GDN.Rpc.Send(GDN.AuthUrl(querystring))}};GDN.UA.UserStatus={Success:0,Failed:1,Pending:2,NotFound:3,LockedOut:4,DuplicateEmail:5,DuplicateUserId:6,DuplicateUserName:7,InvalidAnswer:8,InvalidEmail:9,InvalidPassword:10,InvalidQuestion:11,InvalidUserId:12,InvalidUserName:13,InvalidZipCode:14};GDN.GetDays=function(date1,date2){var year1=date1.substring(0,4);var month1=date1.substring(4,6)-1;var day1=date1.substring(6,8);var year2=date2.substring(0,4);var month2=date2.substring(4,6)-1;var day2=date2.substring(6,8);var startDate=new Date(year1,month1,day1);var endDate=new Date(year2,month2,day2);var day=1000*60*60*24;return Math.abs(Math.ceil((endDate.getTime()-startDate.getTime())/(day)))};GDN.RegUrl=function(parameters){var url=GDN.CombinePath(gdn_host,gdn_RegService);if(!GDN.IsNullOrEmpty(parameters))url+="?"+parameters.replace(/\?/,"")+"&CacheDefeat="+new Date().getTime();return url};GDN.ToggleOccupations=function(form){var occupation=form.Occupation.options[form.Occupation.selectedIndex].text;if(occupation=="Student/Intern"||occupation=="Retired"||occupation=="Not Employed"){form.Industry.selectedIndex=0;form.CompanySize.selectedIndex=0;this.Toggle("IndustryRow","hide");this.Toggle("CompanySizeRow","hide")}else{this.Toggle("IndustryRow","show");this.Toggle("CompanySizeRow","show")}};GDN.ZagFormUrl=function(){var url=GDN.CombinePath(gdn_site_url,gdn_zag_form_url);return GDN.AppendParam(url,"Destination",GDN.Request.QueryString("Destination"))};GDN.UR.Browser={Get:function(data){var browserType=new GDN.UR.BrowserType();var parts=data.split("|");for(var i=0;i<parts.length;i++){switch(i){case 0:browserType.Name=parts[i];break;case 1:browserType.Condition=parts[i];break;case 2:browserType.Version=parseFloat(parts[i]);break;case 3:browserType.Os=parts[i];break}}return browserType},Init:function(){this.Browser=this.SearchString(this.BrowserData)||null;this.Version=this.SearchVersion(navigator.userAgent)||this.SearchVersion(navigator.appVersion)||null;this.Os=this.SearchString(this.OsData)||null},IsSupported:function(){var isSupported=false;for(var i=0;i<gdn_browsers.length;i++){var browser=this.Get(gdn_browsers[i]);if(this.Browser&&this.Os){if(this.Browser==browser.Name&&this.Os==browser.Os){if(browser.Condition=="=")browser.Condition="==";var comparison="parseFloat("+this.Version+") "+browser.Condition+" parseFloat("+browser.Version+")";try{if(eval(comparison)){isSupported=true;break}}catch(e){}}}}return isSupported},SearchString:function(data){for(var i=0;i<data.length;i++){var browser=data[i].String;var os=data[i].Prop;this.VersionSearchString=data[i].VersionSearch||data[i].Identity;if(browser){if(browser.indexOf(data[i].SubString)!=-1)return data[i].Identity}else if(os)return data[i].Identity}},SearchVersion:function(data){var index=data.indexOf(this.VersionSearchString);if(index==-1)return;return parseFloat(data.substring(index+this.VersionSearchString.length+1))},BrowserData:[{String:navigator.vendor,SubString:"Apple",Identity:"Safari"},{String:navigator.userAgent,SubString:"Firefox",Identity:"Firefox"},{String:navigator.vendor,SubString:"iCab",Identity:"iCab"},{String:navigator.userAgent,SubString:"MSIE",Identity:"Explorer",VersionSearch:"MSIE"},{String:navigator.vendor,SubString:"KDE",Identity:"Konqueror"},{String:navigator.userAgent,SubString:"Gecko",Identity:"Mozilla",VersionSearch:"rv"},{String:navigator.userAgent,SubString:"Netscape",Identity:"Netscape"},{String:navigator.userAgent,SubString:"Mozilla",Identity:"Netscape",VersionSearch:"Mozilla"},{Prop:window.opera,Identity:"Opera"}],OsData:[{String:navigator.platform,SubString:"Linux",Identity:"Linux"},{String:navigator.platform,SubString:"Mac",Identity:"Mac"},{String:navigator.platform,SubString:"Win",Identity:"Windows"}]};GDN.UR.Browser.Init();GDN.UR.BrowserType=function(){var _condition=null;var _name=null;var _os=null;var _version=null;this.Condition=function(){if(arguments[0])_condition=arguments[0];else return _condition};this.Name=function(){if(arguments[0])_name=arguments[0];else return _name};this.Os=function(){if(arguments[0])_os=arguments[0];else return _os};this.Version=function(){if(arguments[0])_version=arguments[0];else return _version}};GDN.Cookies.GCION={CoppaFormat:"{gcionid}~{version}~{date_created}~{status}~",Expires:365,Name:"GCIONID",PostZagFormat:"{gcionid}~{version}~{date_created}~{status}~"+"zip:{zip}|yob:{yob}|gen:{gen}|cou:{cou}|sit:{sit}|"+"adr:{adr}|ind:{ind}|job:{job}|siz:{siz}",PreZagFormat:"{gcionid}~{version}~{date_created}~{status}~"+"ses:{ses}",Version:"1",Get:function(){var user=new GDN.UR.User();user.CompanySize(this.GetValue("CompanySize"));user.Country(this.GetValue("Country"));user.Email(this.GetValue("Email"));user.GcionId(this.GetValue("GcionId"));user.Gender(this.GetValue("Gender"));user.Industry(this.GetValue("Industry"));user.Occupation(this.GetValue("Occupation"));user.Sessions(this.GetSessions());user.Site(this.GetValue("Site"));user.Status(this.GetValue("Status"));user.Yob(this.GetValue("Yob"));user.Zip(this.GetValue("Zip"));return user},GetMatch:function(key){switch(key){case"CompanySize":return"siz";case"Country":return"cou";case"Email":return"adr";case"Gender":return"gen";case"Industry":return"ind";case"Occupation":return"job";case"Sessions":return"ses";case"Site":return"sit";case"Yob":return"yob";case"Zip":return"zip"}return null},GetSession:function(entry){if(GDN.IsNullOrEmpty(entry))return null;if(entry.indexOf("#")!=-1){entry=entry.split('#');var session=new GDN.UR.Session();session.Id(entry[0]);session.Date(entry[1]);session.PageViews(entry[2]);session.SectionFront(entry[3]);return session}else return null},GetSessions:function(){var entries=this.GetValue("Sessions");if(GDN.IsNullOrEmpty(entries))return null;if(entries.indexOf("$")!=-1){entries=entries.split('$');var sessions=[];for(var i=0;i<entries.length;i++)sessions.push(this.GetSession(entries[i]));return sessions}else return new Array(this.GetSession(entries))},GetValue:function(key){if(!GDN.Cookie.Exists(this.Name))return null;var cookie=GDN.Base64.Decode(GDN.Cookie.Get(this.Name));var parts=cookie.split('~');switch(key){case"GcionId":return parts[0];case"Version":return parts[1];case"DateCreated":return parts[2];case"Status":return parts[3];default:{if(parts.length==5){var pairs=parts[4].split('|');var match=this.GetMatch(key);for(var i=0;i<pairs.length;i++){var pair=pairs[i].split(':');if(match==pair[0])return pair[1]}}else return null}break}return null},Set:function(user,zagState){if(zagState==GDN.UR.UserStatus.UnderAge){var cookie=this.CoppaFormat;cookie=cookie.replace(/{gcionid}/gi,"0");cookie=cookie.replace(/{date_created}/gi,GDN.GetCreationDate());cookie=cookie.replace(/{version}/gi,this.Version);cookie=cookie.replace(/{status}/gi,user.Status())}else{var cookie=(zagState==GDN.UR.UserStatus.IdentifierCreated)?this.PreZagFormat:this.PostZagFormat;cookie=cookie.replace(/{gcionid}/gi,user.GcionId());cookie=cookie.replace(/{date_created}/gi,GDN.GetCreationDate());cookie=cookie.replace(/{version}/gi,this.Version);cookie=cookie.replace(/{status}/gi,user.Status());cookie=cookie.replace(/{zip}/gi,user.Zip());cookie=cookie.replace(/{yob}/gi,user.Yob());cookie=cookie.replace(/{gen}/gi,user.Gender());cookie=cookie.replace(/{cou}/gi,user.Country());cookie=cookie.replace(/{sit}/gi,user.Site());cookie=(!GDN.IsNullOrEmpty(user.Email()))?cookie.replace(/{adr}/gi,user.Email()):cookie.replace(/\|adr:{adr}/gi,"");cookie=(!GDN.IsNullOrEmpty(user.Industry()))?cookie.replace(/{ind}/gi,user.Industry()):cookie.replace(/\|ind:{ind}/gi,"");cookie=(!GDN.IsNullOrEmpty(user.Occupation()))?cookie.replace(/{job}/gi,user.Occupation()):cookie.replace(/\|job:{job}/gi,"");cookie=(!GDN.IsNullOrEmpty(user.CompanySize()))?cookie.replace(/{siz}/gi,user.CompanySize()):cookie.replace(/\|siz:{siz}/gi,"");cookie=cookie.replace(/{ses}/gi,this.SetSessions(user.Sessions()))}GDN.Cookie.Set(this.Name,GDN.Base64.Encode(cookie),this.Expires)},SetSessions:function(sessions){var entries="";for(var i=0;i<sessions.length;i++){if(i==(sessions.length-1)){entries+=sessions[i].Id()+"#"+sessions[i].Date()+"#"+sessions[i].PageViews()+"#"+sessions[i].SectionFront()}else{entries+=sessions[i].Id()+"#"+sessions[i].Date()+"#"+sessions[i].PageViews()+"#"+sessions[i].SectionFront()+"$"}}return entries}};GDN.UR.Intercept={CanIntercept:function(){if(window.location.href==GDN.ZagFormUrl())return false;var canIntercept=false;var count=0;var user=GDN.Cookies.GCION.Get();for(var i=0;i<user.Sessions().length;i++){if(canIntercept)break;if(i!=0){var days=GDN.GetDays(user.Sessions()[i-1].Date(),user.Sessions()[i].Date());if(days<=gdn_days){count++;if(count>=gdn_sessions){if(user.Sessions()[i].PageViews()>=(gdn_page_views-1)){if(user.Sessions()[i].SectionFront()=="frontpage"||user.Sessions()[i].SectionFront()=="section")canIntercept=true}}}else{if(i==1)count=1;else count=0}}else{count++;if(gdn_sessions==1){if(user.Sessions()[i].PageViews()>=(gdn_page_views-1)){if(user.Sessions()[i].SectionFront()=="frontpage"||user.Sessions()[i].SectionFront()=="section")canIntercept=true}}}}return canIntercept},ChangeLink:function(link,href){var innerText=link.innerText;link.href=href;if(link.innerText!=innerText)link.innerText=innerText},EscapeRegEx:function(value){if(!arguments.callee.sRE){var specials=['/'];arguments.callee.sRE=new RegExp('(\\'+specials.join('|\\')+')','g')}return value.replace(arguments.callee.sRE,'\\$1')},GetRegEx:function(ex){if(ex.indexOf("http")==-1){if(ex.charAt(0)!="/")ex=location.protocol+"//"+location.host+"/"+ex;else ex=location.protocol+"//"+location.host+ex}var index=ex.indexOf("*");if(index!=-1&&index==ex.length){var prefix=ex.substring(0,index);var suffix=ex.substring(index+1,ex.length);ex=prefix+"([a-zA-Z0-9_-]{1,})"+suffix}return"/"+this.EscapeRegEx(ex)+"/i"},InterceptLinks:function(){var links=document.links;for(var i=0;i<links.length;i++){if(GDN.IsNullOrEmpty(links[i].target)){if(links[i].href.indexOf(location.hostname)!=-1){try{var useInclusion=gdn_use_inclusion}catch(e){var useInclusion=false}if(useInclusion)var canIntercept=!(this.IsException(links[i].href,gdn_local_ex));else var canIntercept=this.IsException(links[i].href,gdn_local_ex)}else var canIntercept=!(this.IsException(links[i].href,gdn_ext_ex));if(canIntercept){if(gdn_zag_form_url.indexOf("?")==-1)var href=links[i].href.replace(gdn_zag_form_url+"?Destination=","");else var href=links[i].href.replace(gdn_zag_form_url+"&Destination=","");href=GDN.AppendParam(GDN.CombinePath(gdn_site_url,gdn_zag_form_url),"Destination",escape(href));this.ChangeLink(document.links[i],href)}}}},IsException:function(href,ex){if(href.toLowerCase().substring(0,11)=="javascript:")return true;var isException=true;for(var i=0;i<ex.length;i++){if(!GDN.IsNullOrEmpty(ex[i])){var exception=new RegExp(eval(this.GetRegEx(ex[i])));if(exception.test(href)){isException=false;break}}}return isException}};GDN.UR.Page={Intercept:function(){var user=GDN.Cookies.GCION.Get();if(user.Status()==GDN.UR.UserStatus.IdentifierCreated){GDN.UR.Page.UpdateSession();if(GDN.UR.Intercept.CanIntercept()){GDN.LoadFile("ValidateUser","UREvents")}}},Load:function(){if(GDN.UR.Browser.IsSupported()){if(document.getElementById("URWidget-Zag"))GDN.LoadFile("ZagUser","UREvents");if(GDN.Cookie.Exists(GDN.Cookies.GCION.Name)){if(GDN.IsNullOrEmpty(GDN.Cookies.GCION.GetValue("GcionId")))GDN.LoadFile("CreateUser","UREvents");else GDN.UR.Page.PreZag()}else GDN.LoadFile("CreateUser","UREvents")}},PreZag:function(){var user=GDN.Cookies.GCION.Get();if(user.Status()!=GDN.UR.UserStatus.IdentifierCreated)GDN.UR.Page.PostZag();else{if(!GDN.IsNullOrEmpty(GDN.Request.QueryString("GID"))){var gcionId=GDN.Request.QueryString("GID");if(user.GcionId()!=gcionId){if(gcionId=="0"){user.Yob(new Date().getFullYear());GDN.Cookies.GCION.Set(user,GDN.UR.UserStatus.UnderAge)}else GDN.LoadFile("GetUser","UREvents")}}else GDN.UR.Page.Intercept()}},PostZag:function(){var user=GDN.Cookies.GCION.Get();if(GDN.IsNullOrEmpty(GDN.Cookies.Session.GetValue("ref"))){GDN.LoadFile("GetUser","UREvents")}GDN.Cookies.Session.SetValue("ref",0)},UpdateSession:function(){var user=GDN.Cookies.GCION.Get();try{if(gdn_section_front=="frontpage"||gdn_section_front=="section")var sectionFront=gdn_section_front}catch(e){var sectionFront=null}if(GDN.IsNullOrEmpty(GDN.Cookies.Session.GetValue("ses"))){user.AddSession(sectionFront);GDN.Cookies.Session.SetValue("ses",user.Sessions().length)}else{user.UpdateSession(user.Sessions().length,sectionFront)}GDN.Cookies.GCION.Set(user,GDN.UR.UserStatus.IdentifierCreated)}};GDN.UR.Session=function(){var _date=null;var _id=0;var _pageViews=0;var _sectionFront=null;this.Date=function(){if(arguments[0])_date=arguments[0];else return _date};this.Id=function(){if(arguments[0])_id=arguments[0];else return _id};this.PageViews=function(){if(arguments[0])_pageViews=arguments[0];else return _pageViews};this.SectionFront=function(){if(arguments[0])_sectionFront=arguments[0];else return _sectionFront}};GDN.UR.User=function(){var _companySize=null;var _country=null;var _email=null;var _gcionId=null;var _gender=0;var _industry=null;var _occupation=null;var _sessions=[];var _site=null;var _status=0;var _yob=0;var _zip=null;this.CompanySize=function(){if(arguments[0])_companySize=arguments[0];else return _companySize};this.Country=function(){if(arguments[0])_country=arguments[0];else return _country};this.Email=function(){if(arguments[0])_email=arguments[0];else return _email};this.GcionId=function(){if(arguments[0])_gcionId=arguments[0];else return _gcionId};this.Gender=function(){if(arguments[0])_gender=arguments[0];else return _gender};this.Industry=function(){if(arguments[0])_industry=arguments[0];else return _industry};this.Occupation=function(){if(arguments[0])_occupation=arguments[0];else return _occupation};this.Sessions=function(){if(arguments[0])_sessions=arguments[0];else return _sessions};this.Site=function(){if(arguments[0])_site=arguments[0];else return _site};this.Status=function(){if(arguments[0])_status=arguments[0];else return _status};this.Yob=function(){if(arguments[0])_yob=arguments[0];else return _yob};this.Zip=function(){if(arguments[0])_zip=arguments[0];else return _zip};this.AddSession=AddSession;this.GetSession=GetSession;this.RemoveSession=RemoveSession;this.UpdateSession=UpdateSession;if(arguments[0])Init(arguments[0]);function Init(){_companySize=arguments[0].CompanySize;_country=arguments[0].Country;_email=arguments[0].Email;_gcionId=arguments[0].GcionId;_gender=arguments[0].Gender;_industry=arguments[0].Industry;_occupation=arguments[0].Occupation;_site=arguments[0].Site;_status=arguments[0].Status;_yob=arguments[0].Yob;_zip=arguments[0].Zip}function AddSession(sectionFront){if((_sessions.length+1)>=gdn_MaxSessions)this.RemoveSession();var session=new GDN.UR.Session();session.Date(GDN.GetCreationDate());session.Id(_sessions.length+1);session.PageViews(1);session.SectionFront(sectionFront);_sessions.push(session)}function GetSession(id){for(var i=0;i<_sessions.length;i++){if(id==_sessions[i].Id())return _sessions[i]}}function RemoveSession(){_sessions.shift()}function UpdateSession(id,sectionFront){for(var i=0;i<_sessions.length;i++){if(id==_sessions[i].Id()){_sessions[i].PageViews(parseInt(_sessions[i].PageViews())+1);if(_sessions[i].SectionFront()!="frontpage"&&_sessions[i].SectionFront()!="section")_sessions[i].SectionFront(sectionFront);break}}}};GDN.UR.UserProvider={Create:function(){var querystring="q=3&c=1&NoCookie=1";GDN.Rpc.Send(GDN.RegUrl(querystring))},Get:function(user){var querystring="q=3&c=1&NoCookie=1&";querystring=GDN.AppendParam(querystring,"GCIONID",user.GcionId());GDN.Rpc.Send(GDN.RegUrl(querystring))},UpdateZag:function(user){var querystring="q=4&c=1&NoCookie=1&";var cookie=GDN.Cookies.GCION.Get();if(user.Country()!="us")user.Zip("00000");querystring=GDN.AppendParam(querystring,"Country",user.Country());querystring=GDN.AppendParam(querystring,"GCIONID",GDN.Cookies.GCION.GetValue("GcionId"));querystring=GDN.AppendParam(querystring,"Gender",user.Gender());querystring=GDN.AppendParam(querystring,"OriginatingSite",escape(gdn_reg_site_code));querystring=GDN.AppendParam(querystring,"YOB",user.Yob());querystring=GDN.AppendParam(querystring,"Zip",user.Zip());if(gdn_occupation_required){if(user.Occupation()){querystring=GDN.AppendParam(querystring,"Occupation",user.Occupation());if(occupation!="Student/Intern"&&occupation!="Retired"&&occupation!="Not Employed"){querystring=GDN.AppendParam(querystring,"Industry",user.Industry());querystring=GDN.AppendParam(querystring,"CompanySize",user.CompanySize())}}}GDN.Rpc.Send(GDN.RegUrl(querystring))},Validate:function(user){var querystring="q=3&c=1&NoCookie=1&";querystring=GDN.AppendParam(querystring,"GCIONID",user.GcionId());GDN.Rpc.Send(GDN.RegUrl(querystring))},Zag:function(user){var querystring="q=2&c=1&NoCookie=1&";var cookie=GDN.Cookies.GCION.Get();if(user.Country()!="us")user.Zip("00000");querystring=GDN.AppendParam(querystring,"Country",user.Country());querystring=GDN.AppendParam(querystring,"GCIONID",GDN.Cookies.GCION.GetValue("GcionId"));querystring=GDN.AppendParam(querystring,"Gender",user.Gender());querystring=GDN.AppendParam(querystring,"OriginatingSite",escape(gdn_reg_site_code));querystring=GDN.AppendParam(querystring,"YOB",user.Yob());querystring=GDN.AppendParam(querystring,"Zip",user.Zip());if(gdn_occupation_required){if(user.Occupation()){querystring=GDN.AppendParam(querystring,"Occupation",user.Occupation());if(occupation!="Student/Intern"&&occupation!="Retired"&&occupation!="Not Employed"){querystring=GDN.AppendParam(querystring,"Industry",user.Industry());querystring=GDN.AppendParam(querystring,"CompanySize",user.CompanySize())}}}GDN.Rpc.Send(GDN.RegUrl(querystring))}};GDN.UR.UserStatus={IdentifierCreated:1,ZagCollected:2,OccupationCollected:4,EmailCollected:8,UnderAge:16};GDN.ChangeCheckedState=function(object,state){for(var i=0;i<object.length;i++){if(state.toLowerCase()=="checked")object[i].checked=true;else object[i].checked=false}};GDN.GetCheckedIndex=function(object,value){for(var i=0;i<object.length;i++){if(object[i].value==value)return i}return 0};GDN.GetCheckedValue=function(object){for(var i=0;i<object.length;i++){if(object[i].checked)return object[i].value}};GDN.HandleKeyPress=function(e,fns,keycode){var key=e.keyCode||e.which;if(key==keycode)fns.call()};GDN.SetCheckedIndex=function(object,value){for(var i=0;i<object.length;i++){if(object[i].value==value){object[i].checked=true;return}}};GDN.SetSelectedIndex=function(object,value){for(var i=0;i<object.options.length;i++){if(object.options[i].value==value){object.selectedIndex=i;return}}};GDN.Toggle=function(elementName,state){if(state=="show")document.getElementById(elementName).style.display='';else document.getElementById(elementName).style.display='none'};GDN.ToggleButton=function(elementName,isEnabled){document.getElementById(elementName).disabled=isEnabled};GDN.ToggleState=function(object,element){var country=object.options[object.selectedIndex].value.toLowerCase();if(GDN.IsNullOrEmpty(country)||country=="us")GDN.Toggle(element,"show");else GDN.Toggle(element,"hide")};GDN.ErrorSummary=function(){var _errors=[];var _header=null;this.AddError=AddError;this.HasErrors=HasErrors;this.Header=Header;this.Hide=Hide;this.Show=Show;this.ToString=ToString;function AddError(message){_errors.push(message)}function HasErrors(){if(_errors.length>0)return true;else return false}function Header(value){if(value)_header=value;else return _header}function Hide(elementName){GDN.Toggle(elementName,"hide")}function Show(elementName){var errorSummary='<p align="center">'+this.Header()+'</p>';errorSummary+='<ul>';for(var i=0;i<_errors.length;i++)errorSummary+='<li>'+_errors[i]+'</li>';errorSummary+='</ul>';GDN.Toggle(elementName,"show");GDN.SetInnerHtml(elementName,errorSummary)}function ToString(){var errorSummary=this.Header()+"\n\n";for(var i=0;i<_errors.length;i++)errorSummary+="* "+_errors[i]+"\n";return errorSummary}};GDN.Validate={IsChecked:function(object){for(var i=0;i<object.length;i++){if(object[i].checked)return true}return false},IsEmail:function(object){var regex=/^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;return regex.test(object)},IsInt:function(object){var regex=/^-{0,1}\d+$/;return regex.test(object)},IsMaxEmail:function(object){var regex=/^.{1,100}$/;return!(regex.test(object))},IsMaxFirstName:function(object){var regex=/^.{1,30}$/;return!(regex.test(object))},IsMaxLastName:function(object){var regex=/^.{1,30}$/;return!(regex.test(object))},IsMaxPassword:function(object){var regex=/^.{1,30}$/;return!(regex.test(object))},IsMaxUserName:function(object){var regex=/^.{1,16}$/;return!(regex.test(object))},IsMinPassword:function(object){var regex=/^.{5,}$/;return!(regex.test(object))},IsMinUserName:function(object){var regex=/^.{5,}$/;return!(regex.test(object))},IsPassword:function(object){var regex=/^[a-zA-Z0-9]+$/;return regex.test(object)},IsUserName:function(object){var regex=/^[a-zA-Z0-9\_\-]+$/;return regex.test(object)},IsYob:function(object){var regex=/(^\d{4}$)/;return regex.test(object)},IsYobUnderAge:function(object){var today=new Date();var curyear=today.getFullYear();return((curyear-parseInt(object))<=(gdn_coppaage))?false:true},IsYobInRange:function(object){var today=new Date();var minYear=1901;var maxYear=today.getFullYear();if((parseInt(object)<minYear)||(parseInt(object)>maxYear))return false;else return true},IsZip:function(object){var regex=/(^\d{5}$)/;return regex.test(object)}};GDN.ValidatedFields=function(){var _invalidFields=[];var _validFields=[];var _validValues=[];this.AddInvalidField=AddInvalidField;this.AddValidField=AddValidField;this.Clear=Clear;this.Populate=Populate;this.SetFocus=SetFocus;function AddInvalidField(name){_invalidFields.push(name)}function AddValidField(name,value){_validFields.push(name);_validValues.push(value)}function Clear(form){for(var i=0;i<_invalidFields.length;i++){var field=eval("form."+_invalidFields[i]);if(!/select/.test(field.type))field.value=""}}function Populate(form){for(var i=0;i<_validFields.length;i++){var field=eval("form."+_validFields[i]);if(!/select/.test(field.type))field.value=_validValues[i].toString()}}function SetFocus(form){var field=eval("form."+_invalidFields[0]);if(field[0])field[0].focus();else field.focus()}};GDN.UA.Disable=function(){GDN.AddListener(gdn_Divs["Login"],GDN.Disable);GDN.AddListener(gdn_Divs["PluckLogin"],GDN.Disable);GDN.AddListener(gdn_Divs["PluckReg"],GDN.Disable);GDN.AddListener(gdn_Divs["SaxotechLogin"],GDN.Disable);GDN.AddListener(gdn_Divs["Newsletters"],GDN.Disable)};GDN.LoadUI=function(){GDN.LoadFile("UI")};if(gdn_enable_auth_by_division){if(gdn_enable_auth_by_site){GDN.AddListener(gdn_Divs["Login"],GDN.UA.Page.Load);GDN.AddHandler(window,'load',GDN.UA.Page.PluckLogin);GDN.AddHandler(window,'load',GDN.UA.Page.PluckReg);GDN.AddHandler(window,'load',GDN.UA.Page.PluckLogout);GDN.AddHandler(window,'load',GDN.UA.Page.SaxotechLogin);GDN.AddHandler(window,'load',GDN.UA.Page.Newsletters)}else GDN.UA.Disable()}else GDN.UA.Disable();if(gdn_enable_reg_by_division){if(gdn_enable_reg_by_site){if(GDN.GetVersion("Cookie")==1){GDN.AddHandler(window,"load",GDN.UR.Page.Load)}}}var gcion_enable_bt=gdn_enable_bt;GDN.AddHandler(window,'load',GDN.LoadUI);
function GoToPDSearch()
{
	location.href='http://'+PDURL+'/sp?aff=1171&skin='+PDSKIN+'&keywords='+document.PDSearch.keywords.value;
}

var UserSearchPopup = '<div align=\"center\" class=\"UAWidget-PopUp\">'  
  + '  <div align=\"left\">'
  + '    <h3>Search People</h3>'
  + '    <span>Search screen names, real names, and profile information.</span>'
  + '  </div>'
  + '  <br />'
  + '  <form id=\"UAWidget-Search\" method=\"get\" name=\"PDSearch\" action=\"javascript:GoToPDSearch();\"  >'
  + '    <table border=\"0\" cellpadding=\"0\" cellspacing=\"10\">'
  + '    <tr>'
  + '      <td align=\"right\" nowrap=\"nowrap\" style=\"vertical-align: middle;\"><label for=\"keywords\">Keywords:</label></td>'
  + '      <td align=\"left\" style=\"vertical-align: middle;\"><input type=\"text\" id=\"keywords\" name=\"keywords\" size=\"30\" /></td>'
  + '      <td align=\"middle\"><img src=\"/graphics/button_go.gif\" OnClick=\"GoToPDSearch()\" alt=\"Go\" border=\"0\" style=\"padding-left: 3px\" /></a></td>'
  + '    </tr>'
  + '    </table>'
  + '	<br>'
  + '  <div align=\"center\">' + GDN.Widget.GetCloseWindow() + '</div>'
  + '   </form>';
   
var UserSearchLink = "| <a href=\"javascript:GDN.Widget.Show(UserSearchPopup,350,50,'UAWidgetRef-PopUp');\" ><b>Search people</b></a>";
  

  

// handle UA events for Saxotech
function SaxotechUAEvent(eventId)
{
  switch (eventId)
  {
    // handles log outs
    case "Out":
    {
      // remove Saxotech session cookie
      GDN.Cookie.Remove("PBCSSESSIONID");
      GDN.Cookie.Remove("PBCSSESSIONID", "/", "", true);
      GDN.Cookie.Remove("PBCSSESSIONID", "/", "." + gdn_site_url, true);
    }
	  break;
	// handles writing out Search link
	case "Search":
	{
	  GDN.SetInnerHtml("CustomLinks", UserSearchLink);
	}
	  break;
	// handles Newsletters log in
	case "NLLogin":
	{
	  if(NLSigninOnly)
	  {
		NLetersRedirect("nlettersubscribe");
	  }
	  else
	  {
		updateNlettersSubscription("SignIn");
	  }
	}
	  break;
	// handles Newsletters log in
	case "NLRegister":
	{
		if (GDN.Cookie.Exists("GDNNL")) 
		{
			updateNlettersSubscription("Register");
		}
		else
		{
			NLetersRedirect("nlettererror");
		}
	  
	}
	  break;
  }
}
 
// register events
GDN.Api.Register(SaxotechUAEvent, "Out", "Logout");

if(typeof(gdn_enable_search)!='undefined' && gdn_enable_search == 1)
{
GDN.Api.Register(SaxotechUAEvent, "Search", "LoggedOut");
GDN.Api.Register(SaxotechUAEvent, "Search", "LoggedIn");
}

function StartNewClip() {
scroll(0,0);
}

function SaxotechSessionCookie()
{
 if(!readCookie("PBCSSESSIONID")) {
  var value=Math.round(Math.random()*1000000000000000 + 9000000000000000);  
  document.cookie = "PBCSSESSIONID=" + value + "; path=/;";
  }
}


// handle UA events for Pluck
function PluckUAEvent(eventId)
{
  switch (eventId)
  {
    // handles log outs
    case "Out":
    {
      // clear avatar for Pluck 
      try
      {
        gsl.personaHref = null;
      }
      catch (e) {}
    }
    break;

    // handles cancellations
    case "Cancel":
    {
      // clear avatar for Pluck 
      try
      {
        gsl.personaHref = null;
      }
      catch (e) {}
    }
    break;
  }
}
 
// register events
GDN.Api.Register(PluckUAEvent, "Out", "Logout");
GDN.Api.Register(PluckUAEvent, "Cancel", "Cancel");



/*
******************************************************************************
       File: NavigationMenu_Object.js
Description: Contains the common JavaScript code used for inserting the child 
             menus on to the page and creating the Navigation Menu.
  Copyright: Copyright (c) 2007, GMTI. All rights reserved.
******************************************************************************
*/

/*****************************************************************************
 Object Name: objNavigationMenu
 Defines the objNavigationMenu object which is used request the all of the 
 child node for the navigation menu level.                                       
*****************************************************************************/
var objNavigationMenu = {
	
		getMenuNode: function(Index) {
		    if(typeof(MenuArray[Index]) != "undefined")
		        return MenuArray[Index].Menu;
		},
		
		addScript: function(requestUrl){
            // define DOM elements
            var htmlTag = document.getElementsByTagName('head').item(0);
            var scriptTag = document.createElement('script');
              
            // set tag attributes
            scriptTag.setAttribute('language', 'javascript');
            scriptTag.setAttribute('type', 'text/javascript');
            scriptTag.setAttribute('src', requestUrl);
              
            // append tag to DOM
            htmlTag.appendChild(scriptTag);
              
            return false;
        },
        
        removeScript: function(){
            // define DOM elements        
            var htmlTag = document.getElementsByTagName('head').item(0);
            var scriptTag = htmlTag.getElementsByTagName('script');
            
            // removes tag from DOM
            htmlTag.removeChild(scriptTag.item(scriptTag.length-1));
        },
        
		browserCheck: function(req){
		    if (typeof(DOMParser) != "undefined") return 0;
            else if (ActiveXObject) return 1;
		    else return null;
		},
		
		displayMenu: function(menuIdx, divName, renderFunc) {
		    if(typeof(MenuArray[menuIdx]) != "undefined")
                for(var x =0; x <MenuArray[menuIdx].Menu.length; x++)
                    document.getElementById(divName).innerHTML += renderFunc(MenuArray[menuIdx].Menu[x]);
		}
};

/*****************************************************************************
 Object Name: menuLayers
 Defines the menuLayer object which is used to hide, display, and set position
 of a menu level.                                       
*****************************************************************************/
var menuLayers = {
  timer: null,
  stack: new Array(),
  activeMenuID: null,
  attachNode: null,
  
  show: function(id, pos, left, top) {
    var mnu = document.getElementById? document.getElementById(id): null;
    if (!mnu) return;
    mnu.style.display = "";
    mnu.innerHTML = "";
    if(menuLayers.stack.length > 0){
            
        if(menuLayers.stack.length > 0)
            var entry1 = menuLayers.stack.pop();
        if(menuLayers.stack.length > 0)
            var entry2 = menuLayers.stack.pop();
        if(menuLayers.stack.length > 0)
            var entry3 = menuLayers.stack.pop();
        if(entry3)
            menuLayers.stack.push(entry3);
        if(entry2)
            menuLayers.stack.push(entry2);
        menuLayers.stack.push(entry1);
        
        if(entry1 != id && entry2 != id && entry3 != id)
            menuLayers.stack.push(id);
    }
    else
        menuLayers.stack.push(id);
        
    if(mnu.onmouseout == null) mnu.onmouseout = this.mouseoutCheck;
    if(mnu.onmouseover == null) mnu.onmouseover = this.clearTimer;
    if(pos){
        mnu.style.position = "absolute";
        if(top) mnu.style.top = top +'px';
        if(left) mnu.style.left = left+'px';
    }
  },
  
  hide: function(id) {
    if(id){
        var entry1 = menuLayers.stack.pop();
        if(entry1 != id)
            menuLayers.stack.push(entry1);
        var mnu = document.getElementById? document.getElementById(id): null;
        if (!mnu) return;
        mnu.style.display = "none";
        mnu.innerHTML = "";
    }
    else{
        if(menuLayers.stack.length>1){
            this.clearTimer();
            this.timer = setTimeout("menuLayers.hideChild()", 300);
        }
    }
  },
  
  hideChild: function(){
        if(menuLayers.stack.length > 0){
            var entry1 = menuLayers.stack.pop();
            var mnu = document.getElementById? document.getElementById(entry1): null;
            if (!mnu) return;
            mnu.style.display = "none";
            mnu.innerHTML = "";
            ResetNode(menuLayers.stack.length+1);
        }
  },
  
  attach: function(parent, child) {
      var p = document.getElementById(parent);
      var c = document.getElementById(child );
      this.attachNode = p.offsetParent.id;
      var top = 0;
      var left= 0;
	
      for (; p; p = p.offsetParent){
        top  += p.offsetTop;
        left += p.offsetLeft;
      }
      var coord = new Object ();
      coord['x'] = left;
      coord['y'] = top;
      return coord;
  },
  
  getPos: function(inputElement) {
	  var coords =  new Object();
	  coords.x = 0;
	  coords.y = 0;
      try {
	    targetElement = inputElement;
		if(targetElement.x && targetElement.y) {
		    coords.x = targetElement.x;
		    coords.y = targetElement.y;
		} else {
		    if(targetElement.offsetParent) {
			    coords.x += targetElement.offsetLeft;
				coords.y += targetElement.offsetTop;
				while(targetElement = targetElement.offsetParent) {
				    coords.x += targetElement.offsetLeft;
					coords.y += targetElement.offsetTop;
				}
			} else {
					    //alert(\"Could not find any reference for coordinate positioning.\");
			}
		}
	    return coords;
	  } catch(error) {
	    return coords;
	  }
  },
    
  mouseoutCheck: function(e) {
    e = e? e: window.event;
    // is element moused into contained by menu? or is it menu (ul or li or a to menu div)?
    if(menuLayers){
        var entry1 = menuLayers.stack.pop();
        var toEl = e.relatedTarget? e.relatedTarget: e.toElement;
        var mnu = document.getElementById(entry1);
        menuLayers.stack.push(entry1);
        //$("debugTag").innerHTML += "<br />Checking: "+entry1+" ,Status: "+(mnu != toEl && !menuLayers.contained(toEl, mnu));
        if ( mnu != toEl && !menuLayers.contained(toEl, mnu)){menuLayers.hide();}
    }
  },
  
  // returns true of oNode is contained by oCont (container)
  contained: function(oNode, oCont) {
    if (!oNode) return; // in case alt-tab away while hovering (prevent error)
    if ( oNode == oCont ) return true;
    while ( oNode = oNode.parentNode ) 
      if ( oNode == oCont ) return true;
    return false;
  },

  clearTimer: function() {
    if (menuLayers.timer) clearTimeout(menuLayers.timer);
  }
};

/*
******************************************************************************
       File: BuildNavigationMenuHeader.js
Description: Contains the common JavaScript code used for creating the 
             Navigation Menu.
  Copyright: Copyright (c) 2007, GMTI. All rights reserved.
  Date:		 01/22/2008
******************************************************************************
*/
var ID = new Array();
ID[0] = null;
ID[1] = 'NavigationMenuLevel1Div';
ID[2] = 'NavigationMenuLevel2Div';
ID[3] = 'NavigationMenuLevel3Div';
ID[4] = 'NavigationMenuLevel4Div';

var MenuOpen = new Array();

/*******************************************************************************
 This function changes the menu node style.
*******************************************************************************/
function ChangeNode(Level, subNode ) {
    ResetNode(Level);
  	document.getElementById('node'+subNode).className = "level"+Level+"-collapse";
};

/*******************************************************************************
 This function changes the menu node style back to its default value.
*******************************************************************************/
function ResetNode(Level) {
    MenuOpen[Level] = "";
    ResetColor(Level);
};

/*******************************************************************************
 This function changes the menu color style back to its default value.
*******************************************************************************/
function ResetColor(Level) {
    var offArray = document.getNavMenuElementsByClassName("level"+Level+"-collapse");
  	for (var x=0;x<offArray.length;x++) {
  	      offArray[x].className = "level"+Level+"-expand";
  	}
};

/*******************************************************************************
 This function captures the unload page event.
*******************************************************************************/
window.onbeforeunload = function () {
    var MenuMarkIDs = getMenuCookie();
    //MenuMarkIDs.URL = encodeURIComponent(window.location);
    MenuMarkIDs.URL = window.location.toString();
    setMenuCookie(MenuMarkIDs);
};

/*******************************************************************************
 This function creates a DOM method to retrieve an array of tags by class name.
*******************************************************************************/ 
document.getNavMenuElementsByClassName = function (className, tag, elm){
	var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
	var tag = tag || "*";
	var elm = elm || document;
	var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
	var returnElements = [];
	var current;
	var length = elements.length;
	for(var i=0; i<length; i++){
		current = elements[i];
		if(testClass.test(current.className)){
			returnElements.push(current);
		}
	}
	return returnElements;
};

function enCodeURL(urlInput){
    urlString = urlInput.toString();
    var outValue="";
    for (i=0; i<urlString.length; i++)
	    outValue += '%' + urlString.charCodeAt(i).toString(16);
	return outValue;
};

/*******************************************************************************
 These functions get and set menu data in the cookie.
*******************************************************************************/
GetNavData = function(user)
{
  try
  {
  	if (gdn_version == 2)
      user = GDN.Cookies.Session.Get(user);
    else
  	{
      user.NodeLevel1 = unescape(GDN.Cookies.Session.GetValue("nd1"));
      user.NodeLevel2 = unescape(GDN.Cookies.Session.GetValue("nd2"));
  	}
  }
  catch (e)
  {
    user.NodeLevel1 = unescape(GDN.Cookies.Session.GetValue("nd1"));
    user.NodeLevel2 = unescape(GDN.Cookies.Session.GetValue("nd2"));
  }

  return user;
};

SetNavData = function(user)
{
  try
  {
  	if (gdn_version == 2)
      GDN.Cookies.Session.Set(user);
    else
    {
      user.NodeLevel1 = (GDN.IsNullOrEmpty(user.NodeLevel1)) ? GDN.Cookies.Session.GetValue("nd1") : user.NodeLevel1;
      user.NodeLevel2 = (GDN.IsNullOrEmpty(user.NodeLevel2)) ? GDN.Cookies.Session.GetValue("nd2") : user.NodeLevel2;
      GDN.Cookies.Session.SetValue("nd1", escape(user.NodeLevel1));
      GDN.Cookies.Session.SetValue("nd2", escape(user.NodeLevel2));
    }
  }
  catch (e)
  {
    user.NodeLevel1 = (GDN.IsNullOrEmpty(user.NodeLevel1)) ? GDN.Cookies.Session.GetValue("nd1") : user.NodeLevel1;
    user.NodeLevel2 = (GDN.IsNullOrEmpty(user.NodeLevel2)) ? GDN.Cookies.Session.GetValue("nd2") : user.NodeLevel2;
    GDN.Cookies.Session.SetValue("nd1", escape(user.NodeLevel1));
    GDN.Cookies.Session.SetValue("nd2", escape(user.NodeLevel2));
  }
};

/*******************************************************************************
 This function sets get the object from the session cookie, otherwise returns
 the default object.
*******************************************************************************/
function getMenuCookie() {
    var MenuMarkIDs = {"Level1Node":"","Level2Node":"","NewClick":false,"URL":""};
    var userEmpty = new Object;
    var user = GetNavData(userEmpty);
    if(typeof(user) == "object" && user.NodeLevel1!="null" && user.NodeLevel1!=null && user.NodeLevel1!=""){
        var tempVar = user.NodeLevel1;
        MenuMarkIDs = JSON.parse(tempVar);
    }
    return MenuMarkIDs;
};

/*******************************************************************************
 This function sets the session cookie with the input object.
*******************************************************************************/
function setMenuCookie(userObject){
    var userEmpty = new Object;
    var user = GetNavData(userEmpty);
    if(typeof(user) != "undefined"){
        user.NodeLevel1 = JSON.stringify(userObject);
        SetNavData(user);
    }
    else {
        userEmpty.NodeLevel1 = JSON.stringify(userObject);
        SetNavData(userEmpty);
    }
};

/*******************************************************************************
 This function sets the Level 1 and 2 node IDs to the session cookie which is 
 used to display default menu and style on page load.
*******************************************************************************/
function setNodeIDs(Level, Node1, Node2, Child){
    var setnode = false;
    if(Level==1 && Child=="True") setnode = true;
    else if(Level > 1) setnode = true;
    var MenuMarkIDs = getMenuCookie();
    if(setnode){
        MenuMarkIDs.Level1Node = Node1;
        MenuMarkIDs.Level2Node = Node2;
        MenuMarkIDs.NewClick = true;
    } else {
        MenuMarkIDs.Level1Node = "";
        MenuMarkIDs.Level2Node = "";
        MenuMarkIDs.NewClick = false;
    }
    setMenuCookie(MenuMarkIDs);
};

/*******************************************************************************
 This function set the menu coloring according to the value Level1Node and 
 Level2Node being set.
*******************************************************************************/
function CheckforNavigationIndicator() {
    var MenuMarkIDs = getMenuCookie();
    if((MenuMarkIDs.NewClick) || (MenuMarkIDs.URL == window.location)) {        
        MenuMarkIDs.NewClick = false;
        DisplayNormal(MenuMarkIDs.Level1Node,MenuMarkIDs.Level2Node);
    }else if(typeof(Level1NodeDefault)!= "undefined") {
        MenuMarkIDs.Level1Node = "";
        MenuMarkIDs.Level2Node = "";
        NavigationIndicatorLevel2(Level1NodeDefault,"");
    }else {
        MenuMarkIDs.Level1Node = "";
        MenuMarkIDs.Level2Node = "";
    }
    setMenuCookie(MenuMarkIDs);
};

/*******************************************************************************
 This function highlights the Level 1 node and displays the correct level 2 
 menu with a highlighted node if it exists.
*******************************************************************************/
function DisplayNormal(level1,level2){
    if(typeof(level1) != "undefined" && level1 != "" && level1!=null && level1!="null"){
        if(document.getElementById('node'+level1)){ 
            document.getElementById('node'+level1).className = "level1-collapse"; 
            MenuOpen[1]=level1;
        }
        NavigationIndicatorLevel2(level1,level2);
    }
    else if(typeof(Level1NodeDefault)!= "undefined") 
        NavigationIndicatorLevel2(Level1NodeDefault,"");
};

/*******************************************************************************
 This function requests and set the level 2 menu coloring according to the value 
 Level1Node and Level2Node being set.
*******************************************************************************/
function NavigationIndicatorLevel2(node1, node2){
    notNull = function(count){
        if(objNavigationMenu.getMenuNode(node1) != null){
            menuLayers.show(ID[2], null, null, null);
            objNavigationMenu.displayMenu(node1,ID[2], renderMainItem);
            if(document.getElementById(ID[2]).innerHTML == "")
                document.getElementById(ID[2]).style.display = 'none';
            if(document.getElementById('node'+node2))
                document.getElementById('node'+node2).className = "level2-collapse";
        } else{
            count += 1;
            if(count < 40) setTimeout("notNull("+count+")",50);
        }
    };
    notNull(1);
};


/*******************************************************************************
 This function is the init function to build the navigation menu.
*******************************************************************************/
function initNavigation() {
 
	    
    for(var x = 0; x < 200; x++){
        if(typeof(JSON) != "undefined"){
              
            document.getElementById(ID[1]).style.display = '';

			objNavigationMenu.displayMenu(0,ID[1],renderMainItem);

            CheckforNavigationIndicator();
            x=200;
        } else setTimeout(function(){}, 10);
    };
};




/*
******************************************************************************
       File: BuildNavigationMenuEventOption3.js
Description: Contains the JavaScript code with specific functionalities of the
             Navigation Menu for a given site.
  Copyright: Copyright (c) 2007, GMTI. All rights reserved.
******************************************************************************
*/

var NavTimeOutId=0;
var NavTimeDelay = 250;

/*******************************************************************************
 This function creates the HTML of the nodes for each menu.
*******************************************************************************/
function renderMainItem(menuItem) {
  	var res = "";
  	if(menuItem.MenuLevel < 3){
	    res = "<span id=\"node"+menuItem.MenuID+"\">";
	    res +="<a href=\""+ menuItem.Link +"\"";

	    if(menuItem.HasSubMenu == "True")
	    {
			res +=" onMouseOver=\"NavTimeOutId = setTimeout('menuItemMouseOverHandler("+menuItem.MenuLevel+","+menuItem.MenuID+")',NavTimeDelay);\"";
			res +=" onMouseOut=\"clearTimeout(NavTimeOutId);\"";
            }
        else{ if (menuItem.MenuLevel == 1)
				{
				 res +=" onMouseOver=\"NavTimeOutId = setTimeout('blankInnerHTML("+(parseInt(menuItem.MenuLevel)+1)+","+menuItem.MenuID+")',NavTimeDelay);\"";              
                 res +=" onMouseOut=\"clearTimeout(NavTimeOutId);\"";
                }
              else if (menuItem.MenuLevel == 2)
                res +=" onMouseOver=\"NavTimeOutId = setTimeout('hideMenuLayers("+menuItem.MenuLevel+","+menuItem.MenuID+")',NavTimeDelay);\"";  
                res +=" onMouseOut=\"clearTimeout(NavTimeOutId);\"";
        }
        
        res +=" onClick=\"javascript:setNodeIDs(\'"+menuItem.MenuLevel+"\',\'"+menuItem.Level1Node+"\',\'"+menuItem.Level2Node+"\',\'"+menuItem.HasSubMenu+"\');\"";    
        
        if(menuItem.NewWindow == "True")
        {
			res +=" target=\"_blank\">"+ menuItem.Name;
        }
        else
        {
			res +=">"+ menuItem.Name;
		}
		
        res +="</a></span><span class='navDivider'></span>";
    }else {
  		res = "<span id=\"node"+menuItem.MenuID+"\""; 
  		if(menuItem.HasSubMenu == "True")		
  		    res +=" onMouseOver=\"javascript:menuItemMouseOverHandler("+menuItem.MenuLevel+","+menuItem.MenuID+");\"";
  		else if (menuItem.MenuLevel != 4)
            res +=" onMouseOver=\"javascript:menuLayers.hide(ID["+(parseInt(menuItem.MenuLevel)+1)+"]);ResetColor("+menuItem.MenuLevel+");\"";
        
        res += "><li><a href=\""+ menuItem.Link +"\" onClick=\"javascript:setNodeIDs(\'"+menuItem.MenuLevel+"\',\'"+menuItem.Level1Node+"\',\'"+menuItem.Level2Node+"\',\'"+menuItem.HasSubMenu+"\');\"";
           
		if(menuItem.NewWindow == "True")
        {
			res +=" target=\"_blank\">"+ menuItem.Name+"</a></li></span>";
        }
        else
        {
			res +=">"+menuItem.Name+"</a></li></span>";
		}
    }
  	return res;
};


function hideMenuLayers(Level, Node)
{
	ChangeNode(Level, Node);
	menuLayers.hide(ID[(Level + 1)]);
};

/*******************************************************************************
 This function is the mouseover event handler for a menu node.
*******************************************************************************/

function menuItemMouseOverHandler(Level, Node) {
		ChangeNode(Level, Node);
        MenuOpen[Level] = Node;
       
		if(Level == 1){
		    nodePos = menuLayers.getPos(document.getElementById('node'+Node));
		    findlevelLocation(nodePos.x);
		    
  		    menuLayers.show(ID[Level+1], null, null, null);
		    objNavigationMenu.displayMenu(Node, ID[Level+1], renderMainItem);
		}
		else if(Level == 2){
  		    nodePos = menuLayers.getPos(document.getElementById('node'+Node));
  		    menuLayers.show(ID[Level+1], true, nodePos.x, 0);
  		    objNavigationMenu.displayMenu(Node, ID[Level+1], renderMainItem);   
		} else {
		    nodePos = menuLayers.getPos(document.getElementById('node'+Node));
		    if(objNavigationMenu.browserCheck() == 0) menuLayers.show(ID[Level+1], null, true, nodePos.x+150, nodePos.y+15);
            else menuLayers.show(ID[Level+1], true, nodePos.x+123, nodePos.y-8);
  		    objNavigationMenu.displayMenu(Node, ID[Level+1], renderMainItem);
		}
};

function findlevelLocation(coor) {
    var menuSize = document.getElementById(ID[1]).offsetWidth;
    var startX = menuLayers.getPos(ID[1]).x;
    //document.getElementById("debugTag").innerHTML=coor+"  "+startX+""+ (coor > startX && coor < startX+(menuSize/3));
    if(coor > startX && coor < startX+(menuSize/3))  document.getElementById(ID[2]).style.textAlign="left";
    else if(coor > startX+(menuSize/3) && coor < startX+(menuSize/3*2)) document.getElementById(ID[2]).style.textAlign="center";
    else document.getElementById(ID[2]).style.textAlign="right";
};

function blankInnerHTML(Level,Node){

    ChangeNode(Level - 1, Node);
    if(window.ActiveXObject)
        document.getElementById(ID[2]).innerHTML="<span style=\"height:18px;float:left;filter:alpha(opacity=1);-moz-opacity:.01;opacity:.01;\">a</span>"; 
    else 
        document.getElementById(ID[2]).innerHTML="<span style=\"filter:alpha(opacity=1);-moz-opacity:.01;opacity:.01;\">a</span>";  
};
try {
  document.execCommand("BackgroundImageCache", false, true);
} catch(err) {}
function readCookie(name){var nameEQ=name+"=";var ca=document.cookie.split(';');for(var i=0;i<ca.length;i++){var c=ca[i];while(c.charAt(0)==' ')c=c.substring(1,c.length);if(c.indexOf(nameEQ)==0)return c.substring(nameEQ.length,c.length)}return null}function getnamevalue(query,queryname){keypairs=new Object();numKP=1;while(query.indexOf('&')>-1){keypairs[numKP]=query.substring(0,query.indexOf('&'));query=query.substring((query.indexOf('&'))+1);numKP++;}keypairs[numKP]=query;for(i in keypairs){keyName=keypairs[i].substring(0,keypairs[i].indexOf('='));keyValue=keypairs[i].substring((keypairs[i].indexOf('='))+1);if(keyName==queryname){return keyValue}while(keyValue.indexOf('+')>-1){keyValue=keyValue.substring(0,keyValue.indexOf('+'))+' '+keyValue.substring(keyValue.indexOf('+')+1);}keyValue=unescape(keyValue);}}

var isIE=(navigator.appVersion.indexOf("MSIE")!=-1)?true:false;var isWin=(navigator.appVersion.toLowerCase().indexOf("win")!=-1)?true:false;var isOpera=(navigator.userAgent.indexOf("Opera")!=-1)?true:false;function ControlVersion(){var version;var axo;var e;try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");version=axo.GetVariable("$version")}catch(e){}if(!version){try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");version="WIN 6,0,21,0";axo.AllowScriptAccess="always";version=axo.GetVariable("$version")}catch(e){}}if(!version){try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");version=axo.GetVariable("$version")}catch(e){}}if(!version){try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");version="WIN 3,0,18,0"}catch(e){}}if(!version){try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");version="WIN 2,0,0,11"}catch(e){version=-1}}return version}function GetSwfVer(){var flashVer=-1;if(navigator.plugins!=null&&navigator.plugins.length>0){if(navigator.plugins["Shockwave Flash 2.0"]||navigator.plugins["Shockwave Flash"]){var swVer2=navigator.plugins["Shockwave Flash 2.0"]?" 2.0":"";var flashDescription=navigator.plugins["Shockwave Flash"+swVer2].description;var descArray=flashDescription.split(" ");var tempArrayMajor=descArray[2].split(".");var versionMajor=tempArrayMajor[0];var versionMinor=tempArrayMajor[1];var versionRevision=descArray[3];if(versionRevision==""){versionRevision=descArray[4]}if(versionRevision[0]=="d"){versionRevision=versionRevision.substring(1)}else if(versionRevision[0]=="r"){versionRevision=versionRevision.substring(1);if(versionRevision.indexOf("d")>0){versionRevision=versionRevision.substring(0,versionRevision.indexOf("d"))}}var flashVer=versionMajor+"."+versionMinor+"."+versionRevision}}else if(navigator.userAgent.toLowerCase().indexOf("webtv/2.6")!=-1)flashVer=4;else if(navigator.userAgent.toLowerCase().indexOf("webtv/2.5")!=-1)flashVer=3;else if(navigator.userAgent.toLowerCase().indexOf("webtv")!=-1)flashVer=2;else if(isIE&&isWin&&!isOpera){flashVer=ControlVersion()}return flashVer}function DetectFlashVer(reqMajorVer,reqMinorVer,reqRevision){versionStr=GetSwfVer();if(versionStr==-1){return false}else if(versionStr!=0){if(isIE&&isWin&&!isOpera){tempArray=versionStr.split(" ");tempString=tempArray[1];versionArray=tempString.split(",");}else{versionArray=versionStr.split(".")}var versionMajor=versionArray[0];var versionMinor=versionArray[1];var versionRevision=versionArray[2];if(versionMajor>parseFloat(reqMajorVer)){return true}else if(versionMajor==parseFloat(reqMajorVer)){if(versionMinor>parseFloat(reqMinorVer))return true;else if(versionMinor==parseFloat(reqMinorVer)){if(versionRevision>=parseFloat(reqRevision))return true}}return false}}function AC_AddExtension(src,ext){if(src.indexOf('?')!=-1)return src.replace(/\?/,ext+'?');else return src+ext}function AC_Generateobj(objAttrs,params,embedAttrs){var str='';if(isIE&&isWin&&!isOpera){str+='<object ';for(var i in objAttrs){str+=i+'="'+objAttrs[i]+'" '}str+='>';for(var i in params){str+='<param name="'+i+'" value="'+params[i]+'" /> '}str+='</object>'}else{str+='<embed ';for(var i in embedAttrs){str+=i+'="'+embedAttrs[i]+'" '}str+='> </embed>'}document.write(str)}function AC_FL_RunContent(){var ret=AC_GetArgs(arguments,".swf","movie","clsid:d27cdb6e-ae6d-11cf-96b8-444553540000","application/x-shockwave-flash");AC_Generateobj(ret.objAttrs,ret.params,ret.embedAttrs)}function AC_SW_RunContent(){var ret=AC_GetArgs(arguments,".dcr","src","clsid:166B1BCA-3F9C-11CF-8075-444553540000",null);AC_Generateobj(ret.objAttrs,ret.params,ret.embedAttrs)}function AC_GetArgs(args,ext,srcParamName,classid,mimeType){var ret=new Object();ret.embedAttrs=new Object();ret.params=new Object();ret.objAttrs=new Object();for(var i=0;i<args.length;i=i+2){var currArg=args[i].toLowerCase();switch(currArg){case"classid":break;case"pluginspage":ret.embedAttrs[args[i]]=args[i+1];break;case"src":case"movie":args[i+1]=AC_AddExtension(args[i+1],ext);ret.embedAttrs["src"]=args[i+1];ret.params[srcParamName]=args[i+1];break;case"onafterupdate":case"onbeforeupdate":case"onblur":case"oncellchange":case"onclick":case"ondblClick":case"ondrag":case"ondragend":case"ondragenter":case"ondragleave":case"ondragover":case"ondrop":case"onfinish":case"onfocus":case"onhelp":case"onmousedown":case"onmouseup":case"onmouseover":case"onmousemove":case"onmouseout":case"onkeypress":case"onkeydown":case"onkeyup":case"onload":case"onlosecapture":case"onpropertychange":case"onreadystatechange":case"onrowsdelete":case"onrowenter":case"onrowexit":case"onrowsinserted":case"onstart":case"onscroll":case"onbeforeeditfocus":case"onactivate":case"onbeforedeactivate":case"ondeactivate":case"type":case"codebase":case"id":ret.objAttrs[args[i]]=args[i+1];break;case"width":case"height":case"align":case"vspace":case"hspace":case"class":case"title":case"accesskey":case"name":case"tabindex":ret.embedAttrs[args[i]]=ret.objAttrs[args[i]]=args[i+1];break;default:ret.embedAttrs[args[i]]=ret.params[args[i]]=args[i+1]}}ret.objAttrs["classid"]=classid;if(mimeType)ret.embedAttrs["type"]=mimeType;return ret}
var hideId;

function hideSrchOptions(menu, time) {
	hideId = setTimeout("document.getElementById('"+menu+"').style.visibility='hidden'",time);	
}

function clearTime() {
clearTimeout(hideId);
}

function showSrchOptions(menu) {
	var d3 = document.getElementById(menu);
	if (d3) {
		if (d3.style.visibility !="visible") {
			d3.style.visibility='visible';
		}
	}
}
		
function NewWindow(height,width,url) 
{
	window.open(url,"ShowProdWindow","menubars=0,scrollbars=1,resizable=1,height="+height+",width="+width); 
} 
function snl_click(social_utility) 
{
	var statusType = "";
	var createURL = "";
	var tempurl = "";
	
	if (typeof($("gsl_pg_currentno"))!='undefined' && $("gsl_pg_currentno")!= null)
	{
		if (typeof(gpg.params["plckGalleryID"])!='undefined')
			{	
						u=location.href + "&plckPhotoID=" + gpg.plckPhotoID;

						var pic_num = $("gsl_pg_currentno").value;
						var gtitle = gpg.galleryTitle;
						tempurl = location.href ;
						tempurl = tempurl.replace(/\&plckGalleryID=(.*)/g,"");
						tempurl = tempurl + "&plckGalleryID=" + gpg.plckGalleryID + "&plckPhotoID=" + gpg.plckPhotoID;
						
						createURL = encodeURIComponent(tempurl + '&gthumbnaillink=' + gpg.localMasterPGArray[1][pic_num].Image.Full.replace(/\//g,"slash_replace")  + '&tt=' + gpg.galleryTitle.replace(/\%/g,"percent_replace").replace(/\\/g,"backs_replace").replace(/\//g,"slash_replace").replace(/\&amp;/g,"re_andamp;"));
						
				statusType = "Viewing:"
			} 
				else{
						u=location.href + "&Params=Itemnr=" + $("gsl_pg_currentno").value;
						tempurl = location.href ;
						if(tempurl.match(/\&Params=Itemnr=/)) {tempurl = tempurl.replace(/\&Params=Itemnr=(.*)/g,"");}
						tempurl = tempurl + "&Params=Itemnr=" + $("gsl_pg_currentno").value;
						
						createURL = encodeURIComponent(tempurl);
						if($("gsl_pg_currentno").value == 0) { createURL = createURL+ encodeURIComponent( '&tt=' + gpg.galleryTitle.replace(/\%/g,"percent_replace").replace(/\\/g,"backs_replace").replace(/\//g,"slash_replace").replace(/\&amp;/g,"re_andamp;")) }
						
					statusType = "Viewing:"
					}
		}else {		
		u=location.href ;
		createURL=encodeURIComponent(u);
		statusType = "Reading:"
				}
		t=document.title;

	if(social_utility == "facebook")
	{
		window.open('http://www.facebook.com/sharer.php?u='+createURL,'sharer','toolbar=0,status=0,width=626,height=436');
	}
	if(social_utility == "digg")
	{
		window.open('http://digg.com/submit?phase=2&url='+encodeURIComponent(u)+'&title='+encodeURIComponent(t));
	}

	if(social_utility == "delicious")
	{
		window.open('http://del.icio.us/post?v=2&url='+encodeURIComponent(u)+'&title='+encodeURIComponent(t));
	}

	if(social_utility == "reddit")
	{
		window.open('http://reddit.com/submit?url='+encodeURIComponent(u)+'&title='+encodeURIComponent(t));	
	}

	if(social_utility == "newsvine")
	{
		window.open('http://www.newsvine.com/_tools/seed&save?u='+encodeURIComponent(u)+'&T='+encodeURIComponent(t));
	}
	
	if(social_utility == "twitter")
	{
		window.open('http://twitter.com/home?status= '+statusType+"%20"+encodeURIComponent(u));
	}
		
	return false;
}
//Include the partners widget js code 
function _setPartnerContent(gcibutton) {
   
		for(var p=0;p<pnls.length;p++ )
			$(pnls[p]).hide();
 if(pnlstate[gcibutton]==false){
	   gd_iframe = $$("#"+pnls[gcibutton] + " iframe.ad-frame")[0];
	   if(gd_iframe){
		gd_iframe.setAttribute("src",adtech_urls(gd_iframe.id).iframe);
   	   }

   }
   pnlstate[gcibutton]=true;
   current = $("pd-partner-current");
   if(current!=null)
	   current.id="";
      $$('#pd-partner-tab-header li')[gcibutton].id="pd-partner-current";

  $(pnls[gcibutton]).show();
}


function initPartnersWidget(){
	var gcibutton = Math.floor(Math.random() * 4);
	setPartnerContent(gcibutton);
}

var pnlstate =[false,false,false,false];
/*can be overridden for thos who want to reallytweak this id's of panels in the partners widget this is the default*/
var pnls = ["pd-gci-jobs","pd-gci-cars","pd-gci-home","pd-gci-apts"]


var tabmodule1present=true;
var tabmodule2present=false;
var tabmodule3present=false;
var tabmodule4present=false;

function PopulateFrontPageModule(module,othermodules)
{ 
	switch(module)
	{
		case 1:
		ispresent = tabmodule1present;
		break;    
		case 2:
		ispresent = tabmodule2present;
		break;
		case 3:
		ispresent = tabmodule3present;
		break;    
		case 4:
		ispresent = tabmodule4present;
		break;
		default:
		ispresent = tabmodule1present;
	}

	if(!ispresent)
	{
		document.getElementById("tab-module"+module).innerHTML = '<img src="/gcicommonfiles/sr/graphics/common/ajax-loader.gif">';
		var req = null; 
 
		if (window.XMLHttpRequest)
		{
			req = new XMLHttpRequest();

		} 
		else if (window.ActiveXObject) 
		{
			try {
				req = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e)
			{
				try {
					req = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e) {}
			}
		}

		req.onreadystatechange = function()
		{ 
			if(req.readyState == 4)
			{
				if(req.status == 200)
				{
					var responseTxt = req.responseText;
					document.getElementById("tab-module"+module).innerHTML=responseTxt;
					switch(module)
					{
						case 1:
						tabmodule1present = true;
						break;    
						case 2:
						tabmodule2present = true;
						break;
						case 3:
						tabmodule3present = true;
						break;    
						case 4:
						tabmodule4present = true;
						break;
						default:
						tabmodule1present = true;
					}
					if(responseTxt.indexOf("gsldaapicontent") > 0)
					{
						if (PluckGlobalControl != "0" && PluckSiteControl != "0")
						{
							gsl.getDiscoveryTabContent();
						}
					}
				}	
				else	
				{
					
				}	
				
			} 
		}; 
		req.open("GET", "http://"+location.host+"/apps/pbcs.dll/section?category=frontpagetabmodule-"+module, true); 
		req.send(null); 
	}

	for (j=0; j < 3; j++) {
		document.getElementById("tab-module"+othermodules[j]).style.display='none';
		document.getElementById("tab-module"+othermodules[j]+"tab").className="";
	}
	
	document.getElementById("tab-module"+module).style.display='block';
	document.getElementById("tab-module"+module+"tab").className="tab-selected";

} 

/* ==================================================================== */
/* Defines global settings for Adtech                       */
/* ==================================================================== */

var adtech_global_control =1;//"1" to turn on the adtech calls and "0" to turnoff the adtech calls for all sites on this division

/* ==================================================================== */
/* Defines global settings for Pluck                       */
/* ==================================================================== */

var PluckGlobalControl = "1";

//Dont change anything after this line. it should be changed only by PS as  per request from Corporate 
if(typeof gsl != 'undefined') {
gsl.MaxNumberofAbuse =3; //Maximum number of abuse report count i.e. if it exceeds that comment wont be shown on page. 
gsl.requestsperBatch =5;
var serverUrl = gsl.sitelifeApiUrl; //Added to support SiteLife v3.8.2
}
/* ==================================================================== */
/* Defines global settings for CheckM8                       */
/* ==================================================================== */
var checkM8_global_control = "1"; //"1" to turn on the checkM8 calls and "0" to turnoff the checkM8 calls for all sites on this division

/*
Gannett Newsletters Javascript
This script contain the implementation for the newsletter enhancement. 
Updated:RK,YT,SS
Version:3.4 
Updated: 01/23/2009 	YT	Updated to fix a bug when only one newsletter is displayed
*/
var updateNletters_Ajax;
var updateNletters_Type;

function NLetersRedirect(strPage){

	window.location = "/section/"+strPage;

}

function parseUpdateResponse(){

	try { var xmlDoc = (new DOMParser()).parseFromString(updateNletters_Ajax.ResponseText(), "text/xml"); }
	catch (e) { xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
				xmlDoc.async="false";
				xmlDoc.loadXML(updateNletters_Ajax.ResponseText());
				}
     
	// get status
	var newsletters = xmlDoc.getElementsByTagName("Newsletters");
	
	var status = "";
	for (var i = 0; i < newsletters.length; i++)
	{
	        var status = newsletters[i].getElementsByTagName("Status")[0].firstChild.nodeValue;
	}
	
	if(status == "Success")
	{
		if(updateNletters_Type == "Register")
		{
			NlettersRegisterPopup();
		}
		else
		{
			if(updateNletters_Type == "Subscribe")
			{
				updateNlettersCookie();
			}
			NLetersRedirect("nletterconfirm");			
		}	
	}
	else
	{
		NLetersRedirect("nlettererror");
	}
	
}

function updateNlettersSubscription(strType){

	if(strType == "Subscribe")
	{
		var NlettersLength = document.Nlettersform.NletterCategory.length;
		var contents = "";
		var htmlValue = "";
		if(document.Nlettersform.ReceiveHtml.checked)
		{
			htmlValue = 1;
		}
		else
			{
				htmlValue = 0;
			}
			
		if(typeof(NlettersLength)!='undefined')
		{
			for (i = 0; i < NlettersLength; i++) 
			{
				contents += document.Nlettersform.NletterCategory[i].value + ";";
				
				if(document.Nlettersform.NletterCategory[i].checked)
				{
					contents += "1;";
				}
				else
				{
					contents += "0;";
				}
				
				contents +=  htmlValue;
				
				if(i < NlettersLength - 1)
				{
					contents += "|";
				}
			}
		} else {
				contents += document.Nlettersform.NletterCategory.value + ";";
				
				if(document.Nlettersform.NletterCategory.checked)
				{
					contents += "1;";
				}
				else
				{
					contents += "0;";
				}
				
				contents +=  htmlValue;
			}
	}
	else
	{
		var NlettersCookie = GDN.Cookie.Get("GDNNL");
		var NlettersData = NlettersCookie.split("|");
		var NumNletters = NlettersCookie.split("|").length;
		var contents = "";
		var currentNletter = "";
		var currentValue = "";
		
		for (i = 0; i < NumNletters; i++) 
		{
			currentNletter = NlettersData[i];
			currentValue = currentNletter.split("&!&");

			contents += currentValue[1] + ";";
			
			if(currentValue[2] == 1)
			{
				contents += "1;";
			}
			else
			{
				contents += "0;";
			}
			
			if(currentValue[3] == 1)
			{
				contents += "1";
			}
			else
			{
				contents += "0";
			}
			
			if(i != NumNletters - 1)
			{
				contents += "|";
			}
		
		
		}
	
	}
	updateNletters_Ajax = new GDN.Ajax();
	updateNletters_Type = strType;
	if(strType == "Register")
	{
		var registerForm = document.getElementById("UAWidget-PluckRegistration");
		
		updateNletters_Ajax.RequestUrl("/apps/pbcs.dll/section?category=nlettersignup&email=" + GDN.Base64.Encode(registerForm.Email.value) + "&xml=" + contents);

		updateNletters_Ajax.Callback(parseUpdateResponse);
		
		updateNletters_Ajax.Send();
	}
	else
	{
		if (GDN.Cookie.Exists("at"))
		{
			var user = GDN.Cookies.GDN.Get();

			updateNletters_Ajax.RequestUrl("/apps/pbcs.dll/section?category=nlettersignup&email=" + GDN.Base64.Encode(user.Email()) + "&xml=" + contents);
	
			updateNletters_Ajax.Callback(parseUpdateResponse);	
			
			updateNletters_Ajax.Send();

		}
	}

}
function updateNlettersCookie(){
		/*Get values and add them to Nletters cookie*/
		var NlettersLength = document.Nlettersform.NletterCategory.length;
		var contents = "";
		var htmlValue = "";
		if(document.Nlettersform.ReceiveHtml.checked)
		{
			htmlValue = 1;
		}
		else
		{
			htmlValue = 0;
		}
		
		if(typeof(NlettersLength)!='undefined')
		{
			for (i = 0; i < NlettersLength; i++) 
			{
				contents +=document.Nlettersform.NletterCategoryName[i].value;
				contents += "&!&" + document.Nlettersform.NletterCategory[i].value;
				
				if(document.Nlettersform.NletterCategory[i].checked)
				{
					contents += "&!&1";
				}
				else
				{
					contents += "&!&0";
				}
				
				contents += "&!&" + htmlValue;
				
				if(i < NlettersLength - 1)
				{
					contents += "|";
				}
			}
		}else
			{	
				contents +=document.Nlettersform.NletterCategoryName.value;
				contents += "&!&" + document.Nlettersform.NletterCategory.value;
				if(document.Nlettersform.NletterCategory.checked)
				{
					contents += "&!&1";
				}
				else
				{
					contents += "&!&0";
				}
				contents += "&!&" + htmlValue;
			}
		var cookie = GDN.Cookie.Set("GDNNL",contents);
		window.location = "/section/nlettersignin";
}

function subscribeNewsletterOptions(){
	if(!NLLoggedIn)
	{
		updateNlettersCookie();
	}
	else
	{
		updateNlettersSubscription("Subscribe");
	}
}

function populateNewsletterOptions(){

      try { var xmlDoc = (new DOMParser()).parseFromString(gdn_Ajax.ResponseText(), "text/xml"); }
      catch (e) { xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
				xmlDoc.async="false";
				xmlDoc.loadXML(gdn_Ajax.ResponseText());
				}
     
    // get references
    var form   = document.getElementById("NL-Form");
	var isHtml = true;    
	var NLoutput = "";
    var splitNletter = false;     
	var excludeNL = false;
	var tempexcludeNL = false;
	var actualNL = 0;
	var nlCounter = 0;
	// get nodes
	var newsletters = xmlDoc.getElementsByTagName("Newsletter");
	for (var i = 0; i < newsletters.length; i++)
	{
		var tempactive       = newsletters[i].getElementsByTagName("Active")[0].firstChild.nodeValue;
		var temptype         = newsletters[i].getElementsByTagName("Type")[0].firstChild.nodeValue;
		var tempcategoryId   = newsletters[i].getElementsByTagName("CategoryID")[0].firstChild.nodeValue;
		if(NLExclude_array.length > 0)
			{
				for (j=0; j < NLExclude_array.length; j++) 
				{
					if(NLExclude_array[j].toLowerCase() == tempcategoryId.toLowerCase())
					{	
						tempexcludeNL = true;
						break;
					}
				}
			}
		 if (temptype != "Commercial" && tempactive==1 && !tempexcludeNL)
		    actualNL++;
			
		tempexcludeNL =false;
	}
	
	if (actualNL <=0) NLetersRedirect("nlettererror");
	//alert(actualNL);
    if (actualNL >= 5) splitNletter =true; 
	
	NLoutput += '<table><tr><td>';
	for (var i = 0; i < newsletters.length; i++)
	{
	        // get node values
	        var categoryId   = newsletters[i].getElementsByTagName("CategoryID")[0].firstChild.nodeValue;
	        var categoryName = newsletters[i].getElementsByTagName("Category")[0].firstChild.nodeValue;
	        var receiveHtml  = newsletters[i].getElementsByTagName("ReceiveHTML")[0].firstChild.nodeValue;
	        var subscribed   = newsletters[i].getElementsByTagName("Subscribed")[0].firstChild.nodeValue;
	        var active       = newsletters[i].getElementsByTagName("Active")[0].firstChild.nodeValue;
	        var type         = newsletters[i].getElementsByTagName("Type")[0].firstChild.nodeValue;        
	        
	        try { var shortDesc = newsletters[i].getElementsByTagName("ShortDescription")[0].firstChild.nodeValue; } catch (e) { var shortDesc = ""; }
	        try { var info      = newsletters[i].getElementsByTagName("Info")[0].firstChild.nodeValue; } catch (e) { var info = ""; }
        
	        // determine if newsletters should be in HTML format
	        if (receiveHtml == "0" && active == "1" && subscribed== "1")
	          isHtml = false;
	        
	        // determine checked state
		if(NLLoggedIn)
		{
			if (subscribed == "1")
				var checked = 'checked=\"checked\"';
		    else
				var checked = '';
		}
		else
		{
			if(NLDefault_array.length > 0)
			{
				for (j=0; j < NLDefault_array.length; j++) 
				{
					if(NLDefault_array[j].toLowerCase() == categoryId.toLowerCase())
					{	
						var checked = 'checked=\"checked\"';
						break;
					}
					else
					{	
						var checked = '';
					}
				
				}
			}
		}
		
		if(NLExclude_array.length > 0)
			{
				for (j=0; j < NLExclude_array.length; j++) 
				{
					if(NLExclude_array[j].toLowerCase() == categoryId.toLowerCase())
					{	
						excludeNL = true;
						break;
					}
				}
			}
	          
	        // determine text to show
	        if (!GDN.IsNullOrEmpty(shortDesc))
	          var text = "<b>" + categoryName + "</b></label> (<a href=\"/section/" + categoryId +  "\" target=\"_blank\">view sample</a>)<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<label>" + shortDesc + "</label><br />";
	        else
	          var text = "<b>" +categoryName + "</b></label> (<a href=\"/section/" + categoryId +  "\" target=\"_blank\">view sample</a>)<br />";
	          
	        // encode HTML
	        shortDesc = shortDesc.substr(0, shortDesc.indexOf("<"));
	        info      = info.replace(/\>/gi, "&gt;");
	        info      = info.replace(/\</gi, "&lt;");
        
	        // set output
	        if (type != "Commercial" && active==1 && !excludeNL)
	        {
				nlCounter++;
				
				if (splitNletter && nlCounter==Math.round(parseInt(actualNL)/2)+1)	
					NLoutput += '</td><td>';
		          NLoutput += '<input type=\"hidden\" id=\"' + categoryId + '_Name\" name=\"NletterCategoryName\" value=\"' + categoryName + '\" />';
		          NLoutput += '<input type=\"hidden\" id=\"' + categoryId + '_Desc\" name=\"' + categoryId + '_Desc\" value=\"' + shortDesc + '\" />';
		          NLoutput += '<input type=\"hidden\" id=\"' + categoryId + '_Info\" name=\"' + categoryId + '_Info\" value=\"' + info + '\" />';
		          NLoutput += '<input type=\"checkbox\" id=\"' + categoryId + '\" name=\"NletterCategory\" value=\"' + categoryId + '\" ' + checked + ' />';
		          NLoutput += '<label for=\"' + categoryId + '\" title=\"' + info + '\">' + text + '<br />'; 
	        }
			//turn the default on 
			excludeNL = false;
	}
	//set checked state for HTML newsletters
		NLoutput += "</td></tr></table><div class=\"emailCtrl\" style=\"padding: 0px 0px 0px 325px;\">"; 
	if(isHtml)
	{
		NLoutput += "<input id=\"ReceiveHtml\" type=\"checkbox\" name=\"ReceiveHtml\" checked=\"checked\"/><label for=\"ReceiveHtml\">Receive e-mail in HTML format</label>";
	}
	else
	{
		NLoutput += "<input id=\"ReceiveHtml\" type=\"checkbox\" name=\"ReceiveHtml\"/><label for=\"ReceiveHtml\">Receive e-mail in HTML format</label>";
	}
	
	//set name of form button
	if(NLLoggedIn)
	{
		NLoutput += "<br /><input onclick=\"subscribeNewsletterOptions();\" value=\"Save\" type=\"button\" style=\"margin:10px 0px 0px 115px;\"></div><br>";
	}
	else
	{
		NLoutput += "<br /><input onclick=\"subscribeNewsletterOptions();\" value=\"Sign me up!\" type=\"button\" style=\"margin:10px 0px 0px 75px;\"></div><br>";
	}
	GDN.SetInnerHtml("NLOptions", "<form name=\"Nlettersform\">"+NLoutput+"</form>");
}

function NlettersRegisterPopup(){
	GDN.Cookie.Remove("GDNNL");
	var registerForm = document.getElementById("UAWidget-PluckRegistration");
	registerForm.PluckRegisterButton.disabled=true;
	var NLconfPopup = '<div class=\"UAWidget-PopUp\" align=\"center\">'
			+ ' <h3>'+sitename+ '.com Membership</h3>  '
			+ '<div align=\"left\">  '  
			+ '		<span>The membership process is almost complete.<br><br>    We just sent an e-mail to <strong>' + registerForm.Email.value + '</strong>.     You <u>must</u> click on the link in that e-mail to complete     the membership process.    <br><br>    '
			+ '				<table cellspacing=\"0\" cellpadding=\"3\" border=\"0\"> '   
			+ '					<tbody>	'
			+ '						<tr>  '
			+ '							<td>'
			+ '								<img border=\"0\" style=\"padding-right: 5px;" title=\"Check Email\" alt=\"Check Email\" src=\"/graphics/checkemail.gif\">'
			+ '							</td>  '    
			+ '							<td style=\"vertical-align: middle;\">'
			+ '							<h3><strong>Last Step:</strong> check your email and click link</h3>'
			+'							</td> '   
			+ '						</tr>'
			+ '						<tr>'
			+ '							<td></td>'
			+ '							<td>When you Confirm your email address, you will begin receiving your e-newsletters</td>'
			+ '						</tr>'
			+ '				</tbody>'
			+ '			</table>  '
			+ '		</span>'
			+ '		<br>'
			+ '<div style=\"text-align:center\">'
			+ '			<a href=\"/tos\">Terms of Service</a> | <a href=\"/pp\">Privacy Policy</a> | <a href=\"/faq\">FAQ</a> | <a href=\"/feedback\">Feedback</a>'
			+ '			<br>'
			+ '  <div><a href="http://www.' + sitename + '.com">Close this window</a></div>'
			+ '		</div>'
			+ '	</div>'
			+ '	<br>'
			+ '</div>';
		
	GDN.Widget.Show(NLconfPopup,350,230,'UAWidgetRef-Inline');
}

function getCookieData(n,m,a,b){
	if (GDN.Cookie.Exists("GDNNL"))
	{
	var cookie_stuff = GDN.Cookie.Get("GDNNL");
	var nletterdata = cookie_stuff.split("|");
		var num_nletters = cookie_stuff.split("|").length;
		var nlettervalue = "";
		var headlines = "";
		var nletterheadlines = "";
		var count = "1";
		var arr = new Array();
						
			for (var i = 0; i < num_nletters; i++) 
			{
			nlettervalue = nletterdata[i];
			nletterheadlines = nlettervalue.split("&!&");
			var nletter_selected = nletterheadlines[2];
			//alert(nlettervalue);
				if ( nletter_selected == 1)
				{
				
				headlines = "<b>" + nletterheadlines[0] + "</b>";
				arr.push(headlines);
				}
			}
			var lastElement = arr.pop();
			var firstElements = arr.join(", ");
				if ( arr.length == 0)
				{
				var allElements = lastElement + ".";
				} else 
					{
					var allElements = firstElements + " and " + lastElement + ".";
					}
			if (headlines.length != 0)
			{
			GDN.SetInnerHtml(n, a + allElements + b);
			}
			else
			GDN.SetInnerHtml(n,m);
	}
	else
	GDN.SetInnerHtml(n,m);	
}

function initializeSignIn()
{

	if (GDN.Cookie.Exists("GDNNL"))
	{
		getCookieData(DivMessage,userMessage,firstpart,secondpart);
	}
	else
	{
		var BecomeMemberForm = document.getElementById("NLBecomeMember");
		BecomeMemberForm.BecomeMemberBtn.disabled=true;
		var strMessage = "<p>Please <a href=\"/section/nlettersubscribe\">select the newsletters</a> you would like to subscribe to before completing your registration.</p><br/>";
		GDN.SetInnerHtml("NLconfirmationheader",strMessage);
	}

}
//SlideDown and SlideUp effect
var timerlen = 5;
var slideAniLen = 250;
var timerID = new Array();
var startTime = new Array();
var obj = new Array();
var endHeight = new Array();
var moving = new Array();
var dir = new Array();

function slidedown(objname){
        if(moving[objname])
                return;

        if(document.getElementById(objname).style.display != "none")
                return; // cannot slide down something that is already visible

        moving[objname] = true;
        dir[objname] = "down";
        startslide(objname);
}

function slideup(objname){
        if(moving[objname])
                return;

        if(document.getElementById(objname).style.display == "none")
                return; // cannot slide up something that is already hidden

        moving[objname] = true;
        dir[objname] = "up";
        startslide(objname);
}

function startslide(objname){
        obj[objname] = document.getElementById(objname);

        endHeight[objname] = parseInt(obj[objname].style.height);
        startTime[objname] = (new Date()).getTime();

        if(dir[objname] == "down"){
                obj[objname].style.height = "1px";
        }

        obj[objname].style.display = "block";

        timerID[objname] = setInterval('slidetick(\'' + objname + '\');',timerlen);
}

function slidetick(objname){
        var elapsed = (new Date()).getTime() - startTime[objname];

        if (elapsed > slideAniLen)
                endSlide(objname);
        else {
                var d =Math.round(elapsed / slideAniLen * endHeight[objname]);
                if(dir[objname] == "up")
                        d = endHeight[objname] - d;

                obj[objname].style.height = d + "px";
        }

        return;
}

function endSlide(objname){
        clearInterval(timerID[objname]);

        if(dir[objname] == "up")
                obj[objname].style.display = "none";

        obj[objname].style.height = endHeight[objname] + "px";

        delete(moving[objname]);
        delete(timerID[objname]);
        delete(startTime[objname]);
        delete(endHeight[objname]);
        delete(obj[objname]);
        delete(dir[objname]);

        return;
}
// END SlideDown and SlideUp effect

function gmtiCommonLibSlide(objname, time) {
	slideAniLen = time;
	slidedown(objname);		
}

function gmtiCommonLibSlideUp(objname, time) {
	slideAniLen = time;
	slideup(objname);		
}

//Query String function to get data from adURL
function gmtiCommonLibQuerySt(string,ji) {
	gy = string.split(";");
	for (i=0;i<gy.length;i++) {
		ft = gy[i].split("=");
		if (ft[0] == ji) {
			return ft[1];
		}	
	}
}

/*GMTI Photogalleries Object*/
var gpg = {
  	params:"",
    photoObj:"",
	globalpgpageno:1,
	totalgallerypages:0, /*Number of Pages Per Gallery*/
	totalgalleryphotos:0, /*Number of Photos Per Gallery*/
	saxo_picnumber:0, /*Saxo picnumber*/
	photoCounter:1,
	pgSortOrder:"TimeStampDescending",
	navType:"next",
	galleryTitle:"", /*Gallery Title*/
	photoTitle:"", /*Photo Title*/
	PhotoDescritpion:"", /*Photo Description*/
	myImagessrc:"", /*Saxo Image src*/
	plckPhotoID:"",
	thumbPerBatch:"",  /*Set the thumbnails count per page*/
	thumbPerBatchAccr:"",/*Needed for Pagination*/
	flagPagination:"", /*Set the pagination to be called only onLoad*/
	myImages:"", /*Holds the Thumbnails image src*/
	actualthumbbatch:"",
	plckIsPhoto:false,
	plckGalleryID:"",
	PGgraphicsfolder:"/gcicommonfiles/sr/graphics/common/pluck/",
	localMasterPGArray:new Array(),
	KeyCount: new Array(),
	photogallerypagetemplate:"/apps/pbcs.dll/section?Category=pluckpublicphotogallery",
	startofBatch:0, 
	endofBatch:0,
	localSaxoPluckPGcall:new Array(),
       
    /*************************************************************************/
    /* GMTI Photogalleries Library Initialization **********************************/

    initialSetup: function(userID) {
	
        try {
			gpg.params = new String(window.location.href.toString().replace(/^[^\?]+\?/,"")).toQueryParams();
		    if(gsl.enabled==true && typeof(SaxoObject) == 'undefined') {
				gsl.checkDaapiAvailable();
				if (gsl.wilDaapiWork=="true"){
	        		if($("photo_gallery_wrapper")) { this.getphotogallery(); }
	               }
				else
					document.getElementById("IE6Error").style.display ="block"; 
            } else {
					if($("photo_gallery_wrapper")) { this.getphotogallery(); }
					}   
        } catch(e) {
            gsl.showException("initialSetup", e);
        }
    },

	 /*************************************************************************/
    /*GMTI Photogalleries Functions ******************************************/
	
	getphotogallery: function() {
	gpg.flagPagination = true;
	gpg.myImages = new Array();
	if (typeof(SaxoObject)!='undefined'){
	gpg.photoObj =serverArtResult.ResponseBatch.Responses[0].PhotoPage.Photos; 
	this.processphotogallery(serverArtResult);
	gpg.getPluckPGinfoSaxo(1);}
	else { if (gsl.params=="")
			gsl.params = new String(window.location.href.toString().replace(/^[^\?]+\?/,"")).toQueryParams();
		var rb= new RequestBatch();
		/*Check if gallery has to be requested or the photo*/
		if (gpg.galleryTitle=="" && gsl.params["plckGalleryID"]){
		//make a client request to pluck to get the galelry information 
			var rbg = new RequestBatch();
			 var gallerykey = new GalleryKey(gsl.params["plckGalleryID"]);
			 rbg.AddToRequest(gallerykey);
			  gsl.sitelifeRequest(rbg, "LoadGallery", this._processgallery);
			  } 
		if (gsl.params["plckPhotoID"]) {
			var photokey = new PhotoKey(gsl.params["plckPhotoID"]);
			rb.AddToRequest(photokey);
			gsl.sitelifeRequest(rb, "LoadPhoto", this.processphoto); 
			
		}
		else {
			 if (gsl.params["plckGalleryID"]){
			 var gallerykey = new GalleryKey(gsl.params["plckGalleryID"]);
			 rb.AddToRequest(new PhotoPage(gallerykey,gsl.requestsperBatch,1,gpg.pgSortOrder));
	        } else {
	            gsl.showException("getphotogallery: gallery id not specified");
	        }
	        gsl.sitelifeRequest(rb, "LoadPhotoGallery", this.processphotogallery);
						
		} 
			}
	},
	
	_processgallery:function(result){
	if (result.Responses.length >0) 
		gpg.galleryTitle =result.Responses[0].Gallery.Title;	
	},
	
	getPluckPGinfoSaxo:function(batchno){
		//grab 10 id from the saxo object and add it to the batch 
		//before that check if its already present in local copy
	if(typeof(gpg.localSaxoPluckPGcall[batchno])=='undefined' && typeof($("pgrecommend"))!='undefined' && ($("pgrecommend")!=null)){
	gpg.startofBatch = parseInt((batchno-1)*10);
	if (gpg.startofBatch +10 <= gpg.totalgalleryphotos)
	gpg.endofBatch = gpg.startofBatch +10 ;
	else
	gpg.endofBatch = gpg.totalgalleryphotos;
	var reqBatch;  
	for(i=gpg.startofBatch; i<gpg.endofBatch; i++) {
		 if(!reqBatch) { reqBatch= new RequestBatch(); }
		 gsl.showDebug("adding photo id to batch: " + gpg.photoObj[i].PhotoKey.Key);   
	      reqBatch.AddToRequest(new ArticleKey(gpg.photoObj[i].PhotoKey.Key));  
		}
	gsl.sitelifeRequest(reqBatch, "LoadPhotoCtls", this._processSaxoPhotoCall); 
	gpg.localSaxoPluckPGcall[batchno]=true;
	} else
	 gpg._getpghtml(parseInt($("gsl_pg_currentno").value));
	},
	
	_processSaxoPhotoCall:function(result){
	  
	  //process the result and get the values out of result to the master copy. 
	 if (result.Responses.length >0) {
	 for ( j=0; j<result.Responses.length; j++) {
		for(i=gpg.startofBatch; i<gpg.endofBatch; i++) {
			if (result.Responses[j].Article.ArticleKey.Key == gpg.localMasterPGArray[1][i].PhotoKey.Key ) {
				gpg.localMasterPGArray[1][i].CurrentUserHasRecommended = result.Responses[j].Article.Recommendations.CurrentUserHasRecommended;
				gpg.localMasterPGArray[1][i].NumberOfRecommendations = result.Responses[j].Article.Recommendations.NumberOfRecommendations;
				}
		
	  }}}
	  gpg._getpghtml(parseInt($("gsl_pg_currentno").value));
	
	},
	
	processphoto:function(result){
		gpg.photoObj = result.Responses[0].Photo;
		var temparray  = new Array();
		gpg.localMasterPGArray[1]= temparray;
		gpg.localMasterPGArray[1][0] = gpg.photoObj;
		gpg.plckIsPhoto = true;
		var current_photo = "0";
		gpg._getpghtml(current_photo,true);
		if(gpg.flagPagination == true) /*Call the pagination only once for both Pluck and Saxotech*/
		{
			
							if (gpg.localMasterPGArray[gpg.globalpgpageno].length >0/*gpg.photoObj.length >0*/){
							 if (typeof(gpg.params["plckPhotoID"])!='undefined'){
								 	$("show_hide_Thumbnails").style.display="none";
								}else {
								  gpg.gallery_thumb_pagination();
								  gpg.combine_all(1);
								}
							  }
		}
		var queryparam= window.location.href.toString().replace(/^[^\?]+\?/,"");
		var queryindex = queryparam.indexOf("plckGalleryID");
		if ( queryparam.indexOf("plckGalleryID",queryindex+1) > 1)
		gpg.plckGalleryID = gpg.params["plckGalleryID"][0];
		else
		gpg.plckGalleryID = gpg.params["plckGalleryID"];
	},
	
	processphotogallery:function(result){
		var current_photo = $("gsl_pg_currentno").value;
		gpg.thumbPerBatch = 20 ; /* How Many Thumbnails per Page-Index Pagination*/
		gpg.thumbPerBatchAccr = gpg.thumbPerBatch - 1;
		if (typeof(SaxoObject)!='undefined'){
		gpg.photoObj =result.ResponseBatch.Responses[0].PhotoPage.Photos;
		gpg.localMasterPGArray[1] = gpg.photoObj ;
		gpg.totalgalleryphotos =result.ResponseBatch.Responses[0].PhotoPage.NumberOfPhotos;
		gpg.Saxo_totalgalleryphotos();		
		
		gpg.myImagessrc = new Array();
			params = gpg.params["Params"];
			if (params != "" && typeof(params) != "undefined"){
			valueArray = params.split("=");
			itemnr = valueArray[1];
			current_photo=parseInt(itemnr);
			$("gsl_pg_currentno").value =current_photo;
			}
		}
		else {
			if (result.Responses[0].PhotoPage.Photos.length > 0){
				if (typeof(gpg.localMasterPGArray[gpg.globalpgpageno])=='undefined')
					gpg.localMasterPGArray[gpg.globalpgpageno] =result.Responses[0].PhotoPage.Photos;
				gpg.totalgallerypages = Math.ceil(result.Responses[0].PhotoPage.NumberOfPhotos/10); 
				gpg.totalgalleryphotos =result.Responses[0].PhotoPage.NumberOfPhotos;
				gpg.plckGalleryID = result.Responses[0].PhotoPage.Photos[0].GalleryKey.Key;
			}
			else {
			  $("photo_gallery_right_caption").innerHTML = "<div id=\"photo_gallery_desc\" class=\"photo_gallery_right_caption_text\">Currently there are no photos associated with the gallery please check back later.</div>";
			  gpg.plckGalleryID = gsl.params["plckGalleryID"];
			  return;
			}
		}
	
		gpg._getpghtml(current_photo,false);
		if(gpg.flagPagination == true) /*Call the pagination only once for both Pluck and Saxotech*/
		{
				if (typeof(SaxoObject)!='undefined'){
					if (gpg.photoObj.length >0){
						//gpg._getpghtml(current_photo,false);
						if($("enable-thumbnails")!=null && (typeof($("enable-thumbnails"))!='undefined' ))
						{
							gpg.gallery_thumb_pagination();
							gpg._gallery_thumb(gpg.thumbPerBatch);
						}
					}
				} else 
						{ 
						if($("enable-thumbnails")!=null && (typeof($("enable-thumbnails"))!='undefined' ))
						{
							if (gpg.localMasterPGArray[gpg.globalpgpageno].length >0/*gpg.photoObj.length >0*/){
							  //gpg._getpghtml(current_photo,false);
							  gpg.gallery_thumb_pagination();
							  gpg.combine_all(1);
							  }
						}
					}
			//}
		}
		gpg.flagPagination = false; /*Don't call the Pagination again until next Page Load*/
	},
	
	
	

	_getpghtml:function(photono,isPhoto){
		var photo =	"";
		var isValidReq = false;
		var current_number = 0;
		var gallerycap_html= "";
		var IsBlockedUserloggedin =false;
		var isReported = false;
		try {
			if (typeof(SaxoObject)!='undefined'){
			gpg.galleryTitle = serverArtResult.ResponseBatch.Responses[0].PhotoPage.GalleryTitle;
			photo = gpg.localMasterPGArray[gpg.globalpgpageno][photono];
			current_number= photono + 1;
			if (gpg.photoObj.length >0 && typeof(photo)!="undefined") isValidReq = true;
			} else 	{
					current_number = gpg.photoCounter;
					if (gpg.plckIsPhoto) {
							photo = gpg.photoObj;	
							isValidReq = true; 
					} else {
					photo = gpg.localMasterPGArray[gpg.globalpgpageno][photono];
					isValidReq = gpg.isPhotoValid(photo);
					}
					gpg.plckPhotoID = photo.PhotoKey.Key;
				}
			
			if (isValidReq ){
				$("photo_gallery_bottom_links").style.display="block";
				if (typeof(SaxoObject)=='undefined'){
				    $("gslReportAbuseType").value= "photo";
					$("gslReportAbuseKey").value= photo.PhotoKey.Key;
										if (photo.CurrentUserHasReportedAbuse.toLowerCase() =="true")
						isReported = true;
					
					$("gslRepAbuse").innerHTML = gsl.getReportAbuseLink('photo',photo.PhotoKey.Key,isReported);
					
					var recCtl= $("pgrecommend");
				        if (recCtl) {        // populate content control
				            var recd=false;
				            var recCnt=0;
				            //var artKey= gsl.getArticleKey();
				            //if (article) {
				                recd= (photo.NumberOfRecommendations && photo.CurrentUserHasRecommended=='True')? true: false;
				                recCnt= photo.NumberOfRecommendations;
				                photoKey= photo.PhotoKey.Key;
				            //}
				            
				            recCtl.innerHTML= gsl.getRecommendCountControl('photo', photoKey, recCnt, recd); 
				        }
				}
				else
				{
					
					var recCtl= $("pgrecommend");
				        if (recCtl) {        // populate content control
				            var recd=false;
				            var recCnt=0;
				            //var artKey= gsl.getArticleKey();
				            //if (article) {
				                recd= (photo.NumberOfRecommendations && photo.CurrentUserHasRecommended=='True')? true: false;
				                recCnt= photo.NumberOfRecommendations;
				                photoKey= photo.PhotoKey.Key;
				            //}
				            
				            recCtl.innerHTML= gsl.getRecommendCountControl('saxophoto', photoKey, recCnt, recd); 
				        }
				}

				gpg.photoTitle = photo.Title;
				gpg.PhotoDescritpion= unescape(photo.Description);
				gallerycap_html = "<h5>" + unescape(photo.Title) + "</h5>";
				
				if (typeof(SaxoObject)!='undefined'){
				gallerycap_html += "<span class=\"photo_gallery_right_caption_byline\">"+ unescape(photo.Author.DisplayName)+ "</span><br />";
				$("photo_gallery_image_background").innerHTML= 	"<span></span><img src=\""+photo.Image.Large+"\"  class=\"matted\" id=\"print_photo\">";
					if (photo.Canbuy!="0")
						$("pg_pictopia").style.display="block";
					else
						$("pg_pictopia").style.display="none";
				}else{
				gallerycap_html += "<span class=\"photo_gallery_right_caption_byline\">"+ photo.CreatedOn + "|<a href=\"" + photo.Author.PersonaUrl+"\" target=\"_parent\">"+photo.Author.DisplayName+ "</a></span><br />";
				$("photo_gallery_image_background").innerHTML= 	"<span></span><img src=\""+photo.Image.Large+"\"  class=\"matted\" id=\"print_photo\" name=\"img1\" onload=\"resizeimage('img1')\">";
				}

				gallerycap_html += "<div id=\"photo_gallery_desc\" class=\"photo_gallery_right_caption_text\">"+ gpg.PhotoDescritpion + "</div>";
				
				$("photo_gallery_right_caption").innerHTML = gallerycap_html;
				if (gpg.plckIsPhoto) 
					/*$("OnlyPhotoNext").style.display = "block";*/
					$("photo_gallery_masthead_nav_number").innerHTML = "<div id=\"OnlyPhotoNext\">NEXT PHOTO</div>";
				else {
					$("photo_gallery_masthead_nav_number").innerHTML = parseInt(current_number) + "/" + gpg.totalgalleryphotos;
					}
				$("photo_gallery_masthead_title").innerHTML = "<h3>"+gpg.galleryTitle+"</h3>";
			}else {
				$("photo_gallery_bottom_links").style.display="none";
				$("photo_gallery_image_background").innerHTML= 	"<span></span><img src=\""+gpg.PGgraphicsfolder+"removed_photodefault.gif\" alt=\"\" class=\"matted\" id=\"print_photo\" name=\"img1\" onload=\"resizeimage('img1')\">";
				$("photo_gallery_masthead_nav_number").innerHTML = parseInt(current_number) + "/" + gpg.totalgalleryphotos;
				$("photo_gallery_masthead_title").innerHTML = "<h3>"+gpg.galleryTitle+"</h3>";
				$("photo_gallery_right_caption").innerHTML="";
				}
			if (gpg.plckIsPhoto) {
				$("photo_gallery_masthead_nav").style.display="block";	
				$("photo_gallery_masthead_nav_prev").style.display="none"; 
				$("photo_gallery_masthead_nav_next").style.display="block";	
				
			} else {				
					$("photo_gallery_masthead_nav").style.display="block";		
			}
		}
		catch(e) {
	            gsl.showException("Get PG html", e);
	        }
		
	},
	
	navigatephoto:function(nav_type){
	var current_photo = parseInt($("gsl_pg_currentno").value);
	gpg.navType=nav_type;
		if (nav_type == "next") {
		gpg.photoCounter++;
		if (gpg.plckIsPhoto)gpg.gotoGallery();
			
				if (typeof(SaxoObject)!='undefined'){
				  if (current_photo+1 >= gpg.totalgalleryphotos)
							$("gsl_pg_currentno").value = 0;
							 else 
								$("gsl_pg_currentno").value =current_photo+1; 
							
				if ((current_photo+1) %10 == 0)
					gpg.getPluckPGinfoSaxo((parseInt(current_photo+1)/10)+1);
				 else
				gpg._getpghtml(parseInt($("gsl_pg_currentno").value));
				} else {
				
					if (current_photo >=9 && gpg.globalpgpageno < gpg.totalgallerypages ) {
						$("gsl_pg_currentno").value = 0;
						gpg.globalpgpageno++;
					     gpg._sendGallerySLReq();
						var currentpageno = ((parseInt(gpg.globalpgpageno)-1) *10 )+ parseInt($("gsl_pg_currentno").value)+1;
						
					}
					else {
						var currentpageno = ((parseInt(gpg.globalpgpageno)-1) *10 )+ current_photo+2;
						if (currentpageno > gpg.totalgalleryphotos){
							$("gsl_pg_currentno").value = 0;
							gpg.globalpgpageno = 1;
							gpg.photoCounter= 1;
							gpg._sendGallerySLReq();
							} else {
						gpg._getpghtml(current_photo+1);
						$("gsl_pg_currentno").value =current_photo+1;
						}
					}
				}				
		}
		else
		{
		gpg.photoCounter--;
			if (typeof(SaxoObject)!='undefined'){
			 if (current_photo < 1)
						$("gsl_pg_currentno").value = gpg.totalgalleryphotos-1;
				  else 
						$("gsl_pg_currentno").value =current_photo-1;	
				if (current_photo < 1)
					gpg.getPluckPGinfoSaxo(parseInt(gpg.totalgalleryphotos/10)+1);
				else if ((current_photo) %10 == 0)	gpg.getPluckPGinfoSaxo((parseInt(current_photo)/10));
					else
						gpg._getpghtml(parseInt($("gsl_pg_currentno").value));
				
			} else { 
					if (current_photo < 1 && gpg.globalpgpageno!=1 && gpg.globalpgpageno <= gpg.totalgallerypages ) {
						gpg.globalpgpageno--;	
						$("gsl_pg_currentno").value = 9;
						gpg._sendGallerySLReq(); 
						var currentpageno = ((parseInt(gpg.globalpgpageno)-1) *10 )+ parseInt($("gsl_pg_currentno").value)+1;
					
					} else if (current_photo < 1 && gpg.globalpgpageno==1 ){
							var currentpageno = gpg.totalgalleryphotos % 10;
							if (currentpageno < 1) 
								$("gsl_pg_currentno").value =  9;
							 else 
								$("gsl_pg_currentno").value =  currentpageno -1;
							gpg.globalpgpageno = gpg.totalgallerypages;
							gpg.photoCounter= ((parseInt(gpg.globalpgpageno)-1) *10 )+ parseInt($("gsl_pg_currentno").value)+1;
							gpg._sendGallerySLReq();
						} else {
						var currentpageno = ((parseInt(gpg.globalpgpageno)-1) *10 )+ current_photo;
						gpg._getpghtml(current_photo-1); 
						$("gsl_pg_currentno").value =current_photo-1;
					}
			}
			
			
		}
		/*Get omniture and Ad stuff for the photo  */
			gpg.getMiscstuff();
	},
	
	gotoGallery:function(){
		var queryparam= window.location.href.toString().replace(/^[^\?]+\?/,"");
		var queryindex = queryparam.indexOf("plckGalleryID");
		if ( queryparam.indexOf("plckGalleryID",queryindex+1) > 1)
			window.location.replace(gpg.photogallerypagetemplate+"&plckGalleryID="+gpg.params["plckGalleryID"][0]);
			else
			window.location.replace(gpg.photogallerypagetemplate+"&plckGalleryID="+gpg.params["plckGalleryID"]);
	
	},
	
	isPhotoValid:function(photo){
		var isValidReq = false;
		var IsBlockedUserloggedin =false;
		var isReported = false;
		if(GDN.Cookie.Exists("at") && gsl.getUserPid() == photo.Author.UserKey.Key)
			IsBlockedUserloggedin =true;
			if((photo.Author.IsBlocked!="True" || IsBlockedUserloggedin )&& parseInt(photo.AbuseReportCount) < gsl.MaxNumberofAbuse)
				return true; 
			else 
				return false;
	},
	/*************************************************************************/
    /* GMTI Photogalleries Thumbnail Functions ******************************************/
    /***********PLUCK BATCH CALLS***********/
	combine_all:function(n){
		gpg.myImages.length = 0; //Flush the Image array for the next 2 batches
		var page_secondbatch = n*2;
		var page_firstbatch = page_secondbatch - 1;
		gpg._pluck_gallery_sendGallerySLReq(page_firstbatch); //Make the 1st Call
		gpg._pluck_gallery_sendGallerySLReq(page_secondbatch); //Make the 2nd Call
	},
	
	/*Call Batches  To Build Pluck Thumbnails*/
	processnewobject:function(result){
		gpg.photoObj = result.Responses[0].PhotoPage.Photos;
		gpg.actualthumbbatch = result.Responses[0].PhotoPage.OnPage; //Get the Batch number
		gpg.localMasterPGArray[gpg.actualthumbbatch] = gpg.photoObj; //Write to the Array
		gpg._gallery_thumb(gpg.actualthumbbatch); //Capture only the images from the data returned from pluck
		$("gallery-thumbnails-pluck").innerHTML= "<dl>" + gpg.myImages.join("") + "</dl>"; //Display all src images
	},
	
	/***********END OF PLCUK BATCH CALLS***********/
		
	_gallery_thumb:function(batchnum){
		var contents = "";
			if (typeof(SaxoObject)!='undefined'){/*SAXOTECH*/
				var roundNumber = Math.ceil(batchnum - gpg.thumbPerBatch) ;
				for (var i=roundNumber; i<batchnum; i++) {
					if(gpg.photoObj[i]){
					//contents = 	"<dt><a onclick=\"gpg.gallery_thumb_href(" + i + ");return false;\" href=\"\"><img src=\""+gpg.photoObj[i].Image.Small+" \"  width=\"72\" height=\"72\"></a></dt>";
					contents = 	"<dt><div id=\"p"+i+"\" name=\"thumb\" class=\"photo-wrapper\"><div class=\"gallery-thumbnails-photo\"><a onclick=\"gpg.gallery_thumb_href(" + i + ");return false;\" href=\"\"><img src=\""+gpg.photoObj[i].Image.Small+" \" ></a></div></div></dt>";
					gpg.myImages.push(contents);
					}
				}
			$("gallery-thumbnails").innerHTML= "<dl>" + gpg.myImages.join("") + "</dl>";
			gpg.myImages.length = 0;
				} else {/*PLUCK*/
								if (typeof(gpg.localMasterPGArray[batchnum])!='undefined'){
										for (var i=0; i<10; i++){
											if (typeof(gpg.localMasterPGArray[batchnum][i])!='undefined'){
													 if(gpg.isPhotoValid(gpg.localMasterPGArray[batchnum][i])==false){
														contents = 	"<dt><a onclick=\"gpg.gallery_thumb_href("+i+","+batchnum+");return false;\" href=\"\"><img src=\""+gpg.PGgraphicsfolder+"removed_thumb.gif\"  width=\"72\" height=\"72\"></a></dt>";
														gpg.myImages.push(contents);
													} else {
												contents = 	"<dt><a onclick=\"gpg.gallery_thumb_href("+i+","+batchnum+");return false;\" href=\"\"><img src=\""+gpg.localMasterPGArray[batchnum][i].Image.Small+" \"  width=\"72\" height=\"72\"></a></dt>";
												gpg.myImages.push(contents);
													 }
												}  
												
										}
								} else {/*In Case something happens to the Array, Read directly from Pluck Object*/
											for (var i=0; i<10; i++){
												if(typeof(gpg.photoObj[i])!='undefined'){
												contents = 	"<dt><a onclick=\"gpg.gallery_thumb_href("+i+","+batchnum+");return false;\" href=\"\"><img src=\""+gpg.photoObj[i].Image.Small+" \"  width=\"72\" height=\"72\"></a></dt>";
								gpg.myImages.push(contents);
													}
												}
										}
								
					}
				return gpg.myImages.join("");
			
	},
		
	gallery_thumb_href:function(photono,batchid){
				if (typeof(SaxoObject)=='undefined'){
					gpg.globalpgpageno = batchid;
					if (gpg.globalpgpageno>1){
					var x= ((parseInt(gpg.globalpgpageno)) *10)-10;
					gpg.photoCounter= (parseInt(x+photono+1));
					}else {gpg.photoCounter = photono+1; /*update Pagination*/}
					gpg._getpghtml(photono); /*update Description, Title, Date...etc*/
					$("gsl_pg_currentno").value =photono; /*update Pagination*/
				}
				else
				{
					$("gsl_pg_currentno").value =photono; /*update Pagination*/
					gpg.getPluckPGinfoSaxo(parseInt(photono/10)+1);
				}
				
				gpg.getMiscstuff(); /*Update Omnitures and Ad-Refresh*/
	},
		
	gallery_thumb_pagination:function(){
		var local_totalgallerypages = "";
		var myPageshref = new Array();
		var contents = "";
		var batchnum = "";
		var rangeTwo = "";
		var rangeOne = "";
		
		local_totalgallerypages = Math.ceil(gpg.totalgalleryphotos/gpg.thumbPerBatch);
						
		if(typeof($("enable-thumbnails"))!='undefined'){
			for (var i=0; i<local_totalgallerypages; i++){
				batchnum = i + 1;
				rangeTwo = batchnum * gpg.thumbPerBatch;
				rangeOne = rangeTwo - gpg.thumbPerBatchAccr;
				
				
				if(rangeTwo > gpg.totalgalleryphotos) {rangeTwo = gpg.totalgalleryphotos};
				if (typeof(SaxoObject)!='undefined'){
				gpg.saxo_picnumber = gpg.saxo_picnumber + gpg.thumbPerBatch;
				contents += "<li><a class=\"\" id=\"page"+batchnum+"\" onclick=\"gpg._gallery_thumb("+gpg.saxo_picnumber+");return false;\" onmousedown=\"gpg.gallery_page_highlight_selected('page"+batchnum+"');return false;\" href=\"\"> " +batchnum +" </a></li>";
				} else {
					contents += "<li><a class=\"\" id=\"page"+batchnum+"\" onclick=\"gpg.combine_all("+batchnum+");return false;\" onmousedown=\"gpg.gallery_page_highlight_selected('page"+batchnum+"');return false;\" href=\"\"> " +batchnum +" </a></li>";
						}	
			}
			myPageshref.push(contents);
		$("gallery-thumbnails-pagination").innerHTML = "<ul id=\"pagination-flickr\">" + myPageshref.join("") + "</ul>";
		}
		
	},
	
	gallery_page_highlight_selected:function(id){
		    var anchorTags = document.getElementsByTagName("a");
	        for (var i = 0; i < anchorTags.length ; i++)
	        {
	            anchorTags[i].className= "";
	        }
		    document.getElementById(id).className=  "pagination-selected-page"; 
	},
	
	/*************************************************************************/
    _sendGallerySLReq:function(){
	 if (typeof(gpg.localMasterPGArray[gpg.globalpgpageno])=='undefined'){
		 var rb= new RequestBatch();
		 if (gpg.params["plckGalleryID"]){
			 var gallerykey = new GalleryKey(gpg.params["plckGalleryID"]);
			 rb.AddToRequest(new PhotoPage(gallerykey,gsl.requestsperBatch,gpg.globalpgpageno,gpg.pgSortOrder));
		} else {
				gsl.showException("getphotogallery: gallery id not specified");
		}
		gsl.sitelifeRequest(rb, "LoadPhotoGallery", this.processphotogallery); 
	}
	else { 
		gpg._getpghtml($("gsl_pg_currentno").value,false);
	}
	
	},
	
		
	_pluck_gallery_sendGallerySLReq:function(requestnum){
		if (typeof(gpg.localMasterPGArray[requestnum])=='undefined'){
				 var rb= new RequestBatch();
				 if (gpg.params["plckGalleryID"]){
					 var gallerykey = new GalleryKey(gpg.params["plckGalleryID"]);
					 rb.AddToRequest(new PhotoPage(gallerykey,gsl.requestsperBatch,requestnum,gpg.pgSortOrder));
				} else {
						gsl.showException("getphotogallery: gallery id not specified");
				}
				gsl.sitelifeRequest(rb, "LoadPhotoGallery", this.processnewobject);
			}
			else { 
			     gpg._gallery_thumb(requestnum);
				$("gallery-thumbnails-pluck").innerHTML= "<dl>" + gpg.myImages.join("") + "</dl>"; //Display all src images
				 gpg._getpghtml($("gsl_pg_currentno").value,false);
			}
			
	},
	
	Saxo_totalgalleryphotos:function() {
	var data = "";
			for (var i = 0; i < gpg.totalgalleryphotos ; i++)
		        {
					if (typeof(gpg.photoObj[i])!='undefined')
					{
		            data = gpg.photoObj[i].PhotoKey.Key;
					gpg.KeyCount.push(data);
					}
		        }
		gpg.totalgalleryphotos = gpg.KeyCount.length;
	},
	
	buildScript:function(src){
		var 
			script = document.createElement("SCRIPT"),
			headID = document.getElementsByTagName("head")[0]
		;
        script.type = "text/javascript";
		script.src = src;
		headID.appendChild(script);
	},
	
	getMiscstuff:function(){				
		//Make an Omiture Call to record the page view 
		if (typeof(SaxoObject)!='undefined') 
			s.prop45="Item#"+parseInt(parseInt($("gsl_pg_currentno").value)+1);
		else
			s.prop45="Item#"+gpg.photoCounter;
		var s_code=s.t();if(s_code)document.write(s_code);
		
		gpg.buildScript('http://b.scorecardresearch.com/beacon.js?c1=2&c2=6035223');

		//Make an ad refresh call 
		placeAD('300x250_1');
	}
    
};
/*END OF GPG OBJECT*/
/*Buy, Print, Email Photo*/
function actionPhoto(action,width,height){
		var item   = document.location;
		var left   = (screen.width  - width) / 2;
		var top    = (screen.height - height) / 2;
		var params = 'width=' + width +', height=' + height;
		var url 	 = "";
		var currPic  = "";
		var currGalleryID = gpg.params["Lopenr"];
		var numofPhotos = gpg.totalgalleryphotos;
		var galleryTitle = gpg.galleryTitle;
		var photoTitle = gpg.photoTitle;
		var PhotoDescritpion = gpg.PhotoDescritpion;
		var ptpId = "" ;
		var srcPic = document.getElementById("print_photo").src;
		
		params += ', top=' + top + ', left=' + left;
		params += ', directories=no';
		params += ', location=no';
		params += ', menubar=no';
		params += ', resizable=no';
		params += ', scrollbars=yes';
		params += ', status=no';
		params += ', toolbar=no';

		switch (action)
		{
			case "print":
				url = location.href + "&template=printphoto" + "&src=" + srcPic;
				newWin = window.open(url,'PopUp', params);
				if (window.focus) { newWin.focus(); }
				break;
			case "email":
				if (typeof(gpg.params["plckGalleryID"])!='undefined')
					{ 
					currPic = gpg.plckPhotoID;
					url = location.href + "&plckPhotoID=" + currPic + "&GTITLE="+galleryTitle+ "&template=xsendmailPopUpPic";
					} else {
							currPic = $("gsl_pg_currentno").value;
							url = location.href + "&Params=Itemnr=" + currPic + "&GTITLE="+galleryTitle+"&template=xsendmailPopUpPic";
						}
				newWin = window.open(url,'PopUp', params);
				if (window.focus) { newWin.focus(); }
				break;
			case "buy":
				currPic = $("gsl_pg_currentno").value;
				ptpId = currGalleryID + currPic + numofPhotos;
				return goPtp(ptpId,photoTitle,srcPic,PhotoDescritpion);
				break;
			default:
			document.write("Suit yourself then...");
		}
	
}

/*START OF thumbnails SlideDown and SlideUp*/
// The function used in toggleSlide are located in GMTICommonLibrary.js

function toggleSlide(objname){
  if(document.getElementById(objname).style.display == "none"){
    // div is hidden, so let's slide down
    slidedown(objname);
	$("show_thumbnails").style.display="none";
	$("hide_thumbnails").style.display="block";
  }else{
    // div is not hidden, so slide up
    slideup(objname);
	$("show_thumbnails").style.display="block";
	$("hide_thumbnails").style.display="none";
  }
}

/*END OF thumbnails SlideDown and SlideUp*/

function GPG_OMNITURE(action){	/*Getting  s_prop43 and s_prop45 ready for gpg.getMiscstuff()*/
	var params = new String(window.location.href.toString().replace(/^[^\?]+\?/,"")).toQueryParams();
	var item = params["Params"];
	var myItem_array =  "";
	var itemnr = "";
		
	switch (action)
		{
			case "Saxotech":
				if (typeof(serverArtResult)!='undefined')
				{s_prop43 = serverArtResult.ResponseBatch.Responses[0].PhotoPage.GalleryTitle;
					if (typeof(item)!='undefined')
					{
						myItem_array =  item.split("=");
						itemnr = parseInt(myItem_array[1]) + 1;
						s_prop45 = "Item#"+itemnr;
					} else 
						s_prop45 = "Item#"+1;
				}
				break;
			case "SiteLife":
				if (typeof(gpg)!='undefined') 
				s_prop43 = gpg.galleryTitle;
				if (params["plckPhotoID"]=='undefined' || params["plckPhotoID"]==null)
					s_prop45 = "Item#"+1;
				break;
			default:
			s_prop43 = serverArtResult.ResponseBatch.Responses[0].PhotoPage.GalleryTitle;
			s_prop45 = "Item#"+1;
		}
	}	
	
function resizeimage(imgname){
	var d1=document.images[imgname];
	var currenth=d1.height;
	if(currenth>352)
	d1.height=352;
	}	
if (typeof(PaginationArticleUrl)!='undefined' && GDN.Cookie.Exists("GCIONSN")) //if Cookie Exists
	{
			var GPReferrer = document.referrer;
			var GPHref = document.location.href;
			var GPCookie = GDN.Cookie.Get("GCIONSN");
			var GPvalueEncData= GDN.Base64.Decode(GPCookie);
			var GPvalueDecData= GPvalueEncData.match(/GPvalue:([\w\@\.\-\%\|]+)/i);
			
			if(GPvalueDecData != null && GPvalueDecData[1] != 'undefined'){//get Data, if GPvalue already exists in GCIONSN cookie
					var PaginationCookie = unescape(GPvalueDecData[1]);
					var PaginationData = PaginationCookie.split("|");
					var PaginationArticleCookie = PaginationData[0];
					
					if (PaginationArticleCookie == PaginationArticleUrl && GPReferrer == GPHref ){//if Same Article Read Cookie; PaginationArticleUrl declared in head_article.inc And Same URL
						var PaginationPage = PaginationData[1];
						if(PaginationPage!=1){s_prop41='CPD pagination'};
						var PaginationDivs = PaginationData[2];
						
						var calcPrevPage = parseInt(parseInt(PaginationPage) - 1);
						var calcNextPage = parseInt(parseInt(PaginationPage) + 1);
						var saxoPreviousPage = PaginationArticleCookie + "%7C" + calcPrevPage + "%7C" +PaginationDivs;
						var saxoNextPage = PaginationArticleCookie + "%7C"+ calcNextPage + "%7C" +PaginationDivs;
						
						document.write("<style type='text/css'>");
						for(var i=0;i<PaginationDivs;i++){
							if (parseInt(i+1)==PaginationPage){document.write("#GPage"+parseInt(i+1)+" {display:block !important;}");
								}else{document.write("#GPage"+parseInt(i+1)+" {display:none !important;}");} //Show only the current Page and hide the rest
						}
						if(PaginationPage == 1){
							document.write("#saxo-left-pagination {display:none !important;}"); //Hide "Previous Cursor" for the first page
						}
						if(PaginationPage == PaginationDivs){
							document.write("#saxo-right-pagination {display:none !important;}"); //Hide "Next Cursor" for last page
						}
						document.write(".saxopage"+PaginationPage+" {color: #000000 !important;font-weight: bold !important;text-decoration: underline !important;}"); //Mark current page
						document.write("</style>");
						} else { //otherwise set the default values as the following:
							document.write("<style type='text/css'>");
								document.write(".gpagediv {display:none !important;}"); //Hide the rest of the pages
								document.write("#GPage1 {display:block !important;}"); //Show only the 1st Page
								document.write("#saxo-left-pagination {display:none !important;}"); //Hide "Previous Cursor" for first page
								document.write(".saxopage1 {color: #000000 !important; font-weight: bold !important;text-decoration: underline !important;}"); //Mark current page
							document.write("</style>");
							}
			} else { //otherwise set the default values as the following:
				document.write("<style type='text/css'>");
					document.write(".gpagediv {display:none !important;}"); //Hide the rest of the pages
					document.write("#GPage1 {display:block !important;}"); //Show only the 1st Page
					document.write("#saxo-left-pagination {display:none !important;}"); //Hide "Previous Cursor" for first page
					document.write(".saxopage1 {color: #000000 !important; font-weight: bold !important;text-decoration: underline !important;}"); //Mark current page
				document.write("</style>");
					}
	}else { //if Cookie doesn't Exist, set the default values as the following:
			document.write("<style type='text/css'>");
				document.write(".gpagediv {display:none !important;}"); //Hide the rest of the pages
				document.write("#GPage1 {display:block !important;}"); //Show only the 1st Page
				document.write("#saxo-left-pagination {display:none !important;}"); //Hide "Previous Cursor" for first page
				document.write(".saxopage1 {color: #000000 !important; font-weight: bold !important;text-decoration: underline !important;}"); //Mark current page
			document.write("</style>");
			}
			
function removeHashUrl() {
	var currentRequestJS = location.href;
	var hashCount = subs_count(currentRequestJS,"#");//subs_count function declared in Adtechjs
			if(hashCount>0)
			{
			var re = /^((http[s]?|ftp):\/)?\/?([^:\/\s]+)(:([^\/]*))?((\/\w+)*\/)([\w\-\.]+[^#?\s]+)(\?([^#]*))?(#(.*))?$/;
			//RegEx Definition: SCHEMA = 2, DOMAIN = 3, PORT = 5, PATH = 6, FILE = 8, QUERYSTRING = 9, HASH = 11 , HASHVALUE = 12
			var modcurrentRequestJS = currentRequestJS.replace(re, "$11");
			currentRequestJS = currentRequestJS.split(modcurrentRequestJS)[0];
			}
			return currentRequestJS ;
}
			
function saxoArticlePagination() {
	var saxopages = "";
	var paragraphPagesArray = new Array();
		
		if (numDivs > 1)
		{
			for(var i=0; i<numDivs; i++) 
				{
			if(i == parseInt(numDivs-1)){
				paragraphPagesArray[i] = "<li><a class=\"saxopage"+parseInt(i+1)+"\" onclick=\"GDN.Cookies.Session.SetValue('GPvalue','"+PaginationArticleUrl+"%7C"+parseInt(i+1)+"%7C"+numDivs+"');\" href=\""+currentRequestJS+"\">"+parseInt(i+1)+"</a></li>";
				} else {
					paragraphPagesArray[i] = "<li><a class=\"saxopage"+parseInt(i+1)+"\"a onclick=\"GDN.Cookies.Session.SetValue('GPvalue','"+PaginationArticleUrl+"%7C"+parseInt(i+1)+"%7C"+numDivs+"');\" href=\""+currentRequestJS+"\">"+parseInt(i+1)+"</a>"+" | "+"</li>";
							}
				}
				
			saxopages = "<ul>" + paragraphPagesArray.join("") + "</ul>";
			return 	saxopages;	
		} else {
		document.getElementById("article-pagination").style.display='none';
				}
}

function triggerAd(i,j,k){
	if (typeof(j)!= 'undefined')
		{	if (i==j){
				if(k!=1){
					OAS_AD('ArticleFlex_1');
					}
				};
		} 		else if(i==1)
					{
					if(k!=1){
						OAS_AD('ArticleFlex_1');
						}
					};
}


