/*
    http://www.JSON.org/json2.js
    2008-10-31

    Public Domain.

    NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.

    See http://www.JSON.org/js.html

    This file creates a global JSON object containing two methods: stringify
    and parse.

        JSON.stringify(value, replacer, space)
            value       any JavaScript value, usually an object or array.

            replacer    an optional parameter that determines how object
                        values are stringified for objects. It can be a
                        function or an array of strings.

            space       an optional parameter that specifies the indentation
                        of nested structures. If it is omitted, the text will
                        be packed without extra whitespace. If it is a number,
                        it will specify the number of spaces to indent at each
                        level. If it is a string (such as '\t' or '&nbsp;'),
                        it contains the characters used to indent at each level.

            This method produces a JSON text from a JavaScript value.

            When an object value is found, if the object contains a toJSON
            method, its toJSON method will be called and the result will be
            stringified. A toJSON method does not serialize: it returns the
            value represented by the name/value pair that should be serialized,
            or undefined if nothing should be serialized. The toJSON method
            will be passed the key associated with the value, and this will be
            bound to the object holding the key.

            For example, this would serialize Dates as ISO strings.

                Date.prototype.toJSON = function (key) {
                    function f(n) {
                        // Format integers to have at least two digits.
                        return n < 10 ? '0' + n : n;
                    }

                    return this.getUTCFullYear()   + '-' +
                         f(this.getUTCMonth() + 1) + '-' +
                         f(this.getUTCDate())      + 'T' +
                         f(this.getUTCHours())     + ':' +
                         f(this.getUTCMinutes())   + ':' +
                         f(this.getUTCSeconds())   + 'Z';
                };

            You can provide an optional replacer method. It will be passed the
            key and value of each member, with this bound to the containing
            object. The value that is returned from your method will be
            serialized. If your method returns undefined, then the member will
            be excluded from the serialization.

            If the replacer parameter is an array of strings, then it will be
            used to select the members to be serialized. It filters the results
            such that only members with keys listed in the replacer array are
            stringified.

            Values that do not have JSON representations, such as undefined or
            functions, will not be serialized. Such values in objects will be
            dropped; in arrays they will be replaced with null. You can use
            a replacer function to replace those with JSON values.
            JSON.stringify(undefined) returns undefined.

            The optional space parameter produces a stringification of the
            value that is filled with line breaks and indentation to make it
            easier to read.

            If the space parameter is a non-empty string, then that string will
            be used for indentation. If the space parameter is a number, then
            the indentation will be that many spaces.

            Example:

            text = JSON.stringify(['e', {pluribus: 'unum'}]);
            // text is '["e",{"pluribus":"unum"}]'


            text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
            // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'

            text = JSON.stringify([new Date()], function (key, value) {
                return this[key] instanceof Date ?
                    'Date(' + this[key] + ')' : value;
            });
            // text is '["Date(---current time---)"]'


        JSON.parse(text, reviver)
            This method parses a JSON text to produce an object or array.
            It can throw a SyntaxError exception.

            The optional reviver parameter is a function that can filter and
            transform the results. It receives each of the keys and values,
            and its return value is used instead of the original value.
            If it returns what it received, then the structure is not modified.
            If it returns undefined then the member is deleted.

            Example:

            // Parse the text. Values that look like ISO date strings will
            // be converted to Date objects.

            myData = JSON.parse(text, function (key, value) {
                var a;
                if (typeof value === 'string') {
                    a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
                    if (a) {
                        return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
                            +a[5], +a[6]));
                    }
                }
                return value;
            });

            myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
                var d;
                if (typeof value === 'string' &&
                        value.slice(0, 5) === 'Date(' &&
                        value.slice(-1) === ')') {
                    d = new Date(value.slice(5, -1));
                    if (d) {
                        return d;
                    }
                }
                return value;
            });


    This is a reference implementation. You are free to copy, modify, or
    redistribute.

    This code should be minified before deployment.
    See http://javascript.crockford.com/jsmin.html

    USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
    NOT CONTROL.
*/

/*jslint evil: true */

/*global JSON */

/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", call,
    charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes,
    getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length,
    parse, propertyIsEnumerable, prototype, push, replace, slice, stringify,
    test, toJSON, toString, valueOf
*/

// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.

if (!this.JSON) {
    JSON = {};
}
(function () {

    function f(n) {
        // Format integers to have at least two digits.
        return n < 10 ? '0' + n : n;
    }

    if (typeof Date.prototype.toJSON !== 'function') {

        Date.prototype.toJSON = function (key) {

            return this.getUTCFullYear()   + '-' +
                 f(this.getUTCMonth() + 1) + '-' +
                 f(this.getUTCDate())      + 'T' +
                 f(this.getUTCHours())     + ':' +
                 f(this.getUTCMinutes())   + ':' +
                 f(this.getUTCSeconds())   + 'Z';
        };

        String.prototype.toJSON =
        Number.prototype.toJSON =
        Boolean.prototype.toJSON = function (key) {
            return this.valueOf();
        };
    }

    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        gap,
        indent,
        meta = {    // table of character substitutions
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        rep;


    function quote(string) {

// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.

        escapable.lastIndex = 0;
        return escapable.test(string) ?
            '"' + string.replace(escapable, function (a) {
                var c = meta[a];
                if (typeof c === 'string') {
                    return c;
                }
                return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
            }) + '"' :
            '"' + string + '"';
    }


    function str(key, holder) {

// Produce a string from holder[key].

        var i,          // The loop counter.
            k,          // The member key.
            v,          // The member value.
            length,
            mind = gap,
            partial,
            value = holder[key];

// If the value has a toJSON method, call it to obtain a replacement value.

        if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }

// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.

        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }

// What happens next depends on the value's type.

        switch (typeof value) {
        case 'string':
            return quote(value);

        case 'number':

// JSON numbers must be finite. Encode non-finite numbers as null.

            return isFinite(value) ? String(value) : 'null';

        case 'boolean':
        case 'null':

// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.

            return String(value);

// If the type is 'object', we might be dealing with an object or an array or
// null.

        case 'object':

// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.

            if (!value) {
                return 'null';
            }

// Make an array to hold the partial results of stringifying this object value.

            gap += indent;
            partial = [];

// If the object has a dontEnum length property, we'll treat it as an array.

            if (typeof value.length === 'number' &&
                    !value.propertyIsEnumerable('length')) {

// The object is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.

                length = value.length;
                for (i = 0; i < length; i += 1) {
                    partial[i] = str(i, value) || 'null';
                }

// Join all of the elements together, separated with commas, and wrap them in
// brackets.

                v = partial.length === 0 ? '[]' :
                    gap ? '[\n' + gap +
                            partial.join(',\n' + gap) + '\n' +
                                mind + ']' :
                          '[' + partial.join(',') + ']';
                gap = mind;
                return v;
            }

// If the replacer is an array, use it to select the members to be stringified.

            if (rep && typeof rep === 'object') {
                length = rep.length;
                for (i = 0; i < length; i += 1) {
                    k = rep[i];
                    if (typeof k === 'string') {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            } else {

// Otherwise, iterate through all of the keys in the object.

                for (k in value) {
                    if (Object.hasOwnProperty.call(value, k)) {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
                        }
                    }
                }
            }

// Join all of the member texts together, separated with commas,
// and wrap them in braces.

            v = partial.length === 0 ? '{}' :
                gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                        mind + '}' : '{' + partial.join(',') + '}';
            gap = mind;
            return v;
        }
    }

// If the JSON object does not yet have a stringify method, give it one.

    if (typeof JSON.stringify !== 'function') {
        JSON.stringify = function (value, replacer, space) {

// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.

            var i;
            gap = '';
            indent = '';

// If the space parameter is a number, make an indent string containing that
// many spaces.

            if (typeof space === 'number') {
                for (i = 0; i < space; i += 1) {
                    indent += ' ';
                }

// If the space parameter is a string, it will be used as the indent string.

            } else if (typeof space === 'string') {
                indent = space;
            }

// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.

            rep = replacer;
            if (replacer && typeof replacer !== 'function' &&
                    (typeof replacer !== 'object' ||
                     typeof replacer.length !== 'number')) {
                throw new Error('JSON.stringify');
            }

// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.

            return str('', {'': value});
        };
    }


// If the JSON object does not yet have a parse method, give it one.

    if (typeof JSON.parse !== 'function') {
        JSON.parse = function (text, reviver) {

// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.

            var j;

            function walk(holder, key) {

// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.

                var k, v, value = holder[key];
                if (value && typeof value === 'object') {
                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }


// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.

            cx.lastIndex = 0;
            if (cx.test(text)) {
                text = text.replace(cx, function (a) {
                    return '\\u' +
                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }

// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.

// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

            if (/^[\],:{}\s]*$/.
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

                j = eval('(' + text + ')');

// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.

                return typeof reviver === 'function' ?
                    walk({'': j}, '') : j;
            }

// If the text is not JSON parseable, then a SyntaxError is thrown.

            throw new SyntaxError('JSON.parse');
        };
    }
})();
 
 
/*
 * jQuery JavaScript Library v1.3.1
 * http://jquery.com/
 *
 * Copyright (c) 2009 John Resig
 * Dual licensed under the MIT and GPL licenses.
 * http://docs.jquery.com/License
 *
 * Date: 2009-01-21 20:42:16 -0500 (Wed, 21 Jan 2009)
 * Revision: 6158
 */
(function(){var l=this,g,y=l.jQuery,p=l.$,o=l.jQuery=l.$=function(E,F){return new o.fn.init(E,F)},D=/^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,f=/^.[^:#\[\.,]*$/;o.fn=o.prototype={init:function(E,H){E=E||document;if(E.nodeType){this[0]=E;this.length=1;this.context=E;return this}if(typeof E==="string"){var G=D.exec(E);if(G&&(G[1]||!H)){if(G[1]){E=o.clean([G[1]],H)}else{var I=document.getElementById(G[3]);if(I&&I.id!=G[3]){return o().find(E)}var F=o(I||[]);F.context=document;F.selector=E;return F}}else{return o(H).find(E)}}else{if(o.isFunction(E)){return o(document).ready(E)}}if(E.selector&&E.context){this.selector=E.selector;this.context=E.context}return this.setArray(o.makeArray(E))},selector:"",jquery:"1.3.1",size:function(){return this.length},get:function(E){return E===g?o.makeArray(this):this[E]},pushStack:function(F,H,E){var G=o(F);G.prevObject=this;G.context=this.context;if(H==="find"){G.selector=this.selector+(this.selector?" ":"")+E}else{if(H){G.selector=this.selector+"."+H+"("+E+")"}}return G},setArray:function(E){this.length=0;Array.prototype.push.apply(this,E);return this},each:function(F,E){return o.each(this,F,E)},index:function(E){return o.inArray(E&&E.jquery?E[0]:E,this)},attr:function(F,H,G){var E=F;if(typeof F==="string"){if(H===g){return this[0]&&o[G||"attr"](this[0],F)}else{E={};E[F]=H}}return this.each(function(I){for(F in E){o.attr(G?this.style:this,F,o.prop(this,E[F],G,I,F))}})},css:function(E,F){if((E=="width"||E=="height")&&parseFloat(F)<0){F=g}return this.attr(E,F,"curCSS")},text:function(F){if(typeof F!=="object"&&F!=null){return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(F))}var E="";o.each(F||this,function(){o.each(this.childNodes,function(){if(this.nodeType!=8){E+=this.nodeType!=1?this.nodeValue:o.fn.text([this])}})});return E},wrapAll:function(E){if(this[0]){var F=o(E,this[0].ownerDocument).clone();if(this[0].parentNode){F.insertBefore(this[0])}F.map(function(){var G=this;while(G.firstChild){G=G.firstChild}return G}).append(this)}return this},wrapInner:function(E){return this.each(function(){o(this).contents().wrapAll(E)})},wrap:function(E){return this.each(function(){o(this).wrapAll(E)})},append:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.appendChild(E)}})},prepend:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.insertBefore(E,this.firstChild)}})},before:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this)})},after:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this.nextSibling)})},end:function(){return this.prevObject||o([])},push:[].push,find:function(E){if(this.length===1&&!/,/.test(E)){var G=this.pushStack([],"find",E);G.length=0;o.find(E,this[0],G);return G}else{var F=o.map(this,function(H){return o.find(E,H)});return this.pushStack(/[^+>] [^+>]/.test(E)?o.unique(F):F,"find",E)}},clone:function(F){var E=this.map(function(){if(!o.support.noCloneEvent&&!o.isXMLDoc(this)){var I=this.cloneNode(true),H=document.createElement("div");H.appendChild(I);return o.clean([H.innerHTML])[0]}else{return this.cloneNode(true)}});var G=E.find("*").andSelf().each(function(){if(this[h]!==g){this[h]=null}});if(F===true){this.find("*").andSelf().each(function(I){if(this.nodeType==3){return}var H=o.data(this,"events");for(var K in H){for(var J in H[K]){o.event.add(G[I],K,H[K][J],H[K][J].data)}}})}return E},filter:function(E){return this.pushStack(o.isFunction(E)&&o.grep(this,function(G,F){return E.call(G,F)})||o.multiFilter(E,o.grep(this,function(F){return F.nodeType===1})),"filter",E)},closest:function(E){var F=o.expr.match.POS.test(E)?o(E):null;return this.map(function(){var G=this;while(G&&G.ownerDocument){if(F?F.index(G)>-1:o(G).is(E)){return G}G=G.parentNode}})},not:function(E){if(typeof E==="string"){if(f.test(E)){return this.pushStack(o.multiFilter(E,this,true),"not",E)}else{E=o.multiFilter(E,this)}}var F=E.length&&E[E.length-1]!==g&&!E.nodeType;return this.filter(function(){return F?o.inArray(this,E)<0:this!=E})},add:function(E){return this.pushStack(o.unique(o.merge(this.get(),typeof E==="string"?o(E):o.makeArray(E))))},is:function(E){return !!E&&o.multiFilter(E,this).length>0},hasClass:function(E){return !!E&&this.is("."+E)},val:function(K){if(K===g){var E=this[0];if(E){if(o.nodeName(E,"option")){return(E.attributes.value||{}).specified?E.value:E.text}if(o.nodeName(E,"select")){var I=E.selectedIndex,L=[],M=E.options,H=E.type=="select-one";if(I<0){return null}for(var F=H?I:0,J=H?I+1:M.length;F<J;F++){var G=M[F];if(G.selected){K=o(G).val();if(H){return K}L.push(K)}}return L}return(E.value||"").replace(/\r/g,"")}return g}if(typeof K==="number"){K+=""}return this.each(function(){if(this.nodeType!=1){return}if(o.isArray(K)&&/radio|checkbox/.test(this.type)){this.checked=(o.inArray(this.value,K)>=0||o.inArray(this.name,K)>=0)}else{if(o.nodeName(this,"select")){var N=o.makeArray(K);o("option",this).each(function(){this.selected=(o.inArray(this.value,N)>=0||o.inArray(this.text,N)>=0)});if(!N.length){this.selectedIndex=-1}}else{this.value=K}}})},html:function(E){return E===g?(this[0]?this[0].innerHTML:null):this.empty().append(E)},replaceWith:function(E){return this.after(E).remove()},eq:function(E){return this.slice(E,+E+1)},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments),"slice",Array.prototype.slice.call(arguments).join(","))},map:function(E){return this.pushStack(o.map(this,function(G,F){return E.call(G,F,G)}))},andSelf:function(){return this.add(this.prevObject)},domManip:function(K,N,M){if(this[0]){var J=(this[0].ownerDocument||this[0]).createDocumentFragment(),G=o.clean(K,(this[0].ownerDocument||this[0]),J),I=J.firstChild,E=this.length>1?J.cloneNode(true):J;if(I){for(var H=0,F=this.length;H<F;H++){M.call(L(this[H],I),H>0?E.cloneNode(true):J)}}if(G){o.each(G,z)}}return this;function L(O,P){return N&&o.nodeName(O,"table")&&o.nodeName(P,"tr")?(O.getElementsByTagName("tbody")[0]||O.appendChild(O.ownerDocument.createElement("tbody"))):O}}};o.fn.init.prototype=o.fn;function z(E,F){if(F.src){o.ajax({url:F.src,async:false,dataType:"script"})}else{o.globalEval(F.text||F.textContent||F.innerHTML||"")}if(F.parentNode){F.parentNode.removeChild(F)}}function e(){return +new Date}o.extend=o.fn.extend=function(){var J=arguments[0]||{},H=1,I=arguments.length,E=false,G;if(typeof J==="boolean"){E=J;J=arguments[1]||{};H=2}if(typeof J!=="object"&&!o.isFunction(J)){J={}}if(I==H){J=this;--H}for(;H<I;H++){if((G=arguments[H])!=null){for(var F in G){var K=J[F],L=G[F];if(J===L){continue}if(E&&L&&typeof L==="object"&&!L.nodeType){J[F]=o.extend(E,K||(L.length!=null?[]:{}),L)}else{if(L!==g){J[F]=L}}}}}return J};var b=/z-?index|font-?weight|opacity|zoom|line-?height/i,q=document.defaultView||{},s=Object.prototype.toString;o.extend({noConflict:function(E){l.$=p;if(E){l.jQuery=y}return o},isFunction:function(E){return s.call(E)==="[object Function]"},isArray:function(E){return s.call(E)==="[object Array]"},isXMLDoc:function(E){return E.nodeType===9&&E.documentElement.nodeName!=="HTML"||!!E.ownerDocument&&o.isXMLDoc(E.ownerDocument)},globalEval:function(G){G=o.trim(G);if(G){var F=document.getElementsByTagName("head")[0]||document.documentElement,E=document.createElement("script");E.type="text/javascript";if(o.support.scriptEval){E.appendChild(document.createTextNode(G))}else{E.text=G}F.insertBefore(E,F.firstChild);F.removeChild(E)}},nodeName:function(F,E){return F.nodeName&&F.nodeName.toUpperCase()==E.toUpperCase()},each:function(G,K,F){var E,H=0,I=G.length;if(F){if(I===g){for(E in G){if(K.apply(G[E],F)===false){break}}}else{for(;H<I;){if(K.apply(G[H++],F)===false){break}}}}else{if(I===g){for(E in G){if(K.call(G[E],E,G[E])===false){break}}}else{for(var J=G[0];H<I&&K.call(J,H,J)!==false;J=G[++H]){}}}return G},prop:function(H,I,G,F,E){if(o.isFunction(I)){I=I.call(H,F)}return typeof I==="number"&&G=="curCSS"&&!b.test(E)?I+"px":I},className:{add:function(E,F){o.each((F||"").split(/\s+/),function(G,H){if(E.nodeType==1&&!o.className.has(E.className,H)){E.className+=(E.className?" ":"")+H}})},remove:function(E,F){if(E.nodeType==1){E.className=F!==g?o.grep(E.className.split(/\s+/),function(G){return !o.className.has(F,G)}).join(" "):""}},has:function(F,E){return F&&o.inArray(E,(F.className||F).toString().split(/\s+/))>-1}},swap:function(H,G,I){var E={};for(var F in G){E[F]=H.style[F];H.style[F]=G[F]}I.call(H);for(var F in G){H.style[F]=E[F]}},css:function(G,E,I){if(E=="width"||E=="height"){var K,F={position:"absolute",visibility:"hidden",display:"block"},J=E=="width"?["Left","Right"]:["Top","Bottom"];function H(){K=E=="width"?G.offsetWidth:G.offsetHeight;var M=0,L=0;o.each(J,function(){M+=parseFloat(o.curCSS(G,"padding"+this,true))||0;L+=parseFloat(o.curCSS(G,"border"+this+"Width",true))||0});K-=Math.round(M+L)}if(o(G).is(":visible")){H()}else{o.swap(G,F,H)}return Math.max(0,K)}return o.curCSS(G,E,I)},curCSS:function(I,F,G){var L,E=I.style;if(F=="opacity"&&!o.support.opacity){L=o.attr(E,"opacity");return L==""?"1":L}if(F.match(/float/i)){F=w}if(!G&&E&&E[F]){L=E[F]}else{if(q.getComputedStyle){if(F.match(/float/i)){F="float"}F=F.replace(/([A-Z])/g,"-$1").toLowerCase();var M=q.getComputedStyle(I,null);if(M){L=M.getPropertyValue(F)}if(F=="opacity"&&L==""){L="1"}}else{if(I.currentStyle){var J=F.replace(/\-(\w)/g,function(N,O){return O.toUpperCase()});L=I.currentStyle[F]||I.currentStyle[J];if(!/^\d+(px)?$/i.test(L)&&/^\d/.test(L)){var H=E.left,K=I.runtimeStyle.left;I.runtimeStyle.left=I.currentStyle.left;E.left=L||0;L=E.pixelLeft+"px";E.left=H;I.runtimeStyle.left=K}}}}return L},clean:function(F,K,I){K=K||document;if(typeof K.createElement==="undefined"){K=K.ownerDocument||K[0]&&K[0].ownerDocument||document}if(!I&&F.length===1&&typeof F[0]==="string"){var H=/^<(\w+)\s*\/?>$/.exec(F[0]);if(H){return[K.createElement(H[1])]}}var G=[],E=[],L=K.createElement("div");o.each(F,function(P,R){if(typeof R==="number"){R+=""}if(!R){return}if(typeof R==="string"){R=R.replace(/(<(\w+)[^>]*?)\/>/g,function(T,U,S){return S.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?T:U+"></"+S+">"});var O=o.trim(R).toLowerCase();var Q=!O.indexOf("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!O.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||O.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!O.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!O.indexOf("<td")||!O.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!O.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||!o.support.htmlSerialize&&[1,"div<div>","</div>"]||[0,"",""];L.innerHTML=Q[1]+R+Q[2];while(Q[0]--){L=L.lastChild}if(!o.support.tbody){var N=!O.indexOf("<table")&&O.indexOf("<tbody")<0?L.firstChild&&L.firstChild.childNodes:Q[1]=="<table>"&&O.indexOf("<tbody")<0?L.childNodes:[];for(var M=N.length-1;M>=0;--M){if(o.nodeName(N[M],"tbody")&&!N[M].childNodes.length){N[M].parentNode.removeChild(N[M])}}}if(!o.support.leadingWhitespace&&/^\s/.test(R)){L.insertBefore(K.createTextNode(R.match(/^\s*/)[0]),L.firstChild)}R=o.makeArray(L.childNodes)}if(R.nodeType){G.push(R)}else{G=o.merge(G,R)}});if(I){for(var J=0;G[J];J++){if(o.nodeName(G[J],"script")&&(!G[J].type||G[J].type.toLowerCase()==="text/javascript")){E.push(G[J].parentNode?G[J].parentNode.removeChild(G[J]):G[J])}else{if(G[J].nodeType===1){G.splice.apply(G,[J+1,0].concat(o.makeArray(G[J].getElementsByTagName("script"))))}I.appendChild(G[J])}}return E}return G},attr:function(J,G,K){if(!J||J.nodeType==3||J.nodeType==8){return g}var H=!o.isXMLDoc(J),L=K!==g;G=H&&o.props[G]||G;if(J.tagName){var F=/href|src|style/.test(G);if(G=="selected"&&J.parentNode){J.parentNode.selectedIndex}if(G in J&&H&&!F){if(L){if(G=="type"&&o.nodeName(J,"input")&&J.parentNode){throw"type property can't be changed"}J[G]=K}if(o.nodeName(J,"form")&&J.getAttributeNode(G)){return J.getAttributeNode(G).nodeValue}if(G=="tabIndex"){var I=J.getAttributeNode("tabIndex");return I&&I.specified?I.value:J.nodeName.match(/(button|input|object|select|textarea)/i)?0:J.nodeName.match(/^(a|area)$/i)&&J.href?0:g}return J[G]}if(!o.support.style&&H&&G=="style"){return o.attr(J.style,"cssText",K)}if(L){J.setAttribute(G,""+K)}var E=!o.support.hrefNormalized&&H&&F?J.getAttribute(G,2):J.getAttribute(G);return E===null?g:E}if(!o.support.opacity&&G=="opacity"){if(L){J.zoom=1;J.filter=(J.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(K)+""=="NaN"?"":"alpha(opacity="+K*100+")")}return J.filter&&J.filter.indexOf("opacity=")>=0?(parseFloat(J.filter.match(/opacity=([^)]*)/)[1])/100)+"":""}G=G.replace(/-([a-z])/ig,function(M,N){return N.toUpperCase()});if(L){J[G]=K}return J[G]},trim:function(E){return(E||"").replace(/^\s+|\s+$/g,"")},makeArray:function(G){var E=[];if(G!=null){var F=G.length;if(F==null||typeof G==="string"||o.isFunction(G)||G.setInterval){E[0]=G}else{while(F){E[--F]=G[F]}}}return E},inArray:function(G,H){for(var E=0,F=H.length;E<F;E++){if(H[E]===G){return E}}return -1},merge:function(H,E){var F=0,G,I=H.length;if(!o.support.getAll){while((G=E[F++])!=null){if(G.nodeType!=8){H[I++]=G}}}else{while((G=E[F++])!=null){H[I++]=G}}return H},unique:function(K){var F=[],E={};try{for(var G=0,H=K.length;G<H;G++){var J=o.data(K[G]);if(!E[J]){E[J]=true;F.push(K[G])}}}catch(I){F=K}return F},grep:function(F,J,E){var G=[];for(var H=0,I=F.length;H<I;H++){if(!E!=!J(F[H],H)){G.push(F[H])}}return G},map:function(E,J){var F=[];for(var G=0,H=E.length;G<H;G++){var I=J(E[G],G);if(I!=null){F[F.length]=I}}return F.concat.apply([],F)}});var C=navigator.userAgent.toLowerCase();o.browser={version:(C.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[0,"0"])[1],safari:/webkit/.test(C),opera:/opera/.test(C),msie:/msie/.test(C)&&!/opera/.test(C),mozilla:/mozilla/.test(C)&&!/(compatible|webkit)/.test(C)};o.each({parent:function(E){return E.parentNode},parents:function(E){return o.dir(E,"parentNode")},next:function(E){return o.nth(E,2,"nextSibling")},prev:function(E){return o.nth(E,2,"previousSibling")},nextAll:function(E){return o.dir(E,"nextSibling")},prevAll:function(E){return o.dir(E,"previousSibling")},siblings:function(E){return o.sibling(E.parentNode.firstChild,E)},children:function(E){return o.sibling(E.firstChild)},contents:function(E){return o.nodeName(E,"iframe")?E.contentDocument||E.contentWindow.document:o.makeArray(E.childNodes)}},function(E,F){o.fn[E]=function(G){var H=o.map(this,F);if(G&&typeof G=="string"){H=o.multiFilter(G,H)}return this.pushStack(o.unique(H),E,G)}});o.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(E,F){o.fn[E]=function(){var G=arguments;return this.each(function(){for(var H=0,I=G.length;H<I;H++){o(G[H])[F](this)}})}});o.each({removeAttr:function(E){o.attr(this,E,"");if(this.nodeType==1){this.removeAttribute(E)}},addClass:function(E){o.className.add(this,E)},removeClass:function(E){o.className.remove(this,E)},toggleClass:function(F,E){if(typeof E!=="boolean"){E=!o.className.has(this,F)}o.className[E?"add":"remove"](this,F)},remove:function(E){if(!E||o.filter(E,[this]).length){o("*",this).add([this]).each(function(){o.event.remove(this);o.removeData(this)});if(this.parentNode){this.parentNode.removeChild(this)}}},empty:function(){o(">*",this).remove();while(this.firstChild){this.removeChild(this.firstChild)}}},function(E,F){o.fn[E]=function(){return this.each(F,arguments)}});function j(E,F){return E[0]&&parseInt(o.curCSS(E[0],F,true),10)||0}var h="jQuery"+e(),v=0,A={};o.extend({cache:{},data:function(F,E,G){F=F==l?A:F;var H=F[h];if(!H){H=F[h]=++v}if(E&&!o.cache[H]){o.cache[H]={}}if(G!==g){o.cache[H][E]=G}return E?o.cache[H][E]:H},removeData:function(F,E){F=F==l?A:F;var H=F[h];if(E){if(o.cache[H]){delete o.cache[H][E];E="";for(E in o.cache[H]){break}if(!E){o.removeData(F)}}}else{try{delete F[h]}catch(G){if(F.removeAttribute){F.removeAttribute(h)}}delete o.cache[H]}},queue:function(F,E,H){if(F){E=(E||"fx")+"queue";var G=o.data(F,E);if(!G||o.isArray(H)){G=o.data(F,E,o.makeArray(H))}else{if(H){G.push(H)}}}return G},dequeue:function(H,G){var E=o.queue(H,G),F=E.shift();if(!G||G==="fx"){F=E[0]}if(F!==g){F.call(H)}}});o.fn.extend({data:function(E,G){var H=E.split(".");H[1]=H[1]?"."+H[1]:"";if(G===g){var F=this.triggerHandler("getData"+H[1]+"!",[H[0]]);if(F===g&&this.length){F=o.data(this[0],E)}return F===g&&H[1]?this.data(H[0]):F}else{return this.trigger("setData"+H[1]+"!",[H[0],G]).each(function(){o.data(this,E,G)})}},removeData:function(E){return this.each(function(){o.removeData(this,E)})},queue:function(E,F){if(typeof E!=="string"){F=E;E="fx"}if(F===g){return o.queue(this[0],E)}return this.each(function(){var G=o.queue(this,E,F);if(E=="fx"&&G.length==1){G[0].call(this)}})},dequeue:function(E){return this.each(function(){o.dequeue(this,E)})}});
/*
 * Sizzle CSS Selector Engine - v0.9.3
 *  Copyright 2009, The Dojo Foundation
 *  Released under the MIT, BSD, and GPL Licenses.
 *  More information: http://sizzlejs.com/
 */
(function(){var Q=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]+['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[]+)+|[>+~])(\s*,\s*)?/g,K=0,G=Object.prototype.toString;var F=function(X,T,aa,ab){aa=aa||[];T=T||document;if(T.nodeType!==1&&T.nodeType!==9){return[]}if(!X||typeof X!=="string"){return aa}var Y=[],V,ae,ah,S,ac,U,W=true;Q.lastIndex=0;while((V=Q.exec(X))!==null){Y.push(V[1]);if(V[2]){U=RegExp.rightContext;break}}if(Y.length>1&&L.exec(X)){if(Y.length===2&&H.relative[Y[0]]){ae=I(Y[0]+Y[1],T)}else{ae=H.relative[Y[0]]?[T]:F(Y.shift(),T);while(Y.length){X=Y.shift();if(H.relative[X]){X+=Y.shift()}ae=I(X,ae)}}}else{var ad=ab?{expr:Y.pop(),set:E(ab)}:F.find(Y.pop(),Y.length===1&&T.parentNode?T.parentNode:T,P(T));ae=F.filter(ad.expr,ad.set);if(Y.length>0){ah=E(ae)}else{W=false}while(Y.length){var ag=Y.pop(),af=ag;if(!H.relative[ag]){ag=""}else{af=Y.pop()}if(af==null){af=T}H.relative[ag](ah,af,P(T))}}if(!ah){ah=ae}if(!ah){throw"Syntax error, unrecognized expression: "+(ag||X)}if(G.call(ah)==="[object Array]"){if(!W){aa.push.apply(aa,ah)}else{if(T.nodeType===1){for(var Z=0;ah[Z]!=null;Z++){if(ah[Z]&&(ah[Z]===true||ah[Z].nodeType===1&&J(T,ah[Z]))){aa.push(ae[Z])}}}else{for(var Z=0;ah[Z]!=null;Z++){if(ah[Z]&&ah[Z].nodeType===1){aa.push(ae[Z])}}}}}else{E(ah,aa)}if(U){F(U,T,aa,ab)}return aa};F.matches=function(S,T){return F(S,null,null,T)};F.find=function(Z,S,aa){var Y,W;if(!Z){return[]}for(var V=0,U=H.order.length;V<U;V++){var X=H.order[V],W;if((W=H.match[X].exec(Z))){var T=RegExp.leftContext;if(T.substr(T.length-1)!=="\\"){W[1]=(W[1]||"").replace(/\\/g,"");Y=H.find[X](W,S,aa);if(Y!=null){Z=Z.replace(H.match[X],"");break}}}}if(!Y){Y=S.getElementsByTagName("*")}return{set:Y,expr:Z}};F.filter=function(ab,aa,ae,V){var U=ab,ag=[],Y=aa,X,S;while(ab&&aa.length){for(var Z in H.filter){if((X=H.match[Z].exec(ab))!=null){var T=H.filter[Z],af,ad;S=false;if(Y==ag){ag=[]}if(H.preFilter[Z]){X=H.preFilter[Z](X,Y,ae,ag,V);if(!X){S=af=true}else{if(X===true){continue}}}if(X){for(var W=0;(ad=Y[W])!=null;W++){if(ad){af=T(ad,X,W,Y);var ac=V^!!af;if(ae&&af!=null){if(ac){S=true}else{Y[W]=false}}else{if(ac){ag.push(ad);S=true}}}}}if(af!==g){if(!ae){Y=ag}ab=ab.replace(H.match[Z],"");if(!S){return[]}break}}}ab=ab.replace(/\s*,\s*/,"");if(ab==U){if(S==null){throw"Syntax error, unrecognized expression: "+ab}else{break}}U=ab}return Y};var H=F.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF_-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF_-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*_-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF_-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(S){return S.getAttribute("href")}},relative:{"+":function(W,T){for(var U=0,S=W.length;U<S;U++){var V=W[U];if(V){var X=V.previousSibling;while(X&&X.nodeType!==1){X=X.previousSibling}W[U]=typeof T==="string"?X||false:X===T}}if(typeof T==="string"){F.filter(T,W,true)}},">":function(X,T,Y){if(typeof T==="string"&&!/\W/.test(T)){T=Y?T:T.toUpperCase();for(var U=0,S=X.length;U<S;U++){var W=X[U];if(W){var V=W.parentNode;X[U]=V.nodeName===T?V:false}}}else{for(var U=0,S=X.length;U<S;U++){var W=X[U];if(W){X[U]=typeof T==="string"?W.parentNode:W.parentNode===T}}if(typeof T==="string"){F.filter(T,X,true)}}},"":function(V,T,X){var U="done"+(K++),S=R;if(!T.match(/\W/)){var W=T=X?T:T.toUpperCase();S=O}S("parentNode",T,U,V,W,X)},"~":function(V,T,X){var U="done"+(K++),S=R;if(typeof T==="string"&&!T.match(/\W/)){var W=T=X?T:T.toUpperCase();S=O}S("previousSibling",T,U,V,W,X)}},find:{ID:function(T,U,V){if(typeof U.getElementById!=="undefined"&&!V){var S=U.getElementById(T[1]);return S?[S]:[]}},NAME:function(S,T,U){if(typeof T.getElementsByName!=="undefined"&&!U){return T.getElementsByName(S[1])}},TAG:function(S,T){return T.getElementsByTagName(S[1])}},preFilter:{CLASS:function(V,T,U,S,Y){V=" "+V[1].replace(/\\/g,"")+" ";var X;for(var W=0;(X=T[W])!=null;W++){if(X){if(Y^(" "+X.className+" ").indexOf(V)>=0){if(!U){S.push(X)}}else{if(U){T[W]=false}}}}return false},ID:function(S){return S[1].replace(/\\/g,"")},TAG:function(T,S){for(var U=0;S[U]===false;U++){}return S[U]&&P(S[U])?T[1]:T[1].toUpperCase()},CHILD:function(S){if(S[1]=="nth"){var T=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(S[2]=="even"&&"2n"||S[2]=="odd"&&"2n+1"||!/\D/.test(S[2])&&"0n+"+S[2]||S[2]);S[2]=(T[1]+(T[2]||1))-0;S[3]=T[3]-0}S[0]="done"+(K++);return S},ATTR:function(T){var S=T[1].replace(/\\/g,"");if(H.attrMap[S]){T[1]=H.attrMap[S]}if(T[2]==="~="){T[4]=" "+T[4]+" "}return T},PSEUDO:function(W,T,U,S,X){if(W[1]==="not"){if(W[3].match(Q).length>1){W[3]=F(W[3],null,null,T)}else{var V=F.filter(W[3],T,U,true^X);if(!U){S.push.apply(S,V)}return false}}else{if(H.match.POS.test(W[0])){return true}}return W},POS:function(S){S.unshift(true);return S}},filters:{enabled:function(S){return S.disabled===false&&S.type!=="hidden"},disabled:function(S){return S.disabled===true},checked:function(S){return S.checked===true},selected:function(S){S.parentNode.selectedIndex;return S.selected===true},parent:function(S){return !!S.firstChild},empty:function(S){return !S.firstChild},has:function(U,T,S){return !!F(S[3],U).length},header:function(S){return/h\d/i.test(S.nodeName)},text:function(S){return"text"===S.type},radio:function(S){return"radio"===S.type},checkbox:function(S){return"checkbox"===S.type},file:function(S){return"file"===S.type},password:function(S){return"password"===S.type},submit:function(S){return"submit"===S.type},image:function(S){return"image"===S.type},reset:function(S){return"reset"===S.type},button:function(S){return"button"===S.type||S.nodeName.toUpperCase()==="BUTTON"},input:function(S){return/input|select|textarea|button/i.test(S.nodeName)}},setFilters:{first:function(T,S){return S===0},last:function(U,T,S,V){return T===V.length-1},even:function(T,S){return S%2===0},odd:function(T,S){return S%2===1},lt:function(U,T,S){return T<S[3]-0},gt:function(U,T,S){return T>S[3]-0},nth:function(U,T,S){return S[3]-0==T},eq:function(U,T,S){return S[3]-0==T}},filter:{CHILD:function(S,V){var Y=V[1],Z=S.parentNode;var X=V[0];if(Z&&(!Z[X]||!S.nodeIndex)){var W=1;for(var T=Z.firstChild;T;T=T.nextSibling){if(T.nodeType==1){T.nodeIndex=W++}}Z[X]=W-1}if(Y=="first"){return S.nodeIndex==1}else{if(Y=="last"){return S.nodeIndex==Z[X]}else{if(Y=="only"){return Z[X]==1}else{if(Y=="nth"){var ab=false,U=V[2],aa=V[3];if(U==1&&aa==0){return true}if(U==0){if(S.nodeIndex==aa){ab=true}}else{if((S.nodeIndex-aa)%U==0&&(S.nodeIndex-aa)/U>=0){ab=true}}return ab}}}}},PSEUDO:function(Y,U,V,Z){var T=U[1],W=H.filters[T];if(W){return W(Y,V,U,Z)}else{if(T==="contains"){return(Y.textContent||Y.innerText||"").indexOf(U[3])>=0}else{if(T==="not"){var X=U[3];for(var V=0,S=X.length;V<S;V++){if(X[V]===Y){return false}}return true}}}},ID:function(T,S){return T.nodeType===1&&T.getAttribute("id")===S},TAG:function(T,S){return(S==="*"&&T.nodeType===1)||T.nodeName===S},CLASS:function(T,S){return S.test(T.className)},ATTR:function(W,U){var S=H.attrHandle[U[1]]?H.attrHandle[U[1]](W):W[U[1]]||W.getAttribute(U[1]),X=S+"",V=U[2],T=U[4];return S==null?V==="!=":V==="="?X===T:V==="*="?X.indexOf(T)>=0:V==="~="?(" "+X+" ").indexOf(T)>=0:!U[4]?S:V==="!="?X!=T:V==="^="?X.indexOf(T)===0:V==="$="?X.substr(X.length-T.length)===T:V==="|="?X===T||X.substr(0,T.length+1)===T+"-":false},POS:function(W,T,U,X){var S=T[2],V=H.setFilters[S];if(V){return V(W,U,T,X)}}}};var L=H.match.POS;for(var N in H.match){H.match[N]=RegExp(H.match[N].source+/(?![^\[]*\])(?![^\(]*\))/.source)}var E=function(T,S){T=Array.prototype.slice.call(T);if(S){S.push.apply(S,T);return S}return T};try{Array.prototype.slice.call(document.documentElement.childNodes)}catch(M){E=function(W,V){var T=V||[];if(G.call(W)==="[object Array]"){Array.prototype.push.apply(T,W)}else{if(typeof W.length==="number"){for(var U=0,S=W.length;U<S;U++){T.push(W[U])}}else{for(var U=0;W[U];U++){T.push(W[U])}}}return T}}(function(){var T=document.createElement("form"),U="script"+(new Date).getTime();T.innerHTML="<input name='"+U+"'/>";var S=document.documentElement;S.insertBefore(T,S.firstChild);if(!!document.getElementById(U)){H.find.ID=function(W,X,Y){if(typeof X.getElementById!=="undefined"&&!Y){var V=X.getElementById(W[1]);return V?V.id===W[1]||typeof V.getAttributeNode!=="undefined"&&V.getAttributeNode("id").nodeValue===W[1]?[V]:g:[]}};H.filter.ID=function(X,V){var W=typeof X.getAttributeNode!=="undefined"&&X.getAttributeNode("id");return X.nodeType===1&&W&&W.nodeValue===V}}S.removeChild(T)})();(function(){var S=document.createElement("div");S.appendChild(document.createComment(""));if(S.getElementsByTagName("*").length>0){H.find.TAG=function(T,X){var W=X.getElementsByTagName(T[1]);if(T[1]==="*"){var V=[];for(var U=0;W[U];U++){if(W[U].nodeType===1){V.push(W[U])}}W=V}return W}}S.innerHTML="<a href='#'></a>";if(S.firstChild&&S.firstChild.getAttribute("href")!=="#"){H.attrHandle.href=function(T){return T.getAttribute("href",2)}}})();if(document.querySelectorAll){(function(){var S=F,T=document.createElement("div");T.innerHTML="<p class='TEST'></p>";if(T.querySelectorAll&&T.querySelectorAll(".TEST").length===0){return}F=function(X,W,U,V){W=W||document;if(!V&&W.nodeType===9&&!P(W)){try{return E(W.querySelectorAll(X),U)}catch(Y){}}return S(X,W,U,V)};F.find=S.find;F.filter=S.filter;F.selectors=S.selectors;F.matches=S.matches})()}if(document.getElementsByClassName&&document.documentElement.getElementsByClassName){H.order.splice(1,0,"CLASS");H.find.CLASS=function(S,T){return T.getElementsByClassName(S[1])}}function O(T,Z,Y,ac,aa,ab){for(var W=0,U=ac.length;W<U;W++){var S=ac[W];if(S){S=S[T];var X=false;while(S&&S.nodeType){var V=S[Y];if(V){X=ac[V];break}if(S.nodeType===1&&!ab){S[Y]=W}if(S.nodeName===Z){X=S;break}S=S[T]}ac[W]=X}}}function R(T,Y,X,ab,Z,aa){for(var V=0,U=ab.length;V<U;V++){var S=ab[V];if(S){S=S[T];var W=false;while(S&&S.nodeType){if(S[X]){W=ab[S[X]];break}if(S.nodeType===1){if(!aa){S[X]=V}if(typeof Y!=="string"){if(S===Y){W=true;break}}else{if(F.filter(Y,[S]).length>0){W=S;break}}}S=S[T]}ab[V]=W}}}var J=document.compareDocumentPosition?function(T,S){return T.compareDocumentPosition(S)&16}:function(T,S){return T!==S&&(T.contains?T.contains(S):true)};var P=function(S){return S.nodeType===9&&S.documentElement.nodeName!=="HTML"||!!S.ownerDocument&&P(S.ownerDocument)};var I=function(S,Z){var V=[],W="",X,U=Z.nodeType?[Z]:Z;while((X=H.match.PSEUDO.exec(S))){W+=X[0];S=S.replace(H.match.PSEUDO,"")}S=H.relative[S]?S+"*":S;for(var Y=0,T=U.length;Y<T;Y++){F(S,U[Y],V)}return F.filter(W,V)};o.find=F;o.filter=F.filter;o.expr=F.selectors;o.expr[":"]=o.expr.filters;F.selectors.filters.hidden=function(S){return"hidden"===S.type||o.css(S,"display")==="none"||o.css(S,"visibility")==="hidden"};F.selectors.filters.visible=function(S){return"hidden"!==S.type&&o.css(S,"display")!=="none"&&o.css(S,"visibility")!=="hidden"};F.selectors.filters.animated=function(S){return o.grep(o.timers,function(T){return S===T.elem}).length};o.multiFilter=function(U,S,T){if(T){U=":not("+U+")"}return F.matches(U,S)};o.dir=function(U,T){var S=[],V=U[T];while(V&&V!=document){if(V.nodeType==1){S.push(V)}V=V[T]}return S};o.nth=function(W,S,U,V){S=S||1;var T=0;for(;W;W=W[U]){if(W.nodeType==1&&++T==S){break}}return W};o.sibling=function(U,T){var S=[];for(;U;U=U.nextSibling){if(U.nodeType==1&&U!=T){S.push(U)}}return S};return;l.Sizzle=F})();o.event={add:function(I,F,H,K){if(I.nodeType==3||I.nodeType==8){return}if(I.setInterval&&I!=l){I=l}if(!H.guid){H.guid=this.guid++}if(K!==g){var G=H;H=this.proxy(G);H.data=K}var E=o.data(I,"events")||o.data(I,"events",{}),J=o.data(I,"handle")||o.data(I,"handle",function(){return typeof o!=="undefined"&&!o.event.triggered?o.event.handle.apply(arguments.callee.elem,arguments):g});J.elem=I;o.each(F.split(/\s+/),function(M,N){var O=N.split(".");N=O.shift();H.type=O.slice().sort().join(".");var L=E[N];if(o.event.specialAll[N]){o.event.specialAll[N].setup.call(I,K,O)}if(!L){L=E[N]={};if(!o.event.special[N]||o.event.special[N].setup.call(I,K,O)===false){if(I.addEventListener){I.addEventListener(N,J,false)}else{if(I.attachEvent){I.attachEvent("on"+N,J)}}}}L[H.guid]=H;o.event.global[N]=true});I=null},guid:1,global:{},remove:function(K,H,J){if(K.nodeType==3||K.nodeType==8){return}var G=o.data(K,"events"),F,E;if(G){if(H===g||(typeof H==="string"&&H.charAt(0)==".")){for(var I in G){this.remove(K,I+(H||""))}}else{if(H.type){J=H.handler;H=H.type}o.each(H.split(/\s+/),function(M,O){var Q=O.split(".");O=Q.shift();var N=RegExp("(^|\\.)"+Q.slice().sort().join(".*\\.")+"(\\.|$)");if(G[O]){if(J){delete G[O][J.guid]}else{for(var P in G[O]){if(N.test(G[O][P].type)){delete G[O][P]}}}if(o.event.specialAll[O]){o.event.specialAll[O].teardown.call(K,Q)}for(F in G[O]){break}if(!F){if(!o.event.special[O]||o.event.special[O].teardown.call(K,Q)===false){if(K.removeEventListener){K.removeEventListener(O,o.data(K,"handle"),false)}else{if(K.detachEvent){K.detachEvent("on"+O,o.data(K,"handle"))}}}F=null;delete G[O]}}})}for(F in G){break}if(!F){var L=o.data(K,"handle");if(L){L.elem=null}o.removeData(K,"events");o.removeData(K,"handle")}}},trigger:function(I,K,H,E){var G=I.type||I;if(!E){I=typeof I==="object"?I[h]?I:o.extend(o.Event(G),I):o.Event(G);if(G.indexOf("!")>=0){I.type=G=G.slice(0,-1);I.exclusive=true}if(!H){I.stopPropagation();if(this.global[G]){o.each(o.cache,function(){if(this.events&&this.events[G]){o.event.trigger(I,K,this.handle.elem)}})}}if(!H||H.nodeType==3||H.nodeType==8){return g}I.result=g;I.target=H;K=o.makeArray(K);K.unshift(I)}I.currentTarget=H;var J=o.data(H,"handle");if(J){J.apply(H,K)}if((!H[G]||(o.nodeName(H,"a")&&G=="click"))&&H["on"+G]&&H["on"+G].apply(H,K)===false){I.result=false}if(!E&&H[G]&&!I.isDefaultPrevented()&&!(o.nodeName(H,"a")&&G=="click")){this.triggered=true;try{H[G]()}catch(L){}}this.triggered=false;if(!I.isPropagationStopped()){var F=H.parentNode||H.ownerDocument;if(F){o.event.trigger(I,K,F,true)}}},handle:function(K){var J,E;K=arguments[0]=o.event.fix(K||l.event);var L=K.type.split(".");K.type=L.shift();J=!L.length&&!K.exclusive;var I=RegExp("(^|\\.)"+L.slice().sort().join(".*\\.")+"(\\.|$)");E=(o.data(this,"events")||{})[K.type];for(var G in E){var H=E[G];if(J||I.test(H.type)){K.handler=H;K.data=H.data;var F=H.apply(this,arguments);if(F!==g){K.result=F;if(F===false){K.preventDefault();K.stopPropagation()}}if(K.isImmediatePropagationStopped()){break}}}},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(H){if(H[h]){return H}var F=H;H=o.Event(F);for(var G=this.props.length,J;G;){J=this.props[--G];H[J]=F[J]}if(!H.target){H.target=H.srcElement||document}if(H.target.nodeType==3){H.target=H.target.parentNode}if(!H.relatedTarget&&H.fromElement){H.relatedTarget=H.fromElement==H.target?H.toElement:H.fromElement}if(H.pageX==null&&H.clientX!=null){var I=document.documentElement,E=document.body;H.pageX=H.clientX+(I&&I.scrollLeft||E&&E.scrollLeft||0)-(I.clientLeft||0);H.pageY=H.clientY+(I&&I.scrollTop||E&&E.scrollTop||0)-(I.clientTop||0)}if(!H.which&&((H.charCode||H.charCode===0)?H.charCode:H.keyCode)){H.which=H.charCode||H.keyCode}if(!H.metaKey&&H.ctrlKey){H.metaKey=H.ctrlKey}if(!H.which&&H.button){H.which=(H.button&1?1:(H.button&2?3:(H.button&4?2:0)))}return H},proxy:function(F,E){E=E||function(){return F.apply(this,arguments)};E.guid=F.guid=F.guid||E.guid||this.guid++;return E},special:{ready:{setup:B,teardown:function(){}}},specialAll:{live:{setup:function(E,F){o.event.add(this,F[0],c)},teardown:function(G){if(G.length){var E=0,F=RegExp("(^|\\.)"+G[0]+"(\\.|$)");o.each((o.data(this,"events").live||{}),function(){if(F.test(this.type)){E++}});if(E<1){o.event.remove(this,G[0],c)}}}}}};o.Event=function(E){if(!this.preventDefault){return new o.Event(E)}if(E&&E.type){this.originalEvent=E;this.type=E.type}else{this.type=E}this.timeStamp=e();this[h]=true};function k(){return false}function u(){return true}o.Event.prototype={preventDefault:function(){this.isDefaultPrevented=u;var E=this.originalEvent;if(!E){return}if(E.preventDefault){E.preventDefault()}E.returnValue=false},stopPropagation:function(){this.isPropagationStopped=u;var E=this.originalEvent;if(!E){return}if(E.stopPropagation){E.stopPropagation()}E.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=u;this.stopPropagation()},isDefaultPrevented:k,isPropagationStopped:k,isImmediatePropagationStopped:k};var a=function(F){var E=F.relatedTarget;while(E&&E!=this){try{E=E.parentNode}catch(G){E=this}}if(E!=this){F.type=F.data;o.event.handle.apply(this,arguments)}};o.each({mouseover:"mouseenter",mouseout:"mouseleave"},function(F,E){o.event.special[E]={setup:function(){o.event.add(this,F,a,E)},teardown:function(){o.event.remove(this,F,a)}}});o.fn.extend({bind:function(F,G,E){return F=="unload"?this.one(F,G,E):this.each(function(){o.event.add(this,F,E||G,E&&G)})},one:function(G,H,F){var E=o.event.proxy(F||H,function(I){o(this).unbind(I,E);return(F||H).apply(this,arguments)});return this.each(function(){o.event.add(this,G,E,F&&H)})},unbind:function(F,E){return this.each(function(){o.event.remove(this,F,E)})},trigger:function(E,F){return this.each(function(){o.event.trigger(E,F,this)})},triggerHandler:function(E,G){if(this[0]){var F=o.Event(E);F.preventDefault();F.stopPropagation();o.event.trigger(F,G,this[0]);return F.result}},toggle:function(G){var E=arguments,F=1;while(F<E.length){o.event.proxy(G,E[F++])}return this.click(o.event.proxy(G,function(H){this.lastToggle=(this.lastToggle||0)%F;H.preventDefault();return E[this.lastToggle++].apply(this,arguments)||false}))},hover:function(E,F){return this.mouseenter(E).mouseleave(F)},ready:function(E){B();if(o.isReady){E.call(document,o)}else{o.readyList.push(E)}return this},live:function(G,F){var E=o.event.proxy(F);E.guid+=this.selector+G;o(document).bind(i(G,this.selector),this.selector,E);return this},die:function(F,E){o(document).unbind(i(F,this.selector),E?{guid:E.guid+this.selector+F}:null);return this}});function c(H){var E=RegExp("(^|\\.)"+H.type+"(\\.|$)"),G=true,F=[];o.each(o.data(this,"events").live||[],function(I,J){if(E.test(J.type)){var K=o(H.target).closest(J.data)[0];if(K){F.push({elem:K,fn:J})}}});o.each(F,function(){if(this.fn.call(this.elem,H,this.fn.data)===false){G=false}});return G}function i(F,E){return["live",F,E.replace(/\./g,"`").replace(/ /g,"|")].join(".")}o.extend({isReady:false,readyList:[],ready:function(){if(!o.isReady){o.isReady=true;if(o.readyList){o.each(o.readyList,function(){this.call(document,o)});o.readyList=null}o(document).triggerHandler("ready")}}});var x=false;function B(){if(x){return}x=true;if(document.addEventListener){document.addEventListener("DOMContentLoaded",function(){document.removeEventListener("DOMContentLoaded",arguments.callee,false);o.ready()},false)}else{if(document.attachEvent){document.attachEvent("onreadystatechange",function(){if(document.readyState==="complete"){document.detachEvent("onreadystatechange",arguments.callee);o.ready()}});if(document.documentElement.doScroll&&typeof l.frameElement==="undefined"){(function(){if(o.isReady){return}try{document.documentElement.doScroll("left")}catch(E){setTimeout(arguments.callee,0);return}o.ready()})()}}}o.event.add(l,"load",o.ready)}o.each(("blur,focus,load,resize,scroll,unload,click,dblclick,mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave,change,select,submit,keydown,keypress,keyup,error").split(","),function(F,E){o.fn[E]=function(G){return G?this.bind(E,G):this.trigger(E)}});o(l).bind("unload",function(){for(var E in o.cache){if(E!=1&&o.cache[E].handle){o.event.remove(o.cache[E].handle.elem)}}});(function(){o.support={};var F=document.documentElement,G=document.createElement("script"),K=document.createElement("div"),J="script"+(new Date).getTime();K.style.display="none";K.innerHTML='   <link/><table></table><a href="/a" style="color:red;float:left;opacity:.5;">a</a><select><option>text</option></select><object><param/></object>';var H=K.getElementsByTagName("*"),E=K.getElementsByTagName("a")[0];if(!H||!H.length||!E){return}o.support={leadingWhitespace:K.firstChild.nodeType==3,tbody:!K.getElementsByTagName("tbody").length,objectAll:!!K.getElementsByTagName("object")[0].getElementsByTagName("*").length,htmlSerialize:!!K.getElementsByTagName("link").length,style:/red/.test(E.getAttribute("style")),hrefNormalized:E.getAttribute("href")==="/a",opacity:E.style.opacity==="0.5",cssFloat:!!E.style.cssFloat,scriptEval:false,noCloneEvent:true,boxModel:null};G.type="text/javascript";try{G.appendChild(document.createTextNode("window."+J+"=1;"))}catch(I){}F.insertBefore(G,F.firstChild);if(l[J]){o.support.scriptEval=true;delete l[J]}F.removeChild(G);if(K.attachEvent&&K.fireEvent){K.attachEvent("onclick",function(){o.support.noCloneEvent=false;K.detachEvent("onclick",arguments.callee)});K.cloneNode(true).fireEvent("onclick")}o(function(){var L=document.createElement("div");L.style.width="1px";L.style.paddingLeft="1px";document.body.appendChild(L);o.boxModel=o.support.boxModel=L.offsetWidth===2;document.body.removeChild(L)})})();var w=o.support.cssFloat?"cssFloat":"styleFloat";o.props={"for":"htmlFor","class":"className","float":w,cssFloat:w,styleFloat:w,readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",tabindex:"tabIndex"};o.fn.extend({_load:o.fn.load,load:function(G,J,K){if(typeof G!=="string"){return this._load(G)}var I=G.indexOf(" ");if(I>=0){var E=G.slice(I,G.length);G=G.slice(0,I)}var H="GET";if(J){if(o.isFunction(J)){K=J;J=null}else{if(typeof J==="object"){J=o.param(J);H="POST"}}}var F=this;o.ajax({url:G,type:H,dataType:"html",data:J,complete:function(M,L){if(L=="success"||L=="notmodified"){F.html(E?o("<div/>").append(M.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(E):M.responseText)}if(K){F.each(K,[M.responseText,L,M])}}});return this},serialize:function(){return o.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?o.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password/i.test(this.type))}).map(function(E,F){var G=o(this).val();return G==null?null:o.isArray(G)?o.map(G,function(I,H){return{name:F.name,value:I}}):{name:F.name,value:G}}).get()}});o.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(E,F){o.fn[F]=function(G){return this.bind(F,G)}});var r=e();o.extend({get:function(E,G,H,F){if(o.isFunction(G)){H=G;G=null}return o.ajax({type:"GET",url:E,data:G,success:H,dataType:F})},getScript:function(E,F){return o.get(E,null,F,"script")},getJSON:function(E,F,G){return o.get(E,F,G,"json")},post:function(E,G,H,F){if(o.isFunction(G)){H=G;G={}}return o.ajax({type:"POST",url:E,data:G,success:H,dataType:F})},ajaxSetup:function(E){o.extend(o.ajaxSettings,E)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return l.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest()},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(M){M=o.extend(true,M,o.extend(true,{},o.ajaxSettings,M));var W,F=/=\?(&|$)/g,R,V,G=M.type.toUpperCase();if(M.data&&M.processData&&typeof M.data!=="string"){M.data=o.param(M.data)}if(M.dataType=="jsonp"){if(G=="GET"){if(!M.url.match(F)){M.url+=(M.url.match(/\?/)?"&":"?")+(M.jsonp||"callback")+"=?"}}else{if(!M.data||!M.data.match(F)){M.data=(M.data?M.data+"&":"")+(M.jsonp||"callback")+"=?"}}M.dataType="json"}if(M.dataType=="json"&&(M.data&&M.data.match(F)||M.url.match(F))){W="jsonp"+r++;if(M.data){M.data=(M.data+"").replace(F,"="+W+"$1")}M.url=M.url.replace(F,"="+W+"$1");M.dataType="script";l[W]=function(X){V=X;I();L();l[W]=g;try{delete l[W]}catch(Y){}if(H){H.removeChild(T)}}}if(M.dataType=="script"&&M.cache==null){M.cache=false}if(M.cache===false&&G=="GET"){var E=e();var U=M.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+E+"$2");M.url=U+((U==M.url)?(M.url.match(/\?/)?"&":"?")+"_="+E:"")}if(M.data&&G=="GET"){M.url+=(M.url.match(/\?/)?"&":"?")+M.data;M.data=null}if(M.global&&!o.active++){o.event.trigger("ajaxStart")}var Q=/^(\w+:)?\/\/([^\/?#]+)/.exec(M.url);if(M.dataType=="script"&&G=="GET"&&Q&&(Q[1]&&Q[1]!=location.protocol||Q[2]!=location.host)){var H=document.getElementsByTagName("head")[0];var T=document.createElement("script");T.src=M.url;if(M.scriptCharset){T.charset=M.scriptCharset}if(!W){var O=false;T.onload=T.onreadystatechange=function(){if(!O&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){O=true;I();L();H.removeChild(T)}}}H.appendChild(T);return g}var K=false;var J=M.xhr();if(M.username){J.open(G,M.url,M.async,M.username,M.password)}else{J.open(G,M.url,M.async)}try{if(M.data){J.setRequestHeader("Content-Type",M.contentType)}if(M.ifModified){J.setRequestHeader("If-Modified-Since",o.lastModified[M.url]||"Thu, 01 Jan 1970 00:00:00 GMT")}J.setRequestHeader("X-Requested-With","XMLHttpRequest");J.setRequestHeader("Accept",M.dataType&&M.accepts[M.dataType]?M.accepts[M.dataType]+", */*":M.accepts._default)}catch(S){}if(M.beforeSend&&M.beforeSend(J,M)===false){if(M.global&&!--o.active){o.event.trigger("ajaxStop")}J.abort();return false}if(M.global){o.event.trigger("ajaxSend",[J,M])}var N=function(X){if(J.readyState==0){if(P){clearInterval(P);P=null;if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}}else{if(!K&&J&&(J.readyState==4||X=="timeout")){K=true;if(P){clearInterval(P);P=null}R=X=="timeout"?"timeout":!o.httpSuccess(J)?"error":M.ifModified&&o.httpNotModified(J,M.url)?"notmodified":"success";if(R=="success"){try{V=o.httpData(J,M.dataType,M)}catch(Z){R="parsererror"}}if(R=="success"){var Y;try{Y=J.getResponseHeader("Last-Modified")}catch(Z){}if(M.ifModified&&Y){o.lastModified[M.url]=Y}if(!W){I()}}else{o.handleError(M,J,R)}L();if(X){J.abort()}if(M.async){J=null}}}};if(M.async){var P=setInterval(N,13);if(M.timeout>0){setTimeout(function(){if(J&&!K){N("timeout")}},M.timeout)}}try{J.send(M.data)}catch(S){o.handleError(M,J,null,S)}if(!M.async){N()}function I(){if(M.success){M.success(V,R)}if(M.global){o.event.trigger("ajaxSuccess",[J,M])}}function L(){if(M.complete){M.complete(J,R)}if(M.global){o.event.trigger("ajaxComplete",[J,M])}if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}return J},handleError:function(F,H,E,G){if(F.error){F.error(H,E,G)}if(F.global){o.event.trigger("ajaxError",[H,F,G])}},active:0,httpSuccess:function(F){try{return !F.status&&location.protocol=="file:"||(F.status>=200&&F.status<300)||F.status==304||F.status==1223}catch(E){}return false},httpNotModified:function(G,E){try{var H=G.getResponseHeader("Last-Modified");return G.status==304||H==o.lastModified[E]}catch(F){}return false},httpData:function(J,H,G){var F=J.getResponseHeader("content-type"),E=H=="xml"||!H&&F&&F.indexOf("xml")>=0,I=E?J.responseXML:J.responseText;if(E&&I.documentElement.tagName=="parsererror"){throw"parsererror"}if(G&&G.dataFilter){I=G.dataFilter(I,H)}if(typeof I==="string"){if(H=="script"){o.globalEval(I)}if(H=="json"){I=l["eval"]("("+I+")")}}return I},param:function(E){var G=[];function H(I,J){G[G.length]=encodeURIComponent(I)+"="+encodeURIComponent(J)}if(o.isArray(E)||E.jquery){o.each(E,function(){H(this.name,this.value)})}else{for(var F in E){if(o.isArray(E[F])){o.each(E[F],function(){H(F,this)})}else{H(F,o.isFunction(E[F])?E[F]():E[F])}}}return G.join("&").replace(/%20/g,"+")}});var m={},n,d=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];function t(F,E){var G={};o.each(d.concat.apply([],d.slice(0,E)),function(){G[this]=F});return G}o.fn.extend({show:function(J,L){if(J){return this.animate(t("show",3),J,L)}else{for(var H=0,F=this.length;H<F;H++){var E=o.data(this[H],"olddisplay");this[H].style.display=E||"";if(o.css(this[H],"display")==="none"){var G=this[H].tagName,K;if(m[G]){K=m[G]}else{var I=o("<"+G+" />").appendTo("body");K=I.css("display");if(K==="none"){K="block"}I.remove();m[G]=K}this[H].style.display=o.data(this[H],"olddisplay",K)}}return this}},hide:function(H,I){if(H){return this.animate(t("hide",3),H,I)}else{for(var G=0,F=this.length;G<F;G++){var E=o.data(this[G],"olddisplay");if(!E&&E!=="none"){o.data(this[G],"olddisplay",o.css(this[G],"display"))}this[G].style.display="none"}return this}},_toggle:o.fn.toggle,toggle:function(G,F){var E=typeof G==="boolean";return o.isFunction(G)&&o.isFunction(F)?this._toggle.apply(this,arguments):G==null||E?this.each(function(){var H=E?G:o(this).is(":hidden");o(this)[H?"show":"hide"]()}):this.animate(t("toggle",3),G,F)},fadeTo:function(E,G,F){return this.animate({opacity:G},E,F)},animate:function(I,F,H,G){var E=o.speed(F,H,G);return this[E.queue===false?"each":"queue"](function(){var K=o.extend({},E),M,L=this.nodeType==1&&o(this).is(":hidden"),J=this;for(M in I){if(I[M]=="hide"&&L||I[M]=="show"&&!L){return K.complete.call(this)}if((M=="height"||M=="width")&&this.style){K.display=o.css(this,"display");K.overflow=this.style.overflow}}if(K.overflow!=null){this.style.overflow="hidden"}K.curAnim=o.extend({},I);o.each(I,function(O,S){var R=new o.fx(J,K,O);if(/toggle|show|hide/.test(S)){R[S=="toggle"?L?"show":"hide":S](I)}else{var Q=S.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),T=R.cur(true)||0;if(Q){var N=parseFloat(Q[2]),P=Q[3]||"px";if(P!="px"){J.style[O]=(N||1)+P;T=((N||1)/R.cur(true))*T;J.style[O]=T+P}if(Q[1]){N=((Q[1]=="-="?-1:1)*N)+T}R.custom(T,N,P)}else{R.custom(T,S,"")}}});return true})},stop:function(F,E){var G=o.timers;if(F){this.queue([])}this.each(function(){for(var H=G.length-1;H>=0;H--){if(G[H].elem==this){if(E){G[H](true)}G.splice(H,1)}}});if(!E){this.dequeue()}return this}});o.each({slideDown:t("show",1),slideUp:t("hide",1),slideToggle:t("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(E,F){o.fn[E]=function(G,H){return this.animate(F,G,H)}});o.extend({speed:function(G,H,F){var E=typeof G==="object"?G:{complete:F||!F&&H||o.isFunction(G)&&G,duration:G,easing:F&&H||H&&!o.isFunction(H)&&H};E.duration=o.fx.off?0:typeof E.duration==="number"?E.duration:o.fx.speeds[E.duration]||o.fx.speeds._default;E.old=E.complete;E.complete=function(){if(E.queue!==false){o(this).dequeue()}if(o.isFunction(E.old)){E.old.call(this)}};return E},easing:{linear:function(G,H,E,F){return E+F*G},swing:function(G,H,E,F){return((-Math.cos(G*Math.PI)/2)+0.5)*F+E}},timers:[],fx:function(F,E,G){this.options=E;this.elem=F;this.prop=G;if(!E.orig){E.orig={}}}});o.fx.prototype={update:function(){if(this.options.step){this.options.step.call(this.elem,this.now,this)}(o.fx.step[this.prop]||o.fx.step._default)(this);if((this.prop=="height"||this.prop=="width")&&this.elem.style){this.elem.style.display="block"}},cur:function(F){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null)){return this.elem[this.prop]}var E=parseFloat(o.css(this.elem,this.prop,F));return E&&E>-10000?E:parseFloat(o.curCSS(this.elem,this.prop))||0},custom:function(I,H,G){this.startTime=e();this.start=I;this.end=H;this.unit=G||this.unit||"px";this.now=this.start;this.pos=this.state=0;var E=this;function F(J){return E.step(J)}F.elem=this.elem;if(F()&&o.timers.push(F)==1){n=setInterval(function(){var K=o.timers;for(var J=0;J<K.length;J++){if(!K[J]()){K.splice(J--,1)}}if(!K.length){clearInterval(n)}},13)}},show:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.show=true;this.custom(this.prop=="width"||this.prop=="height"?1:0,this.cur());o(this.elem).show()},hide:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(H){var G=e();if(H||G>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var E=true;for(var F in this.options.curAnim){if(this.options.curAnim[F]!==true){E=false}}if(E){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(o.css(this.elem,"display")=="none"){this.elem.style.display="block"}}if(this.options.hide){o(this.elem).hide()}if(this.options.hide||this.options.show){for(var I in this.options.curAnim){o.attr(this.elem.style,I,this.options.orig[I])}}this.options.complete.call(this.elem)}return false}else{var J=G-this.startTime;this.state=J/this.options.duration;this.pos=o.easing[this.options.easing||(o.easing.swing?"swing":"linear")](this.state,J,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update()}return true}};o.extend(o.fx,{speeds:{slow:600,fast:200,_default:400},step:{opacity:function(E){o.attr(E.elem.style,"opacity",E.now)},_default:function(E){if(E.elem.style&&E.elem.style[E.prop]!=null){E.elem.style[E.prop]=E.now+E.unit}else{E.elem[E.prop]=E.now}}}});if(document.documentElement.getBoundingClientRect){o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}var G=this[0].getBoundingClientRect(),J=this[0].ownerDocument,F=J.body,E=J.documentElement,L=E.clientTop||F.clientTop||0,K=E.clientLeft||F.clientLeft||0,I=G.top+(self.pageYOffset||o.boxModel&&E.scrollTop||F.scrollTop)-L,H=G.left+(self.pageXOffset||o.boxModel&&E.scrollLeft||F.scrollLeft)-K;return{top:I,left:H}}}else{o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}o.offset.initialized||o.offset.initialize();var J=this[0],G=J.offsetParent,F=J,O=J.ownerDocument,M,H=O.documentElement,K=O.body,L=O.defaultView,E=L.getComputedStyle(J,null),N=J.offsetTop,I=J.offsetLeft;while((J=J.parentNode)&&J!==K&&J!==H){M=L.getComputedStyle(J,null);N-=J.scrollTop,I-=J.scrollLeft;if(J===G){N+=J.offsetTop,I+=J.offsetLeft;if(o.offset.doesNotAddBorder&&!(o.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(J.tagName))){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}F=G,G=J.offsetParent}if(o.offset.subtractsBorderForOverflowNotVisible&&M.overflow!=="visible"){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}E=M}if(E.position==="relative"||E.position==="static"){N+=K.offsetTop,I+=K.offsetLeft}if(E.position==="fixed"){N+=Math.max(H.scrollTop,K.scrollTop),I+=Math.max(H.scrollLeft,K.scrollLeft)}return{top:N,left:I}}}o.offset={initialize:function(){if(this.initialized){return}var L=document.body,F=document.createElement("div"),H,G,N,I,M,E,J=L.style.marginTop,K='<div style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;"><div></div></div><table style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;" cellpadding="0" cellspacing="0"><tr><td></td></tr></table>';M={position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"};for(E in M){F.style[E]=M[E]}F.innerHTML=K;L.insertBefore(F,L.firstChild);H=F.firstChild,G=H.firstChild,I=H.nextSibling.firstChild.firstChild;this.doesNotAddBorder=(G.offsetTop!==5);this.doesAddBorderForTableAndCells=(I.offsetTop===5);H.style.overflow="hidden",H.style.position="relative";this.subtractsBorderForOverflowNotVisible=(G.offsetTop===-5);L.style.marginTop="1px";this.doesNotIncludeMarginInBodyOffset=(L.offsetTop===0);L.style.marginTop=J;L.removeChild(F);this.initialized=true},bodyOffset:function(E){o.offset.initialized||o.offset.initialize();var G=E.offsetTop,F=E.offsetLeft;if(o.offset.doesNotIncludeMarginInBodyOffset){G+=parseInt(o.curCSS(E,"marginTop",true),10)||0,F+=parseInt(o.curCSS(E,"marginLeft",true),10)||0}return{top:G,left:F}}};o.fn.extend({position:function(){var I=0,H=0,F;if(this[0]){var G=this.offsetParent(),J=this.offset(),E=/^body|html$/i.test(G[0].tagName)?{top:0,left:0}:G.offset();J.top-=j(this,"marginTop");J.left-=j(this,"marginLeft");E.top+=j(G,"borderTopWidth");E.left+=j(G,"borderLeftWidth");F={top:J.top-E.top,left:J.left-E.left}}return F},offsetParent:function(){var E=this[0].offsetParent||document.body;while(E&&(!/^body|html$/i.test(E.tagName)&&o.css(E,"position")=="static")){E=E.offsetParent}return o(E)}});o.each(["Left","Top"],function(F,E){var G="scroll"+E;o.fn[G]=function(H){if(!this[0]){return null}return H!==g?this.each(function(){this==l||this==document?l.scrollTo(!F?H:o(l).scrollLeft(),F?H:o(l).scrollTop()):this[G]=H}):this[0]==l||this[0]==document?self[F?"pageYOffset":"pageXOffset"]||o.boxModel&&document.documentElement[G]||document.body[G]:this[0][G]}});o.each(["Height","Width"],function(H,F){var E=H?"Left":"Top",G=H?"Right":"Bottom";o.fn["inner"+F]=function(){return this[F.toLowerCase()]()+j(this,"padding"+E)+j(this,"padding"+G)};o.fn["outer"+F]=function(J){return this["inner"+F]()+j(this,"border"+E+"Width")+j(this,"border"+G+"Width")+(J?j(this,"margin"+E)+j(this,"margin"+G):0)};var I=F.toLowerCase();o.fn[I]=function(J){return this[0]==l?document.compatMode=="CSS1Compat"&&document.documentElement["client"+F]||document.body["client"+F]:this[0]==document?Math.max(document.documentElement["client"+F],document.body["scroll"+F],document.documentElement["scroll"+F],document.body["offset"+F],document.documentElement["offset"+F]):J===g?(this.length?o.css(this[0],I):null):this.css(I,typeof J==="string"?J:J+"px")}})})(); 
 
/**
 * jquery.dump.js
 * @author Torkild Dyvik Olsen
 * @version 1.0
 * 
 * A simple debug function to gather information about an object.
 * Returns a nested tree with information.
 * 
 */
(function($) {

$.fn.dump = function() {
   return $.dump(this);
}

$.dump = function(object) {
   var recursion = function(obj, level) {
      if(!level) level = 0;
      var dump = '', p = '';
      for(i = 0; i < level; i++) p += "\t";
      
      t = type(obj);
      switch(t) {
         case "string":
            return '"' + obj + '"';
            break;
         case "number":
            return obj.toString();
            break;
         case "boolean":
            return obj ? 'true' : 'false';
         case "date":
            return "Date: " + obj.toLocaleString();
         case "array":
            dump += 'Array ( \n';
            $.each(obj, function(k,v) {
               dump += p +'\t' + k + ' => ' + recursion(v, level + 1) + '\n';
            });
            dump += p + ')';
            break;
         case "object":
            dump += 'Object { \n';
            $.each(obj, function(k,v) {
               dump += p + '\t' + k + ': ' + recursion(v, level + 1) + '\n';
            });
            dump += p + '}';
            break;
         case "jquery":
            dump += 'jQuery Object { \n';
            $.each(obj, function(k,v) {
               dump += p + '\t' + k + ' = ' + recursion(v, level + 1) + '\n';
            });
            dump += p + '}';
            break;
         case "regexp":
            return "RegExp: " + obj.toString();
         case "error":
            return obj.toString();
         case "document":
         case "domelement":
            dump += 'DOMElement [ \n'
                  + p + '\tnodeName: ' + obj.nodeName + '\n'
                  + p + '\tnodeValue: ' + obj.nodeValue + '\n'
                  + p + '\tinnerHTML: [ \n';
            $.each(obj.childNodes, function(k,v) {
               if(k < 1) var r = 0;
               if(type(v) == "string") {
                  if(v.textContent.match(/[^\s]/)) {
                     dump += p + '\t\t' + (k - (r||0)) + ' = String: ' + trim(v.textContent) + '\n';
                  } else {
                     r--;
                  }
               } else {
                  dump += p + '\t\t' + (k - (r||0)) + ' = ' + recursion(v, level + 2) + '\n';
               }
            });
            dump += p + '\t]\n'
                  + p + ']';
            break;
         case "function":
            var match = obj.toString().match(/^(.*)\(([^\)]*)\)/im);
            match[1] = trim(match[1].replace(new RegExp("[\\s]+", "g"), " "));
            match[2] = trim(match[2].replace(new RegExp("[\\s]+", "g"), " "));
            return match[1] + "(" + match[2] + ")";
         case "window":
         default:
            dump += 'N/A: ' + t;
            break;
      }
      
      return dump;
   }
   
   var type = function(obj) {
      var type = typeof(obj);
      
      if(type != "object") {
         return type;
      }
      
      switch(obj) {
         case null:
            return 'null';
         case window:
            return 'window';
         case document:
            return 'document';
         case window.event:
            return 'event';
         default:
            break;
      }
      
      if(obj.jquery) {
         return 'jquery';
      }
      
      switch(obj.constructor) {
         case Array:
            return 'array';
         case Boolean:
            return 'boolean';
         case Date:
            return 'date';
         case Object:
            return 'object';
         case RegExp:
            return 'regexp';
         case ReferenceError:
         case Error:
            return 'error';
         case null:
         default:
            break;
      }
      
      switch(obj.nodeType) {
         case 1:
            return 'domelement';
         case 3:
            return 'string';
         case null:
         default:
            break;
      }
      
      return 'Unknown';
   }
   
   return recursion(object);
}

function trim(str) {
   return ltrim(rtrim(str));
}

function ltrim(str) {
   return str.replace(new RegExp("^[\\s]+", "g"), "");
}

function rtrim(str) {
   return str.replace(new RegExp("[\\s]+$", "g"), "");
}

})(jQuery); 
 
/*
 * SimpleModal 1.2.3 - jQuery Plugin
 * http://www.ericmmartin.com/projects/simplemodal/
 * Copyright (c) 2009 Eric Martin
 * Dual licensed under the MIT and GPL licenses
 * Revision: $Id: jquery.simplemodal.js 185 2009-02-09 21:51:12Z emartin24 $
 */
eval(function(p,a,c,k,e,r){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--)r[e(c)]=k[c]||e(c);k=[function(e){return r[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}('(g($){m f=$.Q.1R&&1d($.Q.1B)==6&&E 11[\'2b\']!="1O",V=D,w=[];$.v=g(a,b){G $.v.12.1l(a,b)};$.v.H=g(){$.v.12.H()};$.1P.v=g(a){G $.v.12.1l(3,a)};$.v.1K={W:2a,1C:\'q-F\',1x:{},21:\'q-n\',20:{},1Z:{},u:2p,H:1p,1U:\'<a 2i="2h" 2g="2d"></a>\',Z:\'q-H\',r:D,1h:L,1g:D,1f:D,1c:D};$.v.12={7:D,4:{},1l:g(a,b){8(3.4.j){G L}V=$.Q.1R&&!$.28;3.7=$.U({},$.v.1K,b);3.u=3.7.u;3.19=L;8(E a==\'1O\'){a=a 26 1A?a:$(a);8(a.16().16().24()>0){3.4.X=a.16();8(!3.7.1h){3.4.22=a.2x(1p)}}}o 8(E a==\'2w\'||E a==\'1t\'){a=$(\'<1s/>\').2t(a)}o{2s(\'2r 2q: 2o j 2l: \'+E a);G L}3.4.j=a.14(\'q-j\').C(3.7.1Z);a=D;3.1T();3.1S();8($.1o(3.7.1f)){3.7.1f.1n(3,[3.4])}G 3},1T:g(){w=3.1m();8(f){3.4.x=$(\'<x 2f="2e:L;"/>\').C($.U(3.7.2c,{1k:\'1j\',W:0,r:\'1i\',A:w[0],B:w[1],u:3.7.u,K:0,y:0})).M(\'z\')}3.4.F=$(\'<1s/>\').1N(\'1M\',3.7.1C).14(\'q-F\').C($.U(3.7.1x,{1k:\'1j\',W:3.7.W/1e,A:w[0],B:w[1],r:\'1i\',y:0,K:0,u:3.7.u+1})).M(\'z\');3.4.n=$(\'<1s/>\').1N(\'1M\',3.7.21).14(\'q-n\').C($.U(3.7.20,{1k:\'1j\',r:\'1i\',u:3.7.u+2})).1J(3.7.H?$(3.7.1U).14(3.7.Z):\'\').M(\'z\');3.1b();8(f||V){3.1a()}3.4.n.1J(3.4.j.1I())},1H:g(){m a=3;$(\'.\'+3.7.Z).1G(\'1L.q\',g(e){e.29();a.H()});$(11).1G(\'1F.q\',g(){w=a.1m();a.1b();8(f||V){a.1a()}o{a.4.x&&a.4.x.C({A:w[0],B:w[1]});a.4.F.C({A:w[0],B:w[1]})}})},1E:g(){$(\'.\'+3.7.Z).1D(\'1L.q\');$(11).1D(\'1F.q\')},1a:g(){m p=3.7.r;$.27([3.4.x||D,3.4.F,3.4.n],g(i,e){8(e){m a=\'k.z.18\',N=\'k.z.1W\',17=\'k.z.25\',T=\'k.z.1z\',S=\'k.z.1y\',1r=\'k.z.23\',1v=\'k.R.18\',1u=\'k.R.1W\',J=\'k.R.1z\',I=\'k.R.1y\',s=e[0].2v;s.r=\'2u\';8(i<2){s.10(\'A\');s.10(\'B\');s.Y(\'A\',\'\'+17+\' > \'+a+\' ? \'+17+\' : \'+a+\' + "l"\');s.Y(\'B\',\'\'+1r+\' > \'+N+\' ? \'+1r+\' : \'+N+\' + "l"\')}o{m b,13;8(p&&p.1Y==1Q){m c=p[0]?E p[0]==\'1t\'?p[0].1X():p[0].P(/l/,\'\'):e.C(\'K\').P(/l/,\'\');b=c.1V(\'%\')==-1?c+\' + (t = \'+I+\' ? \'+I+\' : \'+S+\') + "l"\':1d(c.P(/%/,\'\'))+\' * ((\'+1v+\' || \'+a+\') / 1e) + (t = \'+I+\' ? \'+I+\' : \'+S+\') + "l"\';8(p[1]){m d=E p[1]==\'1t\'?p[1].1X():p[1].P(/l/,\'\');13=d.1V(\'%\')==-1?d+\' + (t = \'+J+\' ? \'+J+\' : \'+T+\') + "l"\':1d(d.P(/%/,\'\'))+\' * ((\'+1u+\' || \'+N+\') / 1e) + (t = \'+J+\' ? \'+J+\' : \'+T+\') + "l"\'}}o{b=\'(\'+1v+\' || \'+a+\') / 2 - (3.2n / 2) + (t = \'+I+\' ? \'+I+\' : \'+S+\') + "l"\';13=\'(\'+1u+\' || \'+N+\') / 2 - (3.2m / 2) + (t = \'+J+\' ? \'+J+\' : \'+T+\') + "l"\'}s.10(\'K\');s.10(\'y\');s.Y(\'K\',b);s.Y(\'y\',13)}}})},1m:g(){m a=$(11);m h=$.Q.2k&&$.Q.1B>\'9.5\'&&$.1P.2j<=\'1.2.6\'?k.R[\'18\']:a.A();G[h,a.B()]},1b:g(){m a,y,1q=(w[0]/2)-((3.4.n.A()||3.4.j.A())/2),1w=(w[1]/2)-((3.4.n.B()||3.4.j.B())/2);8(3.7.r&&3.7.r.1Y==1Q){a=3.7.r[0]||1q;y=3.7.r[1]||1w}o{a=1q;y=1w}3.4.n.C({y:y,K:a})},1S:g(){3.4.x&&3.4.x.15();8($.1o(3.7.1g)){3.7.1g.1n(3,[3.4])}o{3.4.F.15();3.4.n.15();3.4.j.15()}3.1H()},H:g(){8(!3.4.j){G L}8($.1o(3.7.1c)&&!3.19){3.19=1p;3.7.1c.1n(3,[3.4])}o{8(3.4.X){8(3.7.1h){3.4.j.1I().M(3.4.X)}o{3.4.j.O();3.4.22.M(3.4.X)}}o{3.4.j.O()}3.4.n.O();3.4.F.O();3.4.x&&3.4.x.O();3.4={}}3.1E()}}})(1A);',62,158,'|||this|dialog|||opts|if||||||||function|||data|document|px|var|container|else||simplemodal|position|||zIndex|modal||iframe|left|body|height|width|css|null|typeof|overlay|return|close|st|sl|top|false|appendTo|bcw|remove|replace|browser|documentElement|bst|bsl|extend|ieQuirks|opacity|parentNode|setExpression|closeClass|removeExpression|window|impl|le|addClass|show|parent|bsh|clientHeight|occb|fixIE|setPosition|onClose|parseInt|100|onShow|onOpen|persist|fixed|none|display|init|getDimensions|apply|isFunction|true|hCenter|bsw|div|number|cw|ch|vCenter|overlayCss|scrollTop|scrollLeft|jQuery|version|overlayId|unbind|unbindEvents|resize|bind|bindEvents|hide|append|defaults|click|id|attr|object|fn|Array|msie|open|create|closeHTML|indexOf|clientWidth|toString|constructor|dataCss|containerCss|containerId|orig|scrollWidth|size|scrollHeight|instanceof|each|boxModel|preventDefault|50|XMLHttpRequest|iframeCss|Close|javascript|src|title|modalCloseImg|class|jquery|opera|type|offsetWidth|offsetHeight|Unsupported|1000|Error|SimpleModal|alert|html|absolute|style|string|clone'.split('|'),0,{})) 
 
/*
 * jQuery Form Plugin
 * version: 2.25 (08-APR-2009)
 * @requires jQuery v1.2.2 or later
 *
 * Examples and documentation at: http://malsup.com/jquery/form/
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
;(function($) {

/*
    Usage Note:
    -----------
    Do not use both ajaxSubmit and ajaxForm on the same form.  These
    functions are intended to be exclusive.  Use ajaxSubmit if you want
    to bind your own submit handler to the form.  For example,

    $(document).ready(function() {
        $('#myForm').bind('submit', function() {
            $(this).ajaxSubmit({
                target: '#output'
            });
            return false; // <-- important!
        });
    });

    Use ajaxForm when you want the plugin to manage all the event binding
    for you.  For example,

    $(document).ready(function() {
        $('#myForm').ajaxForm({
            target: '#output'
        });
    });

    When using ajaxForm, the ajaxSubmit function will be invoked for you
    at the appropriate time.
*/

/**
 * ajaxSubmit() provides a mechanism for immediately submitting
 * an HTML form using AJAX.
 */
$.fn.ajaxSubmit = function(options) {
    // fast fail if nothing selected (http://dev.jquery.com/ticket/2752)
    if (!this.length) {
        log('ajaxSubmit: skipping submit process - no element selected');
        return this;
    }

    if (typeof options == 'function')
        options = { success: options };

    // clean url (don't include hash vaue)
    var url = this.attr('action') || window.location.href;
    url = (url.match(/^([^#]+)/)||[])[1];
    url = url || '';

    options = $.extend({
        url:  url,
        type: this.attr('method') || 'GET'
    }, options || {});

    // hook for manipulating the form data before it is extracted;
    // convenient for use with rich editors like tinyMCE or FCKEditor
    var veto = {};
    this.trigger('form-pre-serialize', [this, options, veto]);
    if (veto.veto) {
        log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
        return this;
    }

    // provide opportunity to alter form data before it is serialized
    if (options.beforeSerialize && options.beforeSerialize(this, options) === false) {
        log('ajaxSubmit: submit aborted via beforeSerialize callback');
        return this;
    }

    var a = this.formToArray(options.semantic);
    if (options.data) {
        options.extraData = options.data;
        for (var n in options.data) {
          if(options.data[n] instanceof Array) {
            for (var k in options.data[n])
              a.push( { name: n, value: options.data[n][k] } );
          }
          else
             a.push( { name: n, value: options.data[n] } );
        }
    }

    // give pre-submit callback an opportunity to abort the submit
    if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
        log('ajaxSubmit: submit aborted via beforeSubmit callback');
        return this;
    }

    // fire vetoable 'validate' event
    this.trigger('form-submit-validate', [a, this, options, veto]);
    if (veto.veto) {
        log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
        return this;
    }

    var q = $.param(a);

    if (options.type.toUpperCase() == 'GET') {
        options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
        options.data = null;  // data is null for 'get'
    }
    else
        options.data = q; // data is the query string for 'post'

    var $form = this, callbacks = [];
    if (options.resetForm) callbacks.push(function() { $form.resetForm(); });
    if (options.clearForm) callbacks.push(function() { $form.clearForm(); });

    // perform a load on the target only if dataType is not provided
    if (!options.dataType && options.target) {
        var oldSuccess = options.success || function(){};
        callbacks.push(function(data) {
            $(options.target).html(data).each(oldSuccess, arguments);
        });
    }
    else if (options.success)
        callbacks.push(options.success);

    options.success = function(data, status) {
        for (var i=0, max=callbacks.length; i < max; i++)
            callbacks[i].apply(options, [data, status, $form]);
    };

    // are there files to upload?
    var files = $('input:file', this).fieldValue();
    var found = false;
    for (var j=0; j < files.length; j++)
        if (files[j])
            found = true;

    // options.iframe allows user to force iframe mode
   if (options.iframe || found) {
       // hack to fix Safari hang (thanks to Tim Molendijk for this)
       // see:  http://groups.google.com/group/jquery-dev/browse_thread/thread/36395b7ab510dd5d
       if (options.closeKeepAlive)
           $.get(options.closeKeepAlive, fileUpload);
       else
           fileUpload();
       }
   else
       $.ajax(options);

    // fire 'notify' event
    this.trigger('form-submit-notify', [this, options]);
    return this;


    // private function for handling file uploads (hat tip to YAHOO!)
    function fileUpload() {
        var form = $form[0];

        if ($(':input[name=submit]', form).length) {
            alert('Error: Form elements must not be named "submit".');
            return;
        }

        var opts = $.extend({}, $.ajaxSettings, options);
		var s = $.extend(true, {}, $.extend(true, {}, $.ajaxSettings), opts);

        var id = 'jqFormIO' + (new Date().getTime());
        var $io = $('<iframe id="' + id + '" name="' + id + '" src="about:blank" />');
        var io = $io[0];

        $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });

        var xhr = { // mock object
            aborted: 0,
            responseText: null,
            responseXML: null,
            status: 0,
            statusText: 'n/a',
            getAllResponseHeaders: function() {},
            getResponseHeader: function() {},
            setRequestHeader: function() {},
            abort: function() {
                this.aborted = 1;
                $io.attr('src','about:blank'); // abort op in progress
            }
        };

        var g = opts.global;
        // trigger ajax global events so that activity/block indicators work like normal
        if (g && ! $.active++) $.event.trigger("ajaxStart");
        if (g) $.event.trigger("ajaxSend", [xhr, opts]);

		if (s.beforeSend && s.beforeSend(xhr, s) === false) {
			s.global && $.active--;
			return;
        }
        if (xhr.aborted)
            return;

        var cbInvoked = 0;
        var timedOut = 0;

        // add submitting element to data if we know it
        var sub = form.clk;
        if (sub) {
            var n = sub.name;
            if (n && !sub.disabled) {
                options.extraData = options.extraData || {};
                options.extraData[n] = sub.value;
                if (sub.type == "image") {
                    options.extraData[name+'.x'] = form.clk_x;
                    options.extraData[name+'.y'] = form.clk_y;
                }
            }
        }

        // take a breath so that pending repaints get some cpu time before the upload starts
        setTimeout(function() {
            // make sure form attrs are set
            var t = $form.attr('target'), a = $form.attr('action');

			// update form attrs in IE friendly way
			form.setAttribute('target',id);
			if (form.getAttribute('method') != 'POST')
				form.setAttribute('method', 'POST');
			if (form.getAttribute('action') != opts.url)
				form.setAttribute('action', opts.url);

            // ie borks in some cases when setting encoding
            if (! options.skipEncodingOverride) {
                $form.attr({
                    encoding: 'multipart/form-data',
                    enctype:  'multipart/form-data'
                });
            }

            // support timout
            if (opts.timeout)
                setTimeout(function() { timedOut = true; cb(); }, opts.timeout);

            // add "extra" data to form if provided in options
            var extraInputs = [];
            try {
                if (options.extraData)
                    for (var n in options.extraData)
                        extraInputs.push(
                            $('<input type="hidden" name="'+n+'" value="'+options.extraData[n]+'" />')
                                .appendTo(form)[0]);

                // add iframe to doc and submit the form
                $io.appendTo('body');
                io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
                form.submit();
            }
            finally {
                // reset attrs and remove "extra" input elements
				form.setAttribute('action',a);
                t ? form.setAttribute('target', t) : $form.removeAttr('target');
                $(extraInputs).remove();
            }
        }, 10);

        var nullCheckFlag = 0;

        function cb() {
            if (cbInvoked++) return;

            io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);

            var ok = true;
            try {
                if (timedOut) throw 'timeout';
                // extract the server response from the iframe
                var data, doc;

                doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;

                if ((doc.body == null || doc.body.innerHTML == '') && !nullCheckFlag) {
                    // in some browsers (cough, Opera 9.2.x) the iframe DOM is not always traversable when
                    // the onload callback fires, so we give them a 2nd chance
                    nullCheckFlag = 1;
                    cbInvoked--;
                    setTimeout(cb, 100);
                    return;
                }

                xhr.responseText = doc.body ? doc.body.innerHTML : null;
                xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
                xhr.getResponseHeader = function(header){
                    var headers = {'content-type': opts.dataType};
                    return headers[header];
                };

                if (opts.dataType == 'json' || opts.dataType == 'script') {
                    var ta = doc.getElementsByTagName('textarea')[0];
                    xhr.responseText = ta ? ta.value : xhr.responseText;
                }
                else if (opts.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
                    xhr.responseXML = toXml(xhr.responseText);
                }
                data = $.httpData(xhr, opts.dataType);
            }
            catch(e){
                ok = false;
                $.handleError(opts, xhr, 'error', e);
            }

            // ordering of these callbacks/triggers is odd, but that's how $.ajax does it
            if (ok) {
                opts.success(data, 'success');
                if (g) $.event.trigger("ajaxSuccess", [xhr, opts]);
            }
            if (g) $.event.trigger("ajaxComplete", [xhr, opts]);
            if (g && ! --$.active) $.event.trigger("ajaxStop");
            if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error');

            // clean up
            setTimeout(function() {
                $io.remove();
                xhr.responseXML = null;
            }, 100);
        };

        function toXml(s, doc) {
            if (window.ActiveXObject) {
                doc = new ActiveXObject('Microsoft.XMLDOM');
                doc.async = 'false';
                doc.loadXML(s);
            }
            else
                doc = (new DOMParser()).parseFromString(s, 'text/xml');
            return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null;
        };
    };
};

/**
 * ajaxForm() provides a mechanism for fully automating form submission.
 *
 * The advantages of using this method instead of ajaxSubmit() are:
 *
 * 1: This method will include coordinates for <input type="image" /> elements (if the element
 *    is used to submit the form).
 * 2. This method will include the submit element's name/value data (for the element that was
 *    used to submit the form).
 * 3. This method binds the submit() method to the form for you.
 *
 * The options argument for ajaxForm works exactly as it does for ajaxSubmit.  ajaxForm merely
 * passes the options argument along after properly binding events for submit elements and
 * the form itself.
 */
$.fn.ajaxForm = function(options) {
    return this.ajaxFormUnbind().bind('submit.form-plugin',function() {
        $(this).ajaxSubmit(options);
        return false;
    }).each(function() {
        // store options in hash
        $(":submit,input:image", this).bind('click.form-plugin',function(e) {
            var form = this.form;
            form.clk = this;
            if (this.type == 'image') {
                if (e.offsetX != undefined) {
                    form.clk_x = e.offsetX;
                    form.clk_y = e.offsetY;
                } else if (typeof $.fn.offset == 'function') { // try to use dimensions plugin
                    var offset = $(this).offset();
                    form.clk_x = e.pageX - offset.left;
                    form.clk_y = e.pageY - offset.top;
                } else {
                    form.clk_x = e.pageX - this.offsetLeft;
                    form.clk_y = e.pageY - this.offsetTop;
                }
            }
            // clear form vars
            setTimeout(function() { form.clk = form.clk_x = form.clk_y = null; }, 10);
        });
    });
};

// ajaxFormUnbind unbinds the event handlers that were bound by ajaxForm
$.fn.ajaxFormUnbind = function() {
    this.unbind('submit.form-plugin');
    return this.each(function() {
        $(":submit,input:image", this).unbind('click.form-plugin');
    });

};

/**
 * formToArray() gathers form element data into an array of objects that can
 * be passed to any of the following ajax functions: $.get, $.post, or load.
 * Each object in the array has both a 'name' and 'value' property.  An example of
 * an array for a simple login form might be:
 *
 * [ { name: 'username', value: 'jresig' }, { name: 'password', value: 'secret' } ]
 *
 * It is this array that is passed to pre-submit callback functions provided to the
 * ajaxSubmit() and ajaxForm() methods.
 */
$.fn.formToArray = function(semantic) {
    var a = [];
    if (this.length == 0) return a;

    var form = this[0];
    var els = semantic ? form.getElementsByTagName('*') : form.elements;
    if (!els) return a;
    for(var i=0, max=els.length; i < max; i++) {
        var el = els[i];
        var n = el.name;
        if (!n) continue;

        if (semantic && form.clk && el.type == "image") {
            // handle image inputs on the fly when semantic == true
            if(!el.disabled && form.clk == el)
                a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
            continue;
        }

        var v = $.fieldValue(el, true);
        if (v && v.constructor == Array) {
            for(var j=0, jmax=v.length; j < jmax; j++)
                a.push({name: n, value: v[j]});
        }
        else if (v !== null && typeof v != 'undefined')
            a.push({name: n, value: v});
    }

    if (!semantic && form.clk) {
        // input type=='image' are not found in elements array! handle them here
        var inputs = form.getElementsByTagName("input");
        for(var i=0, max=inputs.length; i < max; i++) {
            var input = inputs[i];
            var n = input.name;
            if(n && !input.disabled && input.type == "image" && form.clk == input)
                a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
        }
    }
    return a;
};

/**
 * Serializes form data into a 'submittable' string. This method will return a string
 * in the format: name1=value1&amp;name2=value2
 */
$.fn.formSerialize = function(semantic) {
    //hand off to jQuery.param for proper encoding
    return $.param(this.formToArray(semantic));
};

/**
 * Serializes all field elements in the jQuery object into a query string.
 * This method will return a string in the format: name1=value1&amp;name2=value2
 */
$.fn.fieldSerialize = function(successful) {
    var a = [];
    this.each(function() {
        var n = this.name;
        if (!n) return;
        var v = $.fieldValue(this, successful);
        if (v && v.constructor == Array) {
            for (var i=0,max=v.length; i < max; i++)
                a.push({name: n, value: v[i]});
        }
        else if (v !== null && typeof v != 'undefined')
            a.push({name: this.name, value: v});
    });
    //hand off to jQuery.param for proper encoding
    return $.param(a);
};

/**
 * Returns the value(s) of the element in the matched set.  For example, consider the following form:
 *
 *  <form><fieldset>
 *      <input name="A" type="text" />
 *      <input name="A" type="text" />
 *      <input name="B" type="checkbox" value="B1" />
 *      <input name="B" type="checkbox" value="B2"/>
 *      <input name="C" type="radio" value="C1" />
 *      <input name="C" type="radio" value="C2" />
 *  </fieldset></form>
 *
 *  var v = $(':text').fieldValue();
 *  // if no values are entered into the text inputs
 *  v == ['','']
 *  // if values entered into the text inputs are 'foo' and 'bar'
 *  v == ['foo','bar']
 *
 *  var v = $(':checkbox').fieldValue();
 *  // if neither checkbox is checked
 *  v === undefined
 *  // if both checkboxes are checked
 *  v == ['B1', 'B2']
 *
 *  var v = $(':radio').fieldValue();
 *  // if neither radio is checked
 *  v === undefined
 *  // if first radio is checked
 *  v == ['C1']
 *
 * The successful argument controls whether or not the field element must be 'successful'
 * (per http://www.w3.org/TR/html4/interact/forms.html#successful-controls).
 * The default value of the successful argument is true.  If this value is false the value(s)
 * for each element is returned.
 *
 * Note: This method *always* returns an array.  If no valid value can be determined the
 *       array will be empty, otherwise it will contain one or more values.
 */
$.fn.fieldValue = function(successful) {
    for (var val=[], i=0, max=this.length; i < max; i++) {
        var el = this[i];
        var v = $.fieldValue(el, successful);
        if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
            continue;
        v.constructor == Array ? $.merge(val, v) : val.push(v);
    }
    return val;
};

/**
 * Returns the value of the field element.
 */
$.fieldValue = function(el, successful) {
    var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
    if (typeof successful == 'undefined') successful = true;

    if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
        (t == 'checkbox' || t == 'radio') && !el.checked ||
        (t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
        tag == 'select' && el.selectedIndex == -1))
            return null;

    if (tag == 'select') {
        var index = el.selectedIndex;
        if (index < 0) return null;
        var a = [], ops = el.options;
        var one = (t == 'select-one');
        var max = (one ? index+1 : ops.length);
        for(var i=(one ? index : 0); i < max; i++) {
            var op = ops[i];
            if (op.selected) {
				var v = op.value;
				if (!v) // extra pain for IE...
                	v = (op.attributes && op.attributes['value'] && !(op.attributes['value'].specified)) ? op.text : op.value;
                if (one) return v;
                a.push(v);
            }
        }
        return a;
    }
    return el.value;
};

/**
 * Clears the form data.  Takes the following actions on the form's input fields:
 *  - input text fields will have their 'value' property set to the empty string
 *  - select elements will have their 'selectedIndex' property set to -1
 *  - checkbox and radio inputs will have their 'checked' property set to false
 *  - inputs of type submit, button, reset, and hidden will *not* be effected
 *  - button elements will *not* be effected
 */
$.fn.clearForm = function() {
    return this.each(function() {
        $('input,select,textarea', this).clearFields();
    });
};

/**
 * Clears the selected form elements.
 */
$.fn.clearFields = $.fn.clearInputs = function() {
    return this.each(function() {
        var t = this.type, tag = this.tagName.toLowerCase();
        if (t == 'text' || t == 'password' || tag == 'textarea')
            this.value = '';
        else if (t == 'checkbox' || t == 'radio')
            this.checked = false;
        else if (tag == 'select')
            this.selectedIndex = -1;
    });
};

/**
 * Resets the form data.  Causes all form elements to be reset to their original value.
 */
$.fn.resetForm = function() {
    return this.each(function() {
        // guard against an input with the name of 'reset'
        // note that IE reports the reset function as an 'object'
        if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
            this.reset();
    });
};

/**
 * Enables or disables any matching elements.
 */
$.fn.enable = function(b) {
    if (b == undefined) b = true;
    return this.each(function() {
        this.disabled = !b;
    });
};

/**
 * Checks/unchecks any matching checkboxes or radio buttons and
 * selects/deselects and matching option elements.
 */
$.fn.selected = function(select) {
    if (select == undefined) select = true;
    return this.each(function() {
        var t = this.type;
        if (t == 'checkbox' || t == 'radio')
            this.checked = select;
        else if (this.tagName.toLowerCase() == 'option') {
            var $sel = $(this).parent('select');
            if (select && $sel[0] && $sel[0].type == 'select-one') {
                // deselect all other options
                $sel.find('option').selected(false);
            }
            this.selected = select;
        }
    });
};

// helper fn for console logging
// set $.fn.ajaxSubmit.debug to true to enable debug logging
function log() {
    if ($.fn.ajaxSubmit.debug && window.console && window.console.log)
        window.console.log('[jquery.form] ' + Array.prototype.join.call(arguments,''));
};

})(jQuery);
 
 
/*
 * jQuery Color Animations
 * Copyright 2007 John Resig
 * Released under the MIT and GPL licenses.
 */

(function(jQuery){

	// We override the animation for all of these color styles
	jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
		jQuery.fx.step[attr] = function(fx){
			if ( fx.state == 0 ) {
				fx.start = getColor( fx.elem, attr );
				fx.end = getRGB( fx.end );
			}

			fx.elem.style[attr] = "rgb(" + [
				Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
			].join(",") + ")";
		}
	});

	// Color Conversion functions from highlightFade
	// By Blair Mitchelmore
	// http://jquery.offput.ca/highlightFade/

	// Parse strings looking for color tuples [255,255,255]
	function getRGB(color) {
		var result;

		// Check if we're already dealing with an array of colors
		if ( color && color.constructor == Array && color.length == 3 )
			return color;

		// Look for rgb(num,num,num)
		if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
			return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

		// Look for rgb(num%,num%,num%)
		if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
			return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

		// Look for #a0b1c2
		if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
			return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

		// Look for #fff
		if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
			return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

		// Otherwise, we're most likely dealing with a named color
		return colors[jQuery.trim(color).toLowerCase()];
	}
	
	function getColor(elem, attr) {
		var color;

		do {
			color = jQuery.curCSS(elem, attr);

			// Keep going until we find an element that has color, or we hit the body
			if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
				break; 

			attr = "backgroundColor";
		} while ( elem = elem.parentNode );

		return getRGB(color);
	};
	
	// Some named colors to work with
	// From Interface by Stefan Petre
	// http://interface.eyecon.ro/

	var colors = {
		aqua:[0,255,255],
		azure:[240,255,255],
		beige:[245,245,220],
		black:[0,0,0],
		blue:[0,0,255],
		brown:[165,42,42],
		cyan:[0,255,255],
		darkblue:[0,0,139],
		darkcyan:[0,139,139],
		darkgrey:[169,169,169],
		darkgreen:[0,100,0],
		darkkhaki:[189,183,107],
		darkmagenta:[139,0,139],
		darkolivegreen:[85,107,47],
		darkorange:[255,140,0],
		darkorchid:[153,50,204],
		darkred:[139,0,0],
		darksalmon:[233,150,122],
		darkviolet:[148,0,211],
		fuchsia:[255,0,255],
		gold:[255,215,0],
		green:[0,128,0],
		indigo:[75,0,130],
		khaki:[240,230,140],
		lightblue:[173,216,230],
		lightcyan:[224,255,255],
		lightgreen:[144,238,144],
		lightgrey:[211,211,211],
		lightpink:[255,182,193],
		lightyellow:[255,255,224],
		lime:[0,255,0],
		magenta:[255,0,255],
		maroon:[128,0,0],
		navy:[0,0,128],
		olive:[128,128,0],
		orange:[255,165,0],
		pink:[255,192,203],
		purple:[128,0,128],
		violet:[128,0,128],
		red:[255,0,0],
		silver:[192,192,192],
		white:[255,255,255],
		yellow:[255,255,0]
	};
	
})(jQuery);
 
 
/*
 * $ Watermark 0.1 - A $ plugin for watermarking form inputs, crazy elegant style
 *
 * Copyright (c) 2008 Rogie King (komodomedia.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * $Date: 2008-02-25 $
 * $Rev: 1 $
 */
 
(function ($) {
  $.fn.watermark = function ( opts ) {
	
	var alt = 18;
	
	//setup some defaults
	var defaults = {
		using: 'title', //other defaults are: label, rel, or a callback function
		style: {color:'#555'},
		className: 'watermarked',
		ignoreChars: [38,40,37,39,33,34,36,35,13,9,27,16,17,alt,20,8,224],
		valid: ':text,:password,select,textarea,[type=search]',
		mode: 'watermark'		
	};
	
	var is_down = [];
	
	//extend the defaults
	var options = $.extend( {}, defaults, opts );
	
	//setup a reference to these inputs
	var $inputs = $(this).filter( options.valid );
	
	function rewindCaret(){
		setCaretPosition( this, 0);	
	};
	
	function setCaretPosition(input, pos){
		if(input.setSelectionRange){
			input.setSelectionRange(pos,pos);
		}else if (input.createTextRange ) {
			var range = input.createTextRange();
			range.collapse( true );
			range.move('character', pos);
			range.select();
		};
	};	
		
  	function mark(e){
  		var val = $(this).val().replace(/\s+/g,'');
		var wm 	= $(this).data('watermark').replace(/\s+/g,'');
    	
    	if( val.length < 1 || (val == wm && $(this).data('watermarked') == true) ){
    		
    		if( $(this).attr('type') == 'password' && !$.browser.msie){
    			this.type = 'text';
    			$(this).data('password',true);
    		}
    		
    		$(this).val( $(this).data('watermark') ).css( options.style ).addClass( options.className );
    		$(this).data('watermarked',true);
    	}
  	};  	
  	
  	function unMark(){
  		if( $(this).data('watermarked') ){
	  		$(this).val('').data('watermarked',false);
	  		
	  		if( $(this).data('password') == true && !$.browser.msie){
	   			this.type = 'password';
	   		}
	  		
	  		for( key in options.style ){
	  			$(this).css( key , '' );
	  		}
	  		$(this).removeClass(options.className);
  		}
  	};
  	
  	function isWatermarked(){
  		
  		var val = $(this).val().replace(/\s+/g,'');
		var wm 	= $(this).data('watermark').replace(/\s+/g,'');
    	
    	return ( ( val == wm || val.length < 1 ) &&  $(this).data('watermarked') == true);
  	};
  	
  	function isBlank(){
  		
  		var val = $(this).val().replace(/\s+/g,'');
  		
  		return ( val == '' );
  		
  	};
  	
  	function observe( e ){
		
  		switch(e.type){  			
  			case 'keydown':  				
  				
  				if( options.mode == 'watermark' ){
	  				is_down[e.which] = true;
	  				
	  				if( isWatermarked.call( this ) && $.inArray(e.which,options.ignoreChars) < 0 || is_down[alt] == true){
	  					unMark.call( this );
	  				} else if( isBlank.call(this) ){
	  					mark.call( this );
	  					rewindCaret.call( this );
	  				} else{
	  					//e.preventDefault();
	  				} 
  				} 				
  			break;
				
  			case 'keyup':
  				
  				if( options.mode == 'watermark' ){
	  				is_down[e.which] = false;
	  				
	  				if( isWatermarked.call( this ) && $.inArray(e.which,options.ignoreChars) < 0 ){
	  					unMark.call( this );
	  				} else if( isBlank.call(this) ){
	  					mark.call( this );
	  					rewindCaret.call( this );
	  				} else{
	  					//e.preventDefault();
	  				}
  				}
  				
  			break;
  			
  			case 'mousedown':
  			case 'mouseup': 
  				if( options.mode == 'watermark' ){
	  				if( isWatermarked.call( this ) ){
	  					rewindCaret.call( this );
	  				}
  				}
  			break;
  			
  			case 'focus':
  				if( isWatermarked.call( this ) ){
  					rewindCaret.call( this );
  					
  					$(this).addClass('focused');
  					
  					if( options.mode == 'watermark' ){
	  					if( !$.browser.msie ){
	  						var input = this;
	  						setTimeout(function(){rewindCaret.call(input);},5);
	  					}
	  					e.preventDefault();
	  					this.focus();
  					} else {
  						unMark.call(this);
  					}
  				}
  			break;
  			
  			case 'blur':				
				$(this).removeClass('focused');
				mark.call(this);
  			break;
  			  			
  			default:				
  				if( isWatermarked.call( this ) ){
  					//e.preventDefault();
  					//rewindCaret.call( this );
  				}  			
  			break;
  		}
  	};
	
	function store(){
		$(this).each(
			function(){
				switch( options.using ){
				
					case 'label':
						$(this).data('watermark', $('label[for=' + $(this).attr('id') + ']').text() );
					break;
						
					case 'rel':
					case 'title':
						$(this).data('watermark', $(this).attr(options.using) ); 		
					break;
					
					default:
						if( typeof options.using == 'function' ){
							$(this).data('watermark', options.using.call( this ) );
						}
					break;
				}
			}
		);	
	};
	
	function removeAll(){
		$inputs.each(
			function(){
				unMark.call(this);
			}
		);
	};
		
	//setup the watermark
	store.call( this );
	
	//assign blur and focus functions, triggering blur
	$inputs
		.keydown( observe )
		.keyup( observe )
		.focus( observe )
		.mousedown( observe )
		.mouseup( observe )
		.select( observe )
		.click( observe )
		.dblclick( observe )
		.blur( observe );		
	
	//mark each field and unmark on unload
	$inputs.each(
		function(){
			mark.call(this);
		}
	);
	
	//if the window unloads OR the form submits, watermarks should not be sent
	$inputs
		.parents('form')
		.unbind('submit.remove_watermarks')
		.bind('submit.remove_watermarks', removeAll);
	
	$(window)
		.unbind('unload.remove_watermarks')
		.bind('unload.remove_watermarks', removeAll);
  };
  
  $(document).ready(
	function(){
		//if autorun is specified, then auto setup watermark
        v=$('script[src*=sdna.watermark.js]').attr("src");
		if( v != undefined  && v.match(/.*?autorun/i) ){
			$('.watermark:text,.watermark:textarea').watermark( {mode:'blank'} );
		}

	}
  );

})(jQuery); 
 
(function($) {
	
	function closePersonMenus(e){
		try{
			if( $(e.originalTarget).parents('.person_menu').length < 1 ){
				$('div.person_menu').personMenuClose(e);
			}
		}catch(e){
			return;
		}		
				
	}
		
	$.fn.personMenu = function( options ){
		
		//register a click function on the document that closes all other person menus
		$('body').unbind('click.menu',closePersonMenus).bind('click.menu', closePersonMenus);		

		//assign the click function to open the menu
		$(this).find('.avatar').click(
			function(e){	
							
				var oMenu = $(this).parents('.person_menu').eq(0);
				
				$('div.person_menu.open').not(oMenu).personMenuClose();
				
				if( oMenu.hasClass('open') ){
					oMenu.personMenuClose();
				} else {
					oMenu.personMenuOpen();
				}
				
			}
		);	
	}
	
	$.fn.personMenuClose = function( e ){
		$(this).removeClass('open');
	}
	$.fn.personMenuOpen = function( e ){
		$(this).addClass('open');
	}
	
})(jQuery);


 
 
(function($) {
	
	$.fn.tabs = function( options ){
		
		var oList = $(this);
		
		oList.bindTabReferences();
		oList.bindTabExternalAnchors();
		
		//assign the click function to focus the tab
		$(this).find('li>a')
			.unbind('click.tab')
			.bind('click.tab',
			function(e){

				//stop the link from going
				e.preventDefault();
				
	    		//display the related tab content identified by the href
    			$.fn.tabs.show( this , options );	
				
			}
		);	
		
		//if there is a hash location in the url, go there, 
		//otherwise goto the current class in the markup
		var sHashSelector = 'a[href*=' + document.location.hash + ']';
		if ( document.location.hash && oList.find(sHashSelector).length > 0 ) {
			oList.find( sHashSelector).showTab();								
		} else {
			$j('div.module > ul.tabs, div.main ul.tabs:first').find('> li.current > a').each(function(i,val){$j(val).triggerHandler('click.tab');});
		}
	}
	
	$.fn.bindTabReferences = function(){
		
		//bind the data to the tabs
		var tabs = $(this);
		
		tabs.find('>li>a').each(function(){
			if( this.hash ){
				var $tab 		= $(this);
				var $tabList = $tab.parents('ul').eq(0);
				var $content = $(this.hash);
				
				$content.data('tab_anchor',$tab).data('tab_list',$tabList);
				$tab.data('tab_content', $content).data('tab_list',$tabList);
			}
			
		});
		
	}
	
	$.fn.bindTabExternalAnchors = function( $area ){
		
		//specify the area in this document to look for external anchors
		var $area = $($area || 'html');
		
		//search for anchors to bind them to tabs
		$(this).find('>li>a').each(
			function(){				
				var $tab = $(this);
				$area.find('a[href$=' + this.hash + ']').not(this)
					.unbind('click.tab')
					.bind('click.tab',
						function(e){
							e.preventDefault();
							$tab.showTab();
							$().tabs.scrollTo( this );	
						}
					);
			}
		);	
	}
	
	$.fn.showTab = function(){
		
		//if this tab is a sub tab, we need to open the parent tab first
		var $container 		= $(this).closest('div[id]');
		var $containerTab 	= $('ul.tabs a[href$=#' + $container.attr('id') + ']');
		if( $containerTab.length > 0 ){
			$containerTab.showTab();
		};		
		$(this).triggerHandler('click.tab');
		
	}
	
	$.fn.tabs.tabLoading = function( tab ){
		var $tab = $(tab);
		$tab.addClass('loading');
		$tab.data('tab_list').addClass('loading').parent('div[id]').addClass('loading');
		$tab.data('tab_content').addClass('loading');
	}
	
	$.fn.tabs.isLoading = function( tab ){
		
		return $(tab).hasClass('loading');
		
	}
	
	$.fn.tabs.isLoaded = function( tab ){
		
		return $(tab).hasClass('loaded');
		
	}
	
	$.fn.tabs.tabLoaded = function( tab ){
		var $tab = $(tab);
		$tab.removeClass('loading').addClass('loaded');
		$tab.data('tab_list').removeClass('loading').parent('div[id]').removeClass('loading');
		$tab.data('tab_content').removeClass('loading').addClass('loaded');
	}
	
	$.fn.tabs.scrollTo = function( tab ){
		var $tab = $(tab);
	    if ($tab.length) {
			$('html,body').animate({scrollTop: $tab.offset().top}, 500);
			return false;
		}		
	}
	
	$.fn.tabs.show = function( tab, options ){
		
		//make a jquery ref to the tab
		var $tab = $(tab);
		
		//make sure all the other tabs dont look like the current
		$tab.parent().siblings().removeClass('current');
			
		//focus this tab
		$tab.parent().addClass('current');
		
		//if there's no link, its not linked, so cancel
		if (!$tab.attr('href')) {
			return;
		}
				
		//get the tab path (href)
		var path = $tab.attr('href').replace(tab.hash,'').replace(/\s+/g,'');
		
		
		//tab caching - if it's loaded, don't reload the ajax
		if( $.fn.tabs.isLoaded( tab ) ){
			
			//hide all others
			$tab.parents('ul,ol').find('li>a').not( tab ).each( function(){ $( this.hash ).hide(); } );
			$( tab.hash ).show();
			
		} else if( !$.fn.tabs.isLoading(tab) ){
			
			//create a callback function 
			var callback = function( response ){
				
				//if there was a response, it was loaded via ajax, so do the onload callback
				if( response ){
					if( options && typeof options.onload == 'function' ){
						options.onload.call( tab, $(tab.hash).get(0) );
					}

					//bind any external anchors that may be in this content
					$tab.data('tab_list').bindTabExternalAnchors();
					
				}
				
				//hide all others
				$tab.parents('ul,ol').find('li>a').not( tab ).each( function(){ $( this.hash ).hide(); }  );
		
				//show this one
				$( tab.hash ).show();
									
				//mark this tab as loaded
				$.fn.tabs.tabLoaded( tab );
				
				//call the change tab callback			
				if( options && typeof options.change == 'function' ){
					options.change.call( tab );
				}
			}

			//mark this tab as loading
			$.fn.tabs.tabLoading( tab );		

			//if there is a path to the url, not just a hash, load it
			if( path ){				
				
				if ($('input#friends_only[type=checkbox]').attr('checked')) {
					path += '/friendsonly:true';
				}
				$( tab.hash ).load( path , callback);
			
			} else {
				callback();
			}
		}
		
		//show subtabs if there is no ajax request on this item
		if (path == '') {
			
			var subTab = $(tab.hash).find('li.current > a').get(0);
			$.fn.tabs.show( subTab , options );
		
		}
		
	}	
	
	$.fn.setupShowMore = function () {
		//this contains one or more show more buttons
		$(this).each(function(){
			var $button = $(this);

			var $container = $button.prevAll('ul').eq(0);
			var count = $container.children('li').length;
			if (count < 5) {
				$button.remove();
			} else {
				$button.text('Show More').click( function() { $(this).showMore(); } );
			}		
		});
	}
	
	$.fn.showMore = function( options ){
		
		//make a reference to this
		var $this = $(this);
		
		//make the show more button unclickable and indicate loading
		var $button = $this.addClass('submitting').attr('disabled','disabled').text('Loading more...');
		
		var $container = $this.eq(0).prevAll('ul');
		var count = $container.children('li:not(.share)').length;
		var link = $this.eq(0).parents('.tabs_content').eq(0).prevAll('ul').find('li.current > a').get(0);
		
		//yank the path from the href
		//remove any /start:x if it exists
		//remove any #hash
		var realLink = $(link).attr('href').replace(link.hash,'').replace(/\s+/g,'').replace(/\/start\:[^\/]+/g, '');
		
		realLink += '/start:' + count;
		
		if ($('input#friends_only[type=checkbox]').attr('checked')) {
			realLink += '/friendsonly:true';
		}
		
		$.ajax({
				url: realLink,
				cache: false,
				success: function(html){
					if (html == '') {
						$button.replaceWith( $('<span />').text('There are no more posts to display.').addClass('no_more') );
					} else {
						$html = $(html);
						$button.removeClass('submitting').removeAttr('disabled');
						
						elements = $html.filter('li');
						//we suppose there is a "empty message state" if the class name is empty
						if (!(elements.length == 1 && elements.eq(0).hasClass('empty'))) {
							$container.append($html);
						}
												
						//bind any external anchors that may be in this content
						$tabs = $container.parent('div[id]').data('tab_list').bindTabExternalAnchors();;
						
						//find out if we have anymore 
						if (elements.length < 5) {
							$button.replaceWith( $('<span />').text('There are no more posts to display.').addClass('no_more') );
						} else {
							$button.text('Show More');
						}
						
						//fire off the area load function
						SDNA.global.onAreaLoad( $html );
					}
				}
		});
	}
	
	$.fn.clickFriendsOnly = function() {
		//should we do this or $(this).parent().parent().find('.loaded').removeClass('loaded')
		$(this).parent().nextAll('div.tabs_content').find('.loaded.friendsonly').removeClass('loaded').each( function() { $($(this).get(0).hash).text(''); } );
		$(this).parent().nextAll('ul.tabs').find('.loaded.friendsonly').removeClass('loaded').each( function() { $($(this).get(0).hash).text(''); } );
		
		var tabCounts = $(this).parent().nextAll('ul.tabs').find('span.count').text('#');
		var url = $(this).attr('href');
		if ($(this).attr('checked')) {
			url += '/friendsonly:true';
		}
		
		$.ajax({
				url: url,
				cache: true,
				async: false,
				dataType: 'json',
				success: function(data){
					tabCounts.each( function() {
						var name = $(this).parent().html().replace(/ \<span.+/, '');
						if (data['counts'][name]) {
							$(this).text(data['counts'][name]);
						} else {
							$(this).text('0');
						}
					})
				}
		       });
		
		var currentTab = $j( $j('div.main ul.tabs').eq(0).find('> li.current > a').get(0).hash + ' > ul.tabs > li.current > a');
		if (currentTab.length == 0) {
			currentTab = $j('div.main ul.tabs').eq(0).find('> li.current > a');
		}
		
		currentTab.triggerHandler('click.tab');
	}
	
})(jQuery);
 
 
(function($) {
	
	function filterInput( e ){
		
		var oInput = $(this);
		var val = oInput.val();
		var re  = new RegExp( val.replace(/\s+/g,''), "i");
		var oItems = $(oInput.data('if_options').item);
		
		if( val.replace(/\s+/g,'') != '' ){
			oItems.each(function(){
				if( !$(this).text().replace(/\s+/g,'').match(re) ){
					$(this).hide();
				}else{
					$(this).show();
				}
			});
		}else{
			oItems.show();
		}
	}
		
	$.fn.inputFilter = function( options ){
		
		$(this)
			.filter(':text')
			.unbind('keyup', filterInput )
			.data( 'if_options' , options )
			.keyup( filterInput );
	}
	
})(jQuery);


 
 
//noConflict jQuery
var $j = jQuery.noConflict();

//extend prototypes
String.prototype.truncate = function( chars, loc, ellip ){
    var s = this, loc = loc || 'start', ellip = ellip || 8230;
    ellip = isNaN(ellip)? ellip: String.fromCharCode(ellip);
   
    if( s.length > chars){
        if( loc == 'start' ){
            s = s.slice(0,chars - ellip.length) + ellip;
        } else if( loc == 'middle' ){
            s = s.slice(0,Math.floor(chars/2)) + ellip + s.slice(s.length - Math.ceil(chars/2),s.length);
        } else {
            s = ellip+s.slice(s.length-chars+ellip.length,s.length);
        }
    }
    return s.toString();
}

//jQuery customizations
$j.getScript = function(url, callback, cache){ $j.ajax({ type: "GET", url: url, success: callback, dataType: "script", cache: cache }); };

//create a spectrum style serialize (how our urls expect get params)
$j.fn.extend(
	{
		sdnaSerialize:function(){
			return '/' + $j(this).serialize().replace(/&/g,'/').replace(/=/g,':');
		}
	}
);

if (!SDNA) {
	var SDNA = {};
}

SDNA.global = function(){};
SDNA.user 	= function(){};
SDNA.ajax   = function(){};

SDNA.ajax.Error = function(request, textStatus, a, b) {
	if(textStatus != 'timeout') {
		return;
	}
	
	alert("Sorry, the current action is taking to long. We'll need to reload the page and have you try again");
	
	var submitForm = document.createElement("FORM");
	document.body.appendChild(submitForm);
	submitForm.method = "POST";
	var timeoutElement = document.createElement("input");
	timeoutElement.name='timeoutRequest';
	timeoutElement.type='hidden';
	submitForm.appendChild(timeoutElement);
	timeoutElement.value = this.url;
	submitForm.action = window.location.href;
	submitForm.submit();
};

//setup a timeout for ajax calls
// jQuery.ajaxSetup( {"timeout":10000, "error":SDNA.ajax.Error} ); 

SDNA.tabs = function(){};
SDNA.tabs.setupHelpButtons = function( $area ){

	$area.find('.tabs_content ul.tabs')
		.each(function(){
			$tabs = $j(this);
			$help = $j('<a class="tabs_help" />').text('Help').attr('title','What are filters?').fadeIn('slow');
			$tabs.after($help);	
			$help.unbind('click.help').bind('click.help', function(){
				
				//build the list of help from the tabs' titles
				$tabs = $j(this).siblings('ul.tabs').find('li a');
				
				//build the tabs modal content
				$content = $j('<div />').append( '<h2>About these filters</h2>' );
				$info		 = $content.append( '<p class="instructions">Filters provide a of way of calming down the activity that you see. For instance, you might want to view only what the host has said about an event or maybe only the guests that are coming to an event. </p>' );
				$tabs.each(function(){
					var $this = $j(this);
					var title = $this.attr('title');
					
					if( title ){
						$title = $j('<strong />').text( $this.text() ).appendTo( $content );
						$par = $j('<p class="info"/>').text(title).appendTo( $content );
					}
				});
				
				//open the modal
				$content.modal( {onOpen: SDNA.global.onModalOpen, onClose: SDNA.global.onModalClose });
			});
		});	
};

SDNA.global.setupModals = function( oModalContent ){
	
}

//setup the interactions working with forms
SDNA.global.setupForms = function( sArea ){

	//setup form input watermarking
	
	$j(sArea).find('.watermark').watermark( {mode:'blank'} );
	
	$j(sArea).find('.form .field').each( function(){
		
		$j(this).find(':input').focus(
			function(e){
				var $field = $j(this).parents('.field').eq(0);
				var $prev = $j().data('focused_field');
				
				if( !$prev || ($prev && $field.get(0) != $prev.get(0)) ){
					$j().data('focused_field', $field);
					$j('.field_focused').removeClass('field_focused');
					$field.addClass('field_focused');
				}
			}
		).blur(
			function( e ){				
				var $field = $j(this).parents('.field').eq(0);
				var $prev = $j().data('focused_field');
				
				if( !($prev && $prev.get(0) ==  $field.get(0) )  ){
					$field.removeClass('field_focused');
				}
			}
		);
	});
	
	//setup user choices
	$j(sArea).find('li.user_choice').unbind('click.user_choice').bind('click.user_choice',
		function(e){
			var $li 	= $j(this);
			var $check 	= $li.find(':checkbox'); 	

			if( $j(e.originalTarget).is('li') ){
				if( $check.is(':checked')  ){
					$check.removeAttr('checked');
					$li.removeClass('selected');
				} else {
					$check.attr('checked','checked');
					$li.addClass('selected');
				}
				$check.triggerHandler('change');
			} else {
				if( $check.is(':checked')  ){
					$li.addClass('selected');
				} else {
					$li.removeClass('selected');
				}
			}
	});
	
	//setup submit buttons
	$j(sArea).find('form.form').submit(
		function(e){
			$j(this).find(':submit').addClass('submitting').attr('disabled','disabled').fadeTo(0,0.5);
		}
	).bind('submitted',
		function(){
			$j(this).find(':input').trigger('blur');
			$j(this).find(':submit').removeClass('submitting').removeAttr('disabled').fadeTo("slow",1);
		}
	);
	

}

SDNA.global.onModalOpen = function( oDialog, options ){
	
	var opts = { delay:200, modal: false };
	$j.extend( opts, options );
	opts.delay = opts.delay == 0? 1 : opts.delay;
	
	//create some custom handlers
	oDialog.container
		.unbind('modal.loading')
		.bind('modal.loading',
			function(){ 
				$j(this).addClass('dialog_loading').triggerHandler('modal.center'); 				
			}
		)
		.unbind('modal.loaded')
		.bind('modal.loaded',
			function(){ 
				$j(this).removeClass('dialog_loading');
				$j(this).triggerHandler('modal.center');
			}
		)
		.unbind('modal.center')
		.bind('modal.center',
			function(){ 
				$j(window).triggerHandler('resize');
			}
		);

	oDialog.overlay.fadeIn(opts.delay, function () {
		oDialog.container.fadeIn(opts.delay);
		oDialog.data.hide().fadeIn(opts.delay);
		
		//add sdna interactions and scripts to the content
		SDNA.global.onAreaLoad( oDialog.data );
		
		if( opts && opts.modal == false ){
			//register a click function on the modal overlay to close ala facebox
			oDialog.overlay
				.unbind('click.modal_close')
				.bind('click.modal_close', 
				function(){
					$j.modal.close();
				}	
			);
		}
		
		oDialog.container.triggerHandler('modal.center');
		
		//setup any interactions
		SDNA.global.setupModals(oDialog);
	});

}

SDNA.global.onModalShow = function( oDialog ){
	oDialog.container.triggerHandler('modal.center');
}

SDNA.global.reloadPage = function( oDialog ){
    window.location.reload();
}

SDNA.global.onModalClose = function( oDialog, options ){
	var opts = { delay:0 };
	$j.extend( opts, options );
	
	if( !isNaN(opts.delay) && opts.delay > 0 ){
	
		oDialog.data.fadeTo(opts.delay,0);
		oDialog.container.fadeTo(opts.delay,0, function () {
		  oDialog.overlay.fadeTo(opts.delay,0, function () {
		    $j.modal.close(); // must call this!
		  });
		});
	} else {
		$j.modal.close();
	}
}

//A global actions namespace
SDNA.global.actions = {};

//Setup some handlers specific to the Check-in action
SDNA.global.actions.checkin = function(){}

//Checkin Handler: A function to handle common and shared
//tasks when a successful checkin occurs
SDNA.global.actions.checkin.handler = function( response ){

	if( response.location_id ){		
		$j('.current_location').filter('strong,span').text( response.location_title );
		$j('a.current_location').text( response.location_title ).attr('href','/Location/View/id:' + response.location_id );
	}else if(  response.event_id ){
		$j('.current_location').filter('strong,span').text( response.event_title );
		$j('a.current_location').text( response.event_title ).attr('href','/Event/View/id:' + response.event_id );
	}
	var $checkinLinks = $j('a.set_location.selected').removeClass('selected');
	$checkinLinks.filter('[href*=locationid]').text('Check in at this place');
	$checkinLinks.filter('[href*=eventid]').text('Check in at this event');

	//update the checkins on the map	
	if( SDNA.map && SDNA.map.selectedWindow ){
		
		var $content = $j(SDNA.map.selectedWindow.getContent());
		var id = parseInt($content.find('input[name=id]').val());
		
		if( id == response.location_id ){
			//force an ajax load of the selected window
			SDNA.map.selectedWindow.reload(true);
		};
	}
		
}




SDNA.global.actions.rate = function(){}

//setup default action handlers
SDNA.global.actions.success = function(){
	$j(this)
		.css({backgroundColor:'#F5E792'})
		.animate({backgroundColor:'#FFFFFF'},1500,
			function(){
				$j(this).css('backgroundColor',null);
			}
		);
}

SDNA.global.actions.failure = function(){
	
}

SDNA.global.actions.loading = function(){
	$j(this).addClass('loading');
}

SDNA.global.actions.loaded = function(){
	$j(this).removeClass('loading');
}

SDNA.global.actions.bindDefaultHandlers = function( actions ){
	
	$actions = $j(actions);
		
	$actions.unbind('action.loading').bind('action.loading', SDNA.global.actions.loading )
	.unbind('action.loaded').bind('action.loaded', SDNA.global.actions.loaded )
	.unbind('action.failure').bind('action.failure', SDNA.global.actions.failure )
	.unbind('action.success').bind('action.success', SDNA.global.actions.success );
	
	return $actions;
}

SDNA.global.actions.rate.handler = function( response ){
	
	//make a jq reference to this action
	var $this = $j(this), sVerbage = '', sPercent = '';
	
	//get the parent rate container
	$rate = $this.parents('.like').eq(0);
	
	//for now, just remove the rating links and update the text
	$rate.find('a.like,a.dislike').remove();	
	
	//update the rating call to action text to represent if they like or dislike this
	$rate.find('.verbage').text( response.dom_text );
	
	
	/*
	
	//get the hidden inputs for rated_yes and rated_no
	var $yes = $rate.find('[name=rated_yes]'); 
	var $no  = $rate.find('[name=rated_no]'); 	
	
	if ($this.hasClass('like')){
		
		if( $no.val() > 0 ){
			$no.val( parseInt($no.val()) - 1 );
		}
		$yes.val( parseInt($yes.val()) + 1 );
		$rate.find('a.dislike').show();
		$this.hide();	
		
		sVerbage = 'You like this';	
		
	} else if ($this.hasClass('dislike')){
		
		if( $yes.val() > 0 ){
			$yes.val( parseInt($yes.val()) - 1 );
		}
		$no.val( parseInt($no.val()) + 1 );
		$rate.find('a.like').show();
		$this.hide();	
		
		sVerbage = "You don't like this";
	}
	
	//percentage var
	var iCount	= parseInt($yes.val()) + parseInt($no.val());
	var iPercent = parseInt($yes.val())/(iCount) * 100;
	
	if( iCount > 0  && iPercent > 0){
		sPercent = iPercent + '%';
		
		if ($this.hasClass('like')){
			sVerbage = "like this, including you";
		} else {
			sVerbage = "like this, but you don't";
		}
	}
	
	//set the percentage
	$rate.find('.percent').text( sPercent );
	$rate.find('.verbage').text( sVerbage );
	
	//scan the page for any other rating areas - they may need to be updated as well
	var $actions = $j('a[href=' + $this.attr('href') + ']').not( $this );
	*/
	
}

SDNA.global.actions.bindJSONActions = function( $actions ){
	
	$actions
		.unbind('click.action')
		.bind( 'click.action', 
		
			function( e ){
			//stop this link from processing, we'll do it with ajax
			e.preventDefault();
			
			//make a reference to this action
			var $action = $j(this), vars;
			var sRequestType = 'get';
			var href = $action.attr('href');
			
			//hook up the json if its there
			var vars = $action.attr('json');
			if( vars != undefined){
				sRequestType = 'post';
			}
			if( href || vars ){
				//post the request
				$j[sRequestType]( 
					href,
					vars,
					function( response ){
						if( response.success == true ){
							
							//broadcast this success to all listeners
							$action.triggerHandler('action.success');
							$action.triggerHandler('action.finished');
							
							//special conditions
							if( $action.hasClass('like') || $action.hasClass('dislike') ){
								
								//find all similar to this
								var $actions = $j('a[href=' + $action.attr('href') + ']');
								$actions.each(
									function(){
										$this = $j(this);
										SDNA.global.actions.rate.handler.call( $this, response );
									}
								);
								
								return;
								
							} else if ($action.hasClass('set_home')){
								
								$j('a.set_home.selected').removeClass('selected').text('Set as home');
								
								if( response.location_title ){
									$j('.home_location').filter('strong,span').text( response.location_title );
								}
							} else if ($action.hasClass('set_location')){
								
								SDNA.global.actions.checkin.handler.call( $action, response );
	
							}
							
							var $actions = $j('a[href=' + $action.attr('href') + ']');
							
							if( vars != undefined ){
									$actions = $action;
							}
							
							$actions.each(
								function(){
									$this = $j(this);                            
                                    // Hide Unfollows
                                    var $actionURL = $action.attr('href');
                                    var id = $this.closest("div").attr("id");
                                    var span_edit = $this.closest("span.follow").find('span.edit');
                                    if (($actionURL.search (/Location/) != -1)){
                                        if (id == "your_locations_following"){
                                            $this.closest('li').hide();
                                        } else{
                                            span_edit.hide();
                                        }
                                    } else if (($actionURL.search (/Event/) != -1)){
                                        if (id == "your_events_followed"){
                                            // Don't hide items attending or hosting.
                                            if (($this.closest('li').find('span.attending').length == 0) &&
                                                ($this.closest('li').find('span.hosting').length == 0)) {
                                                $this.closest('li').hide();                                                
                                            } else {
                                                // Otherwise hide the edit link
                                                span_edit.hide();                                                
                                            }
                                        } else {
                                            span_edit.hide();
                                        }
                                    } else if (($actionURL.search (/User/) != -1)){
                                        if (id == "your_people_following"){
                                            $this.closest('li').hide();
                                        } else {
                                            span_edit.hide();
                                        }
                                    }

									if( response.selected == true ){
										$this.addClass( 'selected' );
									} else if(response.selected == false ) {
										$this.removeClass( 'selected' );
									}
									if( response.dom_text ){
										
										$this.html( $j('<span/>').text(response.dom_text) );
									}
									if( response.undo_action ){
										$this.attr('href',response.undo_action);
									}									
									SDNA.global.setupActions( $this.parent() );
									
								}
							);		
							
						//failure
						}else{
							
							//broadcast this failure to all listeners
							$action.triggerHandler('action.failure');
							$action.triggerHandler('action.finished');
							
						}//if success											
					},//function
					'json'
				);	
			}		
	});	

};

SDNA.global.actions.bindModalActions = function( $actions ){


	$actions.unbind('click.action').bind('click.action',
		
		function(e){
			//prevent this link from traveling, we'll load it in a modal instead			
			e.preventDefault();
				
			//set a ref to this link
			var oAction = $j(this);
			
			//show a loading indicator
			oAction.triggerHandler('action.loading');
			
			//if this action is set location or favorite, we can do it inline, NOT in a modal
			if( oAction.is('.set_location, .block') ){
			
				//TODO: toggle this status and update the oAction text based on status
				setTimeout(
					function(){
											
						if( oAction.hasClass('block') ) {
						
							// TODO: Resolve inconsistency in use of JSON. It's explicitly filtered out above (this is why
							// the set_location stuff below has no affect). However, the original code was looking for a JSON
							// status result (probably a good idea). So, which is it?
							//
							var options = {
								callback: function(data) {

									if (oAction.hasClass('selected')) {
										oAction.removeClass('selected').text(oAction.text().replace(/^Unblock/,'Block'));
									} else {
										oAction.addClass('selected').text(oAction.text().replace(/^Block/,'Unblock'));
									}
								}
							};							
							
							options.url = oAction.attr('href');									
							options.json = oAction.attr('json');
							
							$j.post(options.url, options.json, options.callback, 'html');
							
						} else {
							oAction.addClass('is_current_location').text('This is my location');
						}
							
						//remove loading
						oAction.triggerHandler('action.loaded');
					},
					1000
				);				
			
			//otherwise, if this action cannot be done inline, load it into a modal
			} else {
                $j.ajax({ 
                    url: 		oAction.attr('href') + '/force:' + Math.random().toString(),
                    cache: 		false,
                    success: 	function( data ){
                        
                        //setup dialog options
                        var dialogOptions = { modal: false };
                        
                        //load the appropriate scripts
                        if( oAction.hasClass('.follow, .edit_follow') ){
                            $j.getScript('/js/follow.js', function(){								
                                $j(document).ready( function(){
                                    SDNA.follow.init( $j('#simplemodal-container') );
                                });
                            });
                        }else if( oAction.hasClass('.change_home') || oAction.hasClass('.change_location') ){
                                                
                            dialogOptions.delay = 0;
                            $j.getScript('/js/set_location.js', function(){								
                                $j(document).ready( function(){
                                    SDNA.user.initSetLocation( $j('#simplemodal-container') );
                                });
                            });
                        
                        }else if( oAction.hasClass('share') ){
                            $j.getScript('/js/invite.js', function(){								
                                $j(document).ready( function(){
                                    SDNA.invite.init( $j('#simplemodal-container') );
                                });
                            });
                        }else if ( oAction.hasClass('edit_fsm') ){
                            $j.getScript('/js/fsm.js', function(){								
                                $j(document).ready( function(){
                                    SDNA.fsm.init( $j('#simplemodal-container') );
                                });
                            });                        	
                        }else if ( oAction.hasClass('edit_fp') ){      
                            $j.getScript('/js/fp_admin.js', function(){								
                                $j(document).ready( function(){
                                    SDNA.fp.init( $j('#simplemodal-container') );
                                });
                            });                        	                            
                        }
                        
                        if( oAction.hasClass('modal') ){
                            dialogOptions.modal = true;
                        }
                        
                        //open this content in a modal
                        $j.modal( 
                            data , 
                                {
                                    onOpen: function( oDialog ){ 
                                        SDNA.global.onModalOpen(oDialog, dialogOptions);
                                    }, 
                                    onClose: function( oDialog ){ 
                                        SDNA.global.onModalClose(oDialog, dialogOptions);
                                    },
                                    onShow: function( oDialog ){
                                        SDNA.global.onModalShow( oDialog, dialogOptions );
                                    },
                                    close: !dialogOptions.modal
                                }
                            );
                        
                        //remove loading
                        oAction.triggerHandler('action.loaded');
                    }
                });				
			}
		}
	);
};//End SDNA.global.actions.bindModalActions


SDNA.global.setupActions = function( sArea ){
	
	var method = $j(sArea).length == 1 && $j(sArea).is('a')? 'filter' : 'find';
	
	var $actions = $j(sArea)[method]('a[href*=.jsn][href^=/ajax]').not('a.delete_fsm,a.rsvp');
	
	//setup generic ajax/JSON actions
	SDNA.global.actions.bindDefaultHandlers( $actions );
	SDNA.global.actions.bindJSONActions( $actions );

	
	//setup tag adding
	$j(sArea)[method]
		('form[action*=/ajax/][action*=/Tag.jsn]')
		.unbind('submit.tag')
		.bind('submit.tag',
		function(e){
			
			e.preventDefault();
			
			var $this 	= $j(this);
			var $tags	= $this.find('[name=tag]');
			
			if( !$this.hasClass('submitting') ){
			
				var	vars	= $this.sdnaSerialize();
				var action 	= $this.attr('action') + vars;
				
				//set a status spinner			
				$this.addClass('submitting');
				$this.find('.loading').remove();
				$this.append( '<span class="loading" />' );
							
				$j.get( 
					action,
					function( response ){
						if( response.success == false ){
							throw('Error adding tag');
						} else {
							$this.removeClass('submitting');
							$this.find('.loading').fadeOut();
							
							$j($tags.val().split(',')).each(
								function( i, val ){
									val = $j.trim(val);
									$this.find('ul').append( 
										$j('<li />').append(
											$j('<a />').attr('href','/Search/Index/tag:' + val).text( ' ' + val )
										)
									);
								}
							);
							
							$tags.val('');
						}
					},
					'json'
				);
			}			
		}
	);	


	$j(sArea)
		.find('a.findme')
		.unbind('click.action')
		.bind('click.action',
			function(e){
                if (typeof SDNA.iphone != "undefined") {
                    SDNA.iphone.getLocationFromDevice();
                }
            }
        );

	//setup section toggles
	$j(sArea)
		.find('.details.less_details a.toggle_details')
		.unbind('click.action')
		.bind('click.action',
			function(e){
				e.preventDefault();
				
				//make a ref to this
				$this = $j(this);
				
				//make a ref to the details
				$section = $this.parents('.details').eq(0);
				
				if( $section.hasClass('less_details') ){
					$section.removeClass('less_details');
					$this.text('Less Details');
				}else {
					$section.addClass('less_details');
					$this.text('More Details');
				}
				
			}
		);
	
	//setup the actions menus
	var $modalActions = $j(sArea)[method]('a.share,a.block,a.follow,a.edit_follow,a.change_home,a.change_location,a.edit_fsm,a.edit_fp').not('[href*=.jsn]');
	SDNA.global.actions.bindDefaultHandlers( $modalActions );
	SDNA.global.actions.bindModalActions( $modalActions );


}//SDNA.global.setupActions

SDNA.global.setupCalendarButtons = function( $area ) {
	$area.find('button.date').bind('click', function(e){
		e.preventDefault();
		var $pickerDiv = $j(e.target).next('div.datepicker').eq(0);
		if ($pickerDiv.length == 1) {
			$pickerDiv.remove();
		} else {
			year = $j('form select[name=start_Year]').eq(0).val();  
			month = $j('form select[name=start_Month]').eq(0).val();  
			day = $j('form select[name=start_Day]').eq(0).val();

			selectedDate = new Date();
			selectedDate.setFullYear(year,month-1,day);

			$j(e.target).after(
				$j('<div>').attr({className:'datepicker'}).datepicker({  
					dateFormat: 'yy-mm-dd',
					defaultDate: selectedDate,
					onSelect: function(date,datepicker) {  
						var values = date.split('-');
						//this needs to be generic somehow.
						$j('form select[name=start_Year]').eq(0).val(values[0]);  
						$j('form select[name=start_Month]').eq(0).val(values[1]);  
						$j('form select[name=start_Day]').eq(0).val(values[2]);
						datepicker.dpDiv.parent('div.datepicker').remove();
					}
				})
			);
		}
	});	
}

SDNA.global.onAreaLoad = function( $area ){
	
	var $area = $j($area || 'html');

	//setup the interactions working with forms
	SDNA.global.setupForms( $area );
	SDNA.global.setupActions( $area );
	SDNA.global.setupCalendarButtons( $area );
	
	//setup filter help bubbles
	SDNA.tabs.setupHelpButtons( $area );
	
	//setup file browse buttons
	$area.find('.share_box').bind('shared',
		function(){
			
			//do some cleanup and reset the share form
			var $shareBox 	= $j(this);
			var $form 		= $shareBox.find('form');
	
			//reset the form fields for a new input
			$form.find('textarea.comment,input.photo_caption').val('').blur(); 			
			
			//taking off the share_photo class removes the visible browse and caption fields
			$shareBox.removeClass('share_photo');
			
			//restore 'Add a photo' 
			$form.find('a.browse').text('Add a photo');
			
			//remove temporary file names
			$form.find('.file_name').remove();
			
			//reset the file uploader
			$form.find('[type=file]').val('');			
			
			
			$form.trigger('submitted');
			
		}
	);	
	
	$area.find('.share_box .file_chooser input[type=file]').change(
		function(e){
		
            var $file		= $j(this);
            var $shareBox 	= $file.parents('.share_box').eq(0);
            var $caption	= $shareBox.find('.photo_field');
            var filename 	= $file.val();
            
            // See if filename has a valid file suffixe
            var validFile = /\.(gif|jpg|png|jpeg)$/i;
           
            //this is a new file, remove the old name
            $shareBox.find('span.file_name').remove();
                        
            // If this is a valid file, then show the file name
            if ( validFile.test( filename ) ) {
            	
            	$shareBox.addClass('share_photo');
            	$file.siblings('a.browse').text('Change photo');
                $caption.after( $j('<span />').addClass('file_name').text( filename.truncate(28,'middle') ) );
            
            } else {
                
                // Remove comment
                $shareBox.removeClass('share_photo');
                $file.siblings('a.browse').text('Add a photo');
                
                //popup letting them know only images can be shown
				var message = '<em>' + filename + '</em> is not a valid image. Try to upload a <strong>gif</strong>, <strong>jpg</strong> or <strong>png</strong> image.';
				var $content = $j('<div />').append( '<h2>You can only upload images</h2>' );
				$content.append( $j('<p class="message"></p>').append(message) );
				
				//open the modal
				$content.modal( {onOpen: SDNA.global.onModalOpen, onClose: SDNA.global.onModalClose });

                //empty the file field
                $file.val('');
                
                // Stop bubble up
               e.stopPropagation();
            }
		}
	);	
	
	//setup the comments form 
	$area.find('.share_box form')
		.unbind('submit.share')
		.bind('submit.share',
		function(e){
			
			//create a reference to this form
			var $form 		= $j(this);
			var $shareBox   = $form.parents('.share_box').eq(0);
			var $comment 	= $form.find('textarea.comment'); 
			
			//prevent from a submit to page load
			e.preventDefault();
			
			var shareType = window.location.href.replace(/http:\/\/[^\/]+.([^\/]+).*/, '$1');
			var objectId = window.location.href.replace(/.*id:([^\/#]+).*/, '$1');
			if (objectId == window.location.href) {
				objectId = window.location.href.replace(/.*location=(.*)/, '$1');
			}
			
			var options = {
                'success': function(response) {
						
						//find the activity stream to plug the content into
						var $activity = $j('#location_activity,#home_activity_all,#event_activity_all');
						var $listItems = $activity.find('.item_list>li:not(.share)');
						
						//setup a ref to the new html 
						var $new = $j(response);
													
						//insert the new content into the DOM
						if( $listItems.length == 0 ){
							$activity.find('.item_list').prepend( $new );	
						} else {
							$listItems.eq(0).before( $new );
						}	
						
						//any empty or error rows, remove
						$listItems.filter('.empty,.error').remove();				
						
						//make sure the right tab is shown
						$activity.showTab();
						
						//setup any dynamics in this new html
						SDNA.global.onAreaLoad( $new );
						if (window.CONFIG.event_host_id && 
								window.CONFIG.viewer_id && 
								window.CONFIG.event_host_id == window.CONFIG.viewer_id) {
							$j('a[href*=#event_activity_host]').removeClass('loaded');
						}
						
						//lastly, give an indicator of new content
						$new.css({backgroundColor:'#F5E792'}).animate({backgroundColor:'#FFFFFF'},900);
						
						$shareBox.trigger('shared');
						
                },
                'type': 'POST',
                'iframe': true,
                'data': {
                     'type': shareType,
                     'id': objectId
                 }
            };
			//do a simple test to see if there is a comment
			if( (/\S/).test( $comment.val() ) ){						
				$form.ajaxSubmit(options);
			
			//if no comment, then 
			} else {
				
				e.preventDefault();
				
				//pop a message
				$content = $j('<div />')
							.append( '<h2>Whoopsy Daisy!</h2>' )
							.append( '<p class="message"><strong>Whoa there.</strong> We couldn&apos;t post your comment because it was blank.</p>' );
				
				//open the modal
				$content.modal( {onOpen: SDNA.global.onModalOpen, onClose: SDNA.global.onModalClose });				
				
				//trigger the on submitted form handler
				$form.trigger('submitted');
			
			}
		}
	);	
	$area.find('.share_box textarea.comment').change(function(){
		$j(this).parents('.share_box').eq(0).addClass('share_changed');
	});

	$area.find('.share_box form[action*=SubmitComment]').each(function(i) {
		$j(this).append($j('<input/>').attr({name: 'url', type: 'hidden', value: window.location.href}));
	});
	
	//create tabs of all lists with a class of tabs by default
	$area.find('ol.tabs,ul.tabs').tabs(
		{
			onload: function( oTabContent ){
				SDNA.global.onAreaLoad( oTabContent );
			}
		}
	);	
	
	//setup the person menus
	$area.find('div.person_menu').personMenu();	
					
	$area.find('button.show_more').setupShowMore();
	
	$area.find('input#friends_only[type=checkbox]').click(function() { $j(this).clickFriendsOnly(); });
	
	$area.find('a.rsvp').bind('click.userComing',
		function(e) {
			e.preventDefault();
			$j('input#event_rsvp_attending').trigger('click.rsvp');
		}
	);
	
	
}//SDNA.global.onAreaLoad

SDNA.global.loadShortUrl = function($area) {
    
    var $form = $area.find('.share_box form');
    
    var $checkboxes = $j(this);
    
    //get the short url to append to their comment
    $j.getJSON('/ajax/Shorten/Index.jsn', { 'url' : window.location.href }, function(data) {
        $form.append("<input type='hidden' id='shorturl' name='shorturl' value='" + data.url + "' />");
        $checkboxes.unbind('click.shorturl');
    });
}
	
SDNA.global.triggerAction = function( attrs ){
	
	$action = $j('<a/>').attr( attrs );
	SDNA.global.setupActions( $action );
	$action.triggerHandler('click.action');
	
} 
 
SDNA.photos = {};

window.size = function(){
 var d = document, de = d.documentElement, win = window; 
 var h = (win.innerHeight? win.innerHeight : de.clientHeight?de.clientHeight:d.body.clientHeight );
 var w = (win.innerWidth? win.innerWidth : de.clientWidth?de.clientWidth:d.body.clientWidth );
 return {width:w,height:h};
} 

SDNA.photos.bind = function(){
	
	//setup zoom
	$j('.photo_link,.photo_zoom')
		.live('click.photo',
			function(e){
				
				//keep the image link from opening
				e.preventDefault();
				
				$this = $j(this);
				
				SDNA.photos.zoom( {src: $this.attr('href'), caption:$this.attr('title')} );				
			}		
	);	
}

SDNA.photos.fitTo = function( img, fit ){
	
	var h = img.height;
	var w = img.width;
	var r = h/w;
	
	//fit image dimensions
	if( r <=1 && w > fit.width ){
		w = fit.width;
		h = Math.floor(w * r);
	}
	if( h > fit.height ){
		h = fit.height;
		w = Math.floor(h / r);
	}
	
	return {width:w,height:h};
}

SDNA.photos.zoom = function( opts ){
	
	//extend the options
	opts = $j.extend( {margin:15, caption: '', minWidth: 300}, opts );
	
	//show a progress indicator
	$ind = $j('<div/>').append( $j('<span/>').addClass('loading') );
	$j($ind).modal(
		{	
			  onOpen: SDNA.global.onModalOpen, 
			  onClose: SDNA.global.onModalClose
		}
	);
	
	var $container = $j('#simplemodal-container');
	var $data = $container.find('.simplemodal-data');
	
	//preload the image
	var img = new Image();
	img.onload = function(){
		
		//add the title in
		$caption = $j('<h2/>').text( opts.caption );
		$container.triggerHandler('modal.loaded');
		$data.empty().append( $caption );
		
		var captionHeight = $caption.height() + ( parseInt($caption.css('margin-bottom')) || 0 ) + ( parseInt($caption.css('margin-top')) || 0 );
		captionHeight = captionHeight == 0? 35: 0;

		var pad 	= parseInt($data.css('padding')) || 20;
		var marg 	= opts.margin;
		var win 	= window.size();
		var fitTo 	= {width: win.width - marg*2 - pad*2, height: win.height - marg*2 - pad*2 - captionHeight };
		
		var fit 	= SDNA.photos.fitTo( img, fitTo );
		
		//adjust the fit based on the options
		var boxFit = $j.extend({},fit);
		if( boxFit.width < opts.minWidth )	boxFit.width = opts.minWidth;
		
		var mod 	= {width: boxFit.width + pad, height: 'auto' };
		var data  = {width:boxFit.width, height:'auto'};
		
		$container.css( mod );
		$data.css( data );

		$img = $j(img);
		$img.attr( fit ).attr('alt',opts.title);
		
		//make an img container
		$box = $j('<div/>').addClass("image_box").append( $img );		
		$data.append( $box );
		
		$container.triggerHandler('modal.center');
		
	}
	
	img.onerror = function(){
		$container.triggerHandler('modal.loaded');
		$data.empty().append( $j('<div/>').addClass('error').text('Error loading image.') );
	}
	
	//kick off the image load
	$container.triggerHandler('modal.loading');
	img.src = opts.src;
} 
 
var Location = function() {}

SDNA.Location = new Location();
	
Location.prototype.setHomeLocation = function(jsonSpanID) {
	var jsonLocdata = $j('#' + jsonSpanID).text();
	$j.post(	'/ajax/User/SetHomeLocation.jsn', 
				jsonLocdata, 
				function(data,textStatus) {
					$j('#q').val('');
					$j('#searchResultsDiv').html('');
					$j('#homelocationtitle').text(data['locTitle']);
				}, 
				'json');
}

Location.prototype.setRegHomeLocation = function(jsonSpanID) {
	var jsonLocdata = $j('#' + jsonSpanID).text();	
	$j.post(	'/ajax/User/setRegHomeLocation.jsn', 
				jsonLocdata,
				function(data,textStatus) {
					$j('#q').val('');
					$j('#searchResultsDiv').hide();
					$j('#searchform').hide();
					$j('#currentloc').show();
					$j('#homelocationtitle').text(data['locTitle']);
				}, 
				'json');
}

Location.prototype.addEventLocation = function(jsonSpanID) {
	var jsonLocdata = $j('#' + jsonSpanID).text();	
	var id = $j('#eventid').val();
	jsonLocdata = jsonLocdata.substr(0, jsonLocdata.length -1) + ',"event_id":"'+id+'"}';
	
	$j.post(	'/ajax/Event/createEventLocation.jsn', 
				jsonLocdata,
				function(data,textStatus) {
					$j('#q').val('');
					$j('#searchResultsDiv').hide();
					$j('#searchform').hide();
					$j('#currentloc').show();
					$j('#eventlocationtitle').text(data['locTitle']);
					$j('#removeevent').attr('eventlocid',data['eventlocid']); 
				}, 
				'json');
}

Location.prototype.removeEventLocation = function(element) {
	
	var eventlocid = element.getAttribute('eventlocid');
	var eventid = $j('#eventid').val();
	
	
	$j.post(	'/ajax/Event/removeEventLocation.jsn', 
				{"eventid":eventid, "eventlocid":eventlocid},
				function(data) {
					$j('#q').val('');
					$j('#searchform').show();
					$j('#currentloc').hide();
				}, 
				'json');
}

Location.prototype.setCurrentLocation = function( options ){
	
	//setup the options for the request
	options.callback 	= options.callback || function(){};
	options.json 		= options.json || null;
	options.url 		= options.url || '/ajax/User/SetCurLocation.jsn';
	
	//post the request
	$j.post( 
		options.url,
		options.json,
		options.callback,
		'json'
	);
	
} 

Location.prototype.addFavorite = function( options ) {

	//setup the method to use
	options.method = 'addFavorite.jsn';	

	SDNA.Location.toggleFavorite( options );
	
}

Location.prototype.removeFavorite = function( options ){
	
	//setup the method to use
	options.method = 'removeFavorite';	

	SDNA.Location.toggleFavorite( options );
	
}

Location.prototype.toggleFavorite = function( options ){
	
	options.url 		= '/ajax/Location/' + options.method + '/id:' + options.location_id;
	
	//post the request
	$j.post( 
		options.url,
		options.vars,
		options.callback,
		'json'
	);
}




Location.prototype.setCurLocation = function(jsonSpanID) {
	var jsonLocdata = $j('#' + jsonSpanID).text();
	$j.post(	'/ajax/User/SetCurLocation.jsn', 
				jsonLocdata, 
				function(data,textStatus) {
					$j('#q').val('');
					$j('#searchResultsDiv').html('');
					if (data['success']) {
						$j('#curlocationtitle').text(data['locTitle']);
						$j('#' + jsonSpanID).parent().html("This is your current location.");
					} else {
						$j('#' + jsonSpanID).parent().children("#locationselect").html("We've experienced an error setting your location. Click here to try again.");
					}
				}, 
				'json');
}

Location.prototype.setLocationAsCurrent = function(link, id) {
	 $j(".currentloc").text('Set as current location');
	 //hmm, can't do this as we don't know the other location links id.
	 //at least setting the text back.
	 //$j(".currentloc").attr('onclick', 'SDNA.Location.setLocationAsCurrent(this, {{$locs[i].id}})');

	  $j.ajax({
        url: '/User/setLocationAsCurrent/location:'+id,
        success: function(z) {  
            $j(link).text("This is your current location.");
        }  
    });
    return false;
}

Location.prototype.setLocationAsFavorite = function(link, id) {
	  $j.ajax({
        url: '/Location/addFavorite/id:'+id,
        success: function(z) {  
            $j(link).text("Remove as Favorite");
            link.setAttribute("onclick", 'SDNA.Location.removeLocationAsFavorite(this, '+id+')');
        }  
    });
    return false;
}

Location.prototype.removeLocationAsFavorite = function(link, id) {
	  $j.ajax({
        url: '/Location/removeFavorite/id:'+id,
        success: function(z) {  
            $j(link).text("Add as Favorite");
            link.setAttribute("onclick", 'SDNA.Location.setLocationAsFavorite(this, '+id+')');
        }  
    });
    return false;
}

Location.prototype.removeLocationFromFavList = function(locId, idtoHide) {
	  $j.ajax({
        url: '/Location/removeFavorite/id:'+locId,
        success: function(z) {  
            $j('#'+idtoHide).hide("slow");
        }  
    });
    return false;
}
 
 
var HomePage = function() {}

SDNA.HomePage = new HomePage();

HomePage.prototype.showInfoPanel = function(elementid, active) {
	$j('#welcome-content1').hide();
	$j('#welcome-content2').hide();
	$j('#welcome-content3').hide();
	
	$j("#welcome-tab1").removeClass("active");
	$j("#welcome-tab2").removeClass("active");
	$j("#welcome-tab3").removeClass("active");

	$j(active).addClass("active");
    $j("#"+elementid).fadeIn("slow");     
}


 
 
SDNA.fb = function(){};
SDNA.fb.updatePermissions = function(perms) {
	if (perms != false) {
		if ($j.isArray(perms)) perms = perms.join(',');
		$j.ajax({ type: "POST", url: '/ajax/User/AddFBPermissions.jsn', data: {permissions: perms}, cache: false});
	}
}
SDNA.fb.initFacebookSettingsModal = function(html) {
	$html = $j(html);
	
	$html.find('.facebook_settings form button[name=cancel]')
		.unbind('click.cancel')
		.bind(
		'click.cancel',
		function() { window.location.reload(); }
	);
	
	$html.find('.facebook_settings form').submit(
		function(e) { 
			e.preventDefault();
			$this = $j(this);

			//save the settings
			$j.post(
				$this.attr('action'),
				$this.serialize(),
				function( response ){					
					if( response.success == true ){						
						$this.trigger('submitted');
						$j.modal.close();
						window.location.reload();
					}					
				},
				'json'
			);
		}
	);
}

SDNA.fb.onConnect = function() {
    $j.ajax({ 
        url: 		'/ajax/User/ConnectWithFacebook.htm',
        cache: 		false,
        success: 	function( data ){            
            //setup dialog options
            var dialogOptions = { modal: false };
            
            //open this content in a modal
            $j.modal( 
                data , 
                    {
                        onOpen: function( oDialog ){ 	                	
                            SDNA.global.onModalOpen(oDialog, dialogOptions);
                            SDNA.fb.initFacebookSettingsModal(oDialog.container);
                        }, 
                        onClose: function( oDialog ){ 
                            SDNA.global.onModalClose(oDialog, dialogOptions);
                        },
                        onShow: function( oDialog ){
                            SDNA.global.onModalShow( oDialog, dialogOptions );
                        },
                        close: !dialogOptions.modal
                    }
            );
        }
    });
}

function facebook_onlogin()
{
	location.replace("/User/facebookLogin");
	
}

function facebook_showPostToFB()
{
  jQuery('#facebook_post_fieldset').show();
  jQuery('#facebook_loginbutton').hide();
}
 
 
