/*!
 * Modernizr v2.0.6
 * http://www.modernizr.com
 *
 * Copyright (c) 2009-2011 Faruk Ates, Paul Irish, Alex Sexton
 * Dual-licensed under the BSD or MIT licenses: www.modernizr.com/license/
 */

/*
 * Modernizr tests which native CSS3 and HTML5 features are available in
 * the current UA and makes the results available to you in two ways:
 * as properties on a global Modernizr object, and as classes on the
 * <html> element. This information allows you to progressively enhance
 * your pages with a granular level of control over the experience.
 *
 * Modernizr has an optional (not included) conditional resource loader
 * called Modernizr.load(), based on Yepnope.js (yepnopejs.com).
 * To get a build that includes Modernizr.load(), as well as choosing
 * which tests to include, go to www.modernizr.com/download/
 *
 * Authors        Faruk Ates, Paul Irish, Alex Sexton, 
 * Contributors   Ryan Seddon, Ben Alman
 */

window.Modernizr = (function( window, document, undefined ) {

    var version = '2.0.6',

    Modernizr = {},
    
    // option for enabling the HTML classes to be added
    enableClasses = true,

    docElement = document.documentElement,
    docHead = document.head || document.getElementsByTagName('head')[0],

    /**
     * Create our "modernizr" element that we do most feature tests on.
     */
    mod = 'modernizr',
    modElem = document.createElement(mod),
    mStyle = modElem.style,

    /**
     * Create the input element for various Web Forms feature tests.
     */
    inputElem = document.createElement('input'),

    smile = ':)',

    toString = Object.prototype.toString,

    // List of property values to set for css tests. See ticket #21
    prefixes = ' -webkit- -moz- -o- -ms- -khtml- '.split(' '),

    // Following spec is to expose vendor-specific style properties as:
    //   elem.style.WebkitBorderRadius
    // and the following would be incorrect:
    //   elem.style.webkitBorderRadius

    // Webkit ghosts their properties in lowercase but Opera & Moz do not.
    // Microsoft foregoes prefixes entirely <= IE8, but appears to
    //   use a lowercase `ms` instead of the correct `Ms` in IE9

    // More here: http://github.com/Modernizr/Modernizr/issues/issue/21
    domPrefixes = 'Webkit Moz O ms Khtml'.split(' '),

    ns = {'svg': 'http://www.w3.org/2000/svg'},

    tests = {},
    inputs = {},
    attrs = {},

    classes = [],

    featureName, // used in testing loop


    // Inject element with style element and some CSS rules
    injectElementWithStyles = function( rule, callback, nodes, testnames ) {

      var style, ret, node,
          div = document.createElement('div');

      if ( parseInt(nodes, 10) ) {
          // In order not to give false positives we create a node for each test
          // This also allows the method to scale for unspecified uses
          while ( nodes-- ) {
              node = document.createElement('div');
              node.id = testnames ? testnames[nodes] : mod + (nodes + 1);
              div.appendChild(node);
          }
      }

      // <style> elements in IE6-9 are considered 'NoScope' elements and therefore will be removed
      // when injected with innerHTML. To get around this you need to prepend the 'NoScope' element
      // with a 'scoped' element, in our case the soft-hyphen entity as it won't mess with our measurements.
      // http://msdn.microsoft.com/en-us/library/ms533897%28VS.85%29.aspx
      style = ['&shy;', '<style>', rule, '</style>'].join('');
      div.id = mod;
      div.innerHTML += style;
      docElement.appendChild(div);

      ret = callback(div, rule);
      div.parentNode.removeChild(div);

      return !!ret;

    },


    // adapted from matchMedia polyfill
    // by Scott Jehl and Paul Irish
    // gist.github.com/786768
    testMediaQuery = function( mq ) {

      if ( window.matchMedia ) {
        return matchMedia(mq).matches;
      }

      var bool;

      injectElementWithStyles('@media ' + mq + ' { #' + mod + ' { position: absolute; } }', function( node ) {
        bool = (window.getComputedStyle ?
                  getComputedStyle(node, null) :
                  node.currentStyle)['position'] == 'absolute';
      });

      return bool;

     },


    /**
      * isEventSupported determines if a given element supports the given event
      * function from http://yura.thinkweb2.com/isEventSupported/
      */
    isEventSupported = (function() {

      var TAGNAMES = {
        'select': 'input', 'change': 'input',
        'submit': 'form', 'reset': 'form',
        'error': 'img', 'load': 'img', 'abort': 'img'
      };

      function isEventSupported( eventName, element ) {

        element = element || document.createElement(TAGNAMES[eventName] || 'div');
        eventName = 'on' + eventName;

        // When using `setAttribute`, IE skips "unload", WebKit skips "unload" and "resize", whereas `in` "catches" those
        var isSupported = eventName in element;

        if ( !isSupported ) {
          // If it has no `setAttribute` (i.e. doesn't implement Node interface), try generic element
          if ( !element.setAttribute ) {
            element = document.createElement('div');
          }
          if ( element.setAttribute && element.removeAttribute ) {
            element.setAttribute(eventName, '');
            isSupported = is(element[eventName], 'function');

            // If property was created, "remove it" (by setting value to `undefined`)
            if ( !is(element[eventName], undefined) ) {
              element[eventName] = undefined;
            }
            element.removeAttribute(eventName);
          }
        }

        element = null;
        return isSupported;
      }
      return isEventSupported;
    })();

    // hasOwnProperty shim by kangax needed for Safari 2.0 support
    var _hasOwnProperty = ({}).hasOwnProperty, hasOwnProperty;
    if ( !is(_hasOwnProperty, undefined) && !is(_hasOwnProperty.call, undefined) ) {
      hasOwnProperty = function (object, property) {
        return _hasOwnProperty.call(object, property);
      };
    }
    else {
      hasOwnProperty = function (object, property) { /* yes, this can give false positives/negatives, but most of the time we don't care about those */
        return ((property in object) && is(object.constructor.prototype[property], undefined));
      };
    }

    /**
     * setCss applies given styles to the Modernizr DOM node.
     */
    function setCss( str ) {
        mStyle.cssText = str;
    }

    /**
     * setCssAll extrapolates all vendor-specific css strings.
     */
    function setCssAll( str1, str2 ) {
        return setCss(prefixes.join(str1 + ';') + ( str2 || '' ));
    }

    /**
     * is returns a boolean for if typeof obj is exactly type.
     */
    function is( obj, type ) {
        return typeof obj === type;
    }

    /**
     * contains returns a boolean for if substr is found within str.
     */
    function contains( str, substr ) {
        return !!~('' + str).indexOf(substr);
    }

    /**
     * testProps is a generic CSS / DOM property test; if a browser supports
     *   a certain property, it won't return undefined for it.
     *   A supported CSS property returns empty string when its not yet set.
     */
    function testProps( props, prefixed ) {
        for ( var i in props ) {
            if ( mStyle[ props[i] ] !== undefined ) {
                return prefixed == 'pfx' ? props[i] : true;
            }
        }
        return false;
    }

    /**
     * testPropsAll tests a list of DOM properties we want to check against.
     *   We specify literally ALL possible (known and/or likely) properties on
     *   the element including the non-vendor prefixed one, for forward-
     *   compatibility.
     */
    function testPropsAll( prop, prefixed ) {

        var ucProp  = prop.charAt(0).toUpperCase() + prop.substr(1),
            props   = (prop + ' ' + domPrefixes.join(ucProp + ' ') + ucProp).split(' ');

        return testProps(props, prefixed);
    }

    /**
     * testBundle tests a list of CSS features that require element and style injection.
     *   By bundling them together we can reduce the need to touch the DOM multiple times.
     */
    /*>>testBundle*/
    var testBundle = (function( styles, tests ) {
        var style = styles.join(''),
            len = tests.length;

        injectElementWithStyles(style, function( node, rule ) {
            var style = document.styleSheets[document.styleSheets.length - 1],
                // IE8 will bork if you create a custom build that excludes both fontface and generatedcontent tests.
                // So we check for cssRules and that there is a rule available
                // More here: https://github.com/Modernizr/Modernizr/issues/288 & https://github.com/Modernizr/Modernizr/issues/293
                cssText = style.cssRules && style.cssRules[0] ? style.cssRules[0].cssText : style.cssText || "",
                children = node.childNodes, hash = {};

            while ( len-- ) {
                hash[children[len].id] = children[len];
            }

            /*>>touch*/           Modernizr['touch'] = ('ontouchstart' in window) || hash['touch'].offsetTop === 9; /*>>touch*/
            /*>>csstransforms3d*/ Modernizr['csstransforms3d'] = hash['csstransforms3d'].offsetLeft === 9;          /*>>csstransforms3d*/
            /*>>generatedcontent*/Modernizr['generatedcontent'] = hash['generatedcontent'].offsetHeight >= 1;       /*>>generatedcontent*/
            /*>>fontface*/        Modernizr['fontface'] = /src/i.test(cssText) &&
                                                                  cssText.indexOf(rule.split(' ')[0]) === 0;        /*>>fontface*/
        }, len, tests);

    })([
        // Pass in styles to be injected into document
        /*>>fontface*/        '@font-face {font-family:"font";src:url("https://")}'         /*>>fontface*/
        
        /*>>touch*/           ,['@media (',prefixes.join('touch-enabled),('),mod,')',
                                '{#touch{top:9px;position:absolute}}'].join('')           /*>>touch*/
                                
        /*>>csstransforms3d*/ ,['@media (',prefixes.join('transform-3d),('),mod,')',
                                '{#csstransforms3d{left:9px;position:absolute}}'].join('')/*>>csstransforms3d*/
                                
        /*>>generatedcontent*/,['#generatedcontent:after{content:"',smile,'";visibility:hidden}'].join('')  /*>>generatedcontent*/
    ],
      [
        /*>>fontface*/        'fontface'          /*>>fontface*/
        /*>>touch*/           ,'touch'            /*>>touch*/
        /*>>csstransforms3d*/ ,'csstransforms3d'  /*>>csstransforms3d*/
        /*>>generatedcontent*/,'generatedcontent' /*>>generatedcontent*/
        
    ]);/*>>testBundle*/


    /**
     * Tests
     * -----
     */

    tests['flexbox'] = function() {
        /**
         * setPrefixedValueCSS sets the property of a specified element
         * adding vendor prefixes to the VALUE of the property.
         * @param {Element} element
         * @param {string} property The property name. This will not be prefixed.
         * @param {string} value The value of the property. This WILL be prefixed.
         * @param {string=} extra Additional CSS to append unmodified to the end of
         * the CSS string.
         */
        function setPrefixedValueCSS( element, property, value, extra ) {
            property += ':';
            element.style.cssText = (property + prefixes.join(value + ';' + property)).slice(0, -property.length) + (extra || '');
        }

        /**
         * setPrefixedPropertyCSS sets the property of a specified element
         * adding vendor prefixes to the NAME of the property.
         * @param {Element} element
         * @param {string} property The property name. This WILL be prefixed.
         * @param {string} value The value of the property. This will not be prefixed.
         * @param {string=} extra Additional CSS to append unmodified to the end of
         * the CSS string.
         */
        function setPrefixedPropertyCSS( element, property, value, extra ) {
            element.style.cssText = prefixes.join(property + ':' + value + ';') + (extra || '');
        }

        var c = document.createElement('div'),
            elem = document.createElement('div');

        setPrefixedValueCSS(c, 'display', 'box', 'width:42px;padding:0;');
        setPrefixedPropertyCSS(elem, 'box-flex', '1', 'width:10px;');

        c.appendChild(elem);
        docElement.appendChild(c);

        var ret = elem.offsetWidth === 42;

        c.removeChild(elem);
        docElement.removeChild(c);

        return ret;
    };

    // On the S60 and BB Storm, getContext exists, but always returns undefined
    // http://github.com/Modernizr/Modernizr/issues/issue/97/

    tests['canvas'] = function() {
        var elem = document.createElement('canvas');
        return !!(elem.getContext && elem.getContext('2d'));
    };

    tests['canvastext'] = function() {
        return !!(Modernizr['canvas'] && is(document.createElement('canvas').getContext('2d').fillText, 'function'));
    };

    // This WebGL test may false positive. 
    // But really it's quite impossible to know whether webgl will succeed until after you create the context. 
    // You might have hardware that can support a 100x100 webgl canvas, but will not support a 1000x1000 webgl 
    // canvas. So this feature inference is weak, but intentionally so.
    
    // It is known to false positive in FF4 with certain hardware and the iPad 2.
    
    tests['webgl'] = function() {
        return !!window.WebGLRenderingContext;
    };

    /*
     * The Modernizr.touch test only indicates if the browser supports
     *    touch events, which does not necessarily reflect a touchscreen
     *    device, as evidenced by tablets running Windows 7 or, alas,
     *    the Palm Pre / WebOS (touch) phones.
     *
     * Additionally, Chrome (desktop) used to lie about its support on this,
     *    but that has since been rectified: http://crbug.com/36415
     *
     * We also test for Firefox 4 Multitouch Support.
     *
     * For more info, see: http://modernizr.github.com/Modernizr/touch.html
     */

    tests['touch'] = function() {
        return Modernizr['touch'];
    };

    /**
     * geolocation tests for the new Geolocation API specification.
     *   This test is a standards compliant-only test; for more complete
     *   testing, including a Google Gears fallback, please see:
     *   http://code.google.com/p/geo-location-javascript/
     * or view a fallback solution using google's geo API:
     *   http://gist.github.com/366184
     */
    tests['geolocation'] = function() {
        return !!navigator.geolocation;
    };

    // Per 1.6:
    // This used to be Modernizr.crosswindowmessaging but the longer
    // name has been deprecated in favor of a shorter and property-matching one.
    // The old API is still available in 1.6, but as of 2.0 will throw a warning,
    // and in the first release thereafter disappear entirely.
    tests['postmessage'] = function() {
      return !!window.postMessage;
    };

    // Web SQL database detection is tricky:

    // In chrome incognito mode, openDatabase is truthy, but using it will
    //   throw an exception: http://crbug.com/42380
    // We can create a dummy database, but there is no way to delete it afterwards.

    // Meanwhile, Safari users can get prompted on any database creation.
    //   If they do, any page with Modernizr will give them a prompt:
    //   http://github.com/Modernizr/Modernizr/issues/closed#issue/113

    // We have chosen to allow the Chrome incognito false positive, so that Modernizr
    //   doesn't litter the web with these test databases. As a developer, you'll have
    //   to account for this gotcha yourself.
    tests['websqldatabase'] = function() {
      var result = !!window.openDatabase;
      /*  if (result){
            try {
              result = !!openDatabase( mod + "testdb", "1.0", mod + "testdb", 2e4);
            } catch(e) {
            }
          }  */
      return result;
    };

    // Vendors had inconsistent prefixing with the experimental Indexed DB:
    // - Webkit's implementation is accessible through webkitIndexedDB
    // - Firefox shipped moz_indexedDB before FF4b9, but since then has been mozIndexedDB
    // For speed, we don't test the legacy (and beta-only) indexedDB
    tests['indexedDB'] = function() {
      for ( var i = -1, len = domPrefixes.length; ++i < len; ){
        if ( window[domPrefixes[i].toLowerCase() + 'IndexedDB'] ){
          return true;
        }
      }
      return !!window.indexedDB;
    };

    // documentMode logic from YUI to filter out IE8 Compat Mode
    //   which false positives.
    tests['hashchange'] = function() {
      return isEventSupported('hashchange', window) && (document.documentMode === undefined || document.documentMode > 7);
    };

    // Per 1.6:
    // This used to be Modernizr.historymanagement but the longer
    // name has been deprecated in favor of a shorter and property-matching one.
    // The old API is still available in 1.6, but as of 2.0 will throw a warning,
    // and in the first release thereafter disappear entirely.
    tests['history'] = function() {
      return !!(window.history && history.pushState);
    };

    tests['draganddrop'] = function() {
        return isEventSupported('dragstart') && isEventSupported('drop');
    };

    // Mozilla is targeting to land MozWebSocket for FF6
    // bugzil.la/659324
    tests['websockets'] = function() {
        for ( var i = -1, len = domPrefixes.length; ++i < len; ){
          if ( window[domPrefixes[i] + 'WebSocket'] ){
            return true;
          }
        }
        return 'WebSocket' in window;
    };


    // http://css-tricks.com/rgba-browser-support/
    tests['rgba'] = function() {
        // Set an rgba() color and check the returned value

        setCss('background-color:rgba(150,255,150,.5)');

        return contains(mStyle.backgroundColor, 'rgba');
    };

    tests['hsla'] = function() {
        // Same as rgba(), in fact, browsers re-map hsla() to rgba() internally,
        //   except IE9 who retains it as hsla

        setCss('background-color:hsla(120,40%,100%,.5)');

        return contains(mStyle.backgroundColor, 'rgba') || contains(mStyle.backgroundColor, 'hsla');
    };

    tests['multiplebgs'] = function() {
        // Setting multiple images AND a color on the background shorthand property
        //  and then querying the style.background property value for the number of
        //  occurrences of "url(" is a reliable method for detecting ACTUAL support for this!

        setCss('background:url(https://),url(https://),red url(https://)');

        // If the UA supports multiple backgrounds, there should be three occurrences
        //   of the string "url(" in the return value for elemStyle.background

        return /(url\s*\(.*?){3}/.test(mStyle.background);
    };


    // In testing support for a given CSS property, it's legit to test:
    //    `elem.style[styleName] !== undefined`
    // If the property is supported it will return an empty string,
    // if unsupported it will return undefined.

    // We'll take advantage of this quick test and skip setting a style
    // on our modernizr element, but instead just testing undefined vs
    // empty string.


    tests['backgroundsize'] = function() {
        return testPropsAll('backgroundSize');
    };

    tests['borderimage'] = function() {
        return testPropsAll('borderImage');
    };


    // Super comprehensive table about all the unique implementations of
    // border-radius: http://muddledramblings.com/table-of-css3-border-radius-compliance

    tests['borderradius'] = function() {
        return testPropsAll('borderRadius');
    };

    // WebOS unfortunately false positives on this test.
    tests['boxshadow'] = function() {
        return testPropsAll('boxShadow');
    };

    // FF3.0 will false positive on this test
    tests['textshadow'] = function() {
        return document.createElement('div').style.textShadow === '';
    };


    tests['opacity'] = function() {
        // Browsers that actually have CSS Opacity implemented have done so
        //  according to spec, which means their return values are within the
        //  range of [0.0,1.0] - including the leading zero.

        setCssAll('opacity:.55');

        // The non-literal . in this regex is intentional:
        //   German Chrome returns this value as 0,55
        // https://github.com/Modernizr/Modernizr/issues/#issue/59/comment/516632
        return /^0.55$/.test(mStyle.opacity);
    };


    tests['cssanimations'] = function() {
        return testPropsAll('animationName');
    };


    tests['csscolumns'] = function() {
        return testPropsAll('columnCount');
    };


    tests['cssgradients'] = function() {
        /**
         * For CSS Gradients syntax, please see:
         * http://webkit.org/blog/175/introducing-css-gradients/
         * https://developer.mozilla.org/en/CSS/-moz-linear-gradient
         * https://developer.mozilla.org/en/CSS/-moz-radial-gradient
         * http://dev.w3.org/csswg/css3-images/#gradients-
         */

        var str1 = 'background-image:',
            str2 = 'gradient(linear,left top,right bottom,from(#9f9),to(white));',
            str3 = 'linear-gradient(left top,#9f9, white);';

        setCss(
            (str1 + prefixes.join(str2 + str1) + prefixes.join(str3 + str1)).slice(0, -str1.length)
        );

        return contains(mStyle.backgroundImage, 'gradient');
    };


    tests['cssreflections'] = function() {
        return testPropsAll('boxReflect');
    };


    tests['csstransforms'] = function() {
        return !!testProps(['transformProperty', 'WebkitTransform', 'MozTransform', 'OTransform', 'msTransform']);
    };


    tests['csstransforms3d'] = function() {

        var ret = !!testProps(['perspectiveProperty', 'WebkitPerspective', 'MozPerspective', 'OPerspective', 'msPerspective']);

        // Webkitâ€™s 3D transforms are passed off to the browser's own graphics renderer.
        //   It works fine in Safari on Leopard and Snow Leopard, but not in Chrome in
        //   some conditions. As a result, Webkit typically recognizes the syntax but
        //   will sometimes throw a false positive, thus we must do a more thorough check:
        if ( ret && 'webkitPerspective' in docElement.style ) {

          // Webkit allows this media query to succeed only if the feature is enabled.
          // `@media (transform-3d),(-o-transform-3d),(-moz-transform-3d),(-ms-transform-3d),(-webkit-transform-3d),(modernizr){ ... }`
          ret = Modernizr['csstransforms3d'];
        }
        return ret;
    };


    tests['csstransitions'] = function() {
        return testPropsAll('transitionProperty');
    };


    /*>>fontface*/
    // @font-face detection routine by Diego Perini
    // http://javascript.nwbox.com/CSSSupport/
    tests['fontface'] = function() {
        return Modernizr['fontface'];
    };
    /*>>fontface*/

    // CSS generated content detection
    tests['generatedcontent'] = function() {
        return Modernizr['generatedcontent'];
    };



    // These tests evaluate support of the video/audio elements, as well as
    // testing what types of content they support.
    //
    // We're using the Boolean constructor here, so that we can extend the value
    // e.g.  Modernizr.video     // true
    //       Modernizr.video.ogg // 'probably'
    //
    // Codec values from : http://github.com/NielsLeenheer/html5test/blob/9106a8/index.html#L845
    //                     thx to NielsLeenheer and zcorpan

    // Note: in FF 3.5.1 and 3.5.0, "no" was a return value instead of empty string.
    //   Modernizr does not normalize for that.

    tests['video'] = function() {
        var elem = document.createElement('video'),
            bool = false;
            
        // IE9 Running on Windows Server SKU can cause an exception to be thrown, bug #224
        try {
            if ( bool = !!elem.canPlayType ) {
                bool      = new Boolean(bool);
                bool.ogg  = elem.canPlayType('video/ogg; codecs="theora"');

                // Workaround required for IE9, which doesn't report video support without audio codec specified.
                //   bug 599718 @ msft connect
                var h264 = 'video/mp4; codecs="avc1.42E01E';
                bool.h264 = elem.canPlayType(h264 + '"') || elem.canPlayType(h264 + ', mp4a.40.2"');

                bool.webm = elem.canPlayType('video/webm; codecs="vp8, vorbis"');
            }
            
        } catch(e) { }
        
        return bool;
    };

    tests['audio'] = function() {
        var elem = document.createElement('audio'),
            bool = false;

        try { 
            if ( bool = !!elem.canPlayType ) {
                bool      = new Boolean(bool);
                bool.ogg  = elem.canPlayType('audio/ogg; codecs="vorbis"');
                bool.mp3  = elem.canPlayType('audio/mpeg;');

                // Mimetypes accepted:
                //   https://developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements
                //   http://bit.ly/iphoneoscodecs
                bool.wav  = elem.canPlayType('audio/wav; codecs="1"');
                bool.m4a  = elem.canPlayType('audio/x-m4a;') || elem.canPlayType('audio/aac;');
            }
        } catch(e) { }
        
        return bool;
    };


    // Firefox has made these tests rather unfun.

    // In FF4, if disabled, window.localStorage should === null.

    // Normally, we could not test that directly and need to do a
    //   `('localStorage' in window) && ` test first because otherwise Firefox will
    //   throw http://bugzil.la/365772 if cookies are disabled

    // However, in Firefox 4 betas, if dom.storage.enabled == false, just mentioning
    //   the property will throw an exception. http://bugzil.la/599479
    // This looks to be fixed for FF4 Final.

    // Because we are forced to try/catch this, we'll go aggressive.

    // FWIW: IE8 Compat mode supports these features completely:
    //   http://www.quirksmode.org/dom/html5.html
    // But IE8 doesn't support either with local files

    tests['localstorage'] = function() {
        try {
            return !!localStorage.getItem;
        } catch(e) {
            return false;
        }
    };

    tests['sessionstorage'] = function() {
        try {
            return !!sessionStorage.getItem;
        } catch(e){
            return false;
        }
    };


    tests['webworkers'] = function() {
        return !!window.Worker;
    };


    tests['applicationcache'] = function() {
        return !!window.applicationCache;
    };


    // Thanks to Erik Dahlstrom
    tests['svg'] = function() {
        return !!document.createElementNS && !!document.createElementNS(ns.svg, 'svg').createSVGRect;
    };

    // specifically for SVG inline in HTML, not within XHTML
    // test page: paulirish.com/demo/inline-svg
    tests['inlinesvg'] = function() {
      var div = document.createElement('div');
      div.innerHTML = '<svg/>';
      return (div.firstChild && div.firstChild.namespaceURI) == ns.svg;
    };

    // Thanks to F1lt3r and lucideer, ticket #35
    tests['smil'] = function() {
        return !!document.createElementNS && /SVG/.test(toString.call(document.createElementNS(ns.svg, 'animate')));
    };

    tests['svgclippaths'] = function() {
        // Possibly returns a false positive in Safari 3.2?
        return !!document.createElementNS && /SVG/.test(toString.call(document.createElementNS(ns.svg, 'clipPath')));
    };

    // input features and input types go directly onto the ret object, bypassing the tests loop.
    // Hold this guy to execute in a moment.
    function webforms() {
        // Run through HTML5's new input attributes to see if the UA understands any.
        // We're using f which is the <input> element created early on
        // Mike Taylr has created a comprehensive resource for testing these attributes
        //   when applied to all input types:
        //   http://miketaylr.com/code/input-type-attr.html
        // spec: http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary
        
        // Only input placeholder is tested while textarea's placeholder is not. 
        // Currently Safari 4 and Opera 11 have support only for the input placeholder
        // Both tests are available in feature-detects/forms-placeholder.js
        Modernizr['input'] = (function( props ) {
            for ( var i = 0, len = props.length; i < len; i++ ) {
                attrs[ props[i] ] = !!(props[i] in inputElem);
            }
            return attrs;
        })('autocomplete autofocus list placeholder max min multiple pattern required step'.split(' '));

        // Run through HTML5's new input types to see if the UA understands any.
        //   This is put behind the tests runloop because it doesn't return a
        //   true/false like all the other tests; instead, it returns an object
        //   containing each input type with its corresponding true/false value

        // Big thanks to @miketaylr for the html5 forms expertise. http://miketaylr.com/
        Modernizr['inputtypes'] = (function(props) {

            for ( var i = 0, bool, inputElemType, defaultView, len = props.length; i < len; i++ ) {

                inputElem.setAttribute('type', inputElemType = props[i]);
                bool = inputElem.type !== 'text';

                // We first check to see if the type we give it sticks..
                // If the type does, we feed it a textual value, which shouldn't be valid.
                // If the value doesn't stick, we know there's input sanitization which infers a custom UI
                if ( bool ) {

                    inputElem.value         = smile;
                    inputElem.style.cssText = 'position:absolute;visibility:hidden;';

                    if ( /^range$/.test(inputElemType) && inputElem.style.WebkitAppearance !== undefined ) {

                      docElement.appendChild(inputElem);
                      defaultView = document.defaultView;

                      // Safari 2-4 allows the smiley as a value, despite making a slider
                      bool =  defaultView.getComputedStyle &&
                              defaultView.getComputedStyle(inputElem, null).WebkitAppearance !== 'textfield' &&
                              // Mobile android web browser has false positive, so must
                              // check the height to see if the widget is actually there.
                              (inputElem.offsetHeight !== 0);

                      docElement.removeChild(inputElem);

                    } else if ( /^(search|tel)$/.test(inputElemType) ){
                      // Spec doesnt define any special parsing or detectable UI
                      //   behaviors so we pass these through as true

                      // Interestingly, opera fails the earlier test, so it doesn't
                      //  even make it here.

                    } else if ( /^(url|email)$/.test(inputElemType) ) {
                      // Real url and email support comes with prebaked validation.
                      bool = inputElem.checkValidity && inputElem.checkValidity() === false;

                    } else if ( /^color$/.test(inputElemType) ) {
                        // chuck into DOM and force reflow for Opera bug in 11.00
                        // github.com/Modernizr/Modernizr/issues#issue/159
                        docElement.appendChild(inputElem);
                        docElement.offsetWidth;
                        bool = inputElem.value != smile;
                        docElement.removeChild(inputElem);

                    } else {
                      // If the upgraded input compontent rejects the :) text, we got a winner
                      bool = inputElem.value != smile;
                    }
                }

                inputs[ props[i] ] = !!bool;
            }
            return inputs;
        })('search tel url email datetime date month week time datetime-local number range color'.split(' '));
    }


    // End of test definitions
    // -----------------------



    // Run through all tests and detect their support in the current UA.
    // todo: hypothetically we could be doing an array of tests and use a basic loop here.
    for ( var feature in tests ) {
        if ( hasOwnProperty(tests, feature) ) {
            // run the test, throw the return value into the Modernizr,
            //   then based on that boolean, define an appropriate className
            //   and push it into an array of classes we'll join later.
            featureName  = feature.toLowerCase();
            Modernizr[featureName] = tests[feature]();

            classes.push((Modernizr[featureName] ? '' : 'no-') + featureName);
        }
    }

    // input tests need to run.
    Modernizr.input || webforms();


    /**
     * addTest allows the user to define their own feature tests
     * the result will be added onto the Modernizr object,
     * as well as an appropriate className set on the html element
     *
     * @param feature - String naming the feature
     * @param test - Function returning true if feature is supported, false if not
     */
     Modernizr.addTest = function ( feature, test ) {
       if ( typeof feature == "object" ) {
         for ( var key in feature ) {
           if ( hasOwnProperty( feature, key ) ) { 
             Modernizr.addTest( key, feature[ key ] );
           }
         }
       } else {

         feature = feature.toLowerCase();

         if ( Modernizr[feature] !== undefined ) {
           // we're going to quit if you're trying to overwrite an existing test
           // if we were to allow it, we'd do this:
           //   var re = new RegExp("\\b(no-)?" + feature + "\\b");  
           //   docElement.className = docElement.className.replace( re, '' );
           // but, no rly, stuff 'em.
           return; 
         }

         test = typeof test == "boolean" ? test : !!test();

         docElement.className += ' ' + (test ? '' : 'no-') + feature;
         Modernizr[feature] = test;

       }

       return Modernizr; // allow chaining.
     };
    

    // Reset modElem.cssText to nothing to reduce memory footprint.
    setCss('');
    modElem = inputElem = null;

    //>>BEGIN IEPP
    // Enable HTML 5 elements for styling (and printing) in IE.
    if ( window.attachEvent && (function(){ var elem = document.createElement('div');
                                            elem.innerHTML = '<elem></elem>';
                                            return elem.childNodes.length !== 1; })() ) {
                                              
        // iepp v2 by @jon_neal & afarkas : github.com/aFarkas/iepp/
        (function(win, doc) {
          win.iepp = win.iepp || {};
          var iepp = win.iepp,
            elems = iepp.html5elements || 'abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video',
            elemsArr = elems.split('|'),
            elemsArrLen = elemsArr.length,
            elemRegExp = new RegExp('(^|\\s)('+elems+')', 'gi'),
            tagRegExp = new RegExp('<(\/*)('+elems+')', 'gi'),
            filterReg = /^\s*[\{\}]\s*$/,
            ruleRegExp = new RegExp('(^|[^\\n]*?\\s)('+elems+')([^\\n]*)({[\\n\\w\\W]*?})', 'gi'),
            docFrag = doc.createDocumentFragment(),
            html = doc.documentElement,
            head = html.firstChild,
            bodyElem = doc.createElement('body'),
            styleElem = doc.createElement('style'),
            printMedias = /print|all/,
            body;
          function shim(doc) {
            var a = -1;
            while (++a < elemsArrLen)
              // Use createElement so IE allows HTML5-named elements in a document
              doc.createElement(elemsArr[a]);
          }

          iepp.getCSS = function(styleSheetList, mediaType) {
            if(styleSheetList+'' === undefined){return '';}
            var a = -1,
              len = styleSheetList.length,
              styleSheet,
              cssTextArr = [];
            while (++a < len) {
              styleSheet = styleSheetList[a];
              //currently no test for disabled/alternate stylesheets
              if(styleSheet.disabled){continue;}
              mediaType = styleSheet.media || mediaType;
              // Get css from all non-screen stylesheets and their imports
              if (printMedias.test(mediaType)) cssTextArr.push(iepp.getCSS(styleSheet.imports, mediaType), styleSheet.cssText);
              //reset mediaType to all with every new *not imported* stylesheet
              mediaType = 'all';
            }
            return cssTextArr.join('');
          };

          iepp.parseCSS = function(cssText) {
            var cssTextArr = [],
              rule;
            while ((rule = ruleRegExp.exec(cssText)) != null){
              // Replace all html5 element references with iepp substitute classnames
              cssTextArr.push(( (filterReg.exec(rule[1]) ? '\n' : rule[1]) +rule[2]+rule[3]).replace(elemRegExp, '$1.iepp_$2')+rule[4]);
            }
            return cssTextArr.join('\n');
          };

          iepp.writeHTML = function() {
            var a = -1;
            body = body || doc.body;
            while (++a < elemsArrLen) {
              var nodeList = doc.getElementsByTagName(elemsArr[a]),
                nodeListLen = nodeList.length,
                b = -1;
              while (++b < nodeListLen)
                if (nodeList[b].className.indexOf('iepp_') < 0)
                  // Append iepp substitute classnames to all html5 elements
                  nodeList[b].className += ' iepp_'+elemsArr[a];
            }
            docFrag.appendChild(body);
            html.appendChild(bodyElem);
            // Write iepp substitute print-safe document
            bodyElem.className = body.className;
            bodyElem.id = body.id;
            // Replace HTML5 elements with <font> which is print-safe and shouldn't conflict since it isn't part of html5
            bodyElem.innerHTML = body.innerHTML.replace(tagRegExp, '<$1font');
          };


          iepp._beforePrint = function() {
            // Write iepp custom print CSS
            styleElem.styleSheet.cssText = iepp.parseCSS(iepp.getCSS(doc.styleSheets, 'all'));
            iepp.writeHTML();
          };

          iepp.restoreHTML = function(){
            // Undo everything done in onbeforeprint
            bodyElem.innerHTML = '';
            html.removeChild(bodyElem);
            html.appendChild(body);
          };

          iepp._afterPrint = function(){
            // Undo everything done in onbeforeprint
            iepp.restoreHTML();
            styleElem.styleSheet.cssText = '';
          };



          // Shim the document and iepp fragment
          shim(doc);
          shim(docFrag);

          //
          if(iepp.disablePP){return;}

          // Add iepp custom print style element
          head.insertBefore(styleElem, head.firstChild);
          styleElem.media = 'print';
          styleElem.className = 'iepp-printshim';
          win.attachEvent(
            'onbeforeprint',
            iepp._beforePrint
          );
          win.attachEvent(
            'onafterprint',
            iepp._afterPrint
          );
        })(window, document);
    }
    //>>END IEPP

    // Assign private properties to the return object with prefix
    Modernizr._version      = version;

    // expose these for the plugin API. Look in the source for how to join() them against your input
    Modernizr._prefixes     = prefixes;
    Modernizr._domPrefixes  = domPrefixes;
    
    // Modernizr.mq tests a given media query, live against the current state of the window
    // A few important notes:
    //   * If a browser does not support media queries at all (eg. oldIE) the mq() will always return false
    //   * A max-width or orientation query will be evaluated against the current state, which may change later.
    //   * You must specify values. Eg. If you are testing support for the min-width media query use: 
    //       Modernizr.mq('(min-width:0)')
    // usage:
    // Modernizr.mq('only screen and (max-width:768)')
    Modernizr.mq            = testMediaQuery;   
    
    // Modernizr.hasEvent() detects support for a given event, with an optional element to test on
    // Modernizr.hasEvent('gesturestart', elem)
    Modernizr.hasEvent      = isEventSupported; 

    // Modernizr.testProp() investigates whether a given style property is recognized
    // Note that the property names must be provided in the camelCase variant.
    // Modernizr.testProp('pointerEvents')
    Modernizr.testProp      = function(prop){
        return testProps([prop]);
    };        

    // Modernizr.testAllProps() investigates whether a given style property,
    //   or any of its vendor-prefixed variants, is recognized
    // Note that the property names must be provided in the camelCase variant.
    // Modernizr.testAllProps('boxSizing')    
    Modernizr.testAllProps  = testPropsAll;     


    
    // Modernizr.testStyles() allows you to add custom styles to the document and test an element afterwards
    // Modernizr.testStyles('#modernizr { position:absolute }', function(elem, rule){ ... })
    Modernizr.testStyles    = injectElementWithStyles; 


    // Modernizr.prefixed() returns the prefixed or nonprefixed property name variant of your input
    // Modernizr.prefixed('boxSizing') // 'MozBoxSizing'
    
    // Properties must be passed as dom-style camelcase, rather than `box-sizing` hypentated style.
    // Return values will also be the camelCase variant, if you need to translate that to hypenated style use:
    //
    //     str.replace(/([A-Z])/g, function(str,m1){ return '-' + m1.toLowerCase(); }).replace(/^ms-/,'-ms-');
    
    // If you're trying to ascertain which transition end event to bind to, you might do something like...
    // 
    //     var transEndEventNames = {
    //       'WebkitTransition' : 'webkitTransitionEnd',
    //       'MozTransition'    : 'transitionend',
    //       'OTransition'      : 'oTransitionEnd',
    //       'msTransition'     : 'msTransitionEnd', // maybe?
    //       'transition'       : 'transitionEnd'
    //     },
    //     transEndEventName = transEndEventNames[ Modernizr.prefixed('transition') ];
    
    Modernizr.prefixed      = function(prop){
      return testPropsAll(prop, 'pfx');
    };



    // Remove "no-js" class from <html> element, if it exists:
    docElement.className = docElement.className.replace(/\bno-js\b/, '')
                            
                            // Add the new classes to the <html> element.
                            + (enableClasses ? ' js ' + classes.join(' ') : '');

    return Modernizr;

})(this, this.document);



/*
Script: Core.js
	MooTools - My Object Oriented JavaScript Tools.

License:
	MIT-style license.

Copyright:
	Copyright (c) 2006-2008 [Valerio Proietti](http://mad4milk.net/).

Code & Documentation:
	[The MooTools production team](http://mootools.net/developers/).

Inspiration:
	- Class implementation inspired by [Base.js](http://dean.edwards.name/weblog/2006/03/base/) Copyright (c) 2006 Dean Edwards, [GNU Lesser General Public License](http://opensource.org/licenses/lgpl-license.php)
	- Some functionality inspired by [Prototype.js](http://prototypejs.org) Copyright (c) 2005-2007 Sam Stephenson, [MIT License](http://opensource.org/licenses/mit-license.php)
*/

var MooTools = {
	'version': '1.2.1',
	'build': '0d4845aab3d9a4fdee2f0d4a6dd59210e4b697cf'
};

var Native = function(options){
	options = options || {};
	var name = options.name;
	var legacy = options.legacy;
	var protect = options.protect;
	var methods = options.implement;
	var generics = options.generics;
	var initialize = options.initialize;
	var afterImplement = options.afterImplement || function(){};
	var object = initialize || legacy;
	generics = generics !== false;

	object.constructor = Native;
	object.$family = {name: 'native'};
	if (legacy && initialize) object.prototype = legacy.prototype;
	object.prototype.constructor = object;

	if (name){
		var family = name.toLowerCase();
		object.prototype.$family = {name: family};
		Native.typize(object, family);
	}

	var add = function(obj, name, method, force){
		if (!protect || force || !obj.prototype[name]) obj.prototype[name] = method;
		if (generics) Native.genericize(obj, name, protect);
		afterImplement.call(obj, name, method);
		return obj;
	};

	object.alias = function(a1, a2, a3){
		if (typeof a1 == 'string'){
			if ((a1 = this.prototype[a1])) return add(this, a2, a1, a3);
		}
		for (var a in a1) this.alias(a, a1[a], a2);
		return this;
	};

	object.implement = function(a1, a2, a3){
		if (typeof a1 == 'string') return add(this, a1, a2, a3);
		for (var p in a1) add(this, p, a1[p], a2);
		return this;
	};

	if (methods) object.implement(methods);

	return object;
};

Native.genericize = function(object, property, check){
	if ((!check || !object[property]) && typeof object.prototype[property] == 'function') object[property] = function(){
		var args = Array.prototype.slice.call(arguments);
		return object.prototype[property].apply(args.shift(), args);
	};
};

Native.implement = function(objects, properties){
	for (var i = 0, l = objects.length; i < l; i++) objects[i].implement(properties);
};

Native.typize = function(object, family){
	if (!object.type) object.type = function(item){
		return ($type(item) === family);
	};
};

(function(){
	var natives = {'Array': Array, 'Date': Date, 'Function': Function, 'Number': Number, 'RegExp': RegExp, 'String': String};
	for (var n in natives) new Native({name: n, initialize: natives[n], protect: true});

	var types = {'boolean': Boolean, 'native': Native, 'object': Object};
	for (var t in types) Native.typize(types[t], t);

	var generics = {
		'Array': ["concat", "indexOf", "join", "lastIndexOf", "pop", "push", "reverse", "shift", "slice", "sort", "splice", "toString", "unshift", "valueOf"],
		'String': ["charAt", "charCodeAt", "concat", "indexOf", "lastIndexOf", "match", "replace", "search", "slice", "split", "substr", "substring", "toLowerCase", "toUpperCase", "valueOf"]
	};
	for (var g in generics){
		for (var i = generics[g].length; i--;) Native.genericize(window[g], generics[g][i], true);
	};
})();

var Hash = new Native({

	name: 'Hash',

	initialize: function(object){
		if ($type(object) == 'hash') object = $unlink(object.getClean());
		for (var key in object) this[key] = object[key];
		return this;
	}

});

Hash.implement({

	forEach: function(fn, bind){
		for (var key in this){
			if (this.hasOwnProperty(key)) fn.call(bind, this[key], key, this);
		}
	},

	getClean: function(){
		var clean = {};
		for (var key in this){
			if (this.hasOwnProperty(key)) clean[key] = this[key];
		}
		return clean;
	},

	getLength: function(){
		var length = 0;
		for (var key in this){
			if (this.hasOwnProperty(key)) length++;
		}
		return length;
	}

});

Hash.alias('forEach', 'each');

Array.implement({

	forEach: function(fn, bind){
		for (var i = 0, l = this.length; i < l; i++) fn.call(bind, this[i], i, this);
	}

});

Array.alias('forEach', 'each');

function $A(iterable){
	if (iterable.item){
		var array = [];
		for (var i = 0, l = iterable.length; i < l; i++) array[i] = iterable[i];
		return array;
	}
	return Array.prototype.slice.call(iterable);
};

function $arguments(i){
	return function(){
		return arguments[i];
	};
};

function $chk(obj){
	return !!(obj || obj === 0);
};

function $clear(timer){
	clearTimeout(timer);
	clearInterval(timer);
	return null;
};

function $defined(obj){
	return (obj != undefined);
};

function $each(iterable, fn, bind){
	var type = $type(iterable);
	((type == 'arguments' || type == 'collection' || type == 'array') ? Array : Hash).each(iterable, fn, bind);
};

function $empty(){};

function $extend(original, extended){
	for (var key in (extended || {})) original[key] = extended[key];
	return original;
};

function $H(object){
	return new Hash(object);
};

function $lambda(value){
	return (typeof value == 'function') ? value : function(){
		return value;
	};
};

function $merge(){
	var mix = {};
	for (var i = 0, l = arguments.length; i < l; i++){
		var object = arguments[i];
		if ($type(object) != 'object') continue;
		for (var key in object){
			var op = object[key], mp = mix[key];
			mix[key] = (mp && $type(op) == 'object' && $type(mp) == 'object') ? $merge(mp, op) : $unlink(op);
		}
	}
	return mix;
};

function $pick(){
	for (var i = 0, l = arguments.length; i < l; i++){
		if (arguments[i] != undefined) return arguments[i];
	}
	return null;
};

function $random(min, max){
	return Math.floor(Math.random() * (max - min + 1) + min);
};

function $splat(obj){
	var type = $type(obj);
	return (type) ? ((type != 'array' && type != 'arguments') ? [obj] : obj) : [];
};

var $time = Date.now || function(){
	return +new Date;
};

function $try(){
	for (var i = 0, l = arguments.length; i < l; i++){
		try {
			return arguments[i]();
		} catch(e){}
	}
	return null;
};

function $type(obj){
	if (obj == undefined) return false;
	if (obj.$family) return (obj.$family.name == 'number' && !isFinite(obj)) ? false : obj.$family.name;
	if (obj.nodeName){
		switch (obj.nodeType){
			case 1: return 'element';
			case 3: return (/\S/).test(obj.nodeValue) ? 'textnode' : 'whitespace';
		}
	} else if (typeof obj.length == 'number'){
		if (obj.callee) return 'arguments';
		else if (obj.item) return 'collection';
	}
	return typeof obj;
};

function $unlink(object){
	var unlinked;
	switch ($type(object)){
		case 'object':
			unlinked = {};
			for (var p in object) unlinked[p] = $unlink(object[p]);
		break;
		case 'hash':
			unlinked = new Hash(object);
		break;
		case 'array':
			unlinked = [];
			for (var i = 0, l = object.length; i < l; i++) unlinked[i] = $unlink(object[i]);
		break;
		default: return object;
	}
	return unlinked;
};


/*
Script: Browser.js
	The Browser Core. Contains Browser initialization, Window and Document, and the Browser Hash.

License:
	MIT-style license.
*/

var Browser = $merge({

	Engine: {name: 'unknown', version: 0},

	Platform: {name: (window.orientation != undefined) ? 'ipod' : (navigator.platform.match(/mac|win|linux/i) || ['other'])[0].toLowerCase()},

	Features: {xpath: !!(document.evaluate), air: !!(window.runtime), query: !!(document.querySelector)},

	Plugins: {},

	Engines: {

		presto: function(){
			return (!window.opera) ? false : ((arguments.callee.caller) ? 960 : ((document.getElementsByClassName) ? 950 : 925));
		},

		trident: function(){
			return (!window.ActiveXObject) ? false : ((window.XMLHttpRequest) ? 5 : 4);
		},

		webkit: function(){
			return (navigator.taintEnabled) ? false : ((Browser.Features.xpath) ? ((Browser.Features.query) ? 525 : 420) : 419);
		},

		gecko: function(){
			return (document.getBoxObjectFor == undefined) ? false : ((document.getElementsByClassName) ? 19 : 18);
		}

	}

}, Browser || {});

Browser.Platform[Browser.Platform.name] = true;

Browser.detect = function(){

	for (var engine in this.Engines){
		var version = this.Engines[engine]();
		if (version){
			this.Engine = {name: engine, version: version};
			this.Engine[engine] = this.Engine[engine + version] = true;
			break;
		}
	}

	return {name: engine, version: version};

};

Browser.detect();

Browser.Request = function(){
	return $try(function(){
		return new XMLHttpRequest();
	}, function(){
		return new ActiveXObject('MSXML2.XMLHTTP');
	});
};

Browser.Features.xhr = !!(Browser.Request());

Browser.Plugins.Flash = (function(){
	var version = ($try(function(){
		return navigator.plugins['Shockwave Flash'].description;
	}, function(){
		return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version');
	}) || '0 r0').match(/\d+/g);
	return {version: parseInt(version[0] || 0 + '.' + version[1] || 0), build: parseInt(version[2] || 0)};
})();

function $exec(text){
	if (!text) return text;
	if (window.execScript){
		try{window.execScript(text);} catch (ex){}
	} else {
		var script = document.createElement('script');
		script.setAttribute('type', 'text/javascript');
		script[(Browser.Engine.webkit && Browser.Engine.version < 420) ? 'innerText' : 'text'] = text;
		document.head.appendChild(script);
		document.head.removeChild(script);
	}
	return text;
};

Native.UID = 1;

var $uid = (Browser.Engine.trident) ? function(item){
	return (item.uid || (item.uid = [Native.UID++]))[0];
} : function(item){
	return item.uid || (item.uid = Native.UID++);
};

var Window = new Native({

	name: 'Window',

	legacy: (Browser.Engine.trident) ? null: window.Window,

	initialize: function(win){
		$uid(win);
		if (!win.Element){
			win.Element = $empty;
			if (Browser.Engine.webkit) win.document.createElement("iframe"); //fixes safari 2
			win.Element.prototype = (Browser.Engine.webkit) ? window["[[DOMElement.prototype]]"] : {};
		}
		win.document.window = win;
		return $extend(win, Window.Prototype);
	},

	afterImplement: function(property, value){
		window[property] = Window.Prototype[property] = value;
	}

});

Window.Prototype = {$family: {name: 'window'}};

new Window(window);

var Document = new Native({

	name: 'Document',

	legacy: (Browser.Engine.trident) ? null: window.Document,

	initialize: function(doc){
		$uid(doc);
		doc.head = doc.getElementsByTagName('head')[0];
		doc.html = doc.getElementsByTagName('html')[0];
		if (Browser.Engine.trident && Browser.Engine.version <= 4) $try(function(){
			doc.execCommand("BackgroundImageCache", false, true);
		});
		if (Browser.Engine.trident) doc.window.attachEvent('onunload', function() {
			doc.window.detachEvent('onunload', arguments.callee);
			doc.head = doc.html = doc.window = null;
		});
		return $extend(doc, Document.Prototype);
	},

	afterImplement: function(property, value){
		document[property] = Document.Prototype[property] = value;
	}

});

Document.Prototype = {$family: {name: 'document'}};

new Document(document);


/*
Script: Array.js
	Contains Array Prototypes like each, contains, and erase.

License:
	MIT-style license.
*/

Array.implement({

	every: function(fn, bind){
		for (var i = 0, l = this.length; i < l; i++){
			if (!fn.call(bind, this[i], i, this)) return false;
		}
		return true;
	},

	filter: function(fn, bind){
		var results = [];
		for (var i = 0, l = this.length; i < l; i++){
			if (fn.call(bind, this[i], i, this)) results.push(this[i]);
		}
		return results;
	},

	clean: function() {
		return this.filter($defined);
	},

	indexOf: function(item, from){
		var len = this.length;
		for (var i = (from < 0) ? Math.max(0, len + from) : from || 0; i < len; i++){
			if (this[i] === item) return i;
		}
		return -1;
	},

	map: function(fn, bind){
		var results = [];
		for (var i = 0, l = this.length; i < l; i++) results[i] = fn.call(bind, this[i], i, this);
		return results;
	},

	some: function(fn, bind){
		for (var i = 0, l = this.length; i < l; i++){
			if (fn.call(bind, this[i], i, this)) return true;
		}
		return false;
	},

	associate: function(keys){
		var obj = {}, length = Math.min(this.length, keys.length);
		for (var i = 0; i < length; i++) obj[keys[i]] = this[i];
		return obj;
	},

	link: function(object){
		var result = {};
		for (var i = 0, l = this.length; i < l; i++){
			for (var key in object){
				if (object[key](this[i])){
					result[key] = this[i];
					delete object[key];
					break;
				}
			}
		}
		return result;
	},

	contains: function(item, from){
		return this.indexOf(item, from) != -1;
	},

	extend: function(array){
		for (var i = 0, j = array.length; i < j; i++) this.push(array[i]);
		return this;
	},

	getLast: function(){
		return (this.length) ? this[this.length - 1] : null;
	},

	getRandom: function(){
		return (this.length) ? this[$random(0, this.length - 1)] : null;
	},

	include: function(item){
		if (!this.contains(item)) this.push(item);
		return this;
	},

	combine: function(array){
		for (var i = 0, l = array.length; i < l; i++) this.include(array[i]);
		return this;
	},

	erase: function(item){
		for (var i = this.length; i--; i){
			if (this[i] === item) this.splice(i, 1);
		}
		return this;
	},

	empty: function(){
		this.length = 0;
		return this;
	},

	flatten: function(){
		var array = [];
		for (var i = 0, l = this.length; i < l; i++){
			var type = $type(this[i]);
			if (!type) continue;
			array = array.concat((type == 'array' || type == 'collection' || type == 'arguments') ? Array.flatten(this[i]) : this[i]);
		}
		return array;
	},

	hexToRgb: function(array){
		if (this.length != 3) return null;
		var rgb = this.map(function(value){
			if (value.length == 1) value += value;
			return value.toInt(16);
		});
		return (array) ? rgb : 'rgb(' + rgb + ')';
	},

	rgbToHex: function(array){
		if (this.length < 3) return null;
		if (this.length == 4 && this[3] == 0 && !array) return 'transparent';
		var hex = [];
		for (var i = 0; i < 3; i++){
			var bit = (this[i] - 0).toString(16);
			hex.push((bit.length == 1) ? '0' + bit : bit);
		}
		return (array) ? hex : '#' + hex.join('');
	}

});


/*
Script: Function.js
	Contains Function Prototypes like create, bind, pass, and delay.

License:
	MIT-style license.
*/

Function.implement({

	extend: function(properties){
		for (var property in properties) this[property] = properties[property];
		return this;
	},

	create: function(options){
		var self = this;
		options = options || {};
		return function(event){
			var args = options.arguments;
			args = (args != undefined) ? $splat(args) : Array.slice(arguments, (options.event) ? 1 : 0);
			if (options.event) args = [event || window.event].extend(args);
			var returns = function(){
				return self.apply(options.bind || null, args);
			};
			if (options.delay) return setTimeout(returns, options.delay);
			if (options.periodical) return setInterval(returns, options.periodical);
			if (options.attempt) return $try(returns);
			return returns();
		};
	},

	run: function(args, bind){
		return this.apply(bind, $splat(args));
	},

	pass: function(args, bind){
		return this.create({bind: bind, arguments: args});
	},

	bind: function(bind, args){
		return this.create({bind: bind, arguments: args});
	},

	bindWithEvent: function(bind, args){
		return this.create({bind: bind, arguments: args, event: true});
	},

	attempt: function(args, bind){
		return this.create({bind: bind, arguments: args, attempt: true})();
	},

	delay: function(delay, bind, args){
		return this.create({bind: bind, arguments: args, delay: delay})();
	},

	periodical: function(periodical, bind, args){
		return this.create({bind: bind, arguments: args, periodical: periodical})();
	}

});


/*
Script: Number.js
	Contains Number Prototypes like limit, round, times, and ceil.

License:
	MIT-style license.
*/

Number.implement({

	limit: function(min, max){
		return Math.min(max, Math.max(min, this));
	},

	round: function(precision){
		precision = Math.pow(10, precision || 0);
		return Math.round(this * precision) / precision;
	},

	times: function(fn, bind){
		for (var i = 0; i < this; i++) fn.call(bind, i, this);
	},

	toFloat: function(){
		return parseFloat(this);
	},

	toInt: function(base){
		return parseInt(this, base || 10);
	}

});

Number.alias('times', 'each');

(function(math){
	var methods = {};
	math.each(function(name){
		if (!Number[name]) methods[name] = function(){
			return Math[name].apply(null, [this].concat($A(arguments)));
		};
	});
	Number.implement(methods);
})(['abs', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'exp', 'floor', 'log', 'max', 'min', 'pow', 'sin', 'sqrt', 'tan']);


/*
Script: String.js
	Contains String Prototypes like camelCase, capitalize, test, and toInt.

License:
	MIT-style license.
*/

String.implement({

	test: function(regex, params){
		return ((typeof regex == 'string') ? new RegExp(regex, params) : regex).test(this);
	},

	contains: function(string, separator){
		return (separator) ? (separator + this + separator).indexOf(separator + string + separator) > -1 : this.indexOf(string) > -1;
	},

	trim: function(){
		return this.replace(/^\s+|\s+$/g, '');
	},

	clean: function(){
		return this.replace(/\s+/g, ' ').trim();
	},

	camelCase: function(){
		return this.replace(/-\D/g, function(match){
			return match.charAt(1).toUpperCase();
		});
	},

	hyphenate: function(){
		return this.replace(/[A-Z]/g, function(match){
			return ('-' + match.charAt(0).toLowerCase());
		});
	},

	capitalize: function(){
		return this.replace(/\b[a-z]/g, function(match){
			return match.toUpperCase();
		});
	},

	escapeRegExp: function(){
		return this.replace(/([-.*+?^${}()|[\]\/\\])/g, '\\$1');
	},

	toInt: function(base){
		return parseInt(this, base || 10);
	},

	toFloat: function(){
		return parseFloat(this);
	},

	hexToRgb: function(array){
		var hex = this.match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/);
		return (hex) ? hex.slice(1).hexToRgb(array) : null;
	},

	rgbToHex: function(array){
		var rgb = this.match(/\d{1,3}/g);
		return (rgb) ? rgb.rgbToHex(array) : null;
	},

	stripScripts: function(option){
		var scripts = '';
		var text = this.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, function(){
			scripts += arguments[1] + '\n';
			return '';
		});
		if (option === true) $exec(scripts);
		else if ($type(option) == 'function') option(scripts, text);
		return text;
	},

	substitute: function(object, regexp){
		return this.replace(regexp || (/\\?\{([^{}]+)\}/g), function(match, name){
			if (match.charAt(0) == '\\') return match.slice(1);
			return (object[name] != undefined) ? object[name] : '';
		});
	}

});


/*
Script: Hash.js
	Contains Hash Prototypes. Provides a means for overcoming the JavaScript practical impossibility of extending native Objects.

License:
	MIT-style license.
*/

Hash.implement({

	has: Object.prototype.hasOwnProperty,

	keyOf: function(value){
		for (var key in this){
			if (this.hasOwnProperty(key) && this[key] === value) return key;
		}
		return null;
	},

	hasValue: function(value){
		return (Hash.keyOf(this, value) !== null);
	},

	extend: function(properties){
		Hash.each(properties, function(value, key){
			Hash.set(this, key, value);
		}, this);
		return this;
	},

	combine: function(properties){
		Hash.each(properties, function(value, key){
			Hash.include(this, key, value);
		}, this);
		return this;
	},

	erase: function(key){
		if (this.hasOwnProperty(key)) delete this[key];
		return this;
	},

	get: function(key){
		return (this.hasOwnProperty(key)) ? this[key] : null;
	},

	set: function(key, value){
		if (!this[key] || this.hasOwnProperty(key)) this[key] = value;
		return this;
	},

	empty: function(){
		Hash.each(this, function(value, key){
			delete this[key];
		}, this);
		return this;
	},

	include: function(key, value){
		var k = this[key];
		if (k == undefined) this[key] = value;
		return this;
	},

	map: function(fn, bind){
		var results = new Hash;
		Hash.each(this, function(value, key){
			results.set(key, fn.call(bind, value, key, this));
		}, this);
		return results;
	},

	filter: function(fn, bind){
		var results = new Hash;
		Hash.each(this, function(value, key){
			if (fn.call(bind, value, key, this)) results.set(key, value);
		}, this);
		return results;
	},

	every: function(fn, bind){
		for (var key in this){
			if (this.hasOwnProperty(key) && !fn.call(bind, this[key], key)) return false;
		}
		return true;
	},

	some: function(fn, bind){
		for (var key in this){
			if (this.hasOwnProperty(key) && fn.call(bind, this[key], key)) return true;
		}
		return false;
	},

	getKeys: function(){
		var keys = [];
		Hash.each(this, function(value, key){
			keys.push(key);
		});
		return keys;
	},

	getValues: function(){
		var values = [];
		Hash.each(this, function(value){
			values.push(value);
		});
		return values;
	},

	toQueryString: function(base){
		var queryString = [];
		Hash.each(this, function(value, key){
			if (base) key = base + '[' + key + ']';
			var result;
			switch ($type(value)){
				case 'object': result = Hash.toQueryString(value, key); break;
				case 'array':
					var qs = {};
					value.each(function(val, i){
						qs[i] = val;
					});
					result = Hash.toQueryString(qs, key);
				break;
				default: result = key + '=' + encodeURIComponent(value);
			}
			if (value != undefined) queryString.push(result);
		});

		return queryString.join('&');
	}

});

Hash.alias({keyOf: 'indexOf', hasValue: 'contains'});


/*
Script: Event.js
	Contains the Event Native, to make the event object completely crossbrowser.

License:
	MIT-style license.
*/

var Event = new Native({

	name: 'Event',

	initialize: function(event, win){
		win = win || window;
		var doc = win.document;
		event = event || win.event;
		if (event.$extended) return event;
		this.$extended = true;
		var type = event.type;
		var target = event.target || event.srcElement;
		while (target && target.nodeType == 3) target = target.parentNode;

		if (type.test(/key/)){
			var code = event.which || event.keyCode;
			var key = Event.Keys.keyOf(code);
			if (type == 'keydown'){
				var fKey = code - 111;
				if (fKey > 0 && fKey < 13) key = 'f' + fKey;
			}
			key = key || String.fromCharCode(code).toLowerCase();
		} else if (type.match(/(click|mouse|menu)/i)){
			doc = (!doc.compatMode || doc.compatMode == 'CSS1Compat') ? doc.html : doc.body;
			var page = {
				x: event.pageX || event.clientX + doc.scrollLeft,
				y: event.pageY || event.clientY + doc.scrollTop
			};
			var client = {
				x: (event.pageX) ? event.pageX - win.pageXOffset : event.clientX,
				y: (event.pageY) ? event.pageY - win.pageYOffset : event.clientY
			};
			if (type.match(/DOMMouseScroll|mousewheel/)){
				var wheel = (event.wheelDelta) ? event.wheelDelta / 120 : -(event.detail || 0) / 3;
			}
			var rightClick = (event.which == 3) || (event.button == 2);
			var related = null;
			if (type.match(/over|out/)){
				switch (type){
					case 'mouseover': related = event.relatedTarget || event.fromElement; break;
					case 'mouseout': related = event.relatedTarget || event.toElement;
				}
				if (!(function(){
					while (related && related.nodeType == 3) related = related.parentNode;
					return true;
				}).create({attempt: Browser.Engine.gecko})()) related = false;
			}
		}

		return $extend(this, {
			event: event,
			type: type,

			page: page,
			client: client,
			rightClick: rightClick,

			wheel: wheel,

			relatedTarget: related,
			target: target,

			code: code,
			key: key,

			shift: event.shiftKey,
			control: event.ctrlKey,
			alt: event.altKey,
			meta: event.metaKey
		});
	}

});

Event.Keys = new Hash({
	'enter': 13,
	'up': 38,
	'down': 40,
	'left': 37,
	'right': 39,
	'esc': 27,
	'space': 32,
	'backspace': 8,
	'tab': 9,
	'delete': 46
});

Event.implement({

	stop: function(){
		return this.stopPropagation().preventDefault();
	},

	stopPropagation: function(){
		if (this.event.stopPropagation) this.event.stopPropagation();
		else this.event.cancelBubble = true;
		return this;
	},

	preventDefault: function(){
		if (this.event.preventDefault) this.event.preventDefault();
		else this.event.returnValue = false;
		return this;
	}

});


/*
Script: Class.js
	Contains the Class Function for easily creating, extending, and implementing reusable Classes.

License:
	MIT-style license.
*/

var Class = new Native({

	name: 'Class',

	initialize: function(properties){
		properties = properties || {};
		var klass = function(){
			for (var key in this){
				if ($type(this[key]) != 'function') this[key] = $unlink(this[key]);
			}
			this.constructor = klass;
			if (Class.prototyping) return this;
			var instance = (this.initialize) ? this.initialize.apply(this, arguments) : this;
			if (this.options && this.options.initialize) this.options.initialize.call(this);
			return instance;
		};

		for (var mutator in Class.Mutators){
			if (!properties[mutator]) continue;
			properties = Class.Mutators[mutator](properties, properties[mutator]);
			delete properties[mutator];
		}

		$extend(klass, this);
		klass.constructor = Class;
		klass.prototype = properties;
		return klass;
	}

});

Class.Mutators = {

	Extends: function(self, klass){
		Class.prototyping = klass.prototype;
		var subclass = new klass;
		delete subclass.parent;
		subclass = Class.inherit(subclass, self);
		delete Class.prototyping;
		return subclass;
	},

	Implements: function(self, klasses){
		$splat(klasses).each(function(klass){
			Class.prototying = klass;
			$extend(self, ($type(klass) == 'class') ? new klass : klass);
			delete Class.prototyping;
		});
		return self;
	}

};

Class.extend({

	inherit: function(object, properties){
		var caller = arguments.callee.caller;
		for (var key in properties){
			var override = properties[key];
			var previous = object[key];
			var type = $type(override);
			if (previous && type == 'function'){
				if (override != previous){
					if (caller){
						override.__parent = previous;
						object[key] = override;
					} else {
						Class.override(object, key, override);
					}
				}
			} else if(type == 'object'){
				object[key] = $merge(previous, override);
			} else {
				object[key] = override;
			}
		}

		if (caller) object.parent = function(){
			return arguments.callee.caller.__parent.apply(this, arguments);
		};

		return object;
	},

	override: function(object, name, method){
		var parent = Class.prototyping;
		if (parent && object[name] != parent[name]) parent = null;
		var override = function(){
			var previous = this.parent;
			this.parent = parent ? parent[name] : object[name];
			var value = method.apply(this, arguments);
			this.parent = previous;
			return value;
		};
		object[name] = override;
	}

});

Class.implement({

	implement: function(){
		var proto = this.prototype;
		$each(arguments, function(properties){
			Class.inherit(proto, properties);
		});
		return this;
	}

});


/*
Script: Class.Extras.js
	Contains Utility Classes that can be implemented into your own Classes to ease the execution of many common tasks.

License:
	MIT-style license.
*/

var Chain = new Class({

	$chain: [],

	chain: function(){
		this.$chain.extend(Array.flatten(arguments));
		return this;
	},

	callChain: function(){
		return (this.$chain.length) ? this.$chain.shift().apply(this, arguments) : false;
	},

	clearChain: function(){
		this.$chain.empty();
		return this;
	}

});

var Events = new Class({

	$events: {},

	addEvent: function(type, fn, internal){
		type = Events.removeOn(type);
		if (fn != $empty){
			this.$events[type] = this.$events[type] || [];
			this.$events[type].include(fn);
			if (internal) fn.internal = true;
		}
		return this;
	},

	addEvents: function(events){
		for (var type in events) this.addEvent(type, events[type]);
		return this;
	},

	fireEvent: function(type, args, delay){
		type = Events.removeOn(type);
		if (!this.$events || !this.$events[type]) return this;
		this.$events[type].each(function(fn){
			fn.create({'bind': this, 'delay': delay, 'arguments': args})();
		}, this);
		return this;
	},

	removeEvent: function(type, fn){
		type = Events.removeOn(type);
		if (!this.$events[type]) return this;
		if (!fn.internal) this.$events[type].erase(fn);
		return this;
	},

	removeEvents: function(events){
		if ($type(events) == 'object'){
			for (var type in events) this.removeEvent(type, events[type]);
			return this;
		}
		if (events) events = Events.removeOn(events);
		for (var type in this.$events){
			if (events && events != type) continue;
			var fns = this.$events[type];
			for (var i = fns.length; i--; i) this.removeEvent(type, fns[i]);
		}
		return this;
	}

});

Events.removeOn = function(string){
	return string.replace(/^on([A-Z])/, function(full, first) {
		return first.toLowerCase();
	});
};

var Options = new Class({

	setOptions: function(){
		this.options = $merge.run([this.options].extend(arguments));
		if (!this.addEvent) return this;
		for (var option in this.options){
			if ($type(this.options[option]) != 'function' || !(/^on[A-Z]/).test(option)) continue;
			this.addEvent(option, this.options[option]);
			delete this.options[option];
		}
		return this;
	}

});


/*
Script: Element.js
	One of the most important items in MooTools. Contains the dollar function, the dollars function, and an handful of cross-browser,
	time-saver methods to let you easily work with HTML Elements.

License:
	MIT-style license.
*/

var Element = new Native({

	name: 'Element',

	legacy: window.Element,

	initialize: function(tag, props){
		
		var konstructor = Element.Constructors.get(tag);
		
		if (konstructor) return konstructor(props);
		
		if (typeof tag == 'string') { return document.newElement(tag, props); }
		
		return $(tag).set(props);
	},

	afterImplement: function(key, value){
		Element.Prototype[key] = value;
		if (Array[key]) return;
		Elements.implement(key, function(){
			var items = [], elements = true;
			for (var i = 0, j = this.length; i < j; i++){
				var returns = this[i][key].apply(this[i], arguments);
				items.push(returns);
				if (elements) elements = ($type(returns) == 'element');
			}
			return (elements) ? new Elements(items) : items;
		});
	}

});

Element.Prototype = {$family: {name: 'element'}};

Element.Constructors = new Hash;

var IFrame = new Native({

	name: 'IFrame',

	generics: false,

	initialize: function(){
		var params = Array.link(arguments, {properties: Object.type, iframe: $defined});
		var props = params.properties || {};
		var iframe = $(params.iframe) || false;
		var onload = props.onload || $empty;
		delete props.onload;
		props.id = props.name = $pick(props.id, props.name, iframe.id, iframe.name, 'IFrame_' + $time());
		iframe = new Element(iframe || 'iframe', props);
		var onFrameLoad = function(){
			var host = $try(function(){
				return iframe.contentWindow.location.host;
			});
			if (host && host == window.location.host){
				var win = new Window(iframe.contentWindow);
				new Document(iframe.contentWindow.document);
				$extend(win.Element.prototype, Element.Prototype);
			}
			onload.call(iframe.contentWindow, iframe.contentWindow.document);
		};
		(window.frames[props.id]) ? onFrameLoad() : iframe.addListener('load', onFrameLoad);
		return iframe;
	}

});

var Elements = new Native({

	initialize: function(elements, options){
		options = $extend({ddup: true, cash: true}, options);
		elements = elements || [];
		if (options.ddup || options.cash){
			var uniques = {}, returned = [];
			for (var i = 0, l = elements.length; i < l; i++){
				var el = $.element(elements[i], !options.cash);
				if (options.ddup){
					if (uniques[el.uid]) continue;
					uniques[el.uid] = true;
				}
				returned.push(el);
			}
			elements = returned;
		}
		return (options.cash) ? $extend(elements, this) : elements;
	}

});

Elements.implement({

	filter: function(filter, bind){
		if (!filter) return this;
		return new Elements(Array.filter(this, (typeof filter == 'string') ? function(item){
			return item.match(filter);
		} : filter, bind));
	}

});

Document.implement({

	newElement: function(tag, props){
		return $.element(this.createElement(tag)).set(props);
	},

	newTextNode: function(text){
		return this.createTextNode(text);
	},

	getDocument: function(){
		return this;
	},

	getWindow: function(){
		return this.window;
	}

});

Window.implement({

	$: function(el, nocash){
		if (el && el.$family && el.uid) return el;
		var type = $type(el);
		return ($[type]) ? $[type](el, nocash, this.document) : null;
	},

	$$: function(selector){
		if (arguments.length == 1 && typeof selector == 'string') return this.document.getElements(selector);
		var elements = [];
		var args = Array.flatten(arguments);
		for (var i = 0, l = args.length; i < l; i++){
			var item = args[i];
			switch ($type(item)){
				case 'element': elements.push(item); break;
				case 'string': elements.extend(this.document.getElements(item, true));
			}
		}
		return new Elements(elements);
	},

	getDocument: function(){
		return this.document;
	},

	getWindow: function(){
		return this;
	}

});

$.string = function(id, nocash, doc){
	id = doc.getElementById(id);
	return (id) ? $.element(id, nocash) : null;
};

$.element = function(el, nocash){
	$uid(el);
	if (!nocash && !el.$family && !(/^object|embed$/i).test(el.tagName)){
		var proto = Element.Prototype;
		for (var p in proto) el[p] = proto[p];
	};
	return el;
};

$.object = function(obj, nocash, doc){
	if (obj.toElement) return $.element(obj.toElement(doc), nocash);
	return null;
};

$.textnode = $.whitespace = $.window = $.document = $arguments(0);

Native.implement([Element, Document], {

	getElement: function(selector, nocash){
		return $(this.getElements(selector, true)[0] || null, nocash);
	},

	getElements: function(tags, nocash){
		tags = tags.split(',');
		var elements = [];
		var ddup = (tags.length > 1);
		tags.each(function(tag){
			var partial = this.getElementsByTagName(tag.trim());
			(ddup) ? elements.extend(partial) : elements = partial;
		}, this);
		return new Elements(elements, {ddup: ddup, cash: !nocash});
	}

});

(function(){

var collected = {}, storage = {};
var props = {input: 'checked', option: 'selected', textarea: (Browser.Engine.webkit && Browser.Engine.version < 420) ? 'innerHTML' : 'value'};

var get = function(uid){
	return (storage[uid] || (storage[uid] = {}));
};

var clean = function(item, retain){
	if (!item) return;
	var uid = item.uid;
	if (Browser.Engine.trident){
		if (item.clearAttributes){
			var clone = retain && item.cloneNode(false);
			item.clearAttributes();
			if (clone) item.mergeAttributes(clone);
		} else if (item.removeEvents){
			item.removeEvents();
		}
		if ((/object/i).test(item.tagName)){
			for (var p in item){
				if (typeof item[p] == 'function') item[p] = $empty;
			}
			Element.dispose(item);
		}
	}	
	if (!uid) return;
	collected[uid] = storage[uid] = null;
};

var purge = function(){
	Hash.each(collected, clean);
	if (Browser.Engine.trident) $A(document.getElementsByTagName('object')).each(clean);
	if (window.CollectGarbage) CollectGarbage();
	collected = storage = null;
};

var walk = function(element, walk, start, match, all, nocash){
	var el = element[start || walk];
	var elements = [];
	while (el){
		if (el.nodeType == 1 && (!match || Element.match(el, match))){
			if (!all) return $(el, nocash);
			elements.push(el);
		}
		el = el[walk];
	}
	return (all) ? new Elements(elements, {ddup: false, cash: !nocash}) : null;
};

var attributes = {
	'html': 'innerHTML',
	'class': 'className',
	'for': 'htmlFor',
	'text': (Browser.Engine.trident || (Browser.Engine.webkit && Browser.Engine.version < 420)) ? 'innerText' : 'textContent'
};
var bools = ['compact', 'nowrap', 'ismap', 'declare', 'noshade', 'checked', 'disabled', 'readonly', 'multiple', 'selected', 'noresize', 'defer'];
var camels = ['value', 'accessKey', 'cellPadding', 'cellSpacing', 'colSpan', 'frameBorder', 'maxLength', 'readOnly', 'rowSpan', 'tabIndex', 'useMap'];

Hash.extend(attributes, bools.associate(bools));
Hash.extend(attributes, camels.associate(camels.map(String.toLowerCase)));

var inserters = {

	before: function(context, element){
		if (element.parentNode) element.parentNode.insertBefore(context, element);
	},

	after: function(context, element){
		if (!element.parentNode) return;
		var next = element.nextSibling;
		(next) ? element.parentNode.insertBefore(context, next) : element.parentNode.appendChild(context);
	},

	bottom: function(context, element){
		
		if(element){ element.appendChild(context); }
	},

	top: function(context, element){
		var first = element.firstChild;
		(first) ? element.insertBefore(context, first) : element.appendChild(context);
	}

};

inserters.inside = inserters.bottom;

Hash.each(inserters, function(inserter, where){

	where = where.capitalize();

	Element.implement('inject' + where, function(el){
		inserter(this, $(el, true));
		return this;
	});

	Element.implement('grab' + where, function(el){
		inserter($(el, true), this);
		return this;
	});

});

Element.implement({

	set: function(prop, value){
		switch ($type(prop)){
			case 'object':
				for (var p in prop) this.set(p, prop[p]);
				break;
			case 'string':
				var property = Element.Properties.get(prop);
				(property && property.set) ? property.set.apply(this, Array.slice(arguments, 1)) : this.setProperty(prop, value);
		}
		return this;
	},

	get: function(prop){
		var property = Element.Properties.get(prop);
		return (property && property.get) ? property.get.apply(this, Array.slice(arguments, 1)) : this.getProperty(prop);
	},

	erase: function(prop){
		var property = Element.Properties.get(prop);
		(property && property.erase) ? property.erase.apply(this) : this.removeProperty(prop);
		return this;
	},

	setProperty: function(attribute, value){
		var key = attributes[attribute];
		if (value == undefined) return this.removeProperty(attribute);
		if (key && bools[attribute]) value = !!value;
		(key) ? this[key] = value : this.setAttribute(attribute, '' + value);
		return this;
	},

	setProperties: function(attributes){
		for (var attribute in attributes) this.setProperty(attribute, attributes[attribute]);
		return this;
	},

	getProperty: function(attribute){
		var key = attributes[attribute];
		var value = (key) ? this[key] : this.getAttribute(attribute, 2);
		return (bools[attribute]) ? !!value : (key) ? value : value || null;
	},

	getProperties: function(){
		var args = $A(arguments);
		return args.map(this.getProperty, this).associate(args);
	},

	removeProperty: function(attribute){
		var key = attributes[attribute];
		(key) ? this[key] = (key && bools[attribute]) ? false : '' : this.removeAttribute(attribute);
		return this;
	},

	removeProperties: function(){
		Array.each(arguments, this.removeProperty, this);
		return this;
	},

	hasClass: function(className){
		return this.className.contains(className, ' ');
	},

	addClass: function(className){
		if (!this.hasClass(className)) this.className = (this.className + ' ' + className).clean();
		return this;
	},

	removeClass: function(className){
		this.className = this.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)'), '$1');
		return this;
	},

	toggleClass: function(className){
		return this.hasClass(className) ? this.removeClass(className) : this.addClass(className);
	},

	adopt: function(){
		Array.flatten(arguments).each(function(element){
			element = $(element, true);
			if (element) this.appendChild(element);
		}, this);
		return this;
	},

	appendText: function(text, where){
		return this.grab(this.getDocument().newTextNode(text), where);
	},

	grab: function(el, where){
		inserters[where || 'bottom']($(el, true), this);
		return this;
	},

	inject: function(el, where){
		inserters[where || 'bottom'](this, $(el, true));
		return this;
	},

	replaces: function(el){
		el = $(el, true);
		el.parentNode.replaceChild(this, el);
		return this;
	},

	wraps: function(el, where){
		el = $(el, true);
		return this.replaces(el).grab(el, where);
	},

	getPrevious: function(match, nocash){
		return walk(this, 'previousSibling', null, match, false, nocash);
	},

	getAllPrevious: function(match, nocash){
		return walk(this, 'previousSibling', null, match, true, nocash);
	},

	getNext: function(match, nocash){
		return walk(this, 'nextSibling', null, match, false, nocash);
	},

	getAllNext: function(match, nocash){
		return walk(this, 'nextSibling', null, match, true, nocash);
	},

	getFirst: function(match, nocash){
		return walk(this, 'nextSibling', 'firstChild', match, false, nocash);
	},

	getLast: function(match, nocash){
		return walk(this, 'previousSibling', 'lastChild', match, false, nocash);
	},

	getParent: function(match, nocash){
		return walk(this, 'parentNode', null, match, false, nocash);
	},

	getParents: function(match, nocash){
		return walk(this, 'parentNode', null, match, true, nocash);
	},

	getChildren: function(match, nocash){
		return walk(this, 'nextSibling', 'firstChild', match, true, nocash);
	},

	getWindow: function(){
		return this.ownerDocument.window;
	},

	getDocument: function(){
		return this.ownerDocument;
	},

	getElementById: function(id, nocash){
		var el = this.ownerDocument.getElementById(id);
		if (!el) return null;
		for (var parent = el.parentNode; parent != this; parent = parent.parentNode){
			if (!parent) return null;
		}
		return $.element(el, nocash);
	},

	getSelected: function(){
		return new Elements($A(this.options).filter(function(option){
			return option.selected;
		}));
	},

	getComputedStyle: function(property){
		if (this.currentStyle) return this.currentStyle[property.camelCase()];
		var computed = this.getDocument().defaultView.getComputedStyle(this, null);
		return (computed) ? computed.getPropertyValue([property.hyphenate()]) : null;
	},

	toQueryString: function(){
		var queryString = [];
		this.getElements('input, select, textarea', true).each(function(el){
			if (!el.name || el.disabled) return;
			var value = (el.tagName.toLowerCase() == 'select') ? Element.getSelected(el).map(function(opt){
				return opt.value;
			}) : ((el.type == 'radio' || el.type == 'checkbox') && !el.checked) ? null : el.value;
			$splat(value).each(function(val){
				if (typeof val != 'undefined') queryString.push(el.name + '=' + encodeURIComponent(val));
			});
		});
		return queryString.join('&');
	},

	clone: function(contents, keepid){
		contents = contents !== false;
		var clone = this.cloneNode(contents);
		var clean = function(node, element){
			if (!keepid) node.removeAttribute('id');
			if (Browser.Engine.trident){
				node.clearAttributes();
				node.mergeAttributes(element);
				node.removeAttribute('uid');
				if (node.options){
					var no = node.options, eo = element.options;
					for (var j = no.length; j--;) no[j].selected = eo[j].selected;
				}
			}
			var prop = props[element.tagName.toLowerCase()];
			if (prop && element[prop]) node[prop] = element[prop];
		};

		if (contents){
			var ce = clone.getElementsByTagName('*'), te = this.getElementsByTagName('*');
			for (var i = ce.length; i--;) clean(ce[i], te[i]);
		}

		clean(clone, this);
		return $(clone);
	},

	destroy: function(){
		Element.empty(this);
		Element.dispose(this);
		clean(this, true);
		return null;
	},

	empty: function(){
		$A(this.childNodes).each(function(node){
			Element.destroy(node);
		});
		return this;
	},

	dispose: function(){
		return (this.parentNode) ? this.parentNode.removeChild(this) : this;
	},

	hasChild: function(el){
		el = $(el, true);
		if (!el) return false;
		if (Browser.Engine.webkit && Browser.Engine.version < 420) return $A(this.getElementsByTagName(el.tagName)).contains(el);
		return (this.contains) ? (this != el && this.contains(el)) : !!(this.compareDocumentPosition(el) & 16);
	},

	match: function(tag){
		return (!tag || (tag == this) || (Element.get(this, 'tag') == tag));
	}

});

Native.implement([Element, Window, Document], {

	addListener: function(type, fn){
		if (type == 'unload'){
			var old = fn, self = this;
			fn = function(){
				self.removeListener('unload', fn);
				old();
			};
		} else {
			collected[this.uid] = this;
		}
		if (this.addEventListener) this.addEventListener(type, fn, false);
		else this.attachEvent('on' + type, fn);
		return this;
	},

	removeListener: function(type, fn){
		if (this.removeEventListener) this.removeEventListener(type, fn, false);
		else this.detachEvent('on' + type, fn);
		return this;
	},

	retrieve: function(property, dflt){
		var storage = get(this.uid), prop = storage[property];
		if (dflt != undefined && prop == undefined) prop = storage[property] = dflt;
		return $pick(prop);
	},

	store: function(property, value){
		var storage = get(this.uid);
		storage[property] = value;
		return this;
	},

	eliminate: function(property){
		var storage = get(this.uid);
		delete storage[property];
		return this;
	}

});

window.addListener('unload', purge);

})();

Element.Properties = new Hash;

Element.Properties.style = {

	set: function(style){
		this.style.cssText = style;
	},

	get: function(){
		return this.style.cssText;
	},

	erase: function(){
		this.style.cssText = '';
	}

};

Element.Properties.tag = {

	get: function(){
		return this.tagName.toLowerCase();
	}

};

Element.Properties.html = (function(){
	var wrapper = document.createElement('div');

	var translations = {
		table: [1, '<table>', '</table>'],
		select: [1, '<select>', '</select>'],
		tbody: [2, '<table><tbody>', '</tbody></table>'],
		tr: [3, '<table><tbody><tr>', '</tr></tbody></table>']
	};
	translations.thead = translations.tfoot = translations.tbody;

	var html = {
		set: function(){
			var html = Array.flatten(arguments).join('');
			var wrap = Browser.Engine.trident && translations[this.get('tag')];
			if (wrap){
				var first = wrapper;
				first.innerHTML = wrap[1] + html + wrap[2];
				for (var i = wrap[0]; i--;) first = first.firstChild;
				this.empty().adopt(first.childNodes);
			} else {
				this.innerHTML = html;
			}
		}
	};

	html.erase = html.set;

	return html;
})();

if (Browser.Engine.webkit && Browser.Engine.version < 420) Element.Properties.text = {
	get: function(){
		if (this.innerText) return this.innerText;
		var temp = this.ownerDocument.newElement('div', {html: this.innerHTML}).inject(this.ownerDocument.body);
		var text = temp.innerText;
		temp.destroy();
		return text;
	}
};


/*
Script: Element.Event.js
	Contains Element methods for dealing with events, and custom Events.

License:
	MIT-style license.
*/

Element.Properties.events = {set: function(events){
	this.addEvents(events);
}};

Native.implement([Element, Window, Document], {

	addEvent: function(type, fn){
		var events = this.retrieve('events', {});
		events[type] = events[type] || {'keys': [], 'values': []};
		if (events[type].keys.contains(fn)) return this;
		events[type].keys.push(fn);
		var realType = type, custom = Element.Events.get(type), condition = fn, self = this;
		if (custom){
			if (custom.onAdd) custom.onAdd.call(this, fn);
			if (custom.condition){
				condition = function(event){
					if (custom.condition.call(this, event)) return fn.call(this, event);
					return true;
				};
			}
			realType = custom.base || realType;
		}
		var defn = function(){
			return fn.call(self);
		};
		var nativeEvent = Element.NativeEvents[realType];
		if (nativeEvent){
			if (nativeEvent == 2){
				defn = function(event){
					event = new Event(event, self.getWindow());
					if (condition.call(self, event) === false) event.stop();
				};
			}
			this.addListener(realType, defn);
		}
		events[type].values.push(defn);
		return this;
	},

	removeEvent: function(type, fn){
		var events = this.retrieve('events');
		if (!events || !events[type]) return this;
		var pos = events[type].keys.indexOf(fn);
		if (pos == -1) return this;
		events[type].keys.splice(pos, 1);
		var value = events[type].values.splice(pos, 1)[0];
		var custom = Element.Events.get(type);
		if (custom){
			if (custom.onRemove) custom.onRemove.call(this, fn);
			type = custom.base || type;
		}
		return (Element.NativeEvents[type]) ? this.removeListener(type, value) : this;
	},

	addEvents: function(events){
		for (var event in events) this.addEvent(event, events[event]);
		return this;
	},

	removeEvents: function(events){
		if ($type(events) == 'object'){
			for (var type in events) this.removeEvent(type, events[type]);
			return this;
		}
		var attached = this.retrieve('events');
		if (!attached) return this;
		if (!events){
			for (var type in attached) this.removeEvents(type);
			this.eliminate('events');
		} else if (attached[events]){
			while (attached[events].keys[0]) this.removeEvent(events, attached[events].keys[0]);
			attached[events] = null;
		}
		return this;
	},

	fireEvent: function(type, args, delay){
		var events = this.retrieve('events');
		if (!events || !events[type]) return this;
		events[type].keys.each(function(fn){
			fn.create({'bind': this, 'delay': delay, 'arguments': args})();
		}, this);		
		return this;
	},

	cloneEvents: function(from, type){
		from = $(from);
		var fevents = from.retrieve('events');
		if (!fevents) return this;
		if (!type){
			for (var evType in fevents) this.cloneEvents(from, evType);
		} else if (fevents[type]){
			fevents[type].keys.each(function(fn){
				this.addEvent(type, fn);
			}, this);
		}
		return this;
	}

});

Element.NativeEvents = {
	click: 2, dblclick: 2, mouseup: 2, mousedown: 2, contextmenu: 2, //mouse buttons
	mousewheel: 2, DOMMouseScroll: 2, //mouse wheel
	mouseover: 2, mouseout: 2, mousemove: 2, selectstart: 2, selectend: 2, //mouse movement
	keydown: 2, keypress: 2, keyup: 2, //keyboard
	focus: 2, blur: 2, change: 2, reset: 2, select: 2, submit: 2, //form elements
	load: 1, unload: 1, beforeunload: 2, resize: 1, move: 1, DOMContentLoaded: 1, readystatechange: 1, //window
	error: 1, abort: 1, scroll: 1 //misc
};

(function(){

var $check = function(event){
	var related = event.relatedTarget;
	if (related == undefined) return true;
	if (related === false) return false;
	return ($type(this) != 'document' && related != this && related.prefix != 'xul' && !this.hasChild(related));
};

Element.Events = new Hash({

	mouseenter: {
		base: 'mouseover',
		condition: $check
	},

	mouseleave: {
		base: 'mouseout',
		condition: $check
	},

	mousewheel: {
		base: (Browser.Engine.gecko) ? 'DOMMouseScroll' : 'mousewheel'
	}

});

})();


/*
Script: Element.Style.js
	Contains methods for interacting with the styles of Elements in a fashionable way.

License:
	MIT-style license.
*/

Element.Properties.styles = {set: function(styles){
	this.setStyles(styles);
}};

Element.Properties.opacity = {

	set: function(opacity, novisibility){
		if (!novisibility){
			if (opacity == 0){
				if (this.style.visibility != 'hidden') this.style.visibility = 'hidden';
			} else {
				if (this.style.visibility != 'visible') this.style.visibility = 'visible';
			}
		}
		if (!this.currentStyle || !this.currentStyle.hasLayout) this.style.zoom = 1;
		if (Browser.Engine.trident) this.style.filter = (opacity == 1) ? '' : 'alpha(opacity=' + opacity * 100 + ')';
		this.style.opacity = opacity;
		this.store('opacity', opacity);
	},

	get: function(){
		return this.retrieve('opacity', 1);
	}

};

Element.implement({

	setOpacity: function(value){
		return this.set('opacity', value, true);
	},

	getOpacity: function(){
		return this.get('opacity');
	},

	setStyle: function(property, value){
		switch (property){
			case 'opacity': return this.set('opacity', parseFloat(value));
			case 'float': property = (Browser.Engine.trident) ? 'styleFloat' : 'cssFloat';
		}
		property = property.camelCase();
		if ($type(value) != 'string'){
			var map = (Element.Styles.get(property) || '@').split(' ');
			value = $splat(value).map(function(val, i){
				if (!map[i]) return '';
				return ($type(val) == 'number') ? map[i].replace('@', Math.round(val)) : val;
			}).join(' ');
		} else if (value == String(Number(value))){
			value = Math.round(value);
		}
		this.style[property] = value;
		return this;
	},

	getStyle: function(property){
		switch (property){
			case 'opacity': return this.get('opacity');
			case 'float': property = (Browser.Engine.trident) ? 'styleFloat' : 'cssFloat';
		}
		property = property.camelCase();
		var result = this.style[property];
		if (!$chk(result)){
			result = [];
			for (var style in Element.ShortStyles){
				if (property != style) continue;
				for (var s in Element.ShortStyles[style]) result.push(this.getStyle(s));
				return result.join(' ');
			}
			result = this.getComputedStyle(property);
		}
		if (result){
			result = String(result);
			var color = result.match(/rgba?\([\d\s,]+\)/);
			if (color) result = result.replace(color[0], color[0].rgbToHex());
		}
		if (Browser.Engine.presto || (Browser.Engine.trident && !$chk(parseInt(result)))){
			if (property.test(/^(height|width)$/)){
				var values = (property == 'width') ? ['left', 'right'] : ['top', 'bottom'], size = 0;
				values.each(function(value){
					size += this.getStyle('border-' + value + '-width').toInt() + this.getStyle('padding-' + value).toInt();
				}, this);
				return this['offset' + property.capitalize()] - size + 'px';
			}
			if ((Browser.Engine.presto) && String(result).test('px')) return result;
			if (property.test(/(border(.+)Width|margin|padding)/)) return '0px';
		}
		return result;
	},

	setStyles: function(styles){
		for (var style in styles) this.setStyle(style, styles[style]);
		return this;
	},

	getStyles: function(){
		var result = {};
		Array.each(arguments, function(key){
			result[key] = this.getStyle(key);
		}, this);
		return result;
	}

});

Element.Styles = new Hash({
	left: '@px', top: '@px', bottom: '@px', right: '@px',
	width: '@px', height: '@px', maxWidth: '@px', maxHeight: '@px', minWidth: '@px', minHeight: '@px',
	backgroundColor: 'rgb(@, @, @)', backgroundPosition: '@px @px', color: 'rgb(@, @, @)',
	fontSize: '@px', letterSpacing: '@px', lineHeight: '@px', clip: 'rect(@px @px @px @px)',
	margin: '@px @px @px @px', padding: '@px @px @px @px', border: '@px @ rgb(@, @, @) @px @ rgb(@, @, @) @px @ rgb(@, @, @)',
	borderWidth: '@px @px @px @px', borderStyle: '@ @ @ @', borderColor: 'rgb(@, @, @) rgb(@, @, @) rgb(@, @, @) rgb(@, @, @)',
	zIndex: '@', 'zoom': '@', fontWeight: '@', textIndent: '@px', opacity: '@'
});

Element.ShortStyles = {margin: {}, padding: {}, border: {}, borderWidth: {}, borderStyle: {}, borderColor: {}};

['Top', 'Right', 'Bottom', 'Left'].each(function(direction){
	var Short = Element.ShortStyles;
	var All = Element.Styles;
	['margin', 'padding'].each(function(style){
		var sd = style + direction;
		Short[style][sd] = All[sd] = '@px';
	});
	var bd = 'border' + direction;
	Short.border[bd] = All[bd] = '@px @ rgb(@, @, @)';
	var bdw = bd + 'Width', bds = bd + 'Style', bdc = bd + 'Color';
	Short[bd] = {};
	Short.borderWidth[bdw] = Short[bd][bdw] = All[bdw] = '@px';
	Short.borderStyle[bds] = Short[bd][bds] = All[bds] = '@';
	Short.borderColor[bdc] = Short[bd][bdc] = All[bdc] = 'rgb(@, @, @)';
});


/*
Script: Element.Dimensions.js
	Contains methods to work with size, scroll, or positioning of Elements and the window object.

License:
	MIT-style license.

Credits:
	- Element positioning based on the [qooxdoo](http://qooxdoo.org/) code and smart browser fixes, [LGPL License](http://www.gnu.org/licenses/lgpl.html).
	- Viewport dimensions based on [YUI](http://developer.yahoo.com/yui/) code, [BSD License](http://developer.yahoo.com/yui/license.html).
*/

(function(){

Element.implement({

	scrollTo: function(x, y){
		if (isBody(this)){
			this.getWindow().scrollTo(x, y);
		} else {
			this.scrollLeft = x;
			this.scrollTop = y;
		}
		return this;
	},

	getSize: function(){
		if (isBody(this)) return this.getWindow().getSize();
		return {x: this.offsetWidth, y: this.offsetHeight};
	},

	getScrollSize: function(){
		if (isBody(this)) return this.getWindow().getScrollSize();
		return {x: this.scrollWidth, y: this.scrollHeight};
	},

	getScroll: function(){
		if (isBody(this)) return this.getWindow().getScroll();
		return {x: this.scrollLeft, y: this.scrollTop};
	},

	getScrolls: function(){
		var element = this, position = {x: 0, y: 0};
		while (element && !isBody(element)){
			position.x += element.scrollLeft;
			position.y += element.scrollTop;
			element = element.parentNode;
		}
		return position;
	},

	getOffsetParent: function(){
		var element = this;
		if (isBody(element)) return null;
		if (!Browser.Engine.trident) return element.offsetParent;
		while ((element = element.parentNode) && !isBody(element)){
			if (styleString(element, 'position') != 'static') return element;
		}
		return null;
	},

	getOffsets: function(){
		if (Browser.Engine.trident){
			try{var bound = this.getBoundingClientRect();}catch (ex){return [0,0];}
			html = this.getDocument().documentElement;
			return {
				x: bound.left + html.scrollLeft - html.clientLeft,
				y: bound.top + html.scrollTop - html.clientTop
			};
		}

		var element = this, position = {x: 0, y: 0};
		if (isBody(this)) return position;

		while (element && !isBody(element)){
			position.x += element.offsetLeft;
			position.y += element.offsetTop;

			if (Browser.Engine.gecko){
				if (!borderBox(element)){
					position.x += leftBorder(element);
					position.y += topBorder(element);
				}
				var parent = element.parentNode;
				if (parent && styleString(parent, 'overflow') != 'visible'){
					position.x += leftBorder(parent);
					position.y += topBorder(parent);
				}
			} else if (element != this && Browser.Engine.webkit){
				position.x += leftBorder(element);
				position.y += topBorder(element);
			}

			element = element.offsetParent;
		}
		if (Browser.Engine.gecko && !borderBox(this)){
			position.x -= leftBorder(this);
			position.y -= topBorder(this);
		}
		return position;
	},

	getPosition: function(relative){
		if (isBody(this)) return {x: 0, y: 0};
		var offset = this.getOffsets(), scroll = this.getScrolls();
		var position = {x: offset.x - scroll.x, y: offset.y - scroll.y};
		var relativePosition = (relative && (relative = $(relative))) ? relative.getPosition() : {x: 0, y: 0};
		return {x: position.x - relativePosition.x, y: position.y - relativePosition.y};
	},

	getCoordinates: function(element){
		if (isBody(this)) return this.getWindow().getCoordinates();
		var position = this.getPosition(element), size = this.getSize();
		var obj = {left: position.x, top: position.y, width: size.x, height: size.y};
		obj.right = obj.left + obj.width;
		obj.bottom = obj.top + obj.height;
		return obj;
	},

	computePosition: function(obj){
		return {left: obj.x - styleNumber(this, 'margin-left'), top: obj.y - styleNumber(this, 'margin-top')};
	},

	position: function(obj){
		return this.setStyles(this.computePosition(obj));
	}

});

Native.implement([Document, Window], {

	getSize: function(){
		var win = this.getWindow();
		if (Browser.Engine.presto || Browser.Engine.webkit) return {x: win.innerWidth, y: win.innerHeight};
		var doc = getCompatElement(this);
		return {x: doc.clientWidth, y: doc.clientHeight};
	},

	getScroll: function(){
		var win = this.getWindow();
		var doc = getCompatElement(this);
		return {x: win.pageXOffset || doc.scrollLeft, y: win.pageYOffset || doc.scrollTop};
	},

	getScrollSize: function(){
		var doc = getCompatElement(this);
		var min = this.getSize();
		return {x: Math.max(doc.scrollWidth, min.x), y: Math.max(doc.scrollHeight, min.y)};
	},

	getPosition: function(){
		return {x: 0, y: 0};
	},

	getCoordinates: function(){
		var size = this.getSize();
		return {top: 0, left: 0, bottom: size.y, right: size.x, height: size.y, width: size.x};
	}

});

// private methods

var styleString = Element.getComputedStyle;

function styleNumber(element, style){
	return styleString(element, style).toInt() || 0;
};

function borderBox(element){
	return styleString(element, '-moz-box-sizing') == 'border-box';
};

function topBorder(element){
	return styleNumber(element, 'border-top-width');
};

function leftBorder(element){
	return styleNumber(element, 'border-left-width');
};

function isBody(element){
	return (/^(?:body|html)$/i).test(element.tagName);
};

function getCompatElement(element){
	var doc = element.getDocument();
	return (!doc.compatMode || doc.compatMode == 'CSS1Compat') ? doc.html : doc.body;
};

})();

//aliases

Native.implement([Window, Document, Element], {

	getHeight: function(){
		return this.getSize().y;
	},

	getWidth: function(){
		return this.getSize().x;
	},

	getScrollTop: function(){
		return this.getScroll().y;
	},

	getScrollLeft: function(){
		return this.getScroll().x;
	},

	getScrollHeight: function(){
		return this.getScrollSize().y;
	},

	getScrollWidth: function(){
		return this.getScrollSize().x;
	},

	getTop: function(){
		return this.getPosition().y;
	},

	getLeft: function(){
		return this.getPosition().x;
	}

});


/*
Script: Selectors.js
	Adds advanced CSS Querying capabilities for targeting elements. Also includes pseudoselectors support.

License:
	MIT-style license.
*/

Native.implement([Document, Element], {

	getElements: function(expression, nocash){
		expression = expression.split(',');
		var items, local = {};
		for (var i = 0, l = expression.length; i < l; i++){
			var selector = expression[i], elements = Selectors.Utils.search(this, selector, local);
			if (i != 0 && elements.item) elements = $A(elements);
			items = (i == 0) ? elements : (items.item) ? $A(items).concat(elements) : items.concat(elements);
		}
		return new Elements(items, {ddup: (expression.length > 1), cash: !nocash});
	}

});

Element.implement({

	match: function(selector){
		if (!selector || (selector == this)) return true;
		var tagid = Selectors.Utils.parseTagAndID(selector);
		var tag = tagid[0], id = tagid[1];
		if (!Selectors.Filters.byID(this, id) || !Selectors.Filters.byTag(this, tag)) return false;
		var parsed = Selectors.Utils.parseSelector(selector);
		return (parsed) ? Selectors.Utils.filter(this, parsed, {}) : true;
	}

});

var Selectors = {Cache: {nth: {}, parsed: {}}};

Selectors.RegExps = {
	id: (/#([\w-]+)/),
	tag: (/^(\w+|\*)/),
	quick: (/^(\w+|\*)$/),
	splitter: (/\s*([+>~\s])\s*([a-zA-Z#.*:\[])/g),
	combined: (/\.([\w-]+)|\[(\w+)(?:([!*^$~|]?=)(["']?)([^\4]*?)\4)?\]|:([\w-]+)(?:\(["']?(.*?)?["']?\)|$)/g)
};

Selectors.Utils = {

	chk: function(item, uniques){
		if (!uniques) return true;
		var uid = $uid(item);
		if (!uniques[uid]) return uniques[uid] = true;
		return false;
	},

	parseNthArgument: function(argument){
		if (Selectors.Cache.nth[argument]) return Selectors.Cache.nth[argument];
		var parsed = argument.match(/^([+-]?\d*)?([a-z]+)?([+-]?\d*)?$/);
		if (!parsed) return false;
		var inta = parseInt(parsed[1]);
		var a = (inta || inta === 0) ? inta : 1;
		var special = parsed[2] || false;
		var b = parseInt(parsed[3]) || 0;
		if (a != 0){
			b--;
			while (b < 1) b += a;
			while (b >= a) b -= a;
		} else {
			a = b;
			special = 'index';
		}
		switch (special){
			case 'n': parsed = {a: a, b: b, special: 'n'}; break;
			case 'odd': parsed = {a: 2, b: 0, special: 'n'}; break;
			case 'even': parsed = {a: 2, b: 1, special: 'n'}; break;
			case 'first': parsed = {a: 0, special: 'index'}; break;
			case 'last': parsed = {special: 'last-child'}; break;
			case 'only': parsed = {special: 'only-child'}; break;
			default: parsed = {a: (a - 1), special: 'index'};
		}

		return Selectors.Cache.nth[argument] = parsed;
	},

	parseSelector: function(selector){
		if (Selectors.Cache.parsed[selector]) return Selectors.Cache.parsed[selector];
		var m, parsed = {classes: [], pseudos: [], attributes: []};
		while ((m = Selectors.RegExps.combined.exec(selector))){
			var cn = m[1], an = m[2], ao = m[3], av = m[5], pn = m[6], pa = m[7];
			if (cn){
				parsed.classes.push(cn);
			} else if (pn){
				var parser = Selectors.Pseudo.get(pn);
				if (parser) parsed.pseudos.push({parser: parser, argument: pa});
				else parsed.attributes.push({name: pn, operator: '=', value: pa});
			} else if (an){
				parsed.attributes.push({name: an, operator: ao, value: av});
			}
		}
		if (!parsed.classes.length) delete parsed.classes;
		if (!parsed.attributes.length) delete parsed.attributes;
		if (!parsed.pseudos.length) delete parsed.pseudos;
		if (!parsed.classes && !parsed.attributes && !parsed.pseudos) parsed = null;
		return Selectors.Cache.parsed[selector] = parsed;
	},

	parseTagAndID: function(selector){
		var tag = selector.match(Selectors.RegExps.tag);
		var id = selector.match(Selectors.RegExps.id);
		return [(tag) ? tag[1] : '*', (id) ? id[1] : false];
	},

	filter: function(item, parsed, local){
		var i;
		if (parsed.classes){
			for (i = parsed.classes.length; i--; i){
				var cn = parsed.classes[i];
				if (!Selectors.Filters.byClass(item, cn)) return false;
			}
		}
		if (parsed.attributes){
			for (i = parsed.attributes.length; i--; i){
				var att = parsed.attributes[i];
				if (!Selectors.Filters.byAttribute(item, att.name, att.operator, att.value)) return false;
			}
		}
		if (parsed.pseudos){
			for (i = parsed.pseudos.length; i--; i){
				var psd = parsed.pseudos[i];
				if (!Selectors.Filters.byPseudo(item, psd.parser, psd.argument, local)) return false;
			}
		}
		return true;
	},

	getByTagAndID: function(ctx, tag, id){
		if (id){
			var item = (ctx.getElementById) ? ctx.getElementById(id, true) : Element.getElementById(ctx, id, true);
			return (item && Selectors.Filters.byTag(item, tag)) ? [item] : [];
		} else {
			return ctx.getElementsByTagName(tag);
		}
	},

	search: function(self, expression, local){
		var splitters = [];

		var selectors = expression.trim().replace(Selectors.RegExps.splitter, function(m0, m1, m2){
			splitters.push(m1);
			return ':)' + m2;
		}).split(':)');

		var items, filtered, item;

		for (var i = 0, l = selectors.length; i < l; i++){

			var selector = selectors[i];

			if (i == 0 && Selectors.RegExps.quick.test(selector)){
				items = self.getElementsByTagName(selector);
				continue;
			}

			var splitter = splitters[i - 1];

			var tagid = Selectors.Utils.parseTagAndID(selector);
			var tag = tagid[0], id = tagid[1];

			if (i == 0){
				items = Selectors.Utils.getByTagAndID(self, tag, id);
			} else {
				var uniques = {}, found = [];
				for (var j = 0, k = items.length; j < k; j++) found = Selectors.Getters[splitter](found, items[j], tag, id, uniques);
				items = found;
			}

			var parsed = Selectors.Utils.parseSelector(selector);

			if (parsed){
				filtered = [];
				for (var m = 0, n = items.length; m < n; m++){
					item = items[m];
					if (Selectors.Utils.filter(item, parsed, local)) filtered.push(item);
				}
				items = filtered;
			}

		}

		return items;

	}

};

Selectors.Getters = {

	' ': function(found, self, tag, id, uniques){
		var items = Selectors.Utils.getByTagAndID(self, tag, id);
		for (var i = 0, l = items.length; i < l; i++){
			var item = items[i];
			if (Selectors.Utils.chk(item, uniques)) found.push(item);
		}
		return found;
	},

	'>': function(found, self, tag, id, uniques){
		var children = Selectors.Utils.getByTagAndID(self, tag, id);
		for (var i = 0, l = children.length; i < l; i++){
			var child = children[i];
			if (child.parentNode == self && Selectors.Utils.chk(child, uniques)) found.push(child);
		}
		return found;
	},

	'+': function(found, self, tag, id, uniques){
		while ((self = self.nextSibling)){
			if (self.nodeType == 1){
				if (Selectors.Utils.chk(self, uniques) && Selectors.Filters.byTag(self, tag) && Selectors.Filters.byID(self, id)) found.push(self);
				break;
			}
		}
		return found;
	},

	'~': function(found, self, tag, id, uniques){
		while ((self = self.nextSibling)){
			if (self.nodeType == 1){
				if (!Selectors.Utils.chk(self, uniques)) break;
				if (Selectors.Filters.byTag(self, tag) && Selectors.Filters.byID(self, id)) found.push(self);
			}
		}
		return found;
	}

};

Selectors.Filters = {

	byTag: function(self, tag){
		return (tag == '*' || (self.tagName && self.tagName.toLowerCase() == tag));
	},

	byID: function(self, id){
		return (!id || (self.id && self.id == id));
	},

	byClass: function(self, klass){
		return (self.className && self.className.contains(klass, ' '));
	},

	byPseudo: function(self, parser, argument, local){
		return parser.call(self, argument, local);
	},

	byAttribute: function(self, name, operator, value){
		var result = Element.prototype.getProperty.call(self, name);
		if (!result) return (operator == '!=');
		if (!operator || value == undefined) return true;
		switch (operator){
			case '=': return (result == value);
			case '*=': return (result.contains(value));
			case '^=': return (result.substr(0, value.length) == value);
			case '$=': return (result.substr(result.length - value.length) == value);
			case '!=': return (result != value);
			case '~=': return result.contains(value, ' ');
			case '|=': return result.contains(value, '-');
		}
		return false;
	}

};

Selectors.Pseudo = new Hash({

	// w3c pseudo selectors

	checked: function(){
		return this.checked;
	},

	empty: function(){
		return !(this.innerText || this.textContent || '').length;
	},

	not: function(selector){
		return !Element.match(this, selector);
	},

	contains: function(text){
		return (this.innerText || this.textContent || '').contains(text);
	},

	'first-child': function(){
		return Selectors.Pseudo.index.call(this, 0);
	},

	'last-child': function(){
		var element = this;
		while ((element = element.nextSibling)){
			if (element.nodeType == 1) return false;
		}
		return true;
	},

	'only-child': function(){
		var prev = this;
		while ((prev = prev.previousSibling)){
			if (prev.nodeType == 1) return false;
		}
		var next = this;
		while ((next = next.nextSibling)){
			if (next.nodeType == 1) return false;
		}
		return true;
	},

	'nth-child': function(argument, local){
		argument = (argument == undefined) ? 'n' : argument;
		var parsed = Selectors.Utils.parseNthArgument(argument);
		if (parsed.special != 'n') return Selectors.Pseudo[parsed.special].call(this, parsed.a, local);
		var count = 0;
		local.positions = local.positions || {};
		var uid = $uid(this);
		if (!local.positions[uid]){
			var self = this;
			while ((self = self.previousSibling)){
				if (self.nodeType != 1) continue;
				count ++;
				var position = local.positions[$uid(self)];
				if (position != undefined){
					count = position + count;
					break;
				}
			}
			local.positions[uid] = count;
		}
		return (local.positions[uid] % parsed.a == parsed.b);
	},

	// custom pseudo selectors

	index: function(index){
		var element = this, count = 0;
		while ((element = element.previousSibling)){
			if (element.nodeType == 1 && ++count > index) return false;
		}
		return (count == index);
	},

	even: function(argument, local){
		return Selectors.Pseudo['nth-child'].call(this, '2n+1', local);
	},

	odd: function(argument, local){
		return Selectors.Pseudo['nth-child'].call(this, '2n', local);
	}

});


/*
Script: Domready.js
	Contains the domready custom event.

License:
	MIT-style license.
*/

Element.Events.domready = {

	onAdd: function(fn){
		if (Browser.loaded) fn.call(this);
	}

};

(function(){

	var domready = function(){
		if (Browser.loaded) return;
		Browser.loaded = true;
		window.fireEvent('domready');
		document.fireEvent('domready');
	};

	if (Browser.Engine.trident){
		var temp = document.createElement('div');
		(function(){
			($try(function(){
				temp.doScroll('left');
				return $(temp).inject(document.body).set('html', 'temp').dispose();
			})) ? domready() : arguments.callee.delay(50);
		})();
	} else if (Browser.Engine.webkit && Browser.Engine.version < 525){
		(function(){
			(['loaded', 'complete'].contains(document.readyState)) ? domready() : arguments.callee.delay(50);
		})();
	} else {
		window.addEvent('load', domready);
		document.addEvent('DOMContentLoaded', domready);
	}

})();


/*
Script: JSON.js
	JSON encoder and decoder.

License:
	MIT-style license.

See Also:
	<http://www.json.org/>
*/

var JSON = new Hash({

	$specialChars: {'\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\'},

	$replaceChars: function(chr){
		return JSON.$specialChars[chr] || '\\u00' + Math.floor(chr.charCodeAt() / 16).toString(16) + (chr.charCodeAt() % 16).toString(16);
	},

	encode: function(obj){
		switch ($type(obj)){
			case 'string':
				return '"' + obj.replace(/[\x00-\x1f\\"]/g, JSON.$replaceChars) + '"';
			case 'array':
				return '[' + String(obj.map(JSON.encode).filter($defined)) + ']';
			case 'object': case 'hash':
				var string = [];
				Hash.each(obj, function(value, key){
					var json = JSON.encode(value);
					if (json) string.push(JSON.encode(key) + ':' + json);
				});
				return '{' + string + '}';
			case 'number': case 'boolean': return String(obj);
			case false: return 'null';
		}
		return null;
	},

	decode: function(string, secure){
		if ($type(string) != 'string' || !string.length) return null;
		if (secure && !(/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(string.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, ''))) return null;
		return eval('(' + string + ')');
	}

});

Native.implement([Hash, Array, String, Number], {

	toJSON: function(){
		return JSON.encode(this);
	}

});


/*
Script: Cookie.js
	Class for creating, loading, and saving browser Cookies.

License:
	MIT-style license.

Credits:
	Based on the functions by Peter-Paul Koch (http://quirksmode.org).
*/

var Cookie = new Class({

	Implements: Options,

	options: {
		path: false,
		domain: false,
		duration: false,
		secure: false,
		document: document
	},

	initialize: function(key, options){
		this.key = key;
		this.setOptions(options);
	},

	write: function(value){
		value = encodeURIComponent(value);
		if (this.options.domain) value += '; domain=' + this.options.domain;
		if (this.options.path) value += '; path=' + this.options.path;
		if (this.options.duration){
			var date = new Date();
			date.setTime(date.getTime() + this.options.duration * 24 * 60 * 60 * 1000);
			value += '; expires=' + date.toGMTString();
		}
		if (this.options.secure) value += '; secure';
		this.options.document.cookie = this.key + '=' + value;
		return this;
	},

	read: function(){
		var value = this.options.document.cookie.match('(?:^|;)\\s*' + this.key.escapeRegExp() + '=([^;]*)');
		return (value) ? decodeURIComponent(value[1]) : null;
	},

	dispose: function(){
		new Cookie(this.key, $merge(this.options, {duration: -1})).write('');
		return this;
	}

});

Cookie.write = function(key, value, options){
	return new Cookie(key, options).write(value);
};

Cookie.read = function(key){
	return new Cookie(key).read();
};

Cookie.dispose = function(key, options){
	return new Cookie(key, options).dispose();
};


/*
Script: Swiff.js
	Wrapper for embedding SWF movies. Supports (and fixes) External Interface Communication.

License:
	MIT-style license.

Credits:
	Flash detection & Internet Explorer + Flash Player 9 fix inspired by SWFObject.
*/

var Swiff = new Class({

	Implements: [Options],

	options: {
		id: null,
		height: 1,
		width: 1,
		container: null,
		properties: {},
		params: {
			quality: 'high',
			allowScriptAccess: 'always',
			wMode: 'transparent',
			swLiveConnect: true
		},
		callBacks: {},
		vars: {}
	},

	toElement: function(){
		return this.object;
	},

	initialize: function(path, options){
		this.instance = 'Swiff_' + $time();

		this.setOptions(options);
		options = this.options;
		var id = this.id = options.id || this.instance;
		var container = $(options.container);

		Swiff.CallBacks[this.instance] = {};

		var params = options.params, vars = options.vars, callBacks = options.callBacks;
		var properties = $extend({height: options.height, width: options.width}, options.properties);

		var self = this;

		for (var callBack in callBacks){
			Swiff.CallBacks[this.instance][callBack] = (function(option){
				return function(){
					return option.apply(self.object, arguments);
				};
			})(callBacks[callBack]);
			vars[callBack] = 'Swiff.CallBacks.' + this.instance + '.' + callBack;
		}

		params.flashVars = Hash.toQueryString(vars);
		if (Browser.Engine.trident){
			properties.classid = 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000';
			params.movie = path;
		} else {
			properties.type = 'application/x-shockwave-flash';
			properties.data = path;
		}
		var build = '<object id="' + id + '"';
		for (var property in properties) build += ' ' + property + '="' + properties[property] + '"';
		build += '>';
		for (var param in params){
			if (params[param]) build += '<param name="' + param + '" value="' + params[param] + '" />';
		}
		build += '</object>';
		this.object = ((container) ? container.empty() : new Element('div')).set('html', build).firstChild;
	},

	replaces: function(element){
		element = $(element, true);
		element.parentNode.replaceChild(this.toElement(), element);
		return this;
	},

	inject: function(element){
		$(element, true).appendChild(this.toElement());
		return this;
	},

	remote: function(){
		return Swiff.remote.apply(Swiff, [this.toElement()].extend(arguments));
	}

});

Swiff.CallBacks = {};

Swiff.remote = function(obj, fn){
	var rs = obj.CallFunction('<invoke name="' + fn + '" returntype="javascript">' + __flash__argumentsToXML(arguments, 2) + '</invoke>');
	return eval(rs);
};


/*
Script: Fx.js
	Contains the basic animation logic to be extended by all other Fx Classes.

License:
	MIT-style license.
*/

var Fx = new Class({

	Implements: [Chain, Events, Options],

	options: {
		/*
		onStart: $empty,
		onCancel: $empty,
		onComplete: $empty,
		*/
		fps: 50,
		unit: false,
		duration: 500,
		link: 'ignore'
	},

	initialize: function(options){
		this.subject = this.subject || this;
		this.setOptions(options);
		this.options.duration = Fx.Durations[this.options.duration] || this.options.duration.toInt();
		var wait = this.options.wait;
		if (wait === false) this.options.link = 'cancel';
	},

	getTransition: function(){
		return function(p){
			return -(Math.cos(Math.PI * p) - 1) / 2;
		};
	},

	step: function(){
		var time = $time();
		if (time < this.time + this.options.duration){
			var delta = this.transition((time - this.time) / this.options.duration);
			this.set(this.compute(this.from, this.to, delta));
		} else {
			this.set(this.compute(this.from, this.to, 1));
			this.complete();
		}
	},

	set: function(now){
		return now;
	},

	compute: function(from, to, delta){
		return Fx.compute(from, to, delta);
	},

	check: function(caller){
		if (!this.timer) return true;
		switch (this.options.link){
			case 'cancel': this.cancel(); return true;
			case 'chain': this.chain(caller.bind(this, Array.slice(arguments, 1))); return false;
		}
		return false;
	},

	start: function(from, to){
		if (!this.check(arguments.callee, from, to)) return this;
		this.from = from;
		this.to = to;
		this.time = 0;
		this.transition = this.getTransition();
		this.startTimer();
		this.onStart();
		return this;
	},

	complete: function(){
		if (this.stopTimer()) this.onComplete();
		return this;
	},

	cancel: function(){
		if (this.stopTimer()) this.onCancel();
		return this;
	},

	onStart: function(){
		this.fireEvent('start', this.subject);
	},

	onComplete: function(){
		this.fireEvent('complete', this.subject);
		if (!this.callChain()) this.fireEvent('chainComplete', this.subject);
	},

	onCancel: function(){
		this.fireEvent('cancel', this.subject).clearChain();
	},

	pause: function(){
		this.stopTimer();
		return this;
	},

	resume: function(){
		this.startTimer();
		return this;
	},

	stopTimer: function(){
		if (!this.timer) return false;
		this.time = $time() - this.time;
		this.timer = $clear(this.timer);
		return true;
	},

	startTimer: function(){
		if (this.timer) return false;
		this.time = $time() - this.time;
		this.timer = this.step.periodical(Math.round(1000 / this.options.fps), this);
		return true;
	}

});

Fx.compute = function(from, to, delta){
	return (to - from) * delta + from;
};

Fx.Durations = {'short': 250, 'normal': 500, 'long': 1000};


/*
Script: Fx.CSS.js
	Contains the CSS animation logic. Used by Fx.Tween, Fx.Morph, Fx.Elements.

License:
	MIT-style license.
*/

Fx.CSS = new Class({

	Extends: Fx,

	//prepares the base from/to object

	prepare: function(element, property, values){
		values = $splat(values);
		var values1 = values[1];
		if (!$chk(values1)){
			values[1] = values[0];
			values[0] = element.getStyle(property);
		}
		var parsed = values.map(this.parse);
		return {from: parsed[0], to: parsed[1]};
	},

	//parses a value into an array

	parse: function(value){
		value = $lambda(value)();
		value = (typeof value == 'string') ? value.split(' ') : $splat(value);
		return value.map(function(val){
			val = String(val);
			var found = false;
			Fx.CSS.Parsers.each(function(parser, key){
				if (found) return;
				var parsed = parser.parse(val);
				if ($chk(parsed)) found = {value: parsed, parser: parser};
			});
			found = found || {value: val, parser: Fx.CSS.Parsers.String};
			return found;
		});
	},

	//computes by a from and to prepared objects, using their parsers.

	compute: function(from, to, delta){
		var computed = [];
		(Math.min(from.length, to.length)).times(function(i){
			computed.push({value: from[i].parser.compute(from[i].value, to[i].value, delta), parser: from[i].parser});
		});
		computed.$family = {name: 'fx:css:value'};
		return computed;
	},

	//serves the value as settable

	serve: function(value, unit){
		if ($type(value) != 'fx:css:value') value = this.parse(value);
		var returned = [];
		value.each(function(bit){
			returned = returned.concat(bit.parser.serve(bit.value, unit));
		});
		return returned;
	},

	//renders the change to an element

	render: function(element, property, value, unit){
		element.setStyle(property, this.serve(value, unit));
	},

	//searches inside the page css to find the values for a selector

	search: function(selector){
		if (Fx.CSS.Cache[selector]) return Fx.CSS.Cache[selector];
		var to = {};
		Array.each(document.styleSheets, function(sheet, j){
			var href = sheet.href;
			if (href && href.contains('://') && !href.contains(document.domain)) return;
			var rules = sheet.rules || sheet.cssRules;
			Array.each(rules, function(rule, i){
				if (!rule.style) return;
				var selectorText = (rule.selectorText) ? rule.selectorText.replace(/^\w+/, function(m){
					return m.toLowerCase();
				}) : null;
				if (!selectorText || !selectorText.test('^' + selector + '$')) return;
				Element.Styles.each(function(value, style){
					if (!rule.style[style] || Element.ShortStyles[style]) return;
					value = String(rule.style[style]);
					to[style] = (value.test(/^rgb/)) ? value.rgbToHex() : value;
				});
			});
		});
		return Fx.CSS.Cache[selector] = to;
	}

});

Fx.CSS.Cache = {};

Fx.CSS.Parsers = new Hash({

	Color: {
		parse: function(value){
			if (value.match(/^#[0-9a-f]{3,6}$/i)) return value.hexToRgb(true);
			return ((value = value.match(/(\d+),\s*(\d+),\s*(\d+)/))) ? [value[1], value[2], value[3]] : false;
		},
		compute: function(from, to, delta){
			return from.map(function(value, i){
				return Math.round(Fx.compute(from[i], to[i], delta));
			});
		},
		serve: function(value){
			return value.map(Number);
		}
	},

	Number: {
		parse: parseFloat,
		compute: Fx.compute,
		serve: function(value, unit){
			return (unit) ? value + unit : value;
		}
	},

	String: {
		parse: $lambda(false),
		compute: $arguments(1),
		serve: $arguments(0)
	}

});


/*
Script: Fx.Tween.js
	Formerly Fx.Style, effect to transition any CSS property for an element.

License:
	MIT-style license.
*/

Fx.Tween = new Class({

	Extends: Fx.CSS,

	initialize: function(element, options){
		this.element = this.subject = $(element);
		this.parent(options);
	},

	set: function(property, now){
		if (arguments.length == 1){
			now = property;
			property = this.property || this.options.property;
		}
		this.render(this.element, property, now, this.options.unit);
		return this;
	},

	start: function(property, from, to){
		if (!this.check(arguments.callee, property, from, to)) return this;
		var args = Array.flatten(arguments);
		this.property = this.options.property || args.shift();
		var parsed = this.prepare(this.element, this.property, args);
		return this.parent(parsed.from, parsed.to);
	}

});

Element.Properties.tween = {

	set: function(options){
		var tween = this.retrieve('tween');
		if (tween) tween.cancel();
		return this.eliminate('tween').store('tween:options', $extend({link: 'cancel'}, options));
	},

	get: function(options){
		if (options || !this.retrieve('tween')){
			if (options || !this.retrieve('tween:options')) this.set('tween', options);
			this.store('tween', new Fx.Tween(this, this.retrieve('tween:options')));
		}
		return this.retrieve('tween');
	}

};

Element.implement({

	tween: function(property, from, to){
		this.get('tween').start(arguments);
		return this;
	},

	fade: function(how){
		var fade = this.get('tween'), o = 'opacity', toggle;
		how = $pick(how, 'toggle');
		switch (how){
			case 'in': fade.start(o, 1); break;
			case 'out': fade.start(o, 0); break;
			case 'show': fade.set(o, 1); break;
			case 'hide': fade.set(o, 0); break;
			case 'toggle':
				var flag = this.retrieve('fade:flag', this.get('opacity') == 1);
				fade.start(o, (flag) ? 0 : 1);
				this.store('fade:flag', !flag);
				toggle = true;
			break;
			default: fade.start(o, arguments);
		}
		if (!toggle) this.eliminate('fade:flag');
		return this;
	},

	highlight: function(start, end){
		if (!end){
			end = this.retrieve('highlight:original', this.getStyle('background-color'));
			end = (end == 'transparent') ? '#fff' : end;
		}
		var tween = this.get('tween');
		tween.start('background-color', start || '#ffff88', end).chain(function(){
			this.setStyle('background-color', this.retrieve('highlight:original'));
			tween.callChain();
		}.bind(this));
		return this;
	}

});


/*
Script: Fx.Morph.js
	Formerly Fx.Styles, effect to transition any number of CSS properties for an element using an object of rules, or CSS based selector rules.

License:
	MIT-style license.
*/

Fx.Morph = new Class({

	Extends: Fx.CSS,

	initialize: function(element, options){
		this.element = this.subject = $(element);
		this.parent(options);
	},

	set: function(now){
		if (typeof now == 'string') now = this.search(now);
		for (var p in now) this.render(this.element, p, now[p], this.options.unit);
		return this;
	},

	compute: function(from, to, delta){
		var now = {};
		for (var p in from) now[p] = this.parent(from[p], to[p], delta);
		return now;
	},

	start: function(properties){
		if (!this.check(arguments.callee, properties)) return this;
		if (typeof properties == 'string') properties = this.search(properties);
		var from = {}, to = {};
		for (var p in properties){
			var parsed = this.prepare(this.element, p, properties[p]);
			from[p] = parsed.from;
			to[p] = parsed.to;
		}
		return this.parent(from, to);
	}

});

Element.Properties.morph = {

	set: function(options){
		var morph = this.retrieve('morph');
		if (morph) morph.cancel();
		return this.eliminate('morph').store('morph:options', $extend({link: 'cancel'}, options));
	},

	get: function(options){
		if (options || !this.retrieve('morph')){
			if (options || !this.retrieve('morph:options')) this.set('morph', options);
			this.store('morph', new Fx.Morph(this, this.retrieve('morph:options')));
		}
		return this.retrieve('morph');
	}

};

Element.implement({

	morph: function(props){
		this.get('morph').start(props);
		return this;
	}

});


/*
Script: Fx.Transitions.js
	Contains a set of advanced transitions to be used with any of the Fx Classes.

License:
	MIT-style license.

Credits:
	Easing Equations by Robert Penner, <http://www.robertpenner.com/easing/>, modified and optimized to be used with MooTools.
*/

Fx.implement({

	getTransition: function(){
		var trans = this.options.transition || Fx.Transitions.Sine.easeInOut;
		if (typeof trans == 'string'){
			var data = trans.split(':');
			trans = Fx.Transitions;
			trans = trans[data[0]] || trans[data[0].capitalize()];
			if (data[1]) trans = trans['ease' + data[1].capitalize() + (data[2] ? data[2].capitalize() : '')];
		}
		return trans;
	}

});

Fx.Transition = function(transition, params){
	params = $splat(params);
	return $extend(transition, {
		easeIn: function(pos){
			return transition(pos, params);
		},
		easeOut: function(pos){
			return 1 - transition(1 - pos, params);
		},
		easeInOut: function(pos){
			return (pos <= 0.5) ? transition(2 * pos, params) / 2 : (2 - transition(2 * (1 - pos), params)) / 2;
		}
	});
};

Fx.Transitions = new Hash({

	linear: $arguments(0)

});

Fx.Transitions.extend = function(transitions){
	for (var transition in transitions) Fx.Transitions[transition] = new Fx.Transition(transitions[transition]);
};

Fx.Transitions.extend({

	Pow: function(p, x){
		return Math.pow(p, x[0] || 6);
	},

	Expo: function(p){
		return Math.pow(2, 8 * (p - 1));
	},

	Circ: function(p){
		return 1 - Math.sin(Math.acos(p));
	},

	Sine: function(p){
		return 1 - Math.sin((1 - p) * Math.PI / 2);
	},

	Back: function(p, x){
		x = x[0] || 1.618;
		return Math.pow(p, 2) * ((x + 1) * p - x);
	},

	Bounce: function(p){
		var value;
		for (var a = 0, b = 1; 1; a += b, b /= 2){
			if (p >= (7 - 4 * a) / 11){
				value = b * b - Math.pow((11 - 6 * a - 11 * p) / 4, 2);
				break;
			}
		}
		return value;
	},

	Elastic: function(p, x){
		return Math.pow(2, 10 * --p) * Math.cos(20 * p * Math.PI * (x[0] || 1) / 3);
	}

});

['Quad', 'Cubic', 'Quart', 'Quint'].each(function(transition, i){
	Fx.Transitions[transition] = new Fx.Transition(function(p){
		return Math.pow(p, [i + 2]);
	});
});


/*
Script: Request.js
	Powerful all purpose Request Class. Uses XMLHTTPRequest.

License:
	MIT-style license.
*/

var Request = new Class({

	Implements: [Chain, Events, Options],

	options: {/*
		onRequest: $empty,
		onComplete: $empty,
		onCancel: $empty,
		onSuccess: $empty,
		onFailure: $empty,
		onException: $empty,*/
		url: '',
		data: '',
		headers: {
			'X-Requested-With': 'XMLHttpRequest',
			'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
		},
		async: true,
		format: false,
		method: 'post',
		link: 'ignore',
		isSuccess: null,
		emulation: true,
		urlEncoded: true,
		encoding: 'utf-8',
		evalScripts: false,
		evalResponse: false
	},

	initialize: function(options){
		this.xhr = new Browser.Request();
		this.setOptions(options);
		this.options.isSuccess = this.options.isSuccess || this.isSuccess;
		this.headers = new Hash(this.options.headers);
	},

	onStateChange: function(){
		if (this.xhr.readyState != 4 || !this.running) return;
		this.running = false;
		this.status = 0;
		$try(function(){
			this.status = this.xhr.status;
		}.bind(this));
		if (this.options.isSuccess.call(this, this.status)){
			this.response = {text: this.xhr.responseText, xml: this.xhr.responseXML};
			this.success(this.response.text, this.response.xml);
		} else {
			this.response = {text: null, xml: null};
			this.failure();
		}
		this.xhr.onreadystatechange = $empty;
	},

	isSuccess: function(){
		return ((this.status >= 200) && (this.status < 300));
	},

	processScripts: function(text){
		if (this.options.evalResponse || (/(ecma|java)script/).test(this.getHeader('Content-type'))) return $exec(text);
		return text.stripScripts(this.options.evalScripts);
	},

	success: function(text, xml){
		this.onSuccess(this.processScripts(text), xml);
	},

	onSuccess: function(){
		this.fireEvent('complete', arguments).fireEvent('success', arguments).callChain();
	},

	failure: function(){
		this.onFailure();
	},

	onFailure: function(){
		this.fireEvent('complete').fireEvent('failure', this.xhr);
	},

	setHeader: function(name, value){
		this.headers.set(name, value);
		return this;
	},

	getHeader: function(name){
		return $try(function(){
			return this.xhr.getResponseHeader(name);
		}.bind(this));
	},

	check: function(caller){
		if (!this.running) return true;
		switch (this.options.link){
			case 'cancel': this.cancel(); return true;
			case 'chain': this.chain(caller.bind(this, Array.slice(arguments, 1))); return false;
		}
		return false;
	},

	send: function(options){
		if (!this.check(arguments.callee, options)) return this;
		this.running = true;

		var type = $type(options);
		if (type == 'string' || type == 'element') options = {data: options};

		var old = this.options;
		options = $extend({data: old.data, url: old.url, method: old.method}, options);
		var data = options.data, url = options.url, method = options.method;

		switch ($type(data)){
			case 'element': data = $(data).toQueryString(); break;
			case 'object': case 'hash': data = Hash.toQueryString(data);
		}

		if (this.options.format){
			var format = 'format=' + this.options.format;
			data = (data) ? format + '&' + data : format;
		}

		if (this.options.emulation && ['put', 'delete'].contains(method)){
			var _method = '_method=' + method;
			data = (data) ? _method + '&' + data : _method;
			method = 'post';
		}

		if (this.options.urlEncoded && method == 'post'){
			var encoding = (this.options.encoding) ? '; charset=' + this.options.encoding : '';
			this.headers.set('Content-type', 'application/x-www-form-urlencoded' + encoding);
		}

		if (data && method == 'get'){
			url = url + (url.contains('?') ? '&' : '?') + data;
			data = null;
		}

		this.xhr.open(method.toUpperCase(), url, this.options.async);

		this.xhr.onreadystatechange = this.onStateChange.bind(this);

		this.headers.each(function(value, key){
			try {
				this.xhr.setRequestHeader(key, value);
			} catch (e){
				this.fireEvent('exception', [key, value]);
			}
		}, this);

		this.fireEvent('request');
		this.xhr.send(data);
		if (!this.options.async) this.onStateChange();
		return this;
	},

	cancel: function(){
		if (!this.running) return this;
		this.running = false;
		this.xhr.abort();
		this.xhr.onreadystatechange = $empty;
		this.xhr = new Browser.Request();
		this.fireEvent('cancel');
		return this;
	}

});

(function(){

var methods = {};
['get', 'post', 'put', 'delete', 'GET', 'POST', 'PUT', 'DELETE'].each(function(method){
	methods[method] = function(){
		var params = Array.link(arguments, {url: String.type, data: $defined});
		return this.send($extend(params, {method: method.toLowerCase()}));
	};
});

Request.implement(methods);

})();

Element.Properties.send = {

	set: function(options){
		var send = this.retrieve('send');
		if (send) send.cancel();
		return this.eliminate('send').store('send:options', $extend({
			data: this, link: 'cancel', method: this.get('method') || 'post', url: this.get('action')
		}, options));
	},

	get: function(options){
		if (options || !this.retrieve('send')){
			if (options || !this.retrieve('send:options')) this.set('send', options);
			this.store('send', new Request(this.retrieve('send:options')));
		}
		return this.retrieve('send');
	}

};

Element.implement({

	send: function(url){
		var sender = this.get('send');
		sender.send({data: this, url: url || sender.options.url});
		return this;
	}

});


/*
Script: Request.HTML.js
	Extends the basic Request Class with additional methods for interacting with HTML responses.

License:
	MIT-style license.
*/

Request.HTML = new Class({

	Extends: Request,

	options: {
		update: false,
		evalScripts: true,
		filter: false
	},

	processHTML: function(text){
		var match = text.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
		text = (match) ? match[1] : text;

		var container = new Element('div');

		return $try(function(){
			var root = '<root>' + text + '</root>', doc;
			if (Browser.Engine.trident){
				doc = new ActiveXObject('Microsoft.XMLDOM');
				doc.async = false;
				doc.loadXML(root);
			} else {
				doc = new DOMParser().parseFromString(root, 'text/xml');
			}
			root = doc.getElementsByTagName('root')[0];
			for (var i = 0, k = root.childNodes.length; i < k; i++){
				var child = Element.clone(root.childNodes[i], true, true);
				if (child) container.grab(child);
			}
			return container;
		}) || container.set('html', text);
	},

	success: function(text){
		var options = this.options, response = this.response;

		response.html = text.stripScripts(function(script){
			response.javascript = script;
		});

		var temp = this.processHTML(response.html);

		response.tree = temp.childNodes;
		response.elements = temp.getElements('*');

		if (options.filter) response.tree = response.elements.filter(options.filter);
		if (options.update) $(options.update).empty().set('html', response.html);
		if (options.evalScripts) $exec(response.javascript);

		this.onSuccess(response.tree, response.elements, response.html, response.javascript);
	}

});

Element.Properties.load = {

	set: function(options){
		var load = this.retrieve('load');
		if (load) load.cancel();
		return this.eliminate('load').store('load:options', $extend({data: this, link: 'cancel', update: this, method: 'get'}, options));
	},

	get: function(options){
		if (options || ! this.retrieve('load')){
			if (options || !this.retrieve('load:options')) this.set('load', options);
			this.store('load', new Request.HTML(this.retrieve('load:options')));
		}
		return this.retrieve('load');
	}

};

Element.implement({

	load: function(){
		this.get('load').send(Array.link(arguments, {data: Object.type, url: String.type}));
		return this;
	}

});


/*
Script: Request.JSON.js
	Extends the basic Request Class with additional methods for sending and receiving JSON data.

License:
	MIT-style license.
*/

Request.JSON = new Class({

	Extends: Request,

	options: {
		secure: true
	},

	initialize: function(options){
		this.parent(options);
		this.headers.extend({'Accept': 'application/json', 'X-Request': 'JSON'});
	},

	success: function(text){
		this.response.json = JSON.decode(text, this.options.secure);
		this.onSuccess(this.response.json, text);
	}

});



//MooTools More, <http://mootools.net/more>. Copyright (c) 2006-2008 Valerio Proietti, <http://mad4milk.net>, MIT Style License.

/*
Script: Fx.Slide.js
	Effect to slide an element in and out of view.

License:
	MIT-style license.
*/

Fx.Slide = new Class({

	Extends: Fx,

	options: {
		mode: 'vertical'
	},

	initialize: function(element, options){
		this.addEvent('complete', function(){
			this.open = (this.wrapper['offset' + this.layout.capitalize()] != 0);
			if (this.open && Browser.Engine.webkit419) this.element.dispose().inject(this.wrapper);
		}, true);
		this.element = this.subject = $(element);
		this.parent(options);
		var wrapper = this.element.retrieve('wrapper');
		this.wrapper = wrapper || new Element('div', {
			styles: $extend(this.element.getStyles('margin', 'position'), {'overflow': 'hidden'})
		}).wraps(this.element);
		this.element.store('wrapper', this.wrapper).setStyle('margin', 0);
		this.now = [];
		this.open = true;
	},

	vertical: function(){
		this.margin = 'margin-top';
		this.layout = 'height';
		this.offset = this.element.offsetHeight;
	},

	horizontal: function(){
		this.margin = 'margin-left';
		this.layout = 'width';
		this.offset = this.element.offsetWidth;
	},

	set: function(now){
		this.element.setStyle(this.margin, now[0]);
		this.wrapper.setStyle(this.layout, now[1]);
		return this;
	},

	compute: function(from, to, delta){
		var now = [];
		var x = 2;
		x.times(function(i){
			now[i] = Fx.compute(from[i], to[i], delta);
		});
		return now;
	},

	start: function(how, mode){
		if (!this.check(arguments.callee, how, mode)) return this;
		this[mode || this.options.mode]();
		var margin = this.element.getStyle(this.margin).toInt();
		var layout = this.wrapper.getStyle(this.layout).toInt();
		var caseIn = [[margin, layout], [0, this.offset]];
		var caseOut = [[margin, layout], [-this.offset, 0]];
		var start;
		switch (how){
			case 'in': start = caseIn; break;
			case 'out': start = caseOut; break;
			case 'toggle': start = (this.wrapper['offset' + this.layout.capitalize()] == 0) ? caseIn : caseOut;
		}
		return this.parent(start[0], start[1]);
	},

	slideIn: function(mode){
		return this.start('in', mode);
	},

	slideOut: function(mode){
		return this.start('out', mode);
	},

	hide: function(mode){
		this[mode || this.options.mode]();
		this.open = false;
		return this.set([-this.offset, 0]);
	},

	show: function(mode){
		this[mode || this.options.mode]();
		this.open = true;
		return this.set([0, this.offset]);
	},

	toggle: function(mode){
		return this.start('toggle', mode);
	}

});

Element.Properties.slide = {

	set: function(options){
		var slide = this.retrieve('slide');
		if (slide) slide.cancel();
		return this.eliminate('slide').store('slide:options', $extend({link: 'cancel'}, options));
	},
	
	get: function(options){
		if (options || !this.retrieve('slide')){
			if (options || !this.retrieve('slide:options')) this.set('slide', options);
			this.store('slide', new Fx.Slide(this, this.retrieve('slide:options')));
		}
		return this.retrieve('slide');
	}

};

Element.implement({

	slide: function(how, mode){
		how = how || 'toggle';
		var slide = this.get('slide'), toggle;
		switch (how){
			case 'hide': slide.hide(mode); break;
			case 'show': slide.show(mode); break;
			case 'toggle':
				var flag = this.retrieve('slide:flag', slide.open);
				slide[(flag) ? 'slideOut' : 'slideIn'](mode);
				this.store('slide:flag', !flag);
				toggle = true;
			break;
			default: slide.start(how, mode);
		}
		if (!toggle) this.eliminate('slide:flag');
		return this;
	}

});


/*
Script: Fx.Scroll.js
	Effect to smoothly scroll any element, including the window.

License:
	MIT-style license.
*/

Fx.Scroll = new Class({

	Extends: Fx,

	options: {
		offset: {'x': 0, 'y': 0},
		wheelStops: true
	},

	initialize: function(element, options){
		this.element = this.subject = $(element);
		this.parent(options);
		var cancel = this.cancel.bind(this, false);

		if ($type(this.element) != 'element') this.element = $(this.element.getDocument().body);

		var stopper = this.element;

		if (this.options.wheelStops){
			this.addEvent('start', function(){
				stopper.addEvent('mousewheel', cancel);
			}, true);
			this.addEvent('complete', function(){
				stopper.removeEvent('mousewheel', cancel);
			}, true);
		}
	},

	set: function(){
		var now = Array.flatten(arguments);
		this.element.scrollTo(now[0], now[1]);
	},

	compute: function(from, to, delta){
		var now = [];
		var x = 2;
		x.times(function(i){
			now.push(Fx.compute(from[i], to[i], delta));
		});
		return now;
	},

	start: function(x, y){
		if (!this.check(arguments.callee, x, y)) return this;
		var offsetSize = this.element.getSize(), scrollSize = this.element.getScrollSize();
		var scroll = this.element.getScroll(), values = {x: x, y: y};
		for (var z in values){
			var max = scrollSize[z] - offsetSize[z];
			if ($chk(values[z])) values[z] = ($type(values[z]) == 'number') ? values[z].limit(0, max) : max;
			else values[z] = scroll[z];
			values[z] += this.options.offset[z];
		}
		return this.parent([scroll.x, scroll.y], [values.x, values.y]);
	},

	toTop: function(){
		return this.start(false, 0);
	},

	toLeft: function(){
		return this.start(0, false);
	},

	toRight: function(){
		return this.start('right', false);
	},

	toBottom: function(){
		return this.start(false, 'bottom');
	},

	toElement: function(el){
		var position = $(el).getPosition(this.element);
		return this.start(position.x, position.y);
	}

});


/*
Script: Fx.Elements.js
	Effect to change any number of CSS properties of any number of Elements.

License:
	MIT-style license.
*/

Fx.Elements = new Class({

	Extends: Fx.CSS,

	initialize: function(elements, options){
		this.elements = this.subject = $$(elements);
		this.parent(options);
	},

	compute: function(from, to, delta){
		var now = {};
		for (var i in from){
			var iFrom = from[i], iTo = to[i], iNow = now[i] = {};
			for (var p in iFrom) iNow[p] = this.parent(iFrom[p], iTo[p], delta);
		}
		return now;
	},

	set: function(now){
		for (var i in now){
			var iNow = now[i];
			for (var p in iNow) this.render(this.elements[i], p, iNow[p], this.options.unit);
		}
		return this;
	},

	start: function(obj){
		if (!this.check(arguments.callee, obj)) return this;
		var from = {}, to = {};
		for (var i in obj){
			var iProps = obj[i], iFrom = from[i] = {}, iTo = to[i] = {};
			for (var p in iProps){
				var parsed = this.prepare(this.elements[i], p, iProps[p]);
				iFrom[p] = parsed.from;
				iTo[p] = parsed.to;
			}
		}
		return this.parent(from, to);
	}

});

/*
Script: Drag.js
  The base Drag Class. Can be used to drag and resize Elements using mouse events.
 
License:
  MIT-style license.
*/
 
var Drag = new Class({
 
  Implements: [Events, Options],
 
  options: {/*
    onBeforeStart: $empty,
    onStart: $empty,
    onDrag: $empty,
    onCancel: $empty,
    onComplete: $empty,*/
    snap: 6,
    unit: 'px',
    grid: false,
    style: true,
    limit: false,
    handle: false,
    invert: false,
    preventDefault: false,
    modifiers: {x: 'left', y: 'top'}
  },
 
  initialize: function(){
    var params = Array.link(arguments, {'options': Object.type, 'element': $defined});
    this.element = $(params.element);
    this.document = this.element.getDocument();
    this.setOptions(params.options || {});
    var htype = $type(this.options.handle);
    this.handles = (htype == 'array' || htype == 'collection') ? $$(this.options.handle) : $(this.options.handle) || this.element;
    this.mouse = {'now': {}, 'pos': {}};
    this.value = {'start': {}, 'now': {}};
 
    this.selection = (Browser.Engine.trident) ? 'selectstart' : 'mousedown';
 
    this.bound = {
      start: this.start.bind(this),
      check: this.check.bind(this),
      drag: this.drag.bind(this),
      stop: this.stop.bind(this),
      cancel: this.cancel.bind(this),
      eventStop: $lambda(false)
    };
    this.attach();
  },
 
  attach: function(){
    this.handles.addEvent('mousedown', this.bound.start);
    return this;
  },
 
  detach: function(){
    this.handles.removeEvent('mousedown', this.bound.start);
    return this;
  },
 
  start: function(event){
    if (this.options.preventDefault) event.preventDefault();
    this.mouse.start = event.page;
    this.fireEvent('beforeStart', this.element);
    var limit = this.options.limit;
    this.limit = {'x': [], 'y': []};
    for (var z in this.options.modifiers){
      if (!this.options.modifiers[z]) continue;
      if (this.options.style) this.value.now[z] = this.element.getStyle(this.options.modifiers[z]).toInt();
      else this.value.now[z] = this.element[this.options.modifiers[z]];
      if (this.options.invert) this.value.now[z] *= -1;
      this.mouse.pos[z] = event.page[z] - this.value.now[z];
      if (limit && limit[z]){
        for (var i = 2; i--; i){
          if ($chk(limit[z][i])) this.limit[z][i] = $lambda(limit[z][i])();
        }
      }
    }
    if ($type(this.options.grid) == 'number') this.options.grid = {'x': this.options.grid, 'y': this.options.grid};
    this.document.addEvents({mousemove: this.bound.check, mouseup: this.bound.cancel});
    this.document.addEvent(this.selection, this.bound.eventStop);
  },
 
  check: function(event){
    if (this.options.preventDefault) event.preventDefault();
    var distance = Math.round(Math.sqrt(Math.pow(event.page.x - this.mouse.start.x, 2) + Math.pow(event.page.y - this.mouse.start.y, 2)));
    if (distance > this.options.snap){
      this.cancel();
      this.document.addEvents({
        mousemove: this.bound.drag,
        mouseup: this.bound.stop
      });
      this.fireEvent('start', this.element).fireEvent('snap', this.element);
    }
	event.preventDefault();
  },
 
  drag: function(event){
    if (this.options.preventDefault) event.preventDefault();
    this.mouse.now = event.page;
    for (var z in this.options.modifiers){
      if (!this.options.modifiers[z]) continue;
      this.value.now[z] = this.mouse.now[z] - this.mouse.pos[z];
      if (this.options.invert) this.value.now[z] *= -1;
      if (this.options.limit && this.limit[z]){
        if ($chk(this.limit[z][1]) && (this.value.now[z] > this.limit[z][1])){
          this.value.now[z] = this.limit[z][1];
        } else if ($chk(this.limit[z][0]) && (this.value.now[z] < this.limit[z][0])){
          this.value.now[z] = this.limit[z][0];
        }
      }
      if (this.options.grid[z]) this.value.now[z] -= (this.value.now[z] % this.options.grid[z]);
      if (this.options.style) this.element.setStyle(this.options.modifiers[z], this.value.now[z] + this.options.unit);
      else this.element[this.options.modifiers[z]] = this.value.now[z];
    }
    this.fireEvent('drag', this.element);
	event.preventDefault();
  },
 
  cancel: function(event){
    this.document.removeEvent('mousemove', this.bound.check);
    this.document.removeEvent('mouseup', this.bound.cancel);
    if (event){
      this.document.removeEvent(this.selection, this.bound.eventStop);
      this.fireEvent('cancel', this.element);
    }
  },
 
  stop: function(event){
    this.document.removeEvent(this.selection, this.bound.eventStop);
    this.document.removeEvent('mousemove', this.bound.drag);
    this.document.removeEvent('mouseup', this.bound.stop);
    if (event) this.fireEvent('complete', this.element);
  }
 
});
 
Element.implement({
 
  makeResizable: function(options){
    return new Drag(this, $merge({modifiers: {'x': 'width', 'y': 'height'}}, options));
  }
 
});

/*
Script: Drag.Move.js
  A Drag extension that provides support for the constraining of draggables to containers and droppables.
 
License:
  MIT-style license.
*/
 
Drag.Move = new Class({
 
  Extends: Drag,
 
  options: {/*
    onEnter: $empty,
    onLeave: $empty,
    onDrop: $empty,*/
    droppables: [],
    container: false
  },
 
  initialize: function(element, options){
    this.parent(element, options);
    this.droppables = $$(this.options.droppables);
    this.container = $(this.options.container);
    if (this.container && $type(this.container) != 'element') this.container = $(this.container.getDocument().body);
    element = this.element;
 
    var current = element.getStyle('position');
    var position = (current != 'static') ? current : 'absolute';
    if (element.getStyle('left') == 'auto' || element.getStyle('top') == 'auto') element.position(element.getPosition(element.offsetParent));
    element.setStyle('position', position);
 
    this.addEvent('start', this.checkDroppables, true);
 
    this.overed = null;
  },
 
  start: function(event){
    if (this.container){
      var el = this.element, cont = this.container, ccoo = cont.getCoordinates(el.offsetParent), cps = {}, ems = {};
 
      ['top', 'right', 'bottom', 'left'].each(function(pad){
        cps[pad] = cont.getStyle('padding-' + pad).toInt();
        ems[pad] = el.getStyle('margin-' + pad).toInt();
      }, this);
 
      var width = el.offsetWidth + ems.left + ems.right, height = el.offsetHeight + ems.top + ems.bottom;
      var x = [ccoo.left + cps.left, ccoo.right - cps.right - width];
      var y = [ccoo.top + cps.top, ccoo.bottom - cps.bottom - height];
 
      this.options.limit = {x: x, y: y};
    }
    this.parent(event);
  },
 
  checkAgainst: function(el){
    el = el.getCoordinates();
    var now = this.mouse.now;
    return (now.x > el.left && now.x < el.right && now.y < el.bottom && now.y > el.top);
  },
 
  checkDroppables: function(){
    var overed = this.droppables.filter(this.checkAgainst, this).getLast();
    if (this.overed != overed){
      if (this.overed) this.fireEvent('leave', [this.element, this.overed]);
      if (overed) this.fireEvent('enter', [this.element, overed]);
      this.overed = overed;
    }
  },
 
  drag: function(event){
    this.parent(event);
    if (this.droppables.length) this.checkDroppables();
  },
 
  stop: function(event){
    this.checkDroppables();
    this.fireEvent('drop', [this.element, this.overed]);
    this.overed = null;
    return this.parent(event);
  }
 
});
 
Element.implement({
 
  makeDraggable: function(options){
    return new Drag.Move(this, options);
  }
 
});


/*
Script: Hash.Cookie.js
	Class for creating, reading, and deleting Cookies in JSON format.

License:
	MIT-style license.
*/

Hash.Cookie = new Class({

	Extends: Cookie,

	options: {
		autoSave: true
	},

	initialize: function(name, options){
		this.parent(name, options);
		this.load();
	},

	save: function(){
		var value = JSON.encode(this.hash);
		if (!value || value.length > 4096) return false; //cookie would be truncated!
		if (value == '{}') this.dispose();
		else this.write(value);
		return true;
	},

	load: function(){
		this.hash = new Hash(JSON.decode(this.read(), true));
		return this;
	}

});

Hash.Cookie.implement((function(){
	
	var methods = {};
	
	Hash.each(Hash.prototype, function(method, name){
		methods[name] = function(){
			var value = method.apply(this.hash, arguments);
			if (this.options.autoSave) this.save();
			return value;
		};
	});
	
	return methods;
	
})());

/*
Script: Color.js
	Class for creating and manipulating colors in JavaScript. Supports HSB -> RGB Conversions and vice versa.

License:
	MIT-style license.
*/

var Color = new Native({
  
	initialize: function(color, type){
		if (arguments.length >= 3){
			type = "rgb"; color = Array.slice(arguments, 0, 3);
		} else if (typeof color == 'string'){
			if (color.match(/rgb/)) color = color.rgbToHex().hexToRgb(true);
			else if (color.match(/hsb/)) color = color.hsbToRgb();
			else color = color.hexToRgb(true);
		}
		type = type || 'rgb';
		switch (type){
			case 'hsb':
				var old = color;
				color = color.hsbToRgb();
				color.hsb = old;
			break;
			case 'hex': color = color.hexToRgb(true); break;
		}
		color.rgb = color.slice(0, 3);
		color.hsb = color.hsb || color.rgbToHsb();
		color.hex = color.rgbToHex();
		return $extend(color, this);
	}

});

Color.implement({

	mix: function(){
		var colors = Array.slice(arguments);
		var alpha = ($type(colors.getLast()) == 'number') ? colors.pop() : 50;
		var rgb = this.slice();
		colors.each(function(color){
			color = new Color(color);
			for (var i = 0; i < 3; i++) rgb[i] = Math.round((rgb[i] / 100 * (100 - alpha)) + (color[i] / 100 * alpha));
		});
		return new Color(rgb, 'rgb');
	},

	invert: function(){
		return new Color(this.map(function(value){
			return 255 - value;
		}));
	},

	setHue: function(value){
		return new Color([value, this.hsb[1], this.hsb[2]], 'hsb');
	},

	setSaturation: function(percent){
		return new Color([this.hsb[0], percent, this.hsb[2]], 'hsb');
	},

	setBrightness: function(percent){
		return new Color([this.hsb[0], this.hsb[1], percent], 'hsb');
	}

});

function $RGB(r, g, b){
	return new Color([r, g, b], 'rgb');
};

function $HSB(h, s, b){
	return new Color([h, s, b], 'hsb');
};

function $HEX(hex){
	return new Color(hex, 'hex');
};

Array.implement({

	rgbToHsb: function(){
		var red = this[0], green = this[1], blue = this[2];
		var hue, saturation, brightness;
		var max = Math.max(red, green, blue), min = Math.min(red, green, blue);
		var delta = max - min;
		brightness = max / 255;
		saturation = (max != 0) ? delta / max : 0;
		if (saturation == 0){
			hue = 0;
		} else {
			var rr = (max - red) / delta;
			var gr = (max - green) / delta;
			var br = (max - blue) / delta;
			if (red == max) hue = br - gr;
			else if (green == max) hue = 2 + rr - br;
			else hue = 4 + gr - rr;
			hue /= 6;
			if (hue < 0) hue++;
		}
		return [Math.round(hue * 360), Math.round(saturation * 100), Math.round(brightness * 100)];
	},

	hsbToRgb: function(){
		var br = Math.round(this[2] / 100 * 255);
		if (this[1] == 0){
			return [br, br, br];
		} else {
			var hue = this[0] % 360;
			var f = hue % 60;
			var p = Math.round((this[2] * (100 - this[1])) / 10000 * 255);
			var q = Math.round((this[2] * (6000 - this[1] * f)) / 600000 * 255);
			var t = Math.round((this[2] * (6000 - this[1] * (60 - f))) / 600000 * 255);
			switch (Math.floor(hue / 60)){
				case 0: return [br, t, p];
				case 1: return [q, br, p];
				case 2: return [p, br, t];
				case 3: return [p, q, br];
				case 4: return [t, p, br];
				case 5: return [br, p, q];
			}
		}
		return false;
	}

});

String.implement({

	rgbToHsb: function(){
		var rgb = this.match(/\d{1,3}/g);
		return (rgb) ? hsb.rgbToHsb() : null;
	},
	
	hsbToRgb: function(){
		var hsb = this.match(/\d{1,3}/g);
		return (hsb) ? hsb.hsbToRgb() : null;
	}

});


/*
Script: Group.js
	Class for monitoring collections of events

License:
	MIT-style license.
*/

var Group = new Class({

	initialize: function(){
		this.instances = Array.flatten(arguments);
		this.events = {};
		this.checker = {};
	},

	addEvent: function(type, fn){
		this.checker[type] = this.checker[type] || {};
		this.events[type] = this.events[type] || [];
		if (this.events[type].contains(fn)) return false;
		else this.events[type].push(fn);
		this.instances.each(function(instance, i){
			instance.addEvent(type, this.check.bind(this, [type, instance, i]));
		}, this);
		return this;
	},

	check: function(type, instance, i){
		this.checker[type][i] = true;
		var every = this.instances.every(function(current, j){
			return this.checker[type][j] || false;
		}, this);
		if (!every) return;
		this.checker[type] = {};
		this.events[type].each(function(event){
			event.call(this, this.instances, instance);
		}, this);
	}

});


//MooTools More, <http://mootools.net/more>. Copyright (c) 2006-2009 Aaron Newton <http://clientcide.com/>, Valerio Proietti <http://mad4milk.net> & the MooTools team <http://mootools.net/developers>, MIT Style License.

/*
---

script: More.js

description: MooTools More

license: MIT-style license

authors:
- Guillermo Rauch
- Thomas Aylott
- Scott Kyle

requires:
- core:1.2.4/MooTools

provides: [MooTools.More]

...
*/

MooTools.More = {
	'version': '1.2.4.4',
	'build': '6f6057dc645fdb7547689183b2311063bd653ddf'
};

/*
---

script: Assets.js

description: Provides methods to dynamically load JavaScript, CSS, and Image files into the document.

license: MIT-style license

authors:
- Valerio Proietti

requires:
- core:1.2.4/Element.Event
- /MooTools.More

provides: [Assets]

...
*/

var Asset = {

	javascript: function(source, properties){
		properties = $extend({
			onload: $empty,
			document: document,
			check: $lambda(true)
		}, properties);
		
		if (properties.onLoad) properties.onload = properties.onLoad;
		
		var script = new Element('script', {src: source, type: 'text/javascript'});

		var load = properties.onload.bind(script), 
			check = properties.check, 
			doc = properties.document;
		delete properties.onload;
		delete properties.check;
		delete properties.document;

		script.addEvents({
			load: load,
			readystatechange: function(){
				if (['loaded', 'complete'].contains(this.readyState)) load();
			}
		}).set(properties);

		if (Browser.Engine.webkit419) var checker = (function(){
			if (!$try(check)) return;
			$clear(checker);
			load();
		}).periodical(50);

		return script.inject(doc.head);
	},

	css: function(source, properties){
		return new Element('link', $merge({
			rel: 'stylesheet',
			media: 'screen',
			type: 'text/css',
			href: source
		}, properties)).inject(document.head);
	},

	image: function(source, properties){
		properties = $merge({
			'onload': $empty,
			'onabort': $empty,
			'onerror': $empty
		}, properties);
		var image = new Image();
		var element = $(image) || new Element('img');
		['load', 'abort', 'error'].each(function(name){
			var type = 'on' + name;
			var event = properties[type];
			delete properties[type];
			image[type] = function(){
				if (!image) return;
				if (!element.parentNode){
					element.width = image.width;
					element.height = image.height;
				}
				image = image.onload = image.onabort = image.onerror = null;
				event.delay(1, element, element);
				element.fireEvent(name, element, 1);
			};
		});
		image.src = element.src = source;
		if (image && image.complete) image.onload.delay(1);
		return element.setProperties(properties);
	},

	images: function(sources, options){
		options = $merge({
			onComplete: $empty,
			onProgress: $empty,
			onError: $empty,
			properties: {}
		}, options);
		sources = $splat(sources);
		var images = [];
		var counter = 0;
		return new Elements(sources.map(function(source){
			return Asset.image(source, $extend(options.properties, {
				onload: function(){
					options.onProgress.call(this, counter, sources.indexOf(source));
					counter++;
					if (counter == sources.length) options.onComplete();
				},
				onerror: function(){
					options.onError.call(this, counter, sources.indexOf(source));
					counter++;
					if (counter == sources.length) options.onComplete();
				}
			}));
		}));
	}

};




/*
Script: Sortables.js
	Class for creating a drag and drop sorting interface for lists of items.

License:
	MIT-style license.
*/

var Sortables = new Class({

	Implements: [Events, Options],

	options: {/*
		onSort: $empty,
		onStart: $empty,
		onComplete: $empty,*/
		snap: 4,
		opacity: 1,
		clone: false,
		revert: false,
		handle: false,
		constrain: false
	},

	initialize: function(lists, options){
		this.setOptions(options);
		this.elements = [];
		this.lists = [];
		this.idle = true;
		
		this.addLists($$($(lists) || lists));
		if (!this.options.clone) this.options.revert = false;
		if (this.options.revert) this.effect = new Fx.Morph(null, $merge({duration: 250, link: 'cancel'}, this.options.revert));
	},

	attach: function(){
		this.addLists(this.lists);
		return this;
	},

	detach: function(){
		this.lists = this.removeLists(this.lists);
		return this;
	},

	addItems: function(){
		Array.flatten(arguments).each(function(element){
			this.elements.push(element);
			var start = element.retrieve('sortables:start', this.start.bindWithEvent(this, element));
			(this.options.handle ? element.getElement(this.options.handle) || element : element).addEvent('mousedown', start);
		}, this);
		return this;
	},

	addLists: function(){
		Array.flatten(arguments).each(function(list){
			this.lists.push(list);
			this.addItems(list.getChildren());
		}, this);
		return this;
	},

	removeItems: function(){
		var elements = [];
		Array.flatten(arguments).each(function(element){
			elements.push(element);
			this.elements.erase(element);
			var start = element.retrieve('sortables:start');
			(this.options.handle ? element.getElement(this.options.handle) || element : element).removeEvent('mousedown', start);
		}, this);
		return $$(elements);
	},

	removeLists: function(){
		var lists = [];
		Array.flatten(arguments).each(function(list){
			lists.push(list);
			this.lists.erase(list);
			this.removeItems(list.getChildren());
		}, this);
		return $$(lists);
	},

	getClone: function(event, element){
		if (!this.options.clone) return new Element('div').inject(document.body);
		if ($type(this.options.clone) == 'function') return this.options.clone.call(this, event, element, this.list);
		return element.clone(true).setStyles({
			'margin': '0px',
			'position': 'absolute',
			'visibility': 'hidden',
			'width': element.getStyle('width')
		}).inject(this.list).position(element.getPosition(element.getOffsetParent()));
	},

	getDroppables: function(){
		var droppables = this.list.getChildren();
		if (!this.options.constrain) droppables = this.lists.concat(droppables).erase(this.list);
		return droppables.erase(this.clone).erase(this.element);
	},

	insert: function(dragging, element){
		var where = 'inside';
		if (this.lists.contains(element)){
			this.list = element;
			this.drag.droppables = this.getDroppables();
		} else {
			where = this.element.getAllPrevious().contains(element) ? 'before' : 'after';
		}
		this.element.inject(element, where);
		this.fireEvent('sort', [this.element, this.clone]);
	},

	start: function(event, element){
		if (!this.idle) return;
		this.idle = false;
		this.element = element;
		this.opacity = element.get('opacity');
		this.list = element.getParent();
		this.clone = this.getClone(event, element);
		
		this.drag = new Drag.Move(this.clone, {
			snap: this.options.snap,
			container: this.options.constrain && this.element.getParent(),
			droppables: this.getDroppables(),
			onSnap: function(){
				event.stop();
				this.clone.setStyle('visibility', 'visible');
				this.element.set('opacity', this.options.opacity || 0);
				this.fireEvent('start', [this.element, this.clone]);
			}.bind(this),
			onEnter: this.insert.bind(this),
			onCancel: this.reset.bind(this),
			onComplete: this.end.bind(this)
		});
		
		this.clone.inject(this.element, 'before');
		this.drag.start(event);
	},

	end: function(){
		this.drag.detach();
		this.element.set('opacity', this.opacity);
		if (this.effect){
			var dim = this.element.getStyles('width', 'height');
			var pos = this.clone.computePosition(this.element.getPosition(this.clone.offsetParent));
			this.effect.element = this.clone;
			this.effect.start({
				top: pos.top,
				left: pos.left,
				width: dim.width,
				height: dim.height,
				opacity: 0.25
			}).chain(this.reset.bind(this));
		} else {
			this.reset();
		}
	},

	reset: function(){
		this.idle = true;
		this.clone.destroy();
		this.fireEvent('complete', this.element);
	},

	serialize: function(){
		var params = Array.link(arguments, {modifier: Function.type, index: $defined});
		var serial = this.lists.map(function(list){
			return list.getChildren().map(params.modifier || function(element){
				return element.get('id');
			}, this);
		}, this);
		
		var index = params.index;
		if (this.lists.length == 1) index = 0;
		return $chk(index) && index >= 0 && index < this.lists.length ? serial[index] : serial;
	}

});

/*
Script: Tips.js
	Class for creating nice tips that follow the mouse cursor when hovering an element.

License:
	MIT-style license.
*/

var Tips = new Class({

	Implements: [Events, Options],

	options: {
		onShow: function(tip){
			tip.setStyle('visibility', 'visible');
		},
		onHide: function(tip){
			tip.setStyle('visibility', 'hidden');
		},
		showDelay: 100,
		hideDelay: 100,
		className: null,
		offsets: {x: 16, y: 16},
		fixed: false
	},

	initialize: function(){
		var params = Array.link(arguments, {options: Object.type, elements: $defined});
		this.setOptions(params.options || null);
		
		this.tip = new Element('div').inject(document.body);
		
		if (this.options.className) this.tip.addClass(this.options.className);
		
		var top = new Element('div', {'class': 'tip-top'}).inject(this.tip);
		this.container = new Element('div', {'class': 'tip'}).inject(this.tip);
		var bottom = new Element('div', {'class': 'tip-bottom'}).inject(this.tip);

		this.tip.setStyles({position: 'absolute', top: 0, left: 0, visibility: 'hidden'});
		
		if (params.elements) this.attach(params.elements);
	},
	
	attach: function(elements){
		$$(elements).each(function(element){
			var title = element.retrieve('tip:title', element.get('title'));
			var text = element.retrieve('tip:text', element.get('rel') || element.get('href'));
			var enter = element.retrieve('tip:enter', this.elementEnter.bindWithEvent(this, element));
			var leave = element.retrieve('tip:leave', this.elementLeave.bindWithEvent(this, element));
			element.addEvents({mouseenter: enter, mouseleave: leave});
			if (!this.options.fixed){
				var move = element.retrieve('tip:move', this.elementMove.bindWithEvent(this, element));
				element.addEvent('mousemove', move);
			}
			element.store('tip:native', element.get('title'));
			element.erase('title');
		}, this);
		return this;
	},
	
	detach: function(elements){
		$$(elements).each(function(element){
			element.removeEvent('mouseenter', element.retrieve('tip:enter') || $empty);
			element.removeEvent('mouseleave', element.retrieve('tip:leave') || $empty);
			element.removeEvent('mousemove', element.retrieve('tip:move') || $empty);
			element.eliminate('tip:enter').eliminate('tip:leave').eliminate('tip:move');
			var original = element.retrieve('tip:native');
			if (original) element.set('title', original);
		});
		return this;
	},
	
	elementEnter: function(event, element){
		
		$A(this.container.childNodes).each(Element.dispose);
		
		var title = element.retrieve('tip:title');
		
		if (title){
			this.titleElement = new Element('div', {'class': 'tip-title'}).inject(this.container);
			this.fill(this.titleElement, title);
		}
		
		var text = element.retrieve('tip:text');
		if (text){
			this.textElement = new Element('div', {'class': 'tip-text'}).inject(this.container);
			this.fill(this.textElement, text);
		}
		
		this.timer = $clear(this.timer);
		this.timer = this.show.delay(this.options.showDelay, this);

		this.position((!this.options.fixed) ? event : {page: element.getPosition()});
	},
	
	elementLeave: function(event){
		$clear(this.timer);
		this.timer = this.hide.delay(this.options.hideDelay, this);
	},
	
	elementMove: function(event){
		this.position(event);
	},
	
	position: function(event){
		var size = window.getSize(), scroll = window.getScroll();
		var tip = {x: this.tip.offsetWidth, y: this.tip.offsetHeight};
		var props = {x: 'left', y: 'top'};
		for (var z in props){
			var pos = event.page[z] + this.options.offsets[z];
			if ((pos + tip[z] - scroll[z]) > size[z]) pos = event.page[z] - this.options.offsets[z] - tip[z];
			this.tip.setStyle(props[z], pos);
		}
	},
	
	fill: function(element, contents){
		(typeof contents == 'string') ? element.set('html', contents) : element.adopt(contents);
	},

	show: function(){
		this.fireEvent('show', this.tip);
	},

	hide: function(){
		this.fireEvent('hide', this.tip);
	}

});

/*
Script: SmoothScroll.js
	Class for creating a smooth scrolling effect to all internal links on the page.

License:
	MIT-style license.
*/

var SmoothScroll = new Class({

	Extends: Fx.Scroll,

	initialize: function(options, context){
		context = context || document;
		var doc = context.getDocument(), win = context.getWindow();
		this.parent(doc, options);
		this.links = (this.options.links) ? $$(this.options.links) : $$(doc.links);
		var location = win.location.href.match(/^[^#]*/)[0] + '#';
		this.links.each(function(link){
			if (link.href.indexOf(location) != 0) return;
			var anchor = link.href.substr(location.length);
			if (anchor && $(anchor)) this.useLink(link, anchor);
		}, this);
		if (!Browser.Engine.webkit419) this.addEvent('complete', function(){
			win.location.hash = this.anchor;
		}, true);
	},

	useLink: function(link, anchor){
		link.addEvent('click', function(event){
			this.anchor = anchor;
			this.toElement(anchor);
			event.stop();
		}.bind(this));
	}

});

/*
Script: Slider.js
	Class for creating horizontal and vertical slider controls.

License:
	MIT-style license.
*/

var Slider = new Class({

	Implements: [Events, Options],

	options: {/*
		onChange: $empty,
		onComplete: $empty,*/
		onTick: function(position){
			if(this.options.snap) position = this.toPosition(this.step);
			this.knob.setStyle(this.property, position);
		},
		snap: false,
		offset: 0,
		range: false,
		wheel: false,
		steps: 100,
		mode: 'horizontal'
	},

	initialize: function(element, knob, options){
		this.setOptions(options);
		this.element = $(element);
		this.knob = $(knob);
		this.previousChange = this.previousEnd = this.step = -1;
		this.element.addEvent('mousedown', this.clickedElement.bind(this));
		if (this.options.wheel) this.element.addEvent('mousewheel', this.scrolledElement.bindWithEvent(this));
		var offset, limit = {}, modifiers = {'x': false, 'y': false};
		switch (this.options.mode){
			case 'vertical':
				this.axis = 'y';
				this.property = 'top';
				offset = 'offsetHeight';
				break;
			case 'horizontal':
				this.axis = 'x';
				this.property = 'left';
				offset = 'offsetWidth';
		}
		this.half = this.knob[offset] / 2;
		this.full = this.element[offset] - this.knob[offset] + (this.options.offset * 2);
		this.min = $chk(this.options.range[0]) ? this.options.range[0] : 0;
		this.max = $chk(this.options.range[1]) ? this.options.range[1] : this.options.steps;
		this.range = this.max - this.min;
		this.steps = this.options.steps || this.full;
		this.stepSize = Math.abs(this.range) / this.steps;
		this.stepWidth = this.stepSize * this.full / Math.abs(this.range) ;
		
		this.knob.setStyle('position', 'relative').setStyle(this.property, - this.options.offset);
		modifiers[this.axis] = this.property;
		limit[this.axis] = [- this.options.offset, this.full - this.options.offset];
		this.drag = new Drag(this.knob, {
			snap: 0,
			limit: limit,
			modifiers: modifiers,
			onDrag: this.draggedKnob.bind(this),
			onStart: this.draggedKnob.bind(this),
			onComplete: function(){
				this.draggedKnob();
				this.end();
			}.bind(this)
		});
		if (this.options.snap) {
			this.drag.options.grid = Math.ceil(this.stepWidth);
			this.drag.options.limit[this.axis][1] = this.full;
		}
	},

	set: function(step){
		
		if (!((this.range > 0) ^ (step < this.min))) step = this.min;
		if (!((this.range > 0) ^ (step > this.max))) step = this.max;
		this.step = Math.round(step);
		this.checkStep();
		//this.end();
		this.fireEvent('tick', this.toPosition(this.step));
		return this;
	},
	
	setRange: function(newRange,maxWidth,minWidth){
		this.range = newRange;
		this.max = maxWidth;
		this.min = minWidth;
		this.stepSize = Math.abs(this.range) / this.steps;
		this.stepWidth = this.stepSize * this.full / Math.abs(this.range) ;
		
	},

	clickedElement: function(event){
		var dir = this.range < 0 ? -1 : 1;
		var position = event.page[this.axis] - this.element.getPosition()[this.axis] - this.half;
		position = position.limit(-this.options.offset, this.full -this.options.offset);
		this.step = Math.round(this.min + dir * this.toStep(position));
		
		this.checkStep();
		this.end();
		this.fireEvent('tick', position);
	},
	
	scrolledElement: function(event){
		var mode = (this.options.mode == 'horizontal') ? (event.wheel < 0) : (event.wheel > 0);
		this.set(mode ? this.step - this.stepSize : this.step + this.stepSize);
		event.stop();
	},

	draggedKnob: function(){
		var dir = this.range < 0 ? -1 : 1;
		var position = this.drag.value.now[this.axis];
		position = position.limit(-this.options.offset, this.full -this.options.offset);
		this.step = Math.round(this.min + dir * this.toStep(position));
		this.checkStep();
	},

	checkStep: function(){
		if (this.previousChange != this.step){
			this.previousChange = this.step;
			this.fireEvent('change', this.step);
		}
	},

	end: function(){
		if (this.previousEnd !== this.step){
			this.previousEnd = this.step;
			this.fireEvent('complete', this.step + '');
		}
	},

	toStep: function(position){
		var step = (position + this.options.offset) * this.stepSize / this.full * this.steps;
		return this.options.steps ? Math.round(step -= step % this.stepSize) : step;
	},

	toPosition: function(step){
		return (this.full * Math.abs(this.min - step)) / (this.steps * this.stepSize) - this.options.offset;
	}

});

/*
Script: Scroller.js
	Class which scrolls the contents of any Element (including the window) when the mouse reaches the Element's boundaries.

License:
	MIT-style license.
*/

var Scroller = new Class({

	Implements: [Events, Options],

	options: {
		area: 20,
		velocity: 1,
		onChange: function(x, y){
			this.element.scrollTo(x, y);
		}
	},

	initialize: function(element, options){
		this.setOptions(options);
		this.element = $(element);
		this.listener = ($type(this.element) != 'element') ? $(this.element.getDocument().body) : this.element;
		this.timer = null;
		this.coord = this.getCoords.bind(this);
	},

	start: function(){
		this.listener.addEvent('mousemove', this.coord);
	},

	stop: function(){
		this.listener.removeEvent('mousemove', this.coord);
		this.timer = $clear(this.timer);
	},

	getCoords: function(event){
		this.page = (this.listener.get('tag') == 'body') ? event.client : event.page;
		if (!this.timer) this.timer = this.scroll.periodical(50, this);
	},

	scroll: function(){
		var size = this.element.getSize(), scroll = this.element.getScroll(), pos = this.element.getPosition(), change = {'x': 0, 'y': 0};
		for (var z in this.page){
			if (this.page[z] < (this.options.area + pos[z]) && scroll[z] != 0)
				change[z] = (this.page[z] - this.options.area - pos[z]) * this.options.velocity;
			else if (this.page[z] + this.options.area > (size[z] + pos[z]) && size[z] + size[z] != scroll[z])
				change[z] = (this.page[z] - size[z] + this.options.area - pos[z]) * this.options.velocity;
		}
		if (change.y || change.x) this.fireEvent('change', [scroll.x + change.x, scroll.y + change.y]);
	}

});

/*
Script: Accordion.js
	An Fx.Elements extension which allows you to easily create accordion type controls.

License:
	MIT-style license.
*/

var Accordion = new Class({

	Extends: Fx.Elements,

	options: {/*
		onActive: $empty,
		onBackground: $empty,*/
		display: 0,
		show: false,
		height: true,
		width: false,
		opacity: true,
		fixedHeight: false,
		fixedWidth: false,
		wait: false,
		alwaysHide: false
	},

	initialize: function(){
		var params = Array.link(arguments, {'container': Element.type, 'options': Object.type, 'togglers': $defined, 'elements': $defined});
		this.parent(params.elements, params.options);
		this.togglers = $$(params.togglers);
		this.container = $(params.container);
		this.previous = -1;
		if (this.options.alwaysHide) this.options.wait = true;
		if ($chk(this.options.show)){
			this.options.display = false;
			this.previous = this.options.show;
		}
		if (this.options.start){
			this.options.display = false;
			this.options.show = false;
		}
		this.effects = {};
		if (this.options.opacity) this.effects.opacity = 'fullOpacity';
		if (this.options.width) this.effects.width = this.options.fixedWidth ? 'fullWidth' : 'offsetWidth';
		if (this.options.height) this.effects.height = this.options.fixedHeight ? 'fullHeight' : 'scrollHeight';
		for (var i = 0, l = this.togglers.length; i < l; i++) this.addSection(this.togglers[i], this.elements[i]);
		this.elements.each(function(el, i){
			if (this.options.show === i){
				this.fireEvent('active', [this.togglers[i], el]);
			} else {
				for (var fx in this.effects) el.setStyle(fx, 0);
			}
		}, this);
		if ($chk(this.options.display)) this.display(this.options.display);
	},

	addSection: function(toggler, element, pos){
		toggler = $(toggler);
		element = $(element);
		var test = this.togglers.contains(toggler);
		var len = this.togglers.length;
		this.togglers.include(toggler);
		this.elements.include(element);
		if (len && (!test || pos)){
			pos = $pick(pos, len - 1);
			toggler.inject(this.togglers[pos], 'before');
			element.inject(toggler, 'after');
		} else if (this.container && !test){
			toggler.inject(this.container);
			element.inject(this.container);
		}
		var idx = this.togglers.indexOf(toggler);
		toggler.addEvent('click', this.display.bind(this, idx));
		if (this.options.height) element.setStyles({'padding-top': 0, 'border-top': 'none', 'padding-bottom': 0, 'border-bottom': 'none'});
		if (this.options.width) element.setStyles({'padding-left': 0, 'border-left': 'none', 'padding-right': 0, 'border-right': 'none'});
		element.fullOpacity = 1;
		if (this.options.fixedWidth) element.fullWidth = this.options.fixedWidth;
		if (this.options.fixedHeight) element.fullHeight = this.options.fixedHeight;
		element.setStyle('overflow', 'hidden');
		if (!test){
			for (var fx in this.effects) element.setStyle(fx, 0);
		}
		return this;
	},

	display: function(index){
		index = ($type(index) == 'element') ? this.elements.indexOf(index) : index;
		if ((this.timer && this.options.wait) || (index === this.previous && !this.options.alwaysHide)) return this;
		this.previous = index;
		var obj = {};
		this.elements.each(function(el, i){
			obj[i] = {};
			var hide = (i != index) || (this.options.alwaysHide && (el.offsetHeight > 0));
			this.fireEvent(hide ? 'background' : 'active', [this.togglers[i], el]);
			for (var fx in this.effects) obj[i][fx] = hide ? 0 : el[this.effects[fx]];
		}, this);
		return this.start(obj);
	}

});
/* 
 * flowplayer.js 3.2.6. The Flowplayer API
 * 
 * Copyright 2009 Flowplayer Oy
 * 
 * This file is part of Flowplayer.
 * 
 * Flowplayer is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Flowplayer is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Flowplayer.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * Date: 2010-08-25 12:48:46 +0000 (Wed, 25 Aug 2010)
 * Revision: 575 
 */
(function(){function g(o){console.log("$f.fireEvent",[].slice.call(o))}function k(q){if(!q||typeof q!="object"){return q}var o=new q.constructor();for(var p in q){if(q.hasOwnProperty(p)){o[p]=k(q[p])}}return o}function m(t,q){if(!t){return}var o,p=0,r=t.length;if(r===undefined){for(o in t){if(q.call(t[o],o,t[o])===false){break}}}else{for(var s=t[0];p<r&&q.call(s,p,s)!==false;s=t[++p]){}}return t}function c(o){return document.getElementById(o)}function i(q,p,o){if(typeof p!="object"){return q}if(q&&p){m(p,function(r,s){if(!o||typeof s!="function"){q[r]=s}})}return q}function n(s){var q=s.indexOf(".");if(q!=-1){var p=s.slice(0,q)||"*";var o=s.slice(q+1,s.length);var r=[];m(document.getElementsByTagName(p),function(){if(this.className&&this.className.indexOf(o)!=-1){r.push(this)}});return r}}function f(o){o=o||window.event;if(o.preventDefault){o.stopPropagation();o.preventDefault()}else{o.returnValue=false;o.cancelBubble=true}return false}function j(q,o,p){q[o]=q[o]||[];q[o].push(p)}function e(){return"_"+(""+Math.random()).slice(2,10)}var h=function(t,r,s){var q=this,p={},u={};q.index=r;if(typeof t=="string"){t={url:t}}i(this,t,true);m(("Begin*,Start,Pause*,Resume*,Seek*,Stop*,Finish*,LastSecond,Update,BufferFull,BufferEmpty,BufferStop").split(","),function(){var v="on"+this;if(v.indexOf("*")!=-1){v=v.slice(0,v.length-1);var w="onBefore"+v.slice(2);q[w]=function(x){j(u,w,x);return q}}q[v]=function(x){j(u,v,x);return q};if(r==-1){if(q[w]){s[w]=q[w]}if(q[v]){s[v]=q[v]}}});i(this,{onCuepoint:function(x,w){if(arguments.length==1){p.embedded=[null,x];return q}if(typeof x=="number"){x=[x]}var v=e();p[v]=[x,w];if(s.isLoaded()){s._api().fp_addCuepoints(x,r,v)}return q},update:function(w){i(q,w);if(s.isLoaded()){s._api().fp_updateClip(w,r)}var v=s.getConfig();var x=(r==-1)?v.clip:v.playlist[r];i(x,w,true)},_fireEvent:function(v,y,w,A){if(v=="onLoad"){m(p,function(B,C){if(C[0]){s._api().fp_addCuepoints(C[0],r,B)}});return false}A=A||q;if(v=="onCuepoint"){var z=p[y];if(z){return z[1].call(s,A,w)}}if(y&&"onBeforeBegin,onMetaData,onStart,onUpdate,onResume".indexOf(v)!=-1){i(A,y);if(y.metaData){if(!A.duration){A.duration=y.metaData.duration}else{A.fullDuration=y.metaData.duration}}}var x=true;m(u[v],function(){x=this.call(s,A,y,w)});return x}});if(t.onCuepoint){var o=t.onCuepoint;q.onCuepoint.apply(q,typeof o=="function"?[o]:o);delete t.onCuepoint}m(t,function(v,w){if(typeof w=="function"){j(u,v,w);delete t[v]}});if(r==-1){s.onCuepoint=this.onCuepoint}};var l=function(p,r,q,t){var o=this,s={},u=false;if(t){i(s,t)}m(r,function(v,w){if(typeof w=="function"){s[v]=w;delete r[v]}});i(this,{animate:function(y,z,x){if(!y){return o}if(typeof z=="function"){x=z;z=500}if(typeof y=="string"){var w=y;y={};y[w]=z;z=500}if(x){var v=e();s[v]=x}if(z===undefined){z=500}r=q._api().fp_animate(p,y,z,v);return o},css:function(w,x){if(x!==undefined){var v={};v[w]=x;w=v}r=q._api().fp_css(p,w);i(o,r);return o},show:function(){this.display="block";q._api().fp_showPlugin(p);return o},hide:function(){this.display="none";q._api().fp_hidePlugin(p);return o},toggle:function(){this.display=q._api().fp_togglePlugin(p);return o},fadeTo:function(y,x,w){if(typeof x=="function"){w=x;x=500}if(w){var v=e();s[v]=w}this.display=q._api().fp_fadeTo(p,y,x,v);this.opacity=y;return o},fadeIn:function(w,v){return o.fadeTo(1,w,v)},fadeOut:function(w,v){return o.fadeTo(0,w,v)},getName:function(){return p},getPlayer:function(){return q},_fireEvent:function(w,v,x){if(w=="onUpdate"){var z=q._api().fp_getPlugin(p);if(!z){return}i(o,z);delete o.methods;if(!u){m(z.methods,function(){var B=""+this;o[B]=function(){var C=[].slice.call(arguments);var D=q._api().fp_invoke(p,B,C);return D==="undefined"||D===undefined?o:D}});u=true}}var A=s[w];if(A){var y=A.apply(o,v);if(w.slice(0,1)=="_"){delete s[w]}return y}return o}})};function b(q,G,t){var w=this,v=null,D=false,u,s,F=[],y={},x={},E,r,p,C,o,A;i(w,{id:function(){return E},isLoaded:function(){return(v!==null&&v.fp_play!==undefined&&!D)},getParent:function(){return q},hide:function(H){if(H){q.style.height="0px"}if(w.isLoaded()){v.style.height="0px"}return w},show:function(){q.style.height=A+"px";if(w.isLoaded()){v.style.height=o+"px"}return w},isHidden:function(){return w.isLoaded()&&parseInt(v.style.height,10)===0},load:function(J){if(!w.isLoaded()&&w._fireEvent("onBeforeLoad")!==false){var H=function(){u=q.innerHTML;if(u&&!flashembed.isSupported(G.version)){q.innerHTML=""}if(J){J.cached=true;j(x,"onLoad",J)}flashembed(q,G,{config:t})};var I=0;m(a,function(){this.unload(function(K){if(++I==a.length){H()}})})}return w},unload:function(J){if(this.isFullscreen()&&/WebKit/i.test(navigator.userAgent)){if(J){J(false)}return w}if(u.replace(/\s/g,"")!==""){if(w._fireEvent("onBeforeUnload")===false){if(J){J(false)}return w}D=true;try{if(v){v.fp_close();w._fireEvent("onUnload")}}catch(H){}var I=function(){v=null;q.innerHTML=u;D=false;if(J){J(true)}};setTimeout(I,50)}else{if(J){J(false)}}return w},getClip:function(H){if(H===undefined){H=C}return F[H]},getCommonClip:function(){return s},getPlaylist:function(){return F},getPlugin:function(H){var J=y[H];if(!J&&w.isLoaded()){var I=w._api().fp_getPlugin(H);if(I){J=new l(H,I,w);y[H]=J}}return J},getScreen:function(){return w.getPlugin("screen")},getControls:function(){return w.getPlugin("controls")._fireEvent("onUpdate")},getLogo:function(){try{return w.getPlugin("logo")._fireEvent("onUpdate")}catch(H){}},getPlay:function(){return w.getPlugin("play")._fireEvent("onUpdate")},getConfig:function(H){return H?k(t):t},getFlashParams:function(){return G},loadPlugin:function(K,J,M,L){if(typeof M=="function"){L=M;M={}}var I=L?e():"_";w._api().fp_loadPlugin(K,J,M,I);var H={};H[I]=L;var N=new l(K,null,w,H);y[K]=N;return N},getState:function(){return w.isLoaded()?v.fp_getState():-1},play:function(I,H){var J=function(){if(I!==undefined){w._api().fp_play(I,H)}else{w._api().fp_play()}};if(w.isLoaded()){J()}else{if(D){setTimeout(function(){w.play(I,H)},50)}else{w.load(function(){J()})}}return w},getVersion:function(){var I="flowplayer.js 3.2.6";if(w.isLoaded()){var H=v.fp_getVersion();H.push(I);return H}return I},_api:function(){if(!w.isLoaded()){throw"Flowplayer "+w.id()+" not loaded when calling an API method"}return v},setClip:function(H){w.setPlaylist([H]);return w},getIndex:function(){return p},_swfHeight:function(){return v.clientHeight}});m(("Click*,Load*,Unload*,Keypress*,Volume*,Mute*,Unmute*,PlaylistReplace,ClipAdd,Fullscreen*,FullscreenExit,Error,MouseOver,MouseOut").split(","),function(){var H="on"+this;if(H.indexOf("*")!=-1){H=H.slice(0,H.length-1);var I="onBefore"+H.slice(2);w[I]=function(J){j(x,I,J);return w}}w[H]=function(J){j(x,H,J);return w}});m(("pause,resume,mute,unmute,stop,toggle,seek,getStatus,getVolume,setVolume,getTime,isPaused,isPlaying,startBuffering,stopBuffering,isFullscreen,toggleFullscreen,reset,close,setPlaylist,addClip,playFeed,setKeyboardShortcutsEnabled,isKeyboardShortcutsEnabled").split(","),function(){var H=this;w[H]=function(J,I){if(!w.isLoaded()){return w}var K=null;if(J!==undefined&&I!==undefined){K=v["fp_"+H](J,I)}else{K=(J===undefined)?v["fp_"+H]():v["fp_"+H](J)}return K==="undefined"||K===undefined?w:K}});w._fireEvent=function(Q){if(typeof Q=="string"){Q=[Q]}var R=Q[0],O=Q[1],M=Q[2],L=Q[3],K=0;if(t.debug){g(Q)}if(!w.isLoaded()&&R=="onLoad"&&O=="player"){v=v||c(r);o=w._swfHeight();m(F,function(){this._fireEvent("onLoad")});m(y,function(S,T){T._fireEvent("onUpdate")});s._fireEvent("onLoad")}if(R=="onLoad"&&O!="player"){return}if(R=="onError"){if(typeof O=="string"||(typeof O=="number"&&typeof M=="number")){O=M;M=L}}if(R=="onContextMenu"){m(t.contextMenu[O],function(S,T){T.call(w)});return}if(R=="onPluginEvent"||R=="onBeforePluginEvent"){var H=O.name||O;var I=y[H];if(I){I._fireEvent("onUpdate",O);return I._fireEvent(M,Q.slice(3))}return}if(R=="onPlaylistReplace"){F=[];var N=0;m(O,function(){F.push(new h(this,N++,w))})}if(R=="onClipAdd"){if(O.isInStream){return}O=new h(O,M,w);F.splice(M,0,O);for(K=M+1;K<F.length;K++){F[K].index++}}var P=true;if(typeof O=="number"&&O<F.length){C=O;var J=F[O];if(J){P=J._fireEvent(R,M,L)}if(!J||P!==false){P=s._fireEvent(R,M,L,J)}}m(x[R],function(){P=this.call(w,O,M);if(this.cached){x[R].splice(K,1)}if(P===false){return false}K++});return P};function B(){if($f(q)){$f(q).getParent().innerHTML="";p=$f(q).getIndex();a[p]=w}else{a.push(w);p=a.length-1}A=parseInt(q.style.height,10)||q.clientHeight;E=q.id||"fp"+e();r=G.id||E+"_api";G.id=r;t.playerId=E;if(typeof t=="string"){t={clip:{url:t}}}if(typeof t.clip=="string"){t.clip={url:t.clip}}t.clip=t.clip||{};if(q.getAttribute("href",2)&&!t.clip.url){t.clip.url=q.getAttribute("href",2)}s=new h(t.clip,-1,w);t.playlist=t.playlist||[t.clip];var I=0;m(t.playlist,function(){var K=this;if(typeof K=="object"&&K.length){K={url:""+K}}m(t.clip,function(L,M){if(M!==undefined&&K[L]===undefined&&typeof M!="function"){K[L]=M}});t.playlist[I]=K;K=new h(K,I,w);F.push(K);I++});m(t,function(K,L){if(typeof L=="function"){if(s[K]){s[K](L)}else{j(x,K,L)}delete t[K]}});m(t.plugins,function(K,L){if(L){y[K]=new l(K,L,w)}});if(!t.plugins||t.plugins.controls===undefined){y.controls=new l("controls",null,w)}y.canvas=new l("canvas",null,w);u=q.innerHTML;function J(L){var K=w.hasiPadSupport&&w.hasiPadSupport();if(/iPad|iPhone|iPod/i.test(navigator.userAgent)&&!/.flv$/i.test(F[0].url)&&!K){return true}if(!w.isLoaded()&&w._fireEvent("onBeforeClick")!==false){w.load()}return f(L)}function H(){if(u.replace(/\s/g,"")!==""){if(q.addEventListener){q.addEventListener("click",J,false)}else{if(q.attachEvent){q.attachEvent("onclick",J)}}}else{if(q.addEventListener){q.addEventListener("click",f,false)}w.load()}}setTimeout(H,0)}if(typeof q=="string"){var z=c(q);if(!z){throw"Flowplayer cannot access element: "+q}q=z;B()}else{B()}}var a=[];function d(o){this.length=o.length;this.each=function(p){m(o,p)};this.size=function(){return o.length}}window.flowplayer=window.$f=function(){var p=null;var o=arguments[0];if(!arguments.length){m(a,function(){if(this.isLoaded()){p=this;return false}});return p||a[0]}if(arguments.length==1){if(typeof o=="number"){return a[o]}else{if(o=="*"){return new d(a)}m(a,function(){if(this.id()==o.id||this.id()==o||this.getParent()==o){p=this;return false}});return p}}if(arguments.length>1){var t=arguments[1],q=(arguments.length==3)?arguments[2]:{};if(typeof t=="string"){t={src:t}}t=i({bgcolor:"#000000",version:[9,0],expressInstall:"http://static.flowplayer.org/swf/expressinstall.swf",cachebusting:false},t);if(typeof o=="string"){if(o.indexOf(".")!=-1){var s=[];m(n(o),function(){s.push(new b(this,k(t),k(q)))});return new d(s)}else{var r=c(o);return new b(r!==null?r:o,t,q)}}else{if(o){return new b(o,t,q)}}}return null};i(window.$f,{fireEvent:function(){var o=[].slice.call(arguments);var q=$f(o[0]);return q?q._fireEvent(o.slice(1)):null},addPlugin:function(o,p){b.prototype[o]=p;return $f},each:m,extend:i});if(typeof jQuery=="function"){jQuery.fn.flowplayer=function(q,p){if(!arguments.length||typeof arguments[0]=="number"){var o=[];this.each(function(){var r=$f(this);if(r){o.push(r)}});return arguments.length?o[arguments[0]]:new d(o)}return this.each(function(){$f(this,k(q),p?k(p):{})})}}})();(function(){var h=document.all,j="http://www.adobe.com/go/getflashplayer",c=typeof jQuery=="function",e=/(\d+)[^\d]+(\d+)[^\d]*(\d*)/,b={width:"100%",height:"100%",id:"_"+(""+Math.random()).slice(9),allowfullscreen:true,allowscriptaccess:"always",quality:"high",version:[3,0],onFail:null,expressInstall:null,w3c:false,cachebusting:false};if(window.attachEvent){window.attachEvent("onbeforeunload",function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){}})}function i(m,l){if(l){for(var f in l){if(l.hasOwnProperty(f)){m[f]=l[f]}}}return m}function a(f,n){var m=[];for(var l in f){if(f.hasOwnProperty(l)){m[l]=n(f[l])}}return m}window.flashembed=function(f,m,l){if(typeof f=="string"){f=document.getElementById(f.replace("#",""))}if(!f){return}if(typeof m=="string"){m={src:m}}return new d(f,i(i({},b),m),l)};var g=i(window.flashembed,{conf:b,getVersion:function(){var m,f;try{f=navigator.plugins["Shockwave Flash"].description.slice(16)}catch(o){try{m=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");f=m&&m.GetVariable("$version")}catch(n){try{m=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");f=m&&m.GetVariable("$version")}catch(l){}}}f=e.exec(f);return f?[f[1],f[3]]:[0,0]},asString:function(l){if(l===null||l===undefined){return null}var f=typeof l;if(f=="object"&&l.push){f="array"}switch(f){case"string":l=l.replace(new RegExp('(["\\\\])',"g"),"\\$1");l=l.replace(/^\s?(\d+\.?\d+)%/,"$1pct");return'"'+l+'"';case"array":return"["+a(l,function(o){return g.asString(o)}).join(",")+"]";case"function":return'"function()"';case"object":var m=[];for(var n in l){if(l.hasOwnProperty(n)){m.push('"'+n+'":'+g.asString(l[n]))}}return"{"+m.join(",")+"}"}return String(l).replace(/\s/g," ").replace(/\'/g,'"')},getHTML:function(o,l){o=i({},o);var n='<object width="'+o.width+'" height="'+o.height+'" id="'+o.id+'" name="'+o.id+'"';if(o.cachebusting){o.src+=((o.src.indexOf("?")!=-1?"&":"?")+Math.random())}if(o.w3c||!h){n+=' data="'+o.src+'" type="application/x-shockwave-flash"'}else{n+=' classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'}n+=">";if(o.w3c||h){n+='<param name="movie" value="'+o.src+'" />'}o.width=o.height=o.id=o.w3c=o.src=null;o.onFail=o.version=o.expressInstall=null;for(var m in o){if(o[m]){n+='<param name="'+m+'" value="'+o[m]+'" />'}}var p="";if(l){for(var f in l){if(l[f]){var q=l[f];p+=f+"="+(/function|object/.test(typeof q)?g.asString(q):q)+"&"}}p=p.slice(0,-1);n+='<param name="flashvars" value=\''+p+"' />"}n+="</object>";return n},isSupported:function(f){return k[0]>f[0]||k[0]==f[0]&&k[1]>=f[1]}});var k=g.getVersion();function d(f,n,m){if(g.isSupported(n.version)){f.innerHTML=g.getHTML(n,m)}else{if(n.expressInstall&&g.isSupported([6,65])){f.innerHTML=g.getHTML(i(n,{src:n.expressInstall}),{MMredirectURL:location.href,MMplayerType:"PlugIn",MMdoctitle:document.title})}else{if(!f.innerHTML.replace(/\s/g,"")){f.innerHTML="<h2>Flash version "+n.version+" or greater is required</h2><h3>"+(k[0]>0?"Your version is "+k:"You have no flash plugin installed")+"</h3>"+(f.tagName=="A"?"<p>Click here to download latest version</p>":"<p>Download latest version from <a href='"+j+"'>here</a></p>");if(f.tagName=="A"){f.onclick=function(){location.href=j}}}if(n.onFail){var l=n.onFail.call(this);if(typeof l=="string"){f.innerHTML=l}}}}if(h){window[n.id]=document.getElementById(n.id)}i(this,{getRoot:function(){return f},getOptions:function(){return n},getConf:function(){return m},getApi:function(){return f.firstChild}})}if(c){jQuery.tools=jQuery.tools||{version:"3.2.6"};jQuery.tools.flashembed={conf:b};jQuery.fn.flashembed=function(l,f){return this.each(function(){jQuery(this).data("flashembed",flashembed(this,l,f))})}}})(); 
scrollBox = new Class({
	Implements: Options,
	
	options: {
		'width':500,
		'height':500,
		'background_color':'#ffffff'
	},
	
	initialize: function(options){
		this.setOptions(options);
		
		this.scroll_position = 0;
        this.scroll_size = 0;
        this.interval = 0;
		        
		this.box = new Element('div',{'class':'oscrollbox'});
		this.box.setStyles({'width':this.options.width-10,'height':this.options.height,'position':'relative','padding':5});
		
		this.content = new Element('div',{'class':'oscrollbox-content'});
		this.content.setStyles({'position':'relative','width':'100%','height':'100%','overflow-x':'hidden','overflow-y':'hidden','background-color':this.options.background_color});
		this.content.inject(this.box);
		this.contentScroll = new Fx.Scroll(this.content,{'duration':10});
		
		this.scrollbar = new Element('div',{'class':'oscroll'});
        this.scrollbar.setStyles({'background-position':'-15px 0px','position':'absolute','opacity':0,'right':-7,'top':0,'width':15,'cursor':'pointer','background-image':'url(/obray/images/box/sbox/scrollbar-bg.png)'});
        this.scrollbar.inject(this.box);
       
        this.scrollbar_handle = new Element('div',{'class':'oscroll-handle'});
        this.scrollbar_handle.setStyles({'background-image':'url(/obray/images/box/sbox/scrollbar.png)','width':14,'height':64,'overflow':'hidden'});
        this.scrollbar_handle.inject(this.scrollbar);
        this.scrollbar_handle.addEvent('mouseenter',function(){ this.scrollbar_handle.setStyles({'background-position':'-15px 0px'}); }.bind(this));
        this.scrollbar_handle.addEvent('mouseleave',function(){ this.scrollbar_handle.setStyles({'background-position':'0px 0px'}); }.bind(this));

        this.scrollbar_top = new Element('div',{'class':'oscroll-top'});
        this.scrollbar_top.setStyles({'position':'absolute','right':6,'top':0,'width':3,'height':4,'background-image':'url(/obray/images/box/sbox/scrollbar-top.png)'});
        this.scrollbar_top.inject(this.scrollbar);
        
        this.scrollbar_bottom = new Element('div',{'class':'oscroll-bottom'});
        this.scrollbar_bottom.setStyles({'position':'absolute','right':6,'bottom':2,'width':3,'height':4,'background-image':'url(/obray/images/box/sbox/scrollbar-bottom.png)'});
        this.scrollbar_bottom.inject(this.scrollbar);
        
         this.content.addEvent('mousewheel',function(e){
            this.scroll_position = this.scroll_position-e.wheel;
            try{this.scrollbar_slider.set(this.scroll_position);} catch(err){}
        }.bind(this));
        
	},
	
	adjustScrollHeight: function(){
        if(this.scroll_size != this.content.getScrollSize().y-this.options.height){
            this.scrollbar.setStyles({'opacity':1});
            this.scrollbar_slider = new Slider(this.scrollbar,this.scrollbar_handle,{'mode':'vertical','steps':this.content.getScrollSize().y-this.options.height,'onChange':function(step){
                this.contentScroll.set(0,step);
                this.scroll_position = step;
            }.bind(this)});
            this.scroll_size = this.content.getScrollSize().y-this.options.height;
            this.scrollbar_slider.set(this.scroll_position);
        }
        if(this.content.getScrollSize().y-this.options.height <= 0){
            this.scrollbar.setStyles({'opacity':0});
        }
    },
    
    scrollUp: function(distance){
        this.contentScroll.pause();
        var scroll_to = this.content.getScrollSize().y-this.options.height+distance-50;
    },
    
    scrollDown: function(distance){
        this.contentScroll.pause();
        var scroll_to = (this.content.getScrollSize().y-this.options.height-distance-15);
        this.contentScroll.toBottom()
    },

    center: function(){
        var x = document.body.getCoordinates().width/2;
        var y = document.body.getCoordinates().height/2;
        return {'x':x-20,'y':y};
    },
	
	inject: function(el){
		this.box.inject(el);
		this.scrollbar.setStyles({'height':this.options.height});
		$clear(this.interval);
		this.interval = this.adjustScrollHeight.periodical(500,this);
	}
})

BoxHeader = new Class({
	Implements: Options,
	
	options:{
		'header':'Default Header',
		'icon':'/obray/images/obray-logo-icon.png'
	},
	
	initialize: function(options){
		this.setOptions(options);
		
		this.container = new Element('div',{'class':'box-header-container ogrid-1 ogrid-self-clear'});
		
		this.header = new Element('div',{'class':'box-header ogrid-1-padding ogrid-self-clear'});
		
		this.header_icon = new Element('div',{'class':'box-header-icon ogrid-float'});
		this.header_text = new Element('h1',{'class':'box-header-text ogrid-float'});
		this.header_text.set('html',this.options.header);		
		
		this.content = new Element('div',{'class':'box-header-content'});
		
	},
	
	inject: function(el){
		this.container.inject(el);
		this.header.inject(this.container);
		this.header_icon.inject(this.header);
		this.header_text.inject(this.header);
		this.content.inject(this.container);
	}
});

BoxToggle = new Class({
	Implements: Options,
	
	options:{
		'label_class':'ogrid-2-5-padding',
		'input_class':'ogrid-3-5-padding',
		'is_open':false
	},
	
	initialize: function(options){
		this.setOptions(options);
		
		this.is_open = this.options.is_open;
		this.elements = [];
		
		this.container = new Element('div',{'class':'box-toggle-container ogrid-1 ogrid-self-clear'});
		this.container.setStyles({'margin':0,padding:0});
				
		this.content = new Element('div',{'class':'bx-toggle-content ogrid-1 ogrid-self-clear'});
		this.content.setStyles({'display':'none','visibility':'hidden','overflow':'hidden'});
		
	},
	
	toggle: function(){
		if(this.is_open){
			this.close();
		} else {
			this.open();
		}	
	},
	
	open: function(){
		this.content.setStyles({'display':'block','visibility':'visible','height':'auto','overflow':'visible'});
		this.is_open = true;
	},
	
	close: function(){
		this.content.setStyles({'dislay':'none','visibility':'hidden','height':0,'overflow':'hidden'});
		this.is_open = false;
	},
	
	addElement: function(el){ this.elements[this.elements.length] = el; },
	
	inject: function(el){
	
		
		this.container.inject(el);
		this.content.inject(this.container);
		
		try{
			for(var i=0;i<this.elements.length;++i){ this.elements[i].inject(this.content); }
		} catch (err) {
			
		}
	},
	
	throwError: $empty,
	
	getProperty:function(property){
		return "";
	}
});
				


sbox = new Class({
    Implements: Options,
    
    options: {
        'width':500,
        'height':500,
        'startx':($(window).getCoordinates().width/2),
        'starty':($(window).getCoordinates().height/2),
        'scroll':true,
        'zIndex':4999,
        'primary_color':'#ffffff',
        'secondary_color':'#ffffff',
        'close':$empty,
        'open':$empty,
        'scrollable':true,
		'show-close-btn':true,
		'show_overflow':false,
		'unique_id':0,
		'sbox_class':'sbox',
		'destroy':false
    },
    
    initialize: function(options){
        this.setOptions(options);
        
        this.body = $$('body');
        
        /****************************************************
        	Elements
        ****************************************************/
        
        this.box_background = new Element('div',{'class':'sbox-background'});
        this.box_background.setStyles({'position':'fixed','background-color':'#000','opacity':0,'left':0,'top':0,'width':document.body.getCoordinates().width,'height':document.body.getCoordinates().height+9,'z-index':this.options.zIndex-1});
        
        this.box = new Element('div',{'class':this.options.sbox_class,'id':'sbox'+this.options.unique_id});
        this.box.setStyles({'position':'fixed','width':this.options.width,'height':this.options.height,'box-shadow':'0px 0px 20px #000','left':this.options.startx-this.options.width/2,'top':this.options.starty-this.options.height/2,'margin-left':0,'background-color':'transparent','z-index':this.options.zIndex,'-webkit-border-bottom-left-radius':'5px','-webkit-border-bottom-right-radius': '5px','-webkit-border-top-left-radius': '5px','-webkit-border-top-right-radius': '5px','-moz-border-radius':'5px 5px 5px 5px','background-color':this.options.primary_color,'padding':10,'opacity':0});

        this.box_fx = new Fx.Morph(this.box, {duration:200,transition: Fx.Transitions.Cubic.easeInOut});
        this.box_background_fx = new Fx.Morph(this.box_background, {duration:200,transition: Fx.Transitions.Cubic.easeInOut});
        
        this.box_close_btn = new Element('div',{'class':'sbox-close-btn'});
        this.box_close_btn.setStyles({'position':'absolute','right':-15,'top':-15,'background-image':'url(/obray/images/box/boxClose_btn.png)','height':30,'width':30,'cursor':'pointer'});
        
        this.scrollbox = new scrollBox({'width':this.options.width,'height':this.options.height});
        
        this.content = this.scrollbox.content;
        
        /****************************************************
        	Events
        ****************************************************/
        
        // resize event
        window.addEvent('resize',function(){
            this.box_background.setStyles({'width':document.body.getCoordinates().width,'height':document.body.getCoordinates().height+9})
            this.box.setStyles({'left':this.options.starty-this.options.width/2,'top':this.options.starty-this.options.height/2});
        }.bind(this));
        
        this.box_close_btn.addEvent('click',function(){
        	this.close(this.options.destroy);
        }.bind(this));
        
        /****************************************************
        	Inject
        ****************************************************/
        
        this.box.inject(document.body);
        this.box_background.inject(document.body);
        this.scrollbox.inject(this.box);
        if(this.options['show-close-btn']){ this.box_close_btn.inject(this.box); }
        
    },
    
    open: function(){
        this.box_fx.start({'opacity':1});
        this.box_background_fx.start({'opacity':.75});
        this.options.open();
    },
    
    close: function(destroy){
    	if(destroy){
    		this.box.destroy();
    		this.box_background.destroy();
    	} else {
    		this.box.setStyles({'opacity':0});
    		this.box_background.setStyles({'opacity':0});
    	}
        this.options.close();
        //this.boxFx.pause();
        //this.boxFx.start({'left':this.options.startx,'top':this.options.starty,'width':0,'height':0,'opacity':0,'margin-left':0,'margin-top':0}).chain(function(){}.bind(this));
        //this.box_background.setStyles({'display':'none'});
        //if(this.options.scroll){document.body.setStyles({'overflow':'scroll'});}
    }
});

sboxConfirm = new Class({
	Implements: Options,
	
	options:{
		'confirm-message':'Are you sure you want to do that?',
		'message':'',
		'onConfirm':$empty,
		'open':$empty
	},
	
	initialize: function(options){
		this.setOptions(options);
		
		if(this.options.message != ''){ this.options['confirm-message'] = this.options.message; }
		
		this.box = new Element('div',{'class':'sboxconfirm obray-admin-container'});
		this.box.setStyles({'position':'fixed','border':'1px solid #ccc','background-color':'#ffffff','box-shadow': '0px 0px 20px #aaa','height':150,'width':300,'-webkit-border-radius':'5px 5px 5px 5px','-moz-border-radius':'5px 5px 5px 5px','z-index':6000});
		
		this.box_content = new Element('div',{'class':'sboxconfirm'});
		this.box_content.set('html',this.options['confirm-message']);
		this.box_content.setStyles({'border-bottom':'1px solid #e5e5e5','font-family':'Arial,Helvetica','font-size':14,'position':'relative','width':280,'height':80,'padding':10,'text-align':'center','color':'#454545'});
		this.box_content.inject(this.box);
		
		this.confirm_btn = new Element('input',{'type':'button','class':'sboxconfirm-btn','value':'Yes'});
		this.confirm_btn.setStyles({'cursor':'pointer','position':'absolute','bottom':-50,'right':0,'margin':10,'width':150});
		this.confirm_btn.inject(this.box_content);
		
		this.confirm_btn.addEvent('click',function(){
			this.options.onConfirm();
			this.close();
		}.bind(this));
		
		this.cancel_btn = new Element('input',{'type':'button','class':'sboxconfirm-cancel-btn','value':'No'})
		this.cancel_btn.setStyles({'cursor':'pointer','position':'absolute','bottom':-50,'left':0,'margin':10,'width':120});
		this.cancel_btn.inject(this.box_content);
		
		this.cancel_btn.addEvent('click',function(){
			this.close();
		}.bind(this));
	},
	
	open: function(){
		this.box.setStyles({'left':this.center().x-150,'top':this.center().y-75})
        var body = $(document.body);
        this.box.inject(body);
        this.box.setStyles({'display':'block'});
        this.options.open();
	},
	
	close: function(){
		this.box.setStyles({'display':'none'});
	},
	
	center: function(){
		
        var x = window.getWidth()/2;
        var y = window.getHeight()/2;
        return {'x':x-20,'y':y};
    }
});




AlertBox = new Class({
	Extends: sbox,
	
	Implements: Options,
	
	options:{
		'message':'Are you sure?',
		'onClose':function(){$empty();},
		'primary_color':'#ffffff',
		'secondary_color':'#ffffff',
		'width':400,
		'height':200
	},
	
	initialize: function(options){
		
		this.options.width = 450;
		this.options.height = 450;
		
		//data members
		this.setOptions(options);
		this.parent(options);
		
		//genereate HTML
		this.alert_container = new Element('div',{'class':'alert-container','id':'alert-container'+this.options.unique_id});
		this.alert_icon = new Element('img',{'src':'/obray/images/box/icon_error.png','class':'alert_icon'});
		this.alert_message = new Element('div',{'class':'alert-message'});
		this.alert_buttons = new Element('div',{'class':'alert-buttons'});
		this.alert_btn = new Element('div',{'class':'alert-btn oform-button'});
		this.br = new Element('br',{'class':'clear'});
		
		//set properties
		this.alert_message.set('html',this.options.message);
		this.alert_btn.set('html','Close');
		
		//set styles
		this.alert_container.setStyles({'padding-top':'10px','width':500})
		this.alert_icon.setStyles({'float':'left','margin':'10px'});
		this.alert_message.setStyles({'text-align':'left','float':'left','width':this.options.width-57-40,'color':'#000000','margin':'0 auto','font-family':'arial','padding':'10px','font-size':'12px'});
		this.alert_buttons.setStyles({'margin':'0 auto','width':'100px','padding':'10px','padding-top':'20px','color':'#888888','font-family':'Arial'});
		this.alert_btn.setStyles({'text-align':'center','padding-right':'10px','padding-left':'10px','cursor':'pointer'});
		
		//construct HTML
		this.alert_container.inject(this.content);
		this.alert_icon.inject(this.alert_container);
		this.alert_message.inject(this.alert_container);
		this.alert_btn.inject(this.alert_buttons);
		this.alert_buttons.inject(this.alert_container);
		this.br.inject(this.alert_container);
		
		//add event
		this.alert_btn.addEvent('click',function(){
			this.options.onClose();
			this.close();
		}.bind(this));
		this.alert_btn.addEvent('mouseenter',function(){
			this.alert_btn.setStyles({'color':'#333333'});
		}.bind(this));
		this.alert_btn.addEvent('mouseleave',function(){
			this.alert_btn.setStyles({'color':'#888888'});
		}.bind(this));
	}
});


StatusBox = new Class({
	Extends: sbox,
	
	Implements: Options,
	
	options:{
		'message':'Loading...',
		'onClose':function(){$empty();},
		'primary_color':'#000000',
		'secondary_color':'#000000',
		'width':200,
		'height':150
	},
	
	initialize: function(options){
		
		//data members
		this.setOptions(options);
		this.parent(options);
		
		
		this.close_btn
		
		alert('hello');
		
		//genereate HTML
		this.alert_container = new Element('div',{'class':'alert_container','id':'alert_container'+this.options.unique_id});
		this.alert_icon = new Element('img',{'src':'obray/images/loaders/loader-standard.gif','class':'alert_icon'});
		this.alert_message = new Element('div',{'class':'alert_message'});
		this.br = new Element('br',{'class':'clear'});
		
		//set properties
		this.alert_message.set('html',this.options.message);
		
		//set styles
		this.alert_container.setStyles({'padding-top':'10px','width':this.options.width,'opacity':.75,'color':'#ffffff'});
		this.alert_icon.setStyles({'float':'left','margin':'10px'});
		this.alert_message.setStyles({'text-align':'left','float':'left','width':this.options.width-57-40,'color':'#ffffff','margin':'0 auto','font-family':'arial','padding':'10px','font-size':'12px'});
		
		//construct HTML
		this.alert_container.inject(this.content);
		this.alert_icon.inject(this.alert_container);
		this.alert_message.inject(this.alert_container);
		this.br.inject(this.alert_container);
		
	}
}); 
OForm = new Class({
    Implements: Options,
    
    options:{
        'class_list':'',
        'id':'',
        'url':'',
        'button':new Element('input',{'type':'button','value':'Submit'}),
		'button2':false,
        'onComplete':$empty,
		'onError':false,
		'process_response':true,
		'responseEvalScripts':false,
		//loader
		'loader_img':'/obray/images/loaders/loader-standard.gif',
		'loader_message':'Processing...',
		'button_class':'',
		'label_class':'ogrid-2-5-padding',
		'form_data':[]
    },
    
    initialize: function(options){
		this.sectionNames = [];
		this.sectionIds = [];
		this.sectioncount = 0;
        this.setOptions(options);
        this.elements = [];
        this.br = new Element('div',{'class':'clear'});
        this.request = new Request({'url':this.options.url,'method':'post'});
        this.label_position = this.options['label-position'];
        var data = ''
        this.sections = [];this.sections[0] = [];
		
		window.select_index = 0;
		
		/*********************************************************
			Second Button
		********************************************************/

		if(this.options.button2 == true) {
			this.button2 = new Element('input',{'id':'oform-button2-'+this.options.form_id,'class':'oform-button2-'+this.options.form_id,'type':'button','value':'Submit'});
			this.button2.set('value',this.options['btn-value']);
			this.button2.addEvent('click',function(){
				//hide submit button and replace with loader
				this.button2.fade('out');
				this.loader = new Element('img', {'src':this.options['loader_img']});
				this.loader.setStyles({'float':'right','font-size':'10px'});
				this.loader.inject(this.form).fade('in');
			
            	var data = '';
            	for(var i=0;i<this.elements.length;++i){ data = data + '&' + this.elements[i].name + '=' + this.elements[i].getProperty('value'); }
				data = data + '&thecoolsubmitbutton=button2';
            	this.request.removeEvents();
            	this.request.setOptions({'data':data,'onComplete':function(response){
            	    //destroy loader & show submit button
					this.loader.destroy();
					//this.options.button.removeClass('Ohidden');
					this.button2.fade('in');
					if(this.options['process_response']){
					
						var json = JSON.decode(response);
					
            	    	if(json.response.ERROR == 'false' || json.response.ERROR == false || json.response.error == 'false' || json.response.error == false){
               	     		this.options.onComplete(json);
               	 		} else {
               	    		if(this.options.onError == false){
               	        		alert(json.response.error_message);
               	     		} else {
               	        		this.options.onError(json);
                    		}
                  		}
                	} else {
                		this.options.onComplete();
                	}
            	  }.bind(this)}).send();
            
        	}.bind(this))
        	
		}
		
		/*********************************************************
			Cancel Button
		********************************************************/
		
		if(this.options.button_cancel == true) {
			this.button_cancel = new Element(
				'input',{
					'id':'oform-button-cancel-'+this.options.form_id,
					'class':this.options.button_cancel_class,
					'type':'button','value':this.options.button_cancel_text,
					'onclick':this.options.button_cancel_action
				}
			);
			
			if(this.options['btn-position'] == 'right'){
				this.button_cancel.setStyles({'float':'right'});
			} else {
				this.button_cancel.setStyles({'float':'left'});
			}
			
		}
		
		/*********************************************************
			Submit Button
		********************************************************/
		
		this.error_container = new Element('div',{'class':'oform-error-container ogrid-outline'});
		this.error_container.setStyles({'visibility':'hidden','display':'none'});
		
		this.success_container = new Element('div',{'class':'oform-success-container ogrid-outline'});
		this.success_container.setStyles({'visibility':'hidden','display':'none'});
		
		if(this.options.button != false) {
		
			this.options.button.addClass('submit-btn');
			this.options.button.addClass(this.options.button_class);
			
			this.options.button.addEvent('click',function(){
				//hide submit button and replace with loader
				
				this.options.button.fade('out');
				this.loader = new Element('img', {'src':this.options['loader_img']});
				this.loader.setStyles({'float':'right','font-size':'10px'});
				this.loader.inject(this.form).fade('in');
	            var data =  '';
	            if(this.options.button2) data = data + '&thecoolsubmitbutton=button2';
	            for(var i=0;i<this.elements.length;++i){ data = data + '&' + this.elements[i].name + '=' + this.elements[i].getProperty('value'); }
	            this.request.removeEvents();
	            
	            this.request.setOptions({'evalScripts':this.options.responseEvalScripts,'data':data,'onComplete':function(response){
					this.loader.destroy();
					this.options.button.fade('in');
					if(this.options['process_response']){
						var json = JSON.decode(response);
						this.elements.each(function(el){el.throwError(false);});
						if((json.response.ERROR || json.response.error) && json.response.error != 'false'){
							this.error_container.setStyles({'visibility':'visible','display':'block'});
							this.error_container.set('html',json.response.ERROR_MESSAGE);
							if(json.response.ERROR_MESSAGE == 'redirect'){ window.location = json.response.URL; }
							for(var i=0;i<this.elements.length;++i){ 
								
								for(var j=0;j<json.response.ERROR_ARRAY.length;++j){ 
									if( this.elements[i].options.name == json.response.ERROR_ARRAY[j] ){ 
										this.elements[i].throwError(true,json.response.ERROR_MESSAGE_ARRAY[j]); 
									}	
								}
							}
						} else { 
							this.success_container.setStyles({'visibility':'visible','display':'block'});
							this.success_container.set('html',json.response.SUCCESS_MESSAGE);
							this.error_container.setStyles({'visibility':'visible','display':'none'});
							this.options.onComplete(json); 
						}			
	                } else {
	                	this.options.onComplete(responsepage);
	                }
	            }.bind(this)}).send();
	        }.bind(this))
		}        
		
		
		if(this.options.form_data.length != 0){	this.autoGenerateForm(); }
		
    },
    
    addElement: function(el,section){
    	
        this.elements[this.elements.length] = el;
        if(!section){ this.sections[0][this.sections[0].length] = el  } else { this.section[section][this.sections[section].length] = el; }
		
		//set label position (relative or absolute) based on value of label-display
		if(this.options['label-display'] == 'inside'){
			var label_position = 'absolute';
		} else if(this.options['label-display'] == 'outside'){
			var label_position = 'relative';
		} else {
			var label_position = this.options['label-position']
		}
		
		try{
			el.addEvent('keypress',function(e){
				if(e.code == 13){ e.preventDefault(); this.options.button.fireEvent('click'); }
			}.bind(this));
		} catch(err){
		
		}

    },
    	
    inject: function(el,inject){
        
        this.form = new Element('form',{'class':this.options.class_list,'id':this.options.id});
        this.form.setStyles({'display':'block','width':this.options['width']});
        this.form.inject(el);
        this.error_container.inject(this.form);
        this.success_container.inject(this.form);
        if(inject != false){
			for(var i=0;i<this.elements.length;++i){
				this.elements[i].inject(this.form);
				if(this.options.orientation == 'vertical'){
					this.br.clone().inject(this.form);
				}
			}
        }
        
        this.options.button_label = new Element('label',{'class':'btn-label ' + this.options.label_class});
        this.options.button_label.set('html','&nbsp;');
        this.options.button_label.inject(this.form);
        
        this.options.button.inject(this.form);
        
        this.br.clone().inject(this.form);
        
    },
    
    reset: function(){
    	for(var i=0;i<this.elements.length;++i){ this.elements[i].setProperty('value',''); }
    	this.elements[0].text_input.focus();
    },
    
    autoGenerateForm: function(){
    	this.sections = [];
    	
    	for(var i=0;i<this.options.form_data.length;++i){
    	
    		for(var j=0;j<this.options.form_data[i].length;++j){
    			
    			
    		}
    	
    	}
    
    },
    
    buildMetaFields: function(meta_data,defaults){
    	
    	this.meta_fields = [];
    	
    	for(var i=0;i<meta_data.length;++i){
    		
    		if(meta_data[i].type == 'offile'){
				this.meta_fields[this.meta_fields.length] = new OFFile(meta_data[i]);
				this.addElement(this.meta_fields[this.meta_fields.length-1]);
			} else if(meta_data[i].type == 'date'){
				
				try{meta_data[i].value = defaults[(meta_data[i].name).toUpperCase()]; } catch(err) { }
				this.meta_fields[this.meta_fields.length] = new OFDate(meta_data[i]);
				this.addElement(this.meta_fields[this.meta_fields.length-1]);
			
			} else if(meta_data[i].type == 'checkbox'){

				if(defaults[(meta_data[i].name).toUpperCase()] != undefined){
					meta_data[i].value = defaults[(meta_data[i].name).toUpperCase()];
					if(meta_data[i].value == 'true'){ meta_data[i].checked = true; }
				}
				
				this.meta_fields[this.meta_fields.length] = new OFCheck(meta_data[i]);
				this.addElement(this.meta_fields[this.meta_fields.length-1]);
			
			} else if(meta_data[i].type == 'select'){

				if(defaults[(meta_data[i].name).toUpperCase()] != undefined){
					meta_data[i].value = defaults[(meta_data[i].name).toUpperCase()];
					
				}
				
				this.meta_fields[this.meta_fields.length] = new OFSelect(meta_data[i]);
				this.addElement(this.meta_fields[this.meta_fields.length-1]);
			
			
			} else if(meta_data[i].type == 'hidden'){

				if(defaults[(meta_data[i].name).toUpperCase()] != undefined){
					meta_data[i].value = defaults[(meta_data[i].name).toUpperCase()];
				}
				
				this.meta_fields[this.meta_fields.length] = new OFHidden(meta_data[i]);
				this.addElement(this.meta_fields[this.meta_fields.length-1]);
			
			} else if(meta_data[i].type == 'none') {
				// do nothing
			
			} else {
				try{meta_data[i].value = defaults[(meta_data[i].name).toUpperCase()]; } catch(err) { }
				this.meta_fields[this.meta_fields.length] = new OFText(meta_data[i]);
				this.addElement(this.meta_fields[this.meta_fields.length-1]);
			}
    		
    		
    	}
    	
    }
});
/****************************************************
	
	File: /javascript1/forms/select.js
	Authors: Nate Obray, Ben Oman
	Copyright: Advent Creative
	
***************************************************/

OFSelect = new Class({
    Implements: Options,
    
    options:{

        'default_value':'Select&nbsp;One',
        'blur':$empty,
        'change':$empty,
        'name':'',
        'label':'',
        'labels':[],
        'values':[],
        'value':'',
        'class_names':[],
        'arrow':false,
        'input_class':'ogrid-3-5-padding ogrid-float',
		'label_class':'ogrid-2-5-padding ogrid-float',
        'content_part_id':'',
		'field_id':'',
		'validate':true,
		'feed_from':0,
		'feed_to':0,
		'dependents':'',
		'input_wrapper_class':'',
		'form_from_db':false
    },
    
    initialize: function(options){
        this.setOptions(options);
		
		window.select_index += 1;
		
        if(this.options.input_class == ''){ this.options.input_class = 'ogrid-3-5-padding ogrid-float'; }
    	if(this.options.label_class == ''){ this.options.label_class = 'ogrid-2-5-padding ogrid-float'; }
    	
        /*******************************************
        	SET VARIABLES
        *******************************************/
        
        this.isOpen = false;
        this.current_index = 0;
        this.value = this.options.value;
        this.name = this.options.name;
        this.has_focus = false;
        this.is_mouse_down_in_items = false;
        this.feed_from = this.options.feed_from;
		this.feed_to = this.options.feed_to;
		this.selected_index = 0;
		this.options.dependents_list = new Array();
        if(this.options.dependents != "") { this.options.dependents_list = this.options.dependents.split(","); }
		
		/* use 'select-wrapper' class to fix ie7 z-index bug where options container appears beneath form elements below it on the page */
        this.select_container = new Element('div',{'class':'input-wrapper select-wrapper ogrid-self-clear ' + this.options.input_wrapper_class,'id':'element-container-'+this.options.field_id}).setStyles({'z-index':(5020-window.select_index)});
        
         /*******************************************
        	SELECT BOX
        *******************************************/
        
        //create select box
        this.select = new Element('div',{'class':'select ' + this.options.input_class});
        this.select.setStyles({'position':'relative'});
        this.select.set('html','<span id="selectlabel'+this.options.field_id+'">'+this.options.value+'</span>');
        this.select.addEvent('click',function(){
            if(this.isOpen){
                this.items_container.setStyles({'display':'none','top':this.select.getCoordinates().height});
                this.isOpen = false;
            } else {
                this.items_container.setStyles({'display':'block','top':this.select.getCoordinates().height,'min-width':this.options.width});
                this.isOpen = true;
            }
            this.select_input.focus();
        }.bind(this));
        
         /*******************************************
        	LABEL
        *******************************************/
        
        this.select_label = new Element('label',{'class':'select-label ' + this.options.label_class});
        if(this.options.label != ''){ this.select_label.set('html',this.options.label); } 
        
        
         /*******************************************
        	Dropdown Icon
        *******************************************/
        
		this.dropdown_icon = new Element('div',{'class':'dropdown-icon'});
		this.dropdown_icon.inject(this.select);
        
         /*******************************************
        	INPUT
        *******************************************/
        
        //select input (allows us to call onBlur and onFocus
        this.select_input = new Element('input',{'type':'text','value':this.value});
        this.select_input.setStyles({'position':'absolute','left':-5000,'height':1,'width':1,'padding':0,'margin':0,'border':0,'z-index':10000});
        this.select_input.inject(this.select);
        this.select_input.addEvent('keydown',function(e){
            if(e.key == 'down'){
                ++this.current_index;
                if(this.current_index > this.items.length){
                    this.current_index = 1;
                }
                this.items[this.current_index-1].fireEvent('mousedown');
            } else if(e.key == 'up'){
                --this.current_index;
                if(this.current_index - 1 < 0){
                    this.current_index = this.items.length;
                }
                this.items[this.current_index-1].fireEvent('mousedown');
            }
        }.bind(this));
        this.select_input.addEvent('focus',function(){
            this.has_focus = true;
            this.select.setStyles({'background-color':this.options['highlight-color']});
        }.bind(this));
        this.select_input.addEvent('blur',function(){
			if(this.is_mouse_down_in_items == false){
				this.has_focus = false;
				this.items_container.setStyles({'display':'none','top':this.select.getCoordinates().height});
				this.isOpen = false;
				if(this.options.form_from_db){ this.oformValidate(); } else { this.options.blur(this.getProperty('value')); }
			}
        }.bind(this));
        
        //Handle Items
        this.items = [];
        this.items_container = new Element('div',{'class':'options-container'});
        this.items_container.setStyles({'position':'absolute','left':0,'display':'none','background-color':this.options.background_color,'z-index':4000,'height':this.options.options_container_height,'width':200,'overflow-y':'scroll'});
		this.items_container.addEvent('mousedown',function(){ this.is_mouse_down_in_items = true; }.bind(this));
        this.items_container.addEvent('mouseup',function(){
        	this.is_mouse_down_in_items = false;
        	this.select_input.focus();
        }.bind(this));
        this.items_container.inject(this.select);
        for(var i=0;i<this.options.labels.length;++i){ this.addOption(this.options.labels[i],this.options.values[i]); }
        
        // error elements
        this.error_icon = new Element('div',{'class':'otext-input-error-icon'});
        this.error_icon.setStyles({'visibility':'hidden','display':'none'});
        this.error_message = new Element('div',{'class':'otext-input-error-message ' + this.options.input_class});
        this.error_message.set(this.options.error_message);
        
        this.throwError(false);
        
    },
    
    /********************************************
		Handle Errors
	********************************************/
    
    throwError: function(is_error,msg){
    	if(is_error){
    		this.error_icon.setStyles({'visibility':'visible','display':'block'});
    		var parent_coordinates = this.select.getParent().getCoordinates();
	    	var input_coordinates = this.select.getCoordinates();
	    	if(this.original_width == undefined){ this.original_width = input_coordinates.width; }
	    	var icon_coordinates = this.error_icon.getCoordinates();
	    	this.error_icon.setStyles({'right':0,'top':input_coordinates.top-parent_coordinates.top+(input_coordinates.height/2-icon_coordinates.height/2)});
	    	this.error_icon.removeClass('error-false');this.error_icon.addClass('error-true');this.select_container.addClass('oform-error');
	    	var padding = this.select_container.getCoordinates().width * .02;
	    	if(input_coordinates.width >= this.original_width ){ this.select.setStyles({'width':input_coordinates.width-icon_coordinates.width-padding-12,'margin-right':icon_coordinates.width+5}); }
	    	var input_coordinates = this.select.getCoordinates();
	    	this.error_message.set('html',msg);
	    	this.error_message.setStyles({'visibility':'visible','display':'block','width':input_coordinates.width,'margin-right':icon_coordinates.width+7});
	    	//this.error_message.setStyles({'visibility':'visible','display':'block','clear':'both'});
    	} else {
    		this.error_icon.removeClass('error-true');this.error_icon.addClass('error-false');this.select_container.removeClass('oform-error');
    		//this.error_icon.setStyles({'visibility':'hidden','display':'none'});
    		this.error_message.setStyles({'visibility':'hidden','display':'none'});
    		//this.text_input.setStyles({'width':this.input_width-padding-5});
    	}
    },
    
    inject: function(el){
    	
    	
    	this.select_container.inject(el);
    	
    	
        if(this.options.label != ''){ this.select_label.inject(this.select_container); }
        this.select.inject(this.select_container);
        
        for(var i=0;i<this.items.length;++i){ 
        	if(this.items[i].value == this.options.value){ 
				
        		var fn = function(i){
               		this.setItem(this.options,this.items[i]);
	        	}
	        	
	        	
	        	fn.delay(1000,this,i);

        	
        	} 
        }
        
        this.error_icon.inject(this.select_container);
		this.error_message.inject(this.select_container);
		try{ this.setDefaultValue.delay(500,this); } catch (err){ alert(err); }
		
		var select_coordinates = this.select.getCoordinates();
		var drop_coordinates = this.dropdown_icon.getCoordinates();
		
		this.dropdown_icon.setStyles({'position':'absolute','right':drop_coordinates.width/2,'top':select_coordinates.height/2-drop_coordinates.height/2});
		
		try{ this.items_container.setStyles({'width':select_coordinates.width-2}); } catch(err) {  }
		
		
    },
    
    setDefaultValue: function(){ this.items.each(function(el,i){ if(el.value == this.options.value){ el.fireEvent('mousedown'); } }.bind(this)); },
            
    addOption: function(label,value,level){
    	
    	level = typeof(level) != 'undefined' ? level : 0;
    	var padding_left = level*5+5;
        this.items[this.items.length] = new Element('div',{'class':'item'});
        this.items[this.items.length-1].setStyles({'cursor':'pointer'});
        if(this.options.class_names.length != 0){ this.items[this.items.length-1].addClass(this.options.class_names[this.items.length-1]); }
        this.items[this.items.length-1].value = value;
        this.items[this.items.length-1].label = label;
        this.items[this.items.length-1].set('html',label);
        this.items[this.items.length-1].inject(this.items_container);
        
        this.items[this.items.length-1].addEvent('mousedown',this.setItem.pass([this.options,this.items[this.items.length-1]],this));
        
         this.items[this.items.length-1].addEvent('mouseup',function(){
        	//this.items_container.setStyles({'display':'none','top':this.select.getCoordinates().height});
			//this.isOpen = false;
        }.bind(this));
        
    },
    
    setItem: function(options,obj){
    	
    	this.select.getFirst().set('text',obj.label);
        this.select.getFirst().index = obj.index;
        this.select.getFirst().getNext().setProperty('value',obj.value);
        if(options.field_id != '') {
			window['signup_first_name'+options.field_id].select_input.value = obj.value;
			window['signup_first_name'+options.field_id].value = obj.value;
		}
		
		if(options.feed_to != 0) {
			window['signup_first_name'+options.feed_to].ajaxlyOperation(options.feed_from,obj.value, options.field_id);
		}
	
		for(var z = 0; z<options.dependents_list.length; z++) {
			window['dependent_fn_'+options.dependents_list[z]](obj.value);
		}
		this.select_input.setProperty('value', obj.value);
		
		this.options.change(obj.value);
    },
    
    clear: function(){
    	for(var i=0;i<this.items.length;++i){ this.items[i].destroy(); }
    	this.items = [];
    	
    },
    
    getFeedFrom: function() {
		return this.options.feed_from;
	},
	
	ajaxlyOperation: function(parent_item_id, value, parent_field_id){
		// Used for nifty country -> state -> county ajax calls.
		
		if(parent_item_id != "") {
		var url = '/cmd/owidgets/getHTML/Oform/?content_part_id=' + this.options.content_part_id + '&do=getFieldValues&feed_from=' + parent_item_id + '&field_id=' + this.options.field_id+'&parent_field_id='+parent_field_id;
				var data = 'field_data=' + value;
				this.request = new Request({'url':url,'method':'post'});
				this.request.removeEvents();
				this.clear();
				if(this.select_input.value == '') {
					this.value=this.select_input.value= '';
				} else {
					this.value = this.select_input.value;
				}
				document.getElementById('selectlabel'+this.options.field_id).innerHTML = '';
				
            	this.request.setOptions({'data':data,'onComplete':function(response){	
					var json = JSON.decode(response);
					this.options.feed_from = json.feed_from;
                	for(i = 0; i < json.listvalues.length; i++) {
						this.addOption(json.listvalues[i].name,json.listvalues[i].value);
					}
					try{ this.setDefaultValue.delay(20,this); } catch (err){ alert(err); }
            	}.bind(this)}).send();	
		}
		
	},
    
    addEvent: $empty,
    
    getProperty: function(property){
        if(property == 'value'){ return this.select_input.getProperty('value'); }
    },
    
    clear: function(){
    	this.items_container.set('html',''); 
    	this.items = [];
    },
    
    oformValidate: function(){
    	if(this.value != null && this.options.validate) {
			var url = '/cmd/owidgets/getHTML/Oform/?content_part_id=' + this.options.content_part_id + '&do=validateField&field_id=' + this.options.field_id;
			var data = 'field_data=' + this.value;
			this.request = new Request({'url':url,'method':'post'});
			this.request.removeEvents();
			this.request.setOptions({'data':data,'onComplete':function(response){	
				var json = JSON.decode(response);
				if(json.response.error == 'false' || json.response.error == false){
					this.throwError(false);
				} else {
					this.throwError(true,json.response.error_message);
				}
				
			}.bind(this)}).send();	
		}
		this.options.blur(this.options.content_part_id, this.options.field_id, encodeURIComponent(this.select_input.getProperty('value')));
    }
    
});





OFDateBox = new Class({
	Implements: Options,
	
	options:{
		'month':new Date().getMonth()+1,
		'year':new Date().getFullYear(),
		'onSelect':$empty,
		'position':'absolute'
	},
	
	initialize: function(btn,options){
		this.setOptions(options);
		this.btn = btn;
		this.is_open = false;
		
		this.month = this.options.month;
		this.year = this.options.year;
		
		this.btn.addEvent('click',function(){
			this.toggle(this.month,this.year);
		}.bind(this))
	},
	
	createBox: function(month,year){
		var btn_coordinates = this.btn.getCoordinates();
		
		this.month = month;
		this.year = year;
		
		this.days = [];
		this.months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
		this.container = new Element('div',{'class':'of-date-box'});
		this.container.inject($(document.body));
		
		this.container.setStyles({'padding':5,'position':this.options.position,'left':btn_coordinates.left + btn_coordinates.width + 7,'top':btn_coordinates.top,'width':140,'background-color':'#fff','border':'1px solid #c5c5c5','box-shadow':'0px 0px 7px #000','z-index':12000});
		
		var days = this.getDaysInMonth(month-1,year);
		
		var date = new Date(); date.setFullYear(year); date.setMonth(month-1);
		
		date.setDate(1);
		
		this.header = new Element('div',{'class':'of-date-box-header'});
		this.previous_month = new Element('div',{'class':'of-date-box-previous'});
		this.previous_month.set('html','<');
		this.previous_month.setStyles({'float':'left','padding':5,'cursor':'pointer'});
		
		this.previous_month.addEvent('click',function(){
			this.toggle();
			if(this.month == 1){ this.toggle(12,this.year-1); } else { this.toggle(this.month-1,this.year); }
		}.bind(this));
		
		this.current_month = new Element('div',{'class':'of-date-box-current-month'});
		this.current_month.set('html',this.months[month-1] + ' ' + this.year);
		this.current_month.setStyles({'float':'left','width':95,'text-align':'center','padding':5})
		this.next_month = new Element('div',{'class':'of-date-box-next'});
		this.next_month.set('html','>');
		this.next_month.setStyles({'float':'left','padding':5,'cursor':'pointer'});
		
		this.next_month.addEvent('click',function(){
			this.toggle();
			if(this.month == 12){ this.toggle(1,this.year+1); } else { this.toggle(this.month+1,this.year); }
		}.bind(this));
		
		this.header.inject(this.container);
		this.previous_month.inject(this.header);
		this.current_month.inject(this.header);
		this.next_month.inject(this.header);
		
		this.createDayBox('S',false);
		this.createDayBox('M',false);
		this.createDayBox('T',false);
		this.createDayBox('W',false);
		this.createDayBox('T',false);
		this.createDayBox('F',false);
		this.createDayBox('S',false);
		
		for(var j=0;j<date.getDay();++j){ this.createDayBox('',false); }
		
		for(var i=0;i<days;++i){ date.setDate(i); this.createDayBox(i+1,true); }
		
	},
	
	toggle: function(month,year){
		if(this.is_open){ this.container.destroy();this.is_open = false; } else { this.createBox(month,year);this.is_open = true;	}
	},
	
	createDayBox: function(html,create_events){
		this.days[this.days.length] = new Element('div',{'class':'of-date-box-day'});
		var day = this.days[this.days.length-1];
		day.set('html',html);
		day.setStyles({'float':'left','width':20,'height':10,'outline':'1px solid #f5f5f5','text-align':'center','padding-top':5,'padding-bottom':5,'cursor':'pointer'})
		day.inject(this.container);
		if(create_events){
			day.addEvent('click',function(){
				this.value = this.month + '/' + html + '/' +  this.year;
				this.options.onSelect(this.value);
				this.toggle();
			}.bind(this))
			
			day.addEvent('mouseenter',function(){ day.setStyles({'color':'#000','outline':'1px solid black'}); }.bind(this));
			day.addEvent('mouseleave',function(){ day.setStyles({'color':'#000','outline':'1px solid #f5f5f5'}); }.bind(this));
		}
		this.days[this.days.length-1]
	},
	
	getDaysInMonth: function(month, year){ return 32 - new Date(year,month,32).getDate(); }
})


OFDate = new Class({
    Implements: Options,
        
    options: {
        'selector_id':'date',
        'timePicker':false,
        'format':'m/d/Y h:i A',
        'width':137,
        'label':'',
        'name':'',
        'value':'',
        'onClick':$empty,
		'blur':$empty,
        'input_id':'',
        'input_class':'date-input',
		'field_id':'',
		'content_part_id':'',
		'validate':true,
		'class_names':'',
		'input_class':'ogrid-3-5 ogrid-float',
		'label_class':'ogrid-2-5-padding ogrid-float',
		'position':'absolute'
    },
    
    initialize: function(options){
        this.setOptions(options);
        if(this.options.input_class == ''){ this.options.input_class = 'ogrid-3-5 ogrid-float'; }
    	if(this.options.label_class == ''){ this.options.label_class = 'ogrid-2-5-padding ogrid-float'; }
        this.type = 'date';
        this.name = this.options.name;
        this.icon_set = false;
        
        this.date_picker = new Element('div',{'class':'date-picker'});
        //this.date_picker.setStyles({'float':'left'})
        
        this.date_label = new Element('label');
        if(this.options.label != ''){
            this.date_label = new Element('label',{'class':'date-label ' + this.options.label_class});
            this.date_label.set('html',this.options.label);
            //this.date_label.setStyles({'float':'left'});
            this.date_label.inject(this.date_picker);
        }
        
        this.date_input = new Element('input',{'id':this.options.input_id,'type':'text','class':'otext-input ' + this.options.input_class,'value':this.options.value});
        this.date_input.inject(this.date_picker);
        
        this.date_icon = new Element('div');
        this.date_icon.setStyles({'display':'none'});
        this.date_icon.inject(this.date_picker);
		
         // error elements
        this.error_icon = new Element('div',{'class':'otext-input-error-icon'});
        this.error_icon.setStyles({'visibility':'hidden','display':'none'});
        this.error_message = new Element('div',{'class':'otext-input-error-message '});
        this.error_message.set(this.options.error_message);
        
        this.date_select = new OFDateBox(this.date_icon,{'position':this.options.position,'onSelect':function(value){
        	this.date_input.setProperty('value',value);
        }.bind(this)});
    },
    
    throwError: function(is_error,msg){
    	this.error_icon.setStyles({'visibility':'visible','display':'block'});
    	var parent_coordinates = this.container.getCoordinates();
    	var input_coordinates = this.date_input.getCoordinates();
    	var icon_coordinates = this.error_icon.getCoordinates();
    	if(this.original_width == undefined){ this.original_width = input_coordinates.width; }
    	this.error_icon.setStyles({'right':0,'top':input_coordinates.top-parent_coordinates.top+(input_coordinates.height/2-icon_coordinates.height/2)});
    	if(is_error){
    		this.error_icon.removeClass('error-false');this.error_icon.addClass('error-true');this.container.addClass('oform-error');
	    	var padding = 1;
	    	if(input_coordinates.width >= this.original_width ){  this.date_input.setStyles({'width':input_coordinates.width-icon_coordinates.width-padding-5,'margin-right':icon_coordinates.width+5}); }
	    	var input_coordinates = this.date_input.getCoordinates();
	    	this.error_message.set('html',msg);
	    	this.error_message.setStyles({'visibility':'visible','display':'block','width':input_coordinates.width,'margin-right':icon_coordinates.width+7,'margin-left':parent_coordinates.width-(icon_coordinates.width+7+input_coordinates.width)});
    	} else {
    		
    		var padding = 1;
	    	this.error_icon.setStyles({'visibility':'visible','display':'block'});
	    	this.error_icon.removeClass('error-true');this.error_icon.addClass('error-false');this.container.removeClass('oform-error');
	    	//if(input_coordinates.width >= this.original_width ){ this.date_input.setStyles({'width':input_coordinates.width-icon_coordinates.width-padding-10}); }
    		this.error_message.setStyles({'visibility':'hidden','display':'none'});
    	}
    },
    
    inject: function(el){
		this.container = this.container = new Element('div',{'class':'input-wrapper ogrid-self-clear','id':'element-container-'+this.options.field_id});
		this.container.addClass(this.options.class_name);
		this.container.inject(el);
        this.date_picker.inject(this.container);
		this.date_input.addClass(this.options.input_class);
		this.error_icon.inject(this.container);
		this.error_message.inject(this.container);
        this.date_input.addEvent('blur',function(){ this.throwError(false); }.bind(this));
		if(this.icon_set == false){ this.setIcon(); this.icon_set = true; }
    },
    
    setIcon: function(){
    
    	var input_coordinates = this.date_input.getCoordinates();
    	this.date_icon.setStyles({'float':'left','display':'block','width':input_coordinates.height-4,'height':input_coordinates.height-4-4,'background-color':'#e5e5e5','color':'#c5c5c5','padding-top':4,'margin-top':3,'margin-left':5,'cursor':'pointer'});
    	this.date_number = new Element('div',{'class':'of-date-box-day-number'});
    	this.date_number.inject(this.date_icon);
    	this.date_number.set('html',new Date().getDate());
    	this.date_number.setStyles({'with':input_coordinates.height-2-4,'margin':1,'height':input_coordinates.height-6-4,'background-color':'#fff','text-align':'center','font-weight':'bold','font-size':14,'cursor':'pointer'});
        var padding = this.container.getCoordinates().width * .02;
        var icon_coordinates = this.date_icon.getCoordinates();
        this.date_input.setStyles({'float':'left','width':input_coordinates.width-icon_coordinates.width-padding-9});
    	
    	this.date_icon.addEvent('mouseenter',function(){ this.date_icon.setStyles({'background-color':'#000','color':'#000'}); }.bind(this));
    	this.date_icon.addEvent('mouseleave',function(){ this.date_icon.setStyles({'background-color':'#e5e5e5','color':'#c5c5c5'}); }.bind(this));
    	
    },
    
    addEvent: $empty,
    
    getProperty: function(property){
        if(property == 'value'){ return this.date_input.getProperty('value'); }
    }
});

OFCheck = new Class({
    Implements: Options,
    
    options: {
        'class':'',
        'checked':false,
        'height':9,
        'width':9,
        'check-color':'#41e011',
        'label':'',
        'name':'default_check',
		'content_part_id':'',
		'field_id':'',
		'validate':true,
		'input_wrapper_class':'',
		'form_from_db':false,
		'input_class':'ogrid-3-5-padding ogrid-float',
		'label_class':'ogrid-2-5-padding ogrid-float',
		'click':$empty
    },
    
    initialize: function(options){
        this.setOptions(options);
        if(this.options.input_class == ''){ this.options.input_class = 'ogrid-3-5-padding ogrid-float'; }
    	if(this.options.label_class == ''){ this.options.label_class = 'ogrid-2-5-padding ogrid-float'; }
		if(this.options.checked == '1' || this.options.checked || this.options.checked == 1) { this.is_checked = true; } else { this.is_checked = false;	}
        this.name = this.options.name;
        this.labeled = false;
        
        this.label = new Element('label',{'class':'ocheck-label ' + this.options.label_class});
        this.label.set('html','&nbsp;');
        this.label.addEvent('click',function(){	this.checkbox.fireEvent('click'); }.bind(this));
        
        
        this.input_container = new Element('div',{'class':'ocheck-input-container '+this.options.input_class})
        
        this.checkbox = new Element('div',{'class':'ocheck-box'});
        this.checkbox.addEvent('mouseenter',function(){ this.checkbox.setStyles({'background-color':this.options['highlight-color']}); }.bind(this));
        this.checkbox.addEvent('mouseleave',function(){ this.checkbox.setStyles({'background-color':this.options['background-color']}); }.bind(this));
        this.checkbox.addEvent('click',function(){
        	
        	
        	
        	this.options.click();
            if(this.is_checked){ 
                this.is_checked = false;
                this.check.setStyles({'display':'none'});
            } else { 
                this.is_checked = true; 
                this.check.setStyles({'display':'block'});
            }

			this.oformValidate();
        }.bind(this));
        
        this.check = new Element('div',{'class':'checkbox-check'});
        this.check.setStyles({'background-color':this.options['check-color'],'width':9,'height':9});
        this.check.inject(this.checkbox);
		
        this.check.addEvent('click',function(e){ e.stopPropagation(); this.checkbox.fireEvent.bind(this,'click'); }.bind(this));
        
		if(this.is_checked) { this.check.setStyles({'display':'block'}); } else { this.check.setStyles({'display':'none'}); }
		
		this.error_icon = new Element('div',{'class':'otext-input-error-icon'});
		this.error_icon.setStyles({'visibility':'hidden','display':'none'});
        this.error_message = new Element('div',{'class':'otext-input-error-message ' + this.options.input_class});
        this.error_message.set(this.options.error_message);
    },
    
     /********************************************
		Handle Errors
	********************************************/
    
    throwError: function(is_error,msg){
    	
    	var parent_coordinates = this.container.getCoordinates();
    	var input_coordinates = this.checkbox.getCoordinates();
    	var icon_coordinates = this.error_icon.getCoordinates();
    	this.error_icon.setStyles({'right':0,'top':input_coordinates.top-parent_coordinates.top+(input_coordinates.height/2-icon_coordinates.height/2)});
    
    	if(is_error){
    		this.error_icon.setStyles({'visibility':'visible','display':'block'});
	    	this.error_icon.removeClass('error-false');this.error_icon.addClass('error-true');this.container.addClass('oform-error');
	    	var padding = this.container.getCoordinates().width * .02;
	    	this.checkbox.setStyles({'width':input_coordinates.width-icon_coordinates.width-padding-5,'margin-right':icon_coordinates.width+5})
	    	var input_coordinates = this.text_input.getCoordinates();
	    	this.error_message.set('html',msg);
	    	this.error_message.setStyles({'visibility':'visible','display':'block','width':input_coordinates.width,'margin-right':icon_coordinates.width+7});
	    	//this.error_message.setStyles({'visibility':'visible','display':'block','clear':'both'});
    	} else {
    		this.error_icon.removeClass('error-true');this.error_icon.addClass('error-false');this.container.removeClass('oform-error');
    		this.error_message.setStyles({'visibility':'hidden','display':'none'});
    		//this.text_input.setStyles({'width':this.input_width-padding-5});
    	}
    },
        
    inject: function(el){
		this.container = new Element('div',{'class':'input-wrapper ogrid-self-clear '+this.options.input_wrapper_class,'id':'element-container-'+this.options.field_id});
		this.container.inject(el);
		this.label.inject(this.container);
		this.input_container.inject(this.container);
        this.checkbox.inject(this.input_container);
        if(this.labeled == false){ this.input_container.appendText(this.options.label); this.labeled = true; } 
		
		this.error_icon.inject(this.container);
		this.error_message.inject(this.container);
		
		this.throwError(false);
    },
    
    addEvent: function(type,fn){
	    this.check.addEvent(type,fn);
	    this.checkbox.addEvent(type,fn);
	},
    
    getProperty: function(value){
        return this.is_checked;
    },
    
    oformValidate: function(){
    	if(this.options.form_from_db){
	    	var url = '/cmd/owidgets/getHTML/Oform/?content_part_id=' + this.options.content_part_id + '&do=validateField&field_id=' + this.options.field_id;
			var data = 'field_data=' + this.is_checked;
			if(this.options.validate) {
				this.request = new Request({'url':url,'method':'post'});
				this.request.removeEvents();
	    	    this.request.setOptions({'data':data,'onComplete':function(response){	
					var json = JSON.decode(response);
					this.error_icon.setStyles({'visibility':'visible','display':'block'});
	    	    	if(json.response.error == 'false' || json.response.error == false){	this.throwError(false);	} else { this.throwError(true,json.response.error_message); }
	         	}.bind(this)}).send();
			}
		}
    }
});

/****************************************************
	
	File: /javascirpt1/forms/radio.js
	Authors: Nate Obray, Ben Oman
	Copyright: Advent Creative
	
***************************************************/

OFRadio = new Class({
    Implements: Options,
    
    options: {
        'input_wrapper_class':'',
        'checked':'',
        'height':9,
        'width':9,
        'check-color':'#41e011',
        'label':'',
        'name':'default_radio',
		'labels':[],
		'values':[],
		'extra_values':[],
		'content_part_id':'',
		'field_id':'',
		'direction':'horizontal',
		'value':'',
		'dependents':'',
		'feed_from':0,
		'feed_to':0,
		'validate':true,
		'onchange': $empty,
		'valnum':-1,
		'input_class':'ogrid-3-5-padding ogrid-float',
		'label_class':'ogrid-2-5-padding ogrid-float'
    },
    
    initialize: function(options){
		this.setOptions(options);
		if(this.options.input_class == ''){ this.options.input_class = 'ogrid-3-5-padding ogrid-float'; }
    	if(this.options.label_class == ''){ this.options.label_class = 'ogrid-2-5-padding ogrid-float'; }
        this.is_checked = this.options['checked'];
        this.name = this.options.name;
		this.val_num = -1;
		this.checkbox = new Array();
		this.check = new Array();
		this.check_label = new Array();
		this.dependents = new Array();
		if(this.options.dependents != "") {	this.dependents = this.options.dependents.split(","); }
		var checkid;
		this.value = this.options.value;
		
		this.radio_input = new Element('input',{'type':'text','id':'form-element-'+this.options.field_id,'value':this.value});
        this.radio_input.setStyles({'position':'absolute','left':-5000,'height':1,'width':1,'padding':0,'margin':0,'border':0,'z-index':10000});

		//main radio label
        this.checkbox_label = new Element('label',{'class':'oradio-label ' + this.options.label_class});
        this.checkbox_label.set('html',this.options.label);
		
		// container for all radio buttons
		this.buttoncontainer = new Element('div',{'class':'radio-container ' + this.options.input_class});
		
		
        for(var i=0;i<this.options.labels.length;++i){
			
			checkid = 'oradio-check' + this.options.field_id + i;
			// MUST HAVE A VALUE TO SET THE CURRENT CHECKED ITEM
			if(this.options.values[i] == this.options.value) this.val_num = i;
			if(this.options.extra_values[i] == '' || this.options.extra_values[i] == 'undefined') this.options.extra_values[i] = '';

			//inject checkbox
        	this.checkbox[i] = new Element('div',{'class':'oradio-button','id':'field-'+this.options.field_id+'-oradio-button-'+i});
			this.checkbox[i].setStyles({'width':this.options['width'],'height':this.options['height'],'cursor':'pointer'});
        	this.checkbox[i].inject(this.buttoncontainer);
			
			this.check[i] = new Element('div',{'class':'oradio-check','id':checkid,'style':'background-color:'+this.options['check-color']});
        	this.check[i].setStyles({'width':this.options['width'],'height':this.options['height'],'cursor':'pointer'});
			this.check[i].inject(this.checkbox[i]);
			
			//inject label
			this.check_label[i] = new Element('label',{'class':'radiobutton-label'});
        	this.check_label[i].set('html',this.options.labels[i]);
			this.check_label[i].inject(this.buttoncontainer);
			new OFHidden({'name':'extra-value-field-'+this.options.field_id+'-'+i,'id':'extra-value-field-'+this.options.field_id+'-'+i,'value':this.options.extra_values[i]}).inject(this.buttoncontainer);
			
        }
		
		// break for radio buttons container
		this.buttoncontainerbreak = new Element('div',{'class':'clear'});
		this.buttoncontainerbreak.inject(this.buttoncontainer);
		
		//loop through the recently created array of check marks and set the display to none if it's not default-selected as well as the style check color.
		this.check.each(function(el,i) {
			if(i != this.val_num){
        	    el.setStyles({'display':'none'})
        	}		
			el.setStyles({'background-color':this.options['check-color']});
		}.bind(this));
		
		//add events to radio buttons.  set the value based on the one that was just checked and clear the last button.
		this.checkbox.each(function(el,i){
			el.value = this.options.values[i];
			this.check[i].addEvent('click',function(){  el.fireEvent.bind(this,'click'); }.bind(this));
			this.check_label[i].addEvent('click',function(){ el.fireEvent('click'); }.bind(this));
        	el.addEvent('click',function(){
        		this.error_icon.setStyles({'display':'block'});
				var checkid = 'oradio-check' + this.options.field_id + this.val_num;
				if(this.val_num != -1) { document.getElementById(checkid).style.display = 'none'; }
				this.val_num = i;
				this.options.valnum = i;
				this.check[this.val_num].setStyles({'display':'block'});
				this.value = this.options.values[this.val_num];
				el.value = this.options.values[this.val_num];
				for(var z = 0; z<this.dependents.length; z++) {
					window['dependent_fn_'+this.dependents[z]](this.value);
				}
				if(this.options.feed_to != 0) {
				window['signup_first_name'+this.options.feed_to].ajaxlyOperation(this.options.feed_from,this.value,this.options.field_id);
				}
				
				if(this.options.validate) {	this.throwError(false);	}
				
				try{this.options.onchange(this);} catch(err) { } 
				
			}.bind(this));
		}.bind(this))
		
		this.error_icon = new Element('div',{'class':'otext-input-error-icon'});
		this.error_icon.setStyles({'display':'none'});
        this.error_message = new Element('div',{'class':'otext-input-error-message ' + this.options.input_class});
        this.error_message.set(this.options.error_message);
		
		
    },
    
    /********************************************
		Handle Errors
	********************************************/
    
    throwError: function(is_error,msg){
    	
    	var parent_coordinates = this.container.getCoordinates();
    	var input_coordinates = this.buttoncontainer.getCoordinates();
    	if(this.original_width == undefined){ this.original_width = input_coordinates.width; }
    	var icon_coordinates = this.error_icon.getCoordinates();
    	this.error_icon.setStyles({'right':0,'top':input_coordinates.top-parent_coordinates.top+(input_coordinates.height/2-icon_coordinates.height/2)});
    
    	if(is_error){
    		this.error_icon.setStyles({'visibility':'visible','display':'block'});
	    	this.error_icon.removeClass('error-false');this.error_icon.addClass('error-true');this.container.addClass('oform-error');
	    	var padding = this.container.getCoordinates().width * .02;
	    	if(input_coordinates.width >= this.original_width ){  this.buttoncontainer.setStyles({'width':input_coordinates.width-icon_coordinates.width-padding-10,'margin-right':icon_coordinates.width+5}); }
	    	var input_coordinates = this.buttoncontainer.getCoordinates();
	    	
	    	this.error_message.set('html',msg);
	    	this.error_message.setStyles({'visibility':'visible','display':'block','width':input_coordinates.width,'margin-right':icon_coordinates.width+7});
	    	//this.error_message.setStyles({'visibility':'visible','display':'block','clear':'both'});
    	} else {
    		this.error_icon.removeClass('error-true');this.error_icon.addClass('error-false');this.container.removeClass('oform-error');
    		this.error_message.setStyles({'visibility':'hidden','display':'none'});
    		//this.text_input.setStyles({'width':this.input_width-padding-5});
    	}
    },
    
    /********************************************
		INJECT
	********************************************/
    
    inject: function(el){
        
		this.container = new Element('div',{'class':'input-wrapper ogrid-self-clear','id':'element-container-'+this.options.field_id});
		this.container.addClass(this.options.input_wrapper_class);
		
		this.container.inject(el);
		this.checkbox_label.inject(this.container);
		this.buttoncontainer.inject(this.container);
		
		this.error_icon.inject(this.container);
		this.error_message.inject(this.container);
		
		this.throwError(false);
    },
	
    
    addEvent: function(type,fn){
	    
	},
    
    getProperty: function(value){
        return this.value;
    }
});



OProgressBar = new Class({	Implements: Options,		options:{			},		initialize: function(options){		this.setOptions(options);				this.bar_container = new Element('div',{'class':'oprogress-bar-container ogrid-1'});		this.bar_container.setStyles({'overflow':'hidden'});				this.bar = new Element('div',{'class':'oprogress-bar'});		this.bar.setStyles({'width':0});		this.bar.inject(this.bar_container);	},		inject: function(el){		this.bar_container.inject(el);	},		setProgress: function(percent,tweak){		var width = this.bar_container.getCoordinates().width-tweak;		progress_width = (width/100) * percent;				this.bar.setStyles({'width':progress_width});		this.bar.set('html','<em>'+percent+'% </em>');	},		show: function(){		this.bar_container.setStyles({'display':'block'});	},		hide: function(){		this.bar_container.setStyles({'display':'none'});	}});// obray file form elementOFFile = new Class({    Implements: Options,        'options':{        'label':'',        'blah':'blah',        'uploadSuccess':$empty,        'upload_url':'/cmd/opages/uploadContent/&requesttimeout=10000',        'extensions':'',        'name':'',        'file_name':'',        'file_ext':'',        'file_size':0,        'file_types': {},        'host_name':window.location.hostname,        'btn_text':'Upload File',        'input_class':'ogrid-3-5-padding ogrid-float',		'label_class':'ogrid-2-5-padding ogrid-float',        'max_file_size':2 * 1024 * 1024 * 1024 * 1024,        'class_name':''    },        initialize: function(options){        this.setOptions(options);        if(this.options.input_class == ''){ this.options.input_class = 'ogrid-3-5 ogrid-float'; }    	if(this.options.label_class == ''){ this.options.label_class = 'ogrid-2-5-padding ogrid-float'; }				        this.upload_target = $('upload_target');        this.json = {'response':{'server_file_name':this.options.file_name,'server_file_ext':this.options.file_ext,'file_size':this.options.file_size}};        this.load_state = 'waiting';        this.name = this.options.name;                // file input container        this.file_container = new Element('div',{'class':'input-wrapper ogrid-self-clear ofile-container'});                // file label        this.file_label = new Element('label',{'class':'ofile-label ' + this.options.label_class});        this.file_label.set('html',this.options.label);        if(this.options.label != ''){ this.file_label.inject(this.file_container); }                this.upload_status = new Element('div',{'class':'upload-status ' + this.options.input_class});        this.upload_status.inject(this.file_container);        this.upload_status.setStyles({'padding-top':2,'padding-bottom':2});                this.upload_btn = new Element('input',{'type':'button','value':this.options.btn_text,'class':'upload-button-wrapper'});        this.upload_btn.inject(this.upload_status);                this.progress_bar = new OProgressBar();        this.progress_bar.inject(this.upload_status);        this.progress_bar.hide();                this.upload_error = new Element('div',{'class':'upload-status-response error'});        this.upload_error.inject(this.upload_status);        this.upload_error.setStyles({'display':'none','font-family':'Helvetica,Arial','color':'#858585','padding':8,'font-size':12,'color':'#AA0000'});                this.upload_success = new Element('div',{'class':'upload-status-response success'});        this.upload_success.inject(this.upload_status);        this.upload_success.setStyles({'display':'none','font-family':'Helvetica,Arial','color':'#858585','padding':8,'font-size':12,'color':'#00AA00'});                 // error elements        this.error_icon = new Element('div',{'class':'otext-input-error-icon'});        this.error_icon.setStyles({'visibility':'hidden','display':'none'});        this.error_message = new Element('div',{'class':'otext-input-error-message ' + this.options.input_class});        this.error_message.set(this.options.error_message);                this.setLoadState('ready');				this.max_file_size = this.options.max_file_size/1024/1024;				// Uploader instance		this.swf = new Swiff.Uploader({			path: '/obray/config/Swiff.Uploader.swf',			///index.cfm?action=forms.uploadFile&fusebox.password=thinkbig&fusebox.load=true&fusebox.%20parse=true&fusebox.execute=true&requesttimeout=5000			url: this.options.upload_url,			verbose: true,			queued: false,			multiple: false,			method: 'post',			target: this.upload_status,			zIndex:20000,			instantStart: true,			typeFilter: this.options.file_types,			fileSizeMax: this.options.max_file_size,			onSelectSuccess: function(files) {				if (Browser.Platform.linux) window.alert('Warning: Due to a misbehaviour of Adobe Flash Player on Linux,\nthe browser will probably freeze during the upload process.\nSince you are prepared now, the upload will start right away ...');								if(files[0].name.search(/[\!@#$%^&*()+\[\]{}\\||]+/) != -1 ){					alert('Please make sure the name of your file only contains number 0-9 and letters A-Z, hyphens or spaces.');				}								this.swf.setEnabled(false);				this.setLoadState('uploading');			}.bind(this),			onSelectFail: function(files) {				alert('' + files[0].name + ' Could not upload the selected file.  Please select one less than '+(this.max_file_size)+' MB. (Error: #' + files[0].validationError + ')');			}.bind(this),			appendCookieData: false,			onQueue: this.progress.bind(this),			onFileComplete: function(file) {				if (file.response.error) {					if(this.swf.fileList[0].name.length > 18){						var file_name = this.swf.fileList[0].name.substring(0,18) + '...';					} else {						var file_name= this.swf.fileList[0].name;					}					file_name = '"' + file_name + '"'					this.upload_error.set('html','' + file_name + ' failed.');					this.try_again = new Element('span');					this.try_again.set('html',' (Try Again)');					this.try_again.setStyles({'color':'#d5d5d5'});					this.try_again.inject(this.upload_error);					this.setLoadState('error');				} else {					this.json = JSON.decode(file.response.text);										if(this.json.response.DATA.SERVERFILE.length > 20){						var file_name = this.json.response.DATA.SERVERFILE.substring(0,20) + '...';					} else {						var file_name=this.json.response.DATA.SERVERFILE;					}					file_name = '"' + file_name + '"';										this.upload_success.set('html','' + file_name + ' (' + (this.json.response.DATA.FILESIZE/1024/1024).toFixed(2) + ' MB)' );					this.setLoadState('finished');					this.options.uploadSuccess(this.json.response);										try{ this.omdia_id = this.json.response.DATA.OMEDIA_ID; } catch(err) {}														}	 				file.remove();				this.swf.setEnabled(true);			}.bind(this),			onComplete: function() {			}		});				// Button state		this.upload_btn.addEvents({			click: function() {				return false;			},			mouseenter: function() {				this.upload_btn.addClass('hover');				this.swf.reposition();			}.bind(this),			mouseleave: function() {				this.removeClass('hover');				this.blur();			},			mousedown: function() {				this.focus();			}		});                		    },        throwError: function(is_error,msg){    			this.error_icon.setStyles({'visibility':'visible','display':'block'});    	var parent_coordinates = this.file_container.getCoordinates();    	var input_coordinates = this.upload_btn.getCoordinates();    	var icon_coordinates = this.error_icon.getCoordinates();    	if(this.original_width == undefined){ this.original_width = input_coordinates.width; }    	this.error_icon.setStyles({'right':0,'top':input_coordinates.top-parent_coordinates.top+(input_coordinates.height/2-icon_coordinates.height/2)});    	    	if(is_error){	    	this.error_icon.removeClass('error-false');this.error_icon.addClass('error-true');	    	var padding = this.file_container.getCoordinates().width * .02;	    	//if(input_coordinates.width >= this.original_width ){ this.upload_btn.setStyles({'width':input_coordinates.width-icon_coordinates.width-padding-5,'margin-right':icon_coordinates.width+5}); }	    	var input_coordinates = this.upload_btn.getCoordinates();	    	this.error_message.set('html',msg);	    	this.error_message.setStyles({'visibility':'visible','display':'block','width':input_coordinates.width,'margin-right':icon_coordinates.width+7});	    	//this.error_message.setStyles({'visibility':'visible','display':'block','clear':'both'});    	} else {    		this.error_icon.removeClass('error-true');this.error_icon.addClass('error-false');    		this.error_message.setStyles({'visibility':'hidden','display':'none'});    		//this.text_input.setStyles({'width':this.input_width-padding-5});    	}    	    },        progress: function(){    	if (!this.swf.uploading) return;			var size = Swiff.Uploader.formatUnit(this.swf.size, 'b');			//link.set('html', '<span class="small">' + swf.percentLoaded + '% of ' + size + '</span>');			this.progress_bar.setProgress(this.swf.percentLoaded,13);    },        setLoadState: function(state){        if(state == 'uploading'){        	this.upload_btn.setStyles({'display':'none'});        	this.upload_success.setStyles({'display':'none'});        	this.upload_error.setStyles({'display':'none'});        	this.progress_bar.show();        } else if (state == 'finished'){        	this.upload_btn.setStyles({'display':'none'});        	this.upload_success.setStyles({'display':'block'});        	this.upload_error.setStyles({'display':'none'});        	this.progress_bar.hide();        } else if (state == 'error'){        	this.upload_btn.setStyles({'display':'none'});        	this.upload_success.setStyles({'display':'none'});        	this.upload_error.setStyles({'display':'block'});        	this.progress_bar.hide();        } else if (state == 'ready'){			this.upload_btn.setStyles({'display':'block'});        	this.upload_success.setStyles({'display':'none'});        	this.upload_error.setStyles({'display':'none'});        	this.progress_bar.hide();        }    },        getProperty: function(property){        if(this.json != ''){        	        	if(!this.json.response.DATA){ this.json.response.DATA = {}; }        	if(!this.json.response.DATA.SERVERFILENAME){ this.json.response.DATA.SERVERFILENAME = ""; this.json.response.DATA.SERVERFILEEXT = "";  this.json.response.DATA.FILESIZE = 0;}        	var qryString = encodeURIComponent(this.json.response.DATA.SERVERFILENAME) + '&file_ext=' + encodeURIComponent(this.json.response.DATA.SERVERFILEEXT) + '&file_size=' + encodeURIComponent(this.json.response.DATA.FILESIZE)+'&full_file_name='+encodeURIComponent(this.json.response.DATA.SERVERFILE)        	try{         		qryString = qryString + '&omedia_id=' + this.json.response.DATA.OMEDIA_ID + '&omedia_file=' + this.json.response.DATA.OMEDIA_FILE + '&omedia_ext=' + this.json.response.DATA.OMEDIA_EXT;         		        	} catch(err) {  }            return qryString;        } else {            return '&file_ext=&file_size=';        }    },        inject: function(el,position){    	this.file_container.addClass(this.options.class_name);        this.file_container.inject(el,position);                this.error_icon.inject(this.file_container);        this.error_message.inject(this.file_container);                this.swf.reposition();        $$('.swiff-uploader-box').setStyles({'position':'fixed'});    },        addEvent: function(type,fn){	    	},        setLabelDisplay: $empty,        destroy: function(){    	this.swf.setEnabled(false);    	this.file_container.dispose();    	this.file_container.destroy();    	this.swf.reposition();    }});/****************************************************
	
	File: /javascirpt1/forms/text.js
	Authors: Nate Obray, Ben Oman
	Copyright: Advent Creative
	
***************************************************/

OFText = new Class({
    Implements: Options,
    
    options: {
        'label':'',
        'text-area':false,
		'type':'text',
        'blur':$empty,
        'focus':$empty,
        'name':'',
        'value':'',
		'text-area-input-height':.50,
		'text-area-background-image':'',
		'input_class':'ogrid-3-5-padding ogrid-float',
		'label_class':'ogrid-2-5-padding ogrid-float',
		'class_name':'',
		'styling':true,
		'input_wrapper_class':'',
		'error_message':'',
		'content_type':'',
		'depends_on':'',
		'form_from_db':false,
		'validate':true,
		'can_edit':true
    },
    
    initialize: function(options){
    	this.setOptions(options);
    	this.name = this.options.name;
    	if(this.options.input_class == ''){ this.options.input_class = 'ogrid-3-5-padding ogrid-float'; }
    	if(this.options.label_class == ''){ this.options.label_class = 'ogrid-2-5-padding ogrid-float'; }
    	
    	/*****************************************
    		Depends on
    	*****************************************/
    	
    	this.depends_on = new Array();
		this.depends_on[0] = '';
		if(this.options.depends_on != '') {
			this.depends_on = this.options.depends_on.split("<?>");
		}
    	
    	
    	/********************************************
    		Elements
    	********************************************/
		// hidden field class for input wrapper
		if(this.options.can_edit != true) {
			this.hidden_field_class = 'hidden-field';
		} else {
			this.hidden_field_class = '';
		}


    	// container
        if(this.options['text-area']){
			var input_class = 'input-wrapper otext-area-input-wrapper ogrid-1 ogrid-self-clear ' + this.options.input_wrapper_class;
		} else { 
			var input_class = 'input-wrapper ogrid-self-clear ' + this.options.input_wrapper_class + this.hidden_field_class;
		}
        this.container = new Element('div',{'class':input_class,'id':'element-container-'+this.options.field_id});
        
        if(this.options.styling){
        	this.container.setStyles({'width':'100%'});
		}
		
		//label
    	this.text_label = new Element('label',{'class':'otext-label ' + this.options.label_class});
    	if(this.options.show_label == false) {  this.text_label.addClass('Ohidden');  }
    	this.text_label.set('html',this.options.label);
        
        //input
        if(this.options.can_edit == true) {
	        if(this.options['text-area']){
	            this.text_input = new Element('textarea',{'class':'otext-input ' + this.options.input_class,'value':this.options.value});
	            this.text_input.set('html',this.options.value);
	        } else {
				this.text_input = new Element('input',{'type':this.options.type, 'class':'otext-input ' + this.options.input_class,'value':this.options.value});
	        }
        } else { this.text_input = new Element('input',{'type':'hidden', 'class':'otext-input','value':this.options.value}); }
        
        // error elements
        this.error_icon = new Element('div',{'class':'otext-input-error-icon'});
        this.error_icon.setStyles({'visibility':'hidden','display':'none'});
        this.error_message = new Element('div',{'class':this.options.input_class + ' otext-input-error-message'});
        this.error_message.set(this.options.error_message);
		
		this.throwError(false);
        
		/********************************************
    		Events
    	********************************************/
        
        this.text_input.addEvent('blur',function(){
        	this.parseContent();
        	this.oformValidate();
        	this.options.blur();
        }.bind(this));
        this.text_input.addEvent('focus',this.options.focus);
        
        this.input_width = 0;
		this.parseContent();
    },
    
    // allows the set of data types... parses them out into correct formats
    
    parseContent: function(){ if(this.options.content_type == 'dollar'){ this.text_input.setProperty('value',parseFloat(this.text_input.getProperty('value')).toFixed(2)); }  },
    
    /********************************************
		Handle Errors
	********************************************/
    
    throwError: function(is_error,msg){
    	if(is_error){
    		this.error_icon.setStyles({'visibility':'visible','display':'block'});
    		var parent_coordinates = this.text_input.getParent().getCoordinates();
	    	var input_coordinates = this.text_input.getCoordinates();
	    	var icon_coordinates = this.error_icon.getCoordinates();
	    	if(this.original_width == undefined){ this.original_width = input_coordinates.width; }
	    	this.error_icon.setStyles({'right':0,'top':input_coordinates.top-parent_coordinates.top+(input_coordinates.height/2-icon_coordinates.height/2)});
	    	this.error_icon.removeClass('error-false');this.error_icon.addClass('error-true');this.container.addClass('oform-error');
	    	var padding = this.container.getCoordinates().width * .02;
	    	if(input_coordinates.width >= this.original_width ){ this.text_input.setStyles({'width':input_coordinates.width-(icon_coordinates.width+padding+2+10),'margin-right':icon_coordinates.width+5}) };
	    	var input_coordinates = this.text_input.getCoordinates();
	    	this.error_message.set('html',msg);
	    	this.error_message.setStyles({'visibility':'visible','display':'block','width':input_coordinates.width,'margin-right':icon_coordinates.width+7});
	    	//this.error_message.setStyles({'visibility':'visible','display':'block','clear':'both'});
    	} else {
    		this.error_icon.removeClass('error-true');this.error_icon.addClass('error-false');this.container.removeClass('oform-error');
    		//this.error_icon.setStyles({'visibility':'hidden','display':'none'});
    		this.error_message.setStyles({'visibility':'hidden','display':'none'});
    		//this.text_input.setStyles({'width':this.input_width-padding-5});
    	}
    },
    
    /********************************************
	 	Add Events
	********************************************/
    
	addEvent: function(type,fn){
		if(!(type == "keypress" && this.options['text-area'])){
	    	this.text_input.addEvent(type,fn);
	    }
	},
	
    // get property
    getProperty: function(){ return encodeURIComponent(this.text_input.getProperty('value')); },
    
    // set property
    setProperty: function(property,value){ this.text_input.setProperty(property,value); },
    
    /********************************************
	 	Injects elements into the document
	********************************************/
    
    inject: function(el){
		this.container.inject(el);
		if(this.options.label != ''){ this.text_label.inject(this.container); }
		this.text_input.inject(this.container);
		this.error_icon.inject(this.container);
		this.error_message.inject(this.container);
		this.original_i_width = this.text_input.getCoordinates().width;
    },
    
    destroy: function(){
    	this.container.destroy();
    },
    
    /********************************************
		 Used for nifty country -> state -> county ajax calls.
	********************************************/
    
    ajaxlyOperation: function(parent_item_id, value){
		
		var where = 0;
		for(i = 0; i<this.options.values.length; i++) {
			if(value == this.options.values[i]) {
				where = i;
				break;
			}
		}
		
		if(this.options.can_edit == true) {
			this.value = this.options.optionlabels[where];
		} else {
			this.text_inputcont.set('html',this.options.optionlabels[where]);
		}
		
	},
	
	/********************************************
		Dynamically validate form against server
	********************************************/
    
    oformValidate: function(){
    	
    	if(this.options.form_from_db){
    		this.value = encodeURIComponent(this.text_input.getProperty('value'));
			if(this.value != null && this.options.validate) {
				var url = '/cmd/owidgets/getHTML/Oform/?content_part_id=' + this.options.content_part_id + '&do=validateField&field_id=' + this.options.field_id;
				var data = 'field_data=' + this.value;
				if(this.depends_on[0] != '') { data = data + '&' + window['signup_first_name'+this.depends_on[0]].name + '=' + window['signup_first_name'+this.depends_on[0]].value; }
				this.request = new Request({'url':url,'method':'post'});
				this.request.removeEvents();
            	this.request.setOptions({'data':data,'onComplete':function(response){	
					var json = JSON.decode(response);
					// handle error
                	if(json.response.error == 'false' || json.response.error == false){ this.throwError(false); } else { this.throwError(true,json.response.error_message); }
            	}.bind(this)}).send();	
			}
            this.options.blur(this.options.content_part_id, this.options.field_id, encodeURIComponent(this.text_input.getProperty('value')));
    	}
    }
});

OFHidden = new Class({
    Implements: Options,
    
    options:{
        'value':'',
        'name':'',
		'id':''
    },
    
    initialize: function(options){
        this.setOptions(options);
        this.name = this.options.name;
        
        this.hidden = new Element('input',{'id':this.options.id,'type':'hidden','value':this.options.value});
    },
    
    throwError: function(is_error,msg){
    	return;
    },
    
    getProperty: function(property){
        return encodeURIComponent(this.hidden.getProperty(property));
    },
    
    setStyles: function(){
    
    },
    
    inject: function(el){
        this.hidden.inject(el);
    },
    
    addEvent: function(type,fn){
	    this.hidden.addEvent(type,fn);
	},
    
    
    setLabelDisplay: $empty
});
OFDateFields = new Class({
    Implements: Options,
    
    options: {
        'label':'',
		'type':'text',
        'blur':$empty,
        'focus':$empty,
        'name':'',
        'value':'',
		'content_part_id':'',
		'field_id':'',
		'validate':true,
		'vmsg':true,
		'depends_on':'',
		'class_name':'',
		'input_class':'ogrid-3-5 ogrid-float',
		'label_class':'ogrid-2-5-padding ogrid-float'
    },
    
    initialize: function(options){
		this.setOptions(options);
		if(this.options.input_class == ''){ this.options.input_class = 'ogrid-3-5 ogrid-float'; }
    	if(this.options.label_class == ''){ this.options.label_class = 'ogrid-2-5-padding ogrid-float'; }
        this.name = this.options.name;       
        this.text_label = new Element('label',{'class':'otext-label ' + this.options.label_class});
        this.text_label.set('html',this.options.label);
		this.depends_on = new Array();
		this.depends_on[0] = '';
		if(this.options.depends_on != '') this.depends_on = this.options.depends_on.split("<?>");
        this.values = this.options.value.split("-");
		this.text_input = new Element('input',{'type':this.options.type, 'class':'otext-input year','value':this.values[0],'style':''});
		
		
		this.numer = new Element('input',{'class':'otext-input day','value':this.values[1],'style':'width:25px;'});
		this.denom = new Element('input',{'class':'otext-input month','value':this.values[2],'style':'width:30px;'});
		this.slash  = new Element('span',{'style':'','class':'year'});
		this.slash.set('html','/');
        
        this.text_input.addEvent('blur',function(){
			var integer = encodeURIComponent(this.text_input.getProperty('value'));
			if(integer == "") integer = ' ';
			var numerator = encodeURIComponent(this.numer.getProperty('value'));
			if(numerator == "") numerator = ' ';
			var denominator = encodeURIComponent(this.denom.getProperty('value'));
			if(denominator == "") denominator = '';
	
			this.value = integer + '-' + numerator + '-' + denominator; 
			if(this.value != null && this.options.validate) {
				var url = '/cmd/owidgets/getHTML/Oform/?content_part_id=' + this.options.content_part_id + '&do=validateField&field_id=' + this.options.field_id;
				var data = 'field_data=' + this.value;
				if(this.depends_on[0] != '') {
					data = data + '&' + window['signup_first_name'+this.depends_on[0]].name + '=' + window['signup_first_name'+this.depends_on[0]].value;
				}
				this.request = new Request({'url':url,'method':'post'});
				this.request.removeEvents();
            	this.request.setOptions({'data':data,'onComplete':function(response){	
					var json = JSON.decode(response);
                	if(json.response.error == 'false' || json.response.error == false){	this.throwError(false); } else { this.throwError(true,json.response.error_message); }
            	}.bind(this)}).send();	
			}
            this.options.blur(this.options.content_part_id, this.options.field_id, encodeURIComponent(this.text_input.getProperty('value')));
        }.bind(this).pass(this));
		this.numer.addEvent('blur',function(){
			
	
			var integer = encodeURIComponent(this.text_input.getProperty('value'));
			if(integer == "") integer = ' ';
			var numerator = encodeURIComponent(this.numer.getProperty('value'));
			if(numerator == "") numerator = ' ';
			var denominator = encodeURIComponent(this.denom.getProperty('value'));
			if(denominator == "") denominator = '';
	
			this.value = integer + '-' + numerator + '-' + denominator; 
			if(this.value != null && this.options.validate) {
				var url = '/cmd/owidgets/getHTML/Oform/?content_part_id=' + this.options.content_part_id + '&do=validateField&field_id=' + this.options.field_id;
				var data = 'field_data=' + this.value;
				if(this.depends_on[0] != '') {
					data = data + '&' + window['signup_first_name'+this.depends_on[0]].name + '=' + window['signup_first_name'+this.depends_on[0]].value;
				}
				this.request = new Request({'url':url,'method':'post'});
				this.request.removeEvents();
            	this.request.setOptions({'data':data,'onComplete':function(response){	
					var json = JSON.decode(response);
                	if(json.response.error == 'false' || json.response.error == false){ this.throwError(false); } else { this.throwError(true,json.response.error_message); }
            	}.bind(this)}).send();	
			}
            this.options.blur(this.options.content_part_id, this.options.field_id, encodeURIComponent(this.text_input.getProperty('value')));
        }.bind(this).pass(this));
		this.denom.addEvent('blur',function(){
			
	
			var integer = encodeURIComponent(this.text_input.getProperty('value'));
			if(integer == "") integer = ' ';
			var numerator = encodeURIComponent(this.numer.getProperty('value'));
			if(numerator == "") numerator = ' ';
			var denominator = encodeURIComponent(this.denom.getProperty('value'));
			if(denominator == "") denominator = '';
	
			this.value = integer + '-' + numerator + '-' + denominator; 
			
			if(this.value != null && this.options.validate) {
				var url = '/cmd/owidgets/getHTML/Oform/?content_part_id=' + this.options.content_part_id + '&do=validateField&field_id=' + this.options.field_id;
				var data = 'field_data=' + this.value;
				if(this.depends_on[0] != '') {
					data = data + '&' + window['signup_first_name'+this.depends_on[0]].name + '=' + window['signup_first_name'+this.depends_on[0]].value;
				}
				this.request = new Request({'url':url,'method':'post'});
				this.request.removeEvents();
            	this.request.setOptions({'data':data,'onComplete':function(response){	
					var json = JSON.decode(response);
                	if(json.response.error == 'false' || json.response.error == false){ this.throwError(false); } else { this.throwError(true,json.response.error_message); }
            	}.bind(this)}).send();	
			}
            this.options.blur(this.options.content_part_id, this.options.field_id, encodeURIComponent(this.text_input.getProperty('value')));
        }.bind(this).pass(this));
        this.text_input.addEvent('focus',this.options.focus);
		
		// container
		// place label and input field into a div to give us control over absolute positioning for label
        this.container = new Element('div',{'class':'input-wrapper ogrid-self-clear '+this.options.class_name+' datefields','id':'element-container-'+this.options.field_id});
		// container styles
		this.container.setStyles({
			'position':'relative'
		});
		
		//inject element and label into container
		if(this.options.label != ''){ this.text_label.inject(this.container); }
        
        // wrapping div for form fields
		this.datefields_wrapper = new Element('div',{'class':this.options.input_class+' ogrid-self-clear datefields-wrapper'});
        
		this.numer.inject(this.datefields_wrapper);
		//this.slash.inject(this.container);
		this.denom.inject(this.datefields_wrapper);
		this.text_input.inject(this.datefields_wrapper);
		
		this.datefields_wrapper.inject(this.container);
		
		// example image
		//this.example_image = new Element('div',{'class':'datefields-example'});
		//this.example_image.inject(this.container);
		
		// error elements
        this.error_icon = new Element('div',{'class':'otext-input-error-icon'});
        this.error_icon.setStyles({'visibility':'hidden','display':'none'});
        this.error_message = new Element('div',{'class':'otext-input-error-message ' + this.options.input_class});
        this.error_message.set(this.options.error_message);
    },
    
    throwError: function(is_error,msg){
    	
    	var parent_coordinates = this.container.getCoordinates();
    	var input_coordinates = this.text_input .getCoordinates();
    	var icon_coordinates = this.error_icon.getCoordinates();
    	this.error_icon.setStyles({'right':0,'top':input_coordinates.top-parent_coordinates.top+(input_coordinates.height/2-icon_coordinates.height/2)});
    	if(is_error){
    		this.error_icon.setStyles({'visibility':'visible','display':'block'});
	    	this.error_icon.removeClass('error-false');this.error_icon.addClass('error-true');this.container.addClass('oform-error');
	    	this.error_message.set('html',msg);
	    	var width = input_coordinates.width *3;
	    	this.error_message.setStyles({'visibility':'visible','display':'block','width':input_coordinates.width*3,'margin-right':icon_coordinates.width+7});
	    	//this.error_message.setStyles({'visibility':'visible','display':'block','clear':'both'});
    	} else {
    		this.error_icon.removeClass('error-true');this.error_icon.addClass('error-false');this.container.removeClass('oform-error');
    		this.error_message.setStyles({'visibility':'hidden','display':'none'});
    		//this.text_input.setStyles({'width':this.input_width-padding-5});
    	}
    },
    	
	addEvent: function(type,fn){
		if(!(type == "keypress" && this.options['text-area'])){
	    	this.text_input.addEvent(type,fn);
	    }
	},
	
    // get property
    getProperty: function(){ 
		var integer = encodeURIComponent(this.text_input.getProperty('value'));
		if(integer == "") integer = ' ';
		var numerator = encodeURIComponent(this.numer.getProperty('value'));
		if(numerator == "") numerator = ' ';
		var denominator = encodeURIComponent(this.denom.getProperty('value'));
		if(denominator == "") denominator = '';
	
		 return integer + '-' + numerator + '-' + denominator; 
		
	},
    
    // set property
    setProperty: function(property,value){ this.text_input.setProperty(property,value); },
    
    inject: function(el){
        //if(this.options.label != ''){ this.text_label.inject(el); }
        //this.text_input.inject(el);
		this.container.inject(el);
		this.error_icon.inject(this.container);
		this.error_message.inject(this.container);
    }
});
/****************************************************
	
	File: /javascirpt1/forms/dateselect.js
	Authors: Nate Obray, Ben Oman
	Copyright: Advent Creative
	
***************************************************/


OFDateSelect = new Class({
    Implements: Options,
    
    options: {
        'label':'',
		'type':'text',
        'blur':$empty,
        'focus':$empty,
        'name':'',
        'value':'',
		'content_part_id':'',
		'field_id':'',
		'validate':true,
		'vmsg':true,
		'valid_years':['2001','2002','2003','2004','2005','2006','2007','2008','2009','2010','2011','2012','2013','2014'],
		'depends_on':'',
		'select_day':'01',
		'select_month':'01',
		'select_year':'2001',
		'input_class':'ogrid-3-5-padding ogrid-outline',
		'label_class':'ogrid-2-5-padding'
    },
    
    initialize: function(options){
		this.setOptions(options);
        this.name = this.options.name;       
        this.text_label = new Element('label',{'class':'otext-label'});
        this.text_label.set('html',this.options.label);
		this.depends_on = new Array();
		this.depends_on[0] = '';
		if(this.options.depends_on != '') this.depends_on = this.options.depends_on.split("<?>");
        this.values = this.options.value.split("-");
        var vMsgId = 'input-vmsg-' + this.options.field_id;
		var vImgId = 'input-vimg-' + this.options.field_id;
		this.vMsg = new Element('div',{'id':vMsgId,'style':'','class':'input-vmsg'});
		this.vImg = new Element('div',{'id':vImgId,'style':'','class':'input-vimg'});
		this.day = new OFSelect2({
			'labels':['01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'],
			'values':['01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23','24','25','26','27','28','29','30','31'],
			'validate':false,
			'class_name':'ofdateselect_day',
			'default_value':this.values[2]
		});
		this.month = new OFSelect2({
			'labels':['January','February','March','April','May','June','July','August','September','October','November','December'],
			'values':['01','02','03','04','05','06','07','08','09','10','11','12'],
			'validate':false,
			'class_name':'ofdateselect_month',
			'default_value':this.values[1]
		});
		this.year = new OFSelect2({
			'labels':this.options.valid_years,
			'values':this.options.valid_years,
			'validate':false,
			'class_name':'ofdateselect_year',
			'default_value':this.values[0]
		});
		this.slash  = new Element('span',{'style':'','class':'fractionslash'});
		this.slash.set('html','/');
        
        this.day.addEvent('blur',function(){
			var day = encodeURIComponent(this.day.getProperty('value'));
			if(day == "") day = ' ';
			var month = encodeURIComponent(this.month.getProperty('value'));
			if(month == "") month = ' ';
			var year = encodeURIComponent(this.year.getProperty('value'));
			if(year == "") year = '';
	
			this.value = year + '-' + month + '-' + day; 
			if(this.value != null && this.options.validate) {
				var url = '/cmd/owidgets/getHTML/Oform/?content_part_id=' + this.options.content_part_id + '&do=validateField&field_id=' + this.options.field_id;
				var data = 'field_data=' + this.value;
				if(this.depends_on[0] != '') {
					data = data + '&' + window['signup_first_name'+this.depends_on[0]].name + '=' + window['signup_first_name'+this.depends_on[0]].value;
				}
				this.request = new Request({'url':url,'method':'post'});
				this.request.removeEvents();
            	this.request.setOptions({'data':data,'onComplete':function(response){	
					var json = JSON.decode(response);
					
                	if(json.response.error == 'false' || json.response.error == false){
						if(this.options.vmsg == true) document.getElementById('input-vmsg-' + this.options.field_id).innerHTML = json.response.message;
						if(json.response.message != '') { this.vMsg.setStyles({'opacity':1}); } else { this.vMsg.setStyles({'opacity':0}); }
						document.getElementById('input-vimg-' + this.options.field_id).className = 'input-vimg-green';
						$('element-container-'+this.options.field_id).removeClass('oform-error');
        	    	} else {
        	       		if(this.options.vmsg == true) document.getElementById('input-vmsg-' + this.options.field_id).innerHTML = json.response.error_message;
						if(json.response.error_message != '') this.vMsg.setStyles({'opacity':1});
						else this.vMsg.setStyles({'opacity':0});
						document.getElementById('input-vimg-' + this.options.field_id).className = 'input-vimg-red';
						$('element-container-'+this.options.field_id).addClass('oform-error');
            		}
                	
            	}.bind(this)}).send();	
			}
            //this.options.blur(this.options.content_part_id, this.options.field_id, encodeURIComponent(this.text_input.getProperty('value')));
        }.bind(this).pass(this));
        
		this.month.addEvent('blur',function(){
			var day = encodeURIComponent(this.day.getProperty('value'));
			if(day == "") day = ' ';
			var month = encodeURIComponent(this.month.getProperty('value'));
			if(month == "") month = ' ';
			var year = encodeURIComponent(this.year.getProperty('value'));
			if(year == "") year = '';
	
			this.value = year + '-' + month + '-' + day; 
			if(this.value != null && this.options.validate) {
				var url = '/cmd/owidgets/getHTML/Oform/?content_part_id=' + this.options.content_part_id + '&do=validateField&field_id=' + this.options.field_id;
				var data = 'field_data=' + this.value;
				if(this.depends_on[0] != '') {
					data = data + '&' + window['signup_first_name'+this.depends_on[0]].name + '=' + window['signup_first_name'+this.depends_on[0]].value;
				}
				this.request = new Request({'url':url,'method':'post'});
				this.request.removeEvents();
            	this.request.setOptions({'data':data,'onComplete':function(response){	
					var json = JSON.decode(response);
					
                	if(json.response.error == 'false' || json.response.error == false){
						if(this.options.vmsg == true) document.getElementById('input-vmsg-' + this.options.field_id).innerHTML = json.response.message;
						if(json.response.message != '') this.vMsg.setStyles({'opacity':1});
						else this.vMsg.setStyles({'opacity':0});
						document.getElementById('input-vimg-' + this.options.field_id).className = 'input-vimg-green';
        	    	} else {
        	       		if(this.options.vmsg == true) document.getElementById('input-vmsg-' + this.options.field_id).innerHTML = json.response.error_message;
						if(json.response.error_message != '') this.vMsg.setStyles({'opacity':1});
						else this.vMsg.setStyles({'opacity':0});
						document.getElementById('input-vimg-' + this.options.field_id).className = 'input-vimg-red';
            		}
                	
            	}.bind(this)}).send();	
			}
            //this.options.blur(this.options.content_part_id, this.options.field_id, encodeURIComponent(this.text_input.getProperty('value')));
        }.bind(this).pass(this));
		
		this.year.addEvent('blur',function(){
			var day = encodeURIComponent(this.day.getProperty('value'));
			if(day == "") day = ' ';
			var month = encodeURIComponent(this.month.getProperty('value'));
			if(month == "") month = ' ';
			var year = encodeURIComponent(this.year.getProperty('value'));
			if(year == "") year = '';
	
			this.value = year + '-' + month + '-' + day; 
			
			if(this.value != null && this.options.validate) {
				var url = '/cmd/owidgets/getHTML/Oform/?content_part_id=' + this.options.content_part_id + '&do=validateField&field_id=' + this.options.field_id;
				var data = 'field_data=' + this.value;
				if(this.depends_on[0] != '') {
					data = data + '&' + window['signup_first_name'+this.depends_on[0]].name + '=' + window['signup_first_name'+this.depends_on[0]].value;
				}
				this.request = new Request({'url':url,'method':'post'});
				this.request.removeEvents();
            	this.request.setOptions({'data':data,'onComplete':function(response){	
					var json = JSON.decode(response);
					
                	if(json.response.error == 'false' || json.response.error == false){
						if(this.options.vmsg) document.getElementById('input-vmsg-' + this.options.field_id).innerHTML = json.response.message;
						if(json.response.message != '') this.vMsg.setStyles({'opacity':1});
						else this.vMsg.setStyles({'opacity':0});
						document.getElementById('input-vimg-' + this.options.field_id).className = 'input-vimg-green';
        	    	} else {
        	       		if(this.options.vmsg) document.getElementById('input-vmsg-' + this.options.field_id).innerHTML = json.response.error_message;
						if(json.response.error_message != '') this.vMsg.setStyles({'opacity':1});
						else this.vMsg.setStyles({'opacity':0});
						document.getElementById('input-vimg-' + this.options.field_id).className = 'input-vimg-red';
            		}
                	
            	}.bind(this)}).send();	
			}
            //this.options.blur(this.options.content_part_id, this.options.field_id, encodeURIComponent(this.text_input.getProperty('value')));
        }.bind(this).pass(this));
        
		this.day.addEvent('focus',this.options.focus);
		
		// container
		// place label and input field into a div to give us control over absolute positioning for label
        this.container = new Element('div',{'class':'input-wrapper ogrid-self-clear','id':'element-container-'+this.options.field_id});
		// container styles
		this.container.setStyles({
			'position':'relative'
		});
		
		//inject element and label into container
		if(this.options.label != ''){ 
			this.text_label.inject(this.container);
		}
		this.day.inject(this.container); 
		this.month.inject(this.container);
		//this.slash.inject(this.container);
		this.year.inject(this.container);
		//this.day.inject(this.container);
		if(this.options.validate) {
			if(this.options.vmsg) {
				this.vMsg.inject(this.container);
			}
			this.vImg.inject(this.container);
		}
    },
    
    throwError: function(is_error,msg){
    	/****
    	var parent_coordinates = this.container.getCoordinates();
    	var input_coordinates = this.buttoncontainer.getCoordinates();
    	var icon_coordinates = this.error_icon.getCoordinates();
    	this.error_icon.setStyles({'right':0,'top':input_coordinates.top-parent_coordinates.top+(input_coordinates.height/2-icon_coordinates.height/2)});
    
    	if(is_error){
    		this.error_icon.setStyles({'visibility':'visible','display':'block'});
	    	this.error_icon.removeClass('error-false');this.error_icon.addClass('error-true');
	    	var padding = this.container.getCoordinates().width * .02;
	    	this.buttoncontainer.setStyles({'width':input_coordinates.width-icon_coordinates.width-padding-5})
	    	var input_coordinates = this.buttoncontainer.getCoordinates();
	    	this.error_message.set('html',msg);
	    	this.error_message.setStyles({'visibility':'visible','display':'block','width':input_coordinates.width,'margin-right':icon_coordinates.width+7});
    	} else {
    		this.error_icon.removeClass('error-true');this.error_icon.addClass('error-false');
    		this.error_message.setStyles({'visibility':'hidden','display':'none'});
    		//this.text_input.setStyles({'width':this.input_width-padding-5});
    	}
    	****/
    },
    
    setStyles: function(style_options){
        
        //if(this.options['text-area'] && style_options['input-height'] == 'auto'){ style_options['input-height'] = (style_options['input-width'] * .50).toInt() }
		if(this.options['text-area'] && style_options['input-height'] == 'auto'){ style_options['input-height'] = (style_options['input-width'] * this.options['text-area-input-height']).toInt() }
        
		this.day.setStyles({'height':                               style_options['input-height']})
		this.day.setStyles();
    },
    
	setLabelDisplay: function(label_position){
		if(label_position == 'inside'){
			this.day.addEvent('focus',function(){
				this.day.addClass('Ohidden');
			}.bind(this));
			
			this.day.addEvent('blur',function(){
				if(this.day.getProperty('value') ==''){
					this.day.removeClass('Ohidden');
				}
			}.bind(this));
			
			this.day.addEvent('click',function(){
				this.day.addClass('Ohidden');
				this.day.focus();
			}.bind(this));
		}
	},
	
	addEvent: function(type,fn){
		if(!(type == "keypress" && this.options['text-area'])){
	    	this.day.addEvent(type,fn);
	    }
	},
	
    // get property
    getProperty: function(){ 
		var day = encodeURIComponent(this.day.getProperty('value'));
		if(day == "") day = ' ';
		var month = encodeURIComponent(this.month.getProperty('value'));
		if(month == "") month = ' ';
		var year = encodeURIComponent(this.year.getProperty('value'));
		if(year == "") year = '';
	
		return year + '-' + month + '-' + day; 
		
	},
    
    // set property
    setProperty: function(property,value){ this.text_input.setProperty(property,value); },
    
    inject: function(el){
		this.container.inject(el);
    }
});
OFMultiSelectOption = new Class({
	Implements: Options,
	
	options:{
		'padding':0,
		'highlight-color':'#ffffff',
		'background-color':'#000000',
		'selected-color':'#ffffff',
		'onChange':$empty
	},
	
	initialize: function(label,value,img_src,options){
		this.setOptions(options);
		this.br = new Element('br',{'class':'clear'});
		this.selected = false;
		this.label = label;
		this.value = value;
		this.mouse_location = 'outside';
		this.submenu_buttons = [];
		this.populated = false;
		// option container
		this.multiselect_option = new Element('div',{'class':'ofmultiselect-option'});
		this.multiselect_option.setStyles({'margin':1,'border-radius':'3px','position':'relative','padding':this.options['padding']});
		
		// option image
		if(img_src.trim() != '' && img_src.trim() != '_'){
			this.multiselect_option.image = new Element('img',{'src':img_src,'width':40,'height':40});
			this.multiselect_option.image.setStyles({'border-radius':'3px'});
			this.multiselect_option.image.setStyles({'float':'left'});
			this.multiselect_option.image.inject(this.multiselect_option);
		}
		
		// option label
		this.multiselect_option.label_container = new Element('div',{'class':'ofmultiselect-label'});
		this.multiselect_option.label_container.setStyles({'float':'left','padding':this.options['padding'],'width':100,'text-align':'left'});
		this.multiselect_option.label_container.inject(this.multiselect_option);
		this.multiselect_option.label_container.set('html',label);
		this.br.clone().inject(this.multiselect_option);
		
		this.multiselect_option.setStyles({'cursor':'pointer'});
		this.multiselect_option.inject(this.multiselect_options_box_content);
		
		// sub menu
		this.sub_menu = new Element('div',{'class':'ofmultiselect-option-submenu'});
		this.sub_menu.setStyles({'display':'none'});
		this.sub_menu.inject(document.body);
		
		this.sub_menu_content = new Element('div',{'class':'ofmultiselect-option-submenu-content'});
		this.sub_menu_content.setStyles({'position':'relative','padding':this.options['padding']-1});
		this.sub_menu_content.inject(this.sub_menu);
		
		this.sub_menu_attacher = new Element('div',{'class':'ofmultiselect-option-submenu-attacher'});
		this.sub_menu_attacher.setStyles({'position':'absolute','left':-21,'top':0,'background-color':'transparent','width':25,'height':40,'z-index':5100,'background-image':'url(/obray/widgets/oshop/images/admin/gap_connector.png)','background-position':'7px 3px','background-repeat':'no-repeat'});
		this.sub_menu_attacher.inject(this.sub_menu_content);
		
		
		this.sub_menu.addEvent('mouseenter',function(){
			this.sub_menu.setStyles({'display':'block','position':'absolute','top':this.multiselect_option.getCoordinates().top,'left':this.multiselect_option.getCoordinates().left+this.multiselect_option.getCoordinates().width+10,'background-color':this.options['selected-color'],'border-radius':'5px','width':200,'z-index':5100});
		}.bind(this));
		
		this.sub_menu.addEvent('mouseleave',function(){
			this.sub_menu.setStyles({'display':'none'});
		}.bind(this))
		
		// mouseneter
		this.multiselect_option.addEvent('mouseenter',function(el){
			if(this.selected == false){ el.setStyles({'background-color':this.options['highlight-color']}); } else {
				this.sub_menu.setStyles({'display':'block','position':'absolute','top':this.multiselect_option.getCoordinates().top,'left':this.multiselect_option.getCoordinates().left+this.multiselect_option.getCoordinates().width+10,'background-color':this.options['selected-color'],'border-radius':'5px','width':200,'z-index':5100});
			}
		}.bind(this,this.multiselect_option));
		
		// mouseleave
		this.multiselect_option.addEvent('mouseleave',function(el){
			if(this.selected){
				el.setStyles({'background-color':this.options['selected-color']});
				this.sub_menu.setStyles({'display':'none'});
			} else {
				el.setStyles({'background-color':this.options['background-color']});
			}
		}.bind(this,this.multiselect_option));
		
		// click
		this.multiselect_option.addEvent('click',function(el){
			if(this.selected){
				this.selected = false;
				el.setStyles({'background-color':this.options['highlight-color']});
			} else {
				this.selected = true;
				el.setStyles({'background-color':this.options['selected-color']});
			}
			if(this.populated){ this.options.onChange(this.value,this.selected); }
		}.bind(this,this.multiselect_option));
		
		
		
		
	},
	
	addSubmenuButton: function(label,fn){
		this.submenu_buttons[this.submenu_buttons.length] = new Element('div',{'class':'ofmultiselect-option-submenu-btn'});
		this.submenu_buttons[this.submenu_buttons.length-1].set('html',label);
		this.submenu_buttons[this.submenu_buttons.length-1].setStyles({'margin':1,'padding':this.options['padding'],'background-color':'#1a1a1a','font-size':12,'font-family':'Helvetica,Arial','color':'#ffffff','border-radius':'3px','cursor':'pointer'});
		this.submenu_buttons[this.submenu_buttons.length-1].addEvent('mouseenter',function(el){ el.setStyles({'background-color':this.options['highlight-color']})  }.bind(this,this.submenu_buttons[this.submenu_buttons.length-1]))
		this.submenu_buttons[this.submenu_buttons.length-1].addEvent('mouseleave',function(el){ el.setStyles({'background-color':'#1a1a1a'})  }.bind(this,this.submenu_buttons[this.submenu_buttons.length-1]))
		this.submenu_buttons[this.submenu_buttons.length-1].addEvent('click',fn);
		this.submenu_buttons[this.submenu_buttons.length-1].inject(this.sub_menu_content);
	},
	
	fireEvent: function(event_type){
		this.multiselect_option.fireEvent(event_type);
	},
	
	inject: function(el){
		this.multiselect_option.inject(el);
		
	}
})


OFMultiSelect = new Class({
	Implements: Options,
	
	options:{
		'label':'untitled',
		'labels':[],
		'values':[],
		'selected':[],
		'selected-color':'#419011',
		'onChange':$empty
	},
	
	initialize: function(options){
		this.setOptions(options);
		
		this.multiselect_options = [];
		this.number_selected = 0;
		this.opened = false;
		
		this.br = new Element('br',{'class':'clear'});
		
		this.multiselect_container = new Element('div',{'class':'ofmuliselect-wrapper'});
		this.multiselect_container.setStyles({'overflow':'hidden','font-family':'Helvetica,Arial','font-size':12,'position':'relative'});
		
		this.multiselect_label = new Element('label',{'class':'ofmultiselect-label'});
		this.multiselect_label.set('html',this.options.label);
		this.multiselect_label.inject(this.multiselect_container);
		
		this.multiselect = new Element('div',{'class':'ofmultiselect'});
		this.multiselect.setStyles({'overflow':'hidden','height':12});
		this.multiselect.inject(this.multiselect_container);
		this.br.clone().inject(this.multiselect_container);
		this.open_fx = new Fx.Morph(this.multiselect,{'duration':800,'transition':Fx.Transitions.Quint.easeOut});
		
		this.multiselect_input = new Element('input',{'class':'ofmultiselect-input'});
		this.multiselect_input.setStyles({'height':1,'width':1,'position':'absolute','top':0,'cursor':'pointer','opacity':.01});
		this.multiselect_input.inject(this.multiselect);
		
		this.multiselect_title = new Element('div',{'class':'ofmultislect-title'});
		this.multiselect_title.setStyles({'padding':1,'padding-bottom':3});
		this.multiselect_title.set('html',this.number_selected + ' Selected');
		
		this.multiselect_title.addEvent('click',function(){
			if(this.opened){
				this.opened = false;
				this.open_fx.pause();
				this.open_fx.start({'height':12})
			} else {
				this.opened = true;
				this.open_fx.pause();
				this.open_fx.start({'height':this.multiselect.getScrollSize().y})
			}
		}.bind(this))
		
		this.multiselect_title.inject(this.multiselect);
		
		this.multiselect_options_box = new scrollBox({'width':200,'height':300});
		this.multiselect_options_box.inject(this.multiselect);
		this.multiselect_options_box_content = this.multiselect_options_box.content;
		
		this.multiselect.addEvent('click',function(){ this.multiselect_input.focus(); }.bind(this));
		
		
		this.multiselect_input.addEvent('focus',function(){
			
		}.bind(this));
		
		this.multiselect_input.addEvent('blur',function(){
			
		}.bind(this));
		
		for(var i=0;i<this.options.labels.length;++i){ this.addOption(labels[i],values[i]); }
	},
	
	addOption: function(label,value,img_src){
		
		
		
		this.multiselect_options[this.multiselect_options.length] = new OFMultiSelectOption(label,value,img_src,{'padding':this.options['padding'],'highlight-color':this.options['highlight-color'],'background-color':this.options['background-color'],'selected-color':this.options['selected-color'],'onChange':function(value,selected){ this.getSelected(); this.options.onChange(value,selected); }.bind(this)});
		this.multiselect_options[this.multiselect_options.length-1].inject(this.multiselect_options_box_content);
		
		this.getSelected();
		return this.multiselect_options[this.multiselect_options.length-1];
	},
	
	 setStyles: function(style_options){
    
        this.multiselect.setStyles({
            'float':'left',
            'border':style_options.border,
            '-webkit-border-bottom-left-radius':	style_options['radius'] + 'px',
            '-webkit-border-bottom-right-radius':	style_options['radius'] + 'px',
            '-webkit-border-top-left-radius':		style_options['radius'] + 'px',
            '-webkit-border-top-right-radius':		style_options['radius'] + 'px',
            '-moz-border-radius':       			style_options['radius'] + 'px ' + style_options['radius'] + 'px '+ style_options['radius'] + 'px '+ style_options['radius'] + 'px',
            'border-radius':						style_options['radius'] + 'px',
            'padding-left':             			style_options['padding-left']+1 + 'px',
            'padding-right':            			style_options['padding-right']+1 + 'px',
            'padding-top':              			style_options['padding-top']+1 + 'px',
            'padding-bottom':           			style_options['padding-bottom']+1 + 'px',
            'margin-left':              			style_options['margin-left'] + 'px',
            'margin-right':             			style_options['margin-right'] + 'px',
            'margin-top':               			style_options['margin-top'] + 'px',
            'margin-bottom':            			style_options['margin-bottom'] + 'px',
            'font-size':                			style_options['input-font-size'] + 'px',
            'font-weight':              			style_options['input-font-weight'],
            'font-style':               			style_options['input-font-style'],
            'background-color':         			style_options['background-color'],
            'color':                    			style_options['input-color'],
            'width':								style_options['input-width']
        })
       
        this.multiselect_label.setStyles({
            'float':'left',
            'border':style_options['border'],
            'border-color':'transparent',
            'padding-left':style_options['padding-left'] + 'px',
            'padding-right':style_options['padding-right'] + 'px',
            'padding-top':style_options['padding-top'] + 'px',
            'padding-bottom':style_options['padding-bottom'] + 'px',
            'margin-left':style_options['margin-left'] + 'px',
            'margin-right':style_options['margin-right'] + 'px',
            'margin-top':style_options['margin-top'] + 'px',
            'margin-bottom':style_options['margin-bottom'] + 'px',
            'font-size':style_options['label-font-size'] + 'px',
            'font-weight':style_options['label-font-weight'],
            'font-style':style_options['label-font-style'],
            'background-color':style_options['background-color'],
            'color':style_options['label-color'],
            'width':style_options['label-width']
        });
        /****
        this.items_container.setStyles({
            'background-color':style_options['background-color'],
            'border':style_options.border,
            '-webkit-border-bottom-left-radius':style_options['radius'] + 'px',
            '-webkit-border-bottom-right-radius':style_options['radius'] + 'px',
            '-webkit-border-top-left-radius':style_options['radius'] + 'px',
            '-webkit-border-top-right-radius':style_options['radius'] + 'px',
            '-moz-border-radius': style_options['radius'] + 'px ' + style_options['radius'] + 'px '+ style_options['radius'] + 'px '+ style_options['radius'] + 'px',
            'border-radius':style_options['radius'] + 'px',
            'padding-left':style_options['margin-left'],
            'padding-right':style_options['margin-right'],
            'padding-top':style_options['margin-top'],
            'padding-bottom':style_options['margin-bottom'],
            'background-color':style_options['background-color']
        })
        ***********/
        this.options['background-color'] = style_options['background-color'];
        this.options['highlight-color'] = style_options['highlight-color'];
        this.options['color'] = style_options['input-color'];
        this.options['padding'] = style_options['padding-left'];
        this.options['width'] = style_options['input-width'];
        for(var i=0;i<this.multiselect_options.length;++i){
            this.multiselect_options[i].setStyles({
                'padding-left':style_options['padding-left'],
                'padding-right':style_options['padding-right'],
                'padding-top':style_options['padding-top'],
                'padding-bottom':style_options['padding-bottom'],
                'text-align':'left',
                'color':style_options['input-color']
            });
            this.multiselect_options[i].label_container.setStyles({'padding':this.options['padding']});
            
        }
       
    },
    
    setPopulated: function(){
    	for(var i=0;i< this.multiselect_options.length;++i){
    		this.multiselect_options[i].populated = true;
    	}
    	this.getSelected();
    },
    
    getSelected: function(){
    	this.number_selected = 0;
    	this.value = "";
    	for(var i=0;i<this.multiselect_options.length;++i){
    		if(this.multiselect_options[i].selected){
    			++this.number_selected;
    			if(this.number_selected > 1){ this.value = this.value + "," + this.multiselect_options[i].value; } else { this.value = this.multiselect_options[i].value; }
    		}
    	}
    	this.multiselect_title.set('html',this.number_selected + ' Selected');  
    	return this.value;
    },
	
	inject: function(el){
		this.multiselect_container.inject(el);
	},
	
	setLabelDisplay: $empty
}); OTabsAnimate = new Class({
	Implements: Options,
	
	options:{
		'otabs_animate_start_index':0,
		'otabs_animate_duration':600,
		'otabs_animate_auto_rotate':true,
		'otabs_animate_rotation_timing':2000,
		'otabs_animate_transition_type':Fx.Transitions.Quint.easeOut,
		'pause_rotation':0,
		'tabs_content_part_id':0,
		'left_btn':new Element('div'),
		'right_btn':new Element('div')
	},

	initialize: function(tabs,content,options){
		this.setOptions(options);

		this.tabs = tabs;
		this.content = content;
		this.auto_rotate_index = this.options.otabs_animate_start_index;
		this.periodical = 0;
		this.fx_array = [];
		this.is_open = [];
		
		this.tab_length = tabs.length;
		
		this.tabs.each(function(el,index){
			this.fx_array[index] = new Fx.Morph(this.content[index],{'duration':this.options.otabs_animate_duration,'transition':this.options.otabs_animate_transition_type});
			el.setStyles({'cursor':'pointer'});
			if(this.options.otabs_animate_start_index == index){ 
				this.is_open[index] = true;
				this.content[index].setStyles({'opacity':1,'display':'block','left':0});
			} else {
				this.is_open[index] = false;
				this.content[index].setStyles({'opacity':0,'left':-5000});
			}
			el.addEvent('click',function(){
				this.setActive(index);
				this.clearPeriodical();
			}.bind(this));
			this.content[index].addEvent('click',function(){
				this.clearPeriodical();
			}.bind(this));
			
		}.bind(this));
		
		this.setActive.delay(1000,this,this.options.otabs_animate_start_index);
			
		// auto rotate
		
		if(this.tabs[0].periodical === undefined){ 
			this.tabs[0].periodical = [];
		}
		if(this.options.otabs_animate_auto_rotate){ this.tabs[0].periodical[this.tabs[0].periodical.length] = this.rotateBanner.periodical(this.options.otabs_animate_rotation_timing,this); }
		
		
		this.options.left_btn[0].addEvent('click',function(){
			this.auto_rotate_index -= 1;
			if(this.auto_rotate_index < 0){ this.auto_rotate_index = this.tab_length-1; }
			this.setActive(this.auto_rotate_index);
		}.bind(this));
		
		this.options.right_btn[0].addEvent('click',function(){
			this.auto_rotate_index += 1;
			if(this.auto_rotate_index >= this.tab_length){ this.auto_rotate_index = 0; }
			this.setActive(this.auto_rotate_index);
		}.bind(this));
		
	},
	
	clearPeriodical: function(){
		for(var i=0;i<this.tabs[0].periodical.length;++i){
			$clear(this.tabs[0].periodical[i]);
		}
	},
	
	setActive: function(index){
		for(var i=0;i<this.tabs.length;++i){
			if(this.is_open[i] && i != index){ 
				this.fx_array[i].pause(); this.fx_array[i].start({'opacity':0});
				this.content[i].setStyles({'left':-5000});
			}
			//this.content[i].setStyles({'z-index':3000,'display':'none'});
			this.tabs[i].removeClass('otabs-tab-active');
			//if(player != undefined) player.controls.pause();
			try{ eval('tab_cleanup_js'+this.options.tabs_content_part_id+'()');	} catch(err) { }
			//alert(this.options.tabs_content_part_id);
			this.is_open[i] = false;
			this.content[i].removeClass('otabs-content-active');
			this.content[i].removeClass('otabs-content-active-'+i);
		}
		this.tabs[index].addClass('otabs-tab-active');
		this.is_open[index] = true;
		this.fx_array[index].pause();
		this.fx_array[index].start({'opacity':1,'display':'block'});
		this.content[index].setStyles({'z-index':4000,'display':'block','left':0});
		this.content[index].addClass('otabs-content-active otabs-content-active-'+index);
		this.content[index].getParent().setStyles({'height':$(this.content[index]).getCoordinates().height});
	},
	
	pauseRotation: function() {
		this.options.pause_rotation = 1;
	},
	
	resumeRotation: function () {
		this.options.pause_rotation = 0;
	},
	
	rotateBanner: function(){
		if(this.options.pause_rotation != 1) {
			this.auto_rotate_index += 1;
			if(this.auto_rotate_index >= this.tab_length){ this.auto_rotate_index = 0; }
			this.setActive(this.auto_rotate_index);
		}
	}
	
});
OCategories = new Class({	Implements: Options,		options:{		'header':'Categories',		'ocategory_object_id':0,		'ocategory_type':'',		'assigned_categories':[],		'label':'',		'enable_select':false,		'enable_edit':false,		'enable_delete':false,		'meta_data':[],		'&ocategory_meta_data':''	},		initialize: function(options){		this.setOptions(options);				this.list = [];		if(this.options.label == ''){ this.options.label = 'Category' }				// create the box		this.box = new sbox({'width':500,'height':490,'zIndex':10001,'sbox_class':'obray-admin-container','open':function(){					// populate list container above			this.getList(this.container,0,0);				}.bind(this),		'close':function(){						//window.location.reload(true);					}.bind(this)});				// create the box header		this.header = new BoxHeader({'header':this.options.header});		this.header.inject(this.box.content);				// container list		this.container = new Element('div',{'class':'container'}).setStyles({'position':'relative','border':'4px solid #d5d5d5','height':400,'overflow-y':'scroll','overflow-x':'hidden','z-index':5000});		this.container.inject(this.header.content);		this.container.loaded = false;								this.box.open();	},		getList: function(el,parent,level){				/*******************************************			Open or close the sub list container based on its state		*******************************************/				if(el.state == 'closed'){			el.state = 'open'; el.setStyles({'display':'block'});		} else { 			el.state = 'closed'; el.setStyles({'display':'none'});		}		if(parent == 0) { el.setStyles({'display':'block'}); } 				/*******************************************			Fetch and load content if it's not loaded already		*******************************************/				if(el.loaded == false){			this.request = new Request({'url':'/cmd/opieces/ocategories/ocategories/get/','data':'ocategory_type='+this.options.ocategory_type+'&ocategory_parent_id='+parent,'onComplete':function(response){								// set loaded property				this.json = JSON.decode(response).response.DATA.QUERY.DATA;				el.loaded = true;								// empty container				el.set('html','');				var id_array = [];				for(var i=0;i<this.json.OCATEGORY_ID.length;++i){										id_array[id_array.length] = this.json.OCATEGORY_ID[i];										// generate the row container					this.list[this.list.length] = new Element('div',{'class':'ogrid-self-clear ocategory-item-'+parent}).setStyles({'position':'relative','width':461	,'background-color':'#fff','padding':10,'padding-bottom':0,'font-size':12,'border-bottom':'1px solid #f5f5f5','cursor':'pointer'});					this.list[this.list.length-1].ocategory_id = this.json.OCATEGORY_ID[i];					this.list[this.list.length-1].ocategory_parent_id = this.json.OCATEGORY_ID[i];					this.list[this.list.length-1].level = level+1;					this.list[this.list.length-1].spacer = new Element('div').setStyles({'float':'left','height':10,'width':(level*22)}).set('html','&nbsp;').inject(this.list[this.list.length-1]);					this.list[this.list.length-1].arrow = new Element('div').setStyles({'background-image':'url(/obray/images/right-arrow.png)','float':'left','margin':7,'width':8,'height':10}).inject(this.list[this.list.length-1]);					this.list[this.list.length-1].name = new Element('div').setStyles({'float':'left','padding':6,'padding-bottom':16}).set('html',this.json.OCATEGORY_NAME[i]).inject(this.list[this.list.length-1]);					if(this.options.enable_select){												this.list[this.list.length-1].check = new Element('div').setStyles({'float':'right','margin':0,'border':'1px solid #e5e5e5','width':24,'height':23}).inject(this.list[this.list.length-1]);																this.list[this.list.length-1].check.checked = false;						for(var j=0;j<this.options.assigned_categories.length;++j){ if(this.options.assigned_categories[j] == this.json.OCATEGORY_ID[i]){ this.list[this.list.length-1].check.checked = true; }	}						if(this.list[this.list.length-1].check.checked ){ this.list[this.list.length-1].check.checked = true; this.list[this.list.length-1].check.setStyles({'background-image':'url(/obray/widgetsv1/Oform/images/form-sprite.png)','background-position':'0px -81px','border':'1px solid transparent'}); } else {							this.list[this.list.length-1].check.checked = false; this.list[this.list.length-1].check.setStyles({'background-image':'none','float':'right','margin':0,'border':'1px solid #e5e5e5','width':24,'height':23});						}						this.list[this.list.length-1].check.addEvent('click',function(){							if(this.checked == false){ this.checked = true; this.setStyles({'background-image':'url(/obray/widgetsv1/Oform/images/form-sprite.png)','background-position':'0px -81px','border':'1px solid transparent'}); } else {								this.checked = false; this.setStyles({'background-image':'none','float':'right','margin':0,'border':'1px solid #e5e5e5','width':24,'height':23});							}						});					}										if(this.options.enable_edit){											this.list[this.list.length-1].edit = new Element('div').setStyles({'background-image':'url(/obray/config/images/edit-btn.png)','float':'right','margin':0,'width':24,'height':23}).inject(this.list[this.list.length-1]);						this.list[this.list.length-1].edit.addEvent('click',function(ocategory_id){													var ocategory = new OCategoryForm({'close':function(){ 															this.container.loaded = false;								this.container.set('html','');								this.box.open(); 															}.bind(this),'enable_delete':this.options.enable_delete,'ocategory_id':ocategory_id,'ocategories':this.json,'ocategory_type':this.options.ocategory_type,'label':this.options.label,'header':'Edit ' + this.options.label,'meta_data':this.options.meta_data,'ocategory_meta_data':this.options.ocategory_meta_data});							this.box.close();												}.bind(this,this.json.OCATEGORY_ID[i]));					}										this.list[this.list.length-1].container = new Element('div',{'class':'ogrid-self-clear'}).setStyles({'clear':'both','border-top':'1px solid #e5e5e5','display':'none','margin-left':-10,'margin-right':-10}).inject(this.list[this.list.length-1]);					this.list[this.list.length-1].container.state = 'closed';					this.list[this.list.length-1].container.loaded = false;					this.list[this.list.length-1].inject(el);										this.list[this.list.length-1].addEvent('mouseover',function(e){this.setStyles({'background-color':'#f5f5f5'});});					this.list[this.list.length-1].addEvent('mouseout',function(e){this.setStyles({'background-color':'#fff'});});					this.list[this.list.length-1].name.addEvent('click',function(el){ this.getList(el.container,el.ocategory_parent_id,el.level); }.bind(this,this.list[this.list.length-1]));									}								new OSort({'container':el,'selector':'.ocategory-item-'+parent,'icon_position':{'left':425,'top':13},'y_drag_offset':250,'x_drag_offset':0,'sortables':this.list,'ids':id_array,'save':function(order){					var list = '';for(var i=0;i<order.length;++i){ if(i!=0){ list = list + ','; } list = list + order[i]; }					var request = new Request({'url':'/cmd/opieces/ocategories/ocategories/orderList/','data':'&order_list='+list,'onComplete':function(){}}).send();									}});									//add btn				this.add = new Element('input',{'type':'button','value':'Add New ' + this.options.label + ''}).setStyles({'position':'absolute','right':0});				this.add.inject(this.box.content);				this.add.addEvent('click',function(){					var ocategory = new OCategoryForm({'close':function(){ 												this.container.loaded = false;						this.container.set('html','');						this.box.open(); 											}.bind(this),'ocategories':this.json,'ocategory_type':this.options.ocategory_type,'label':this.options.label,'header':'Add ' + this.options.label,'meta_data':this.options.meta_data,'ocategory_meta_data':this.options.ocategory_meta_data});					this.box.close();				}.bind(this));												//select btn				if(this.options.enable_select){					this.select = new Element('input',{'type':'button','value':'<< Assign Selected Categories'}).setStyles({'position':'absolute','left':0});					this.select.inject(this.box.content);					this.select.addEvent('click',function(){						var values = '';						for(var i = 0;i<this.list.length;++i){							if(this.list[i].check.checked == true){ if(values != ''){ values = values + ',' + this.list[i].ocategory_id } else { values = this.list[i].ocategory_id;  } }						}						var request = new Request({'url':'/cmd/ocategories/linkOCategoriesFromList/','data':'&ocategory_object_id='+this.options.ocategory_object_id+'&ocategory_type='+this.options.ocategory_type+'&ocategory_id_list='+values,'onComplete':function(){							window.location.reload(true);						}.bind(this)}).send();					}.bind(this));				}							}.bind(this)}).send();			}	}});OCategoryForm  = new Class({	Implements: Options,		options:{		'ocategory_id':0,		'header':'Add Category',		'ocategory_object_id':0,		'ocategory_type':'',		'ocategory_name':'',		'close':$empty,		'ocategories':{},		'label':'Category',		'meta_data':[],		'ocategory_meta_data':'',		'enable_delete':false	},		initialize: function(options){		this.setOptions(options);				this.meta_fields = [];				this.box = new sbox({'width':500,'height':450,'zIndex':10001,'sbox_class':'obray-admin-container','close':function(){			this.options.close();		}.bind(this)});				this.header = new BoxHeader({'header':this.options.header});				this.header.inject(this.box.content);				if(this.options.ocategory_id == 0){					this.url = '/cmd/opieces/ocategories/ocategories/add/';			this.buildForm();				} else {					var request = new Request({'url':'/cmd/opieces/ocategories/ocategories/get/','data':'&ocategory_meta_data='+this.options.ocategory_meta_data+'&ocategory_id='+this.options.ocategory_id,'onComplete':function(response){								this.json = JSON.decode(response).response.DATA.QUERY.DATA;								this.options.ocategory_name = this.json.OCATEGORY_NAME[0];				this.options.ocategory_parent_id = this.json.OCATEGORY_PARENT_ID[0];								for(var key in this.json){ this.options[key] = this.json[key]; }								this.url = '/cmd/opieces/ocategories/ocategories/update/';				this.buildForm();								this.delete_btn = new Element('input',{'type':'button','value':'Delete ' + this.options.label}).setStyles({'position':'absolute','bottom':10,'left':0}).inject(this.header.content);;				this.delete_btn.addEvent('click',function(){					var request = new Request({'url':'/cmd/opieces/ocategories/ocategories/delete/','data':'&ocategory_id='+this.options.ocategory_id,'onComplete':function(){						this.box.close();					}.bind(this)}).send();				}.bind(this));							}.bind(this)}).send();					}				this.box.open();	},		buildForm: function(){				this.form = new OForm({'url':this.url,'onComplete':function(response){ 			window.location.reload(true);		}.bind(this) });				if(this.options.ocategory_id != 0){			this.id = new OFHidden({'name':'ocategory_id','value':this.options.ocategory_id});			this.form.addElement(this.id);			}				this.ocategory = new OFText({'label':this.options.label + ' Name','name':'ocategory_name','value':this.options.ocategory_name});		this.form.addElement(this.ocategory);				var values = [];		var labels = [];				for(var i=0;i<this.options.ocategories.OCATEGORY_ID.length;++i){ values[i] = this.options.ocategories.OCATEGORY_ID[i]; labels[i] = this.options.ocategories.OCATEGORY_NAME[i];	}		this.parent = new OFSelect({'label':this.options.label + ' Parent','name':'ocategory_parent_id','value':'No Parent','values':values,'labels':labels,'value':this.options.ocategory_parent_id});		this.form.addElement(this.parent);				this.type = new OFHidden({'name':'ocategory_type','value':this.options.ocategory_type});		this.form.addElement(this.type);				for(var i=0;i<this.options.meta_data.length;++i){						if(this.options.meta_data[i].type == 'offile'){				this.meta_fields[this.meta_fields.length] = new OFFile(this.options.meta_data[i]);				this.form.addElement(this.meta_fields[this.meta_fields.length-1]);			} else if(this.options.meta_data[i].type == 'none') {				// do nothing			} else {				try{this.options.meta_data[i].value = this.options[(this.options.meta_data[i].name).toUpperCase()]; } catch(err) { }				this.meta_fields[this.meta_fields.length] = new OFText(this.options.meta_data[i]);				this.form.addElement(this.meta_fields[this.meta_fields.length-1]);			}					}				this.form.inject(this.header.content);			},		addButton: function(btn,fn){		btn.addEvent('click',fn.bind(this));		btn.inejct(this.header.content);	}}); /*******************************************************
	Content Area v2
*******************************************************/
ContentAreaV2 = new Class({
	Implements: Options,
	
	options:{
		'content_area_id':0,
		'content_area_name':'',
		'content_area_level':'multipart',
		'content_parts':[]
	},
	
	initialize: function(options){
		this.setOptions(options);
		
		this.content_parts = [];
		this.content_area = $(this.options.content_area_name);
		if(this.options.content_area_level == 'multipart' && this.options.content_part_types != "li"){
			this.droppable = new Droppable(this.content_area,false,{'content_area_id':this.options.content_area_id,'content_parent_id':0,'content_order':0,'siblings':this.getSiblings.bind(this)});
			this.droppable.inject('bottom');
			window.obray.addDroppable(this.droppable.get());
		}
		/********************************************************************
			Recursively get content parts and construct them into the page
		********************************************************************/
		for(var i=0;i<this.options.content_parts.length;++i){
			var additional_options = new Hash({'siblings':this.getSiblings});
			this.options.content_parts[i].siblings = this.getSiblings.bind(this);
			this.content_parts[this.content_parts.length] = new ContentPartV2(this.content_area,this.options.content_parts[i]);
			this.expandContent(this.content_parts[this.content_parts.length-1].el,this.options.content_parts[i].content_parts);
			if(this.options.content_area_level == 'multipart' && this.options.content_parts[i].content_part_type != "li"){
				var droppable = new Droppable(this.content_area,this.content_parts[this.content_parts.length-1],{'content_area_id':this.options.content_area_id,'content_parent_id':this.options.content_parts[i].content_part_parent_id,'content_order':this.options.content_parts[i].content_order,'siblings':this.getSiblings.bind(this),'content_part':this.content_parts[this.content_parts.length-1]});
				droppable.inject('bottom');
				window.obray.addDroppable(droppable.get());
			}
		}
		
		if(this.options.content_area_level == 'singlepart' && this.options.content_parts.length == 0){
			if(this.options.content_part_types == 'image'){
				image = new OImage({
					'max_width':this.options.content_area_width,
					'max_height':this.options.content_area_height,
					'resizable':false,
					'content_area_id':this.options.content_area_id,
					'content_order':0,
					'blog':false
				});
				image.inject(this.content_area,'bottom');
			} else {
				this.content_parts[this.content_parts.length] = new ContentPartV2(this.content_area,{
					'content_part_id':0,
					'content_area_id':this.options.content_area_id,
					'content_part_type':this.options.content_part_types,
					'content_language':window.obray.options.content_language,
					'content_part_parent_id':0,
					'content_order':0,
					'content_text':'Lorem ipsum dolor sit amet',
					'image':{'image_id':0},
					'video':{'video_id':0},
					'siblings':this.getSiblings.bind(this)
				});
			}
		}
	},
	
	getSiblings: function(){
		return this.content_parts;
	},
	
	expandContent: function(parent,content_parts){
		for(var i=0;i<content_parts.length;++i){
			this.content_parts[this.content_parts.length] = new ContentPartV2(parent,content_parts[i]);
			this.expandContent(this.content_parts[this.content_parts.length-1].el,content_parts[i].content_parts);	
			/***
			if(this.options.content_area_level == 'multipart' && content_parts[i].content_part_type != "li"){
				var droppable = new Droppable(this.content_area,this.content_parts[this.content_parts.length-1],{'content_area_id':this.options.content_area_id,'content_parent_id':content_parts[i].content_part_parent_id,'content_order':content_parts[i].content_order});
				droppable.inject('bottom');
				window.obray.addDroppable(droppable.get());
			}
			****/
		}
	}
}); /*******************************************************
	Content Part v2
*******************************************************/
ContentPartV2 = new Class({
	Implements: Options,
	
	options:{
		'siblings':$empty,
		'component_type':'application',
		'content_language':'en',
		'ext_parameter':''
	},
	
	initialize: function(parent,options){
		this.setOptions(options);
		this.parent = parent;
		if(this.options.content_part_id == 0){this.added = false;}else{this.added = true;}
		if(this.options.content_part_type == 'h1' || this.options.content_part_type == 'h2' || this.options.content_part_type == 'h3' || this.options.content_part_type == 'h4' || this.options.content_part_type == 'h5'){
			this.obj = new Header(this.options.content_part_type,this.options.content_part_id,this.options.content_area_id,this.options.content_part_parent_id,this.options.content_order,this.options.content_text,{'hasChildren':this.options.hasChildren,'blog':false,'onDelete':this.del.bind(this),'siblings':this.options.siblings,'content_language':this.options.content_language});
			this.el = this.obj.get();
			this.inject('bottom');
			if(this.options.content_part_id == 0){
				var header = this.el;
				//(function(){header.fireEvent('click');}).delay(200);
			}
		} else if(this.options.content_part_type == 'p'){
			this.obj = new Paragraph(this.options.content_part_id,this.options.content_area_id,this.options.content_part_parent_id,this.options.content_order,this.options.content_text,{'blog':false,'hasChildren':this.options.hasChildren,'onDelete':this.del.bind(this),'siblings':this.options.siblings,'content_language':this.options.content_language});
			this.el = this.obj.get();
			this.inject('bottom');
			if(this.options.content_part_id == 0){
				var paragraph = this.el;
				//(function(){paragraph.fireEvent('click');}).delay(200);
			}
		} else if(this.options.content_part_type == 'ul'){
			this.obj = new List(this.options.content_part_id,this.options.content_area_id,this.options.content_part_parent_id,this.options.content_order,{'hasChildren':this.options.hasChildren,'blog':false,'onDelete':this.del.bind(this),'siblings':this.options.siblings,'content_language':this.options.content_language});
			this.el = this.obj.get();
			this.inject('bottom');
			if(this.options.content_part_id == 0){
				var list = this.el;
				//(function(){list.getFirst().getNext().fireEvent('click');}).delay(200);
			}
		} else if(this.options.content_part_type == 'li'){
			this.obj = new ListItem(this.options.content_part_id,this.options.content_area_id,this.options.content_part_parent_id,this.options.content_order,this.options.content_text,{'blog':false,'onDelete':this.del.bind(this),'siblings':this.options.siblings,'content_language':this.options.content_language});
			this.el = this.obj.get();
			this.inject('bottom');
		} else if(this.options.content_part_type == 'image'){
			//var max_width = this.options.image.oimage_width;
			//var max_height = this.options.image.oimage_height;
			//if($defined(this.parent)){if(this.options.image.oimage_width > this.parent.getCoordinates().width){max_width = this.parent.getCoordinates().width;}}
			var image_src = ""
			if(this.options.image.image_name != 'Untitled'){ image_src = 'assets/images/'+this.options.image.image_name+'.'+this.options.image.image_ext; } 
			if (this.options.image.image_location == "Amazon S3"){ image_src = window.obray.amazon_location+this.options.image.image_name+'.'+this.options.image.image_ext; }
			
			this.image = new OImage({
				'oimage_id':this.options.image.oimage_id,
				'content_area_id':this.options.content_area_id,
				'content_part_id':this.options.content_part_id,
				'content_language':this.options.content_language,
				'content_order':this.options.content_order,
				'resizable':true,
				'max_width':this.options.image.max_width,
				'oimage_width': this.options.image.oimage_width,
				'oimage_height': this.options.image.oimage_height,
				'image_src':image_src,
				'oimage_name':this.options.image.oimage_name,
				'oimage_title':this.options.image.oimage_title,
				'oimage_description':this.options.image.oimage_description,
				'oimage_ext':this.options.image.oimage_ext,
				'oimage_link':this.options.image.oimage_link,
				'oimage_follow':this.options.image.oimage_follow,
				'oimage_location':this.options.image.oimage_location,
				'oimage_resizable':this.options.image.oimage_resizable,
				'onDelete':function(){ var updateContent = new Request({url:'/cmd/opages/deleteContent/?content_part_id='+this.options.content_part_id,method:'get'}).send(); }.bind(this)
				});
			if($defined(this.parent)){
			    this.el = this.image;
			    this.inject('bottom');
			    //image.inject(this.parent);
			}
		} else if(this.options.content_part_type == 'video'){
			
			
			if(this.options.content_part_id == 0){
			
				var request = new Request({'url':'/cmd/opages/updateContent/','data':'&content_part_id=0&content_text=&content_language=en&content_part_type=video&content_area_id='+this.options.content_area_id+'&content_order='+this.options.content_order,'onComplete':function(response){
					this.response = [];
					eval(response);
					this.options.content_part_id = JSON.decode(this.response[0]).content_part_id;
					this.createVideo();
				}.bind(this)}).send()
			
			} else {
			
				this.createVideo();
			
			}
			
			this.el = new Element('div');
		
			
		} else {
			var data = 'content_text=none';
			//index.cfm?action=pages.updateObrayContent&image_id=0&content_part_id=' + this.options.content_part_id + '&content_parent_id=' + this.options.content_part_parent_id + '&content_part_type='+this.options.content_part_type + '&content_area_id=' + this.options.content_area_id + '&content_order=' + this.options.content_order + '&blog=false&content_language='+this.options.content_language+'&ext_parameter='+this.options.ext_parameter
			if(this.options.content_part_id == 0){
					var updateContent = new Request({
					'url':'/cmd/opages/updateContent/?image_id=0&content_part_id=' + this.options.content_part_id + '&content_parent_id=' + this.options.content_part_parent_id + '&content_part_type='+this.options.content_part_type + '&content_area_id=' + this.options.content_area_id + '&content_order=' + this.options.content_order + '&blog=false&content_language='+this.options.content_language+'&ext_parameter='+this.options.ext_parameter,
					data: data,
					method:'get',
					onComplete: function(){
							var location = window.location.href.replace(window.location.hash,'');
							var location = location.replace('#','');
							window.location = location;
						}
					}).send();
			} else {
				this.el = new Element('div',{'class':'component'});
				if($chk(this.parent)){
					this.el.inject(this.parent);
				}
				window.obray.chain.chain(this.request.bind(this));
				//alert(window.obray.executing_request);
				if(window.obray.executing_request == false){
					window.obray.chain.callChain();
				}
			}
		}
	},
	
	createVideo: function(){
		
		var video = new OVideo({
			'path':this.options.video.path,
			'video_id':this.options.video.video_id,
			'content_area_id':this.options.content_area_id,
			'content_part_id':this.options.content_part_id,
			'content_language':this.options.content_language,
			'content_order':this.options.content_order,
			'video_title':this.options.video.video_title,
			'video_description':this.options.video.video_description,
			'video_name':this.options.video.video_name,
			'video_ext':this.options.video.video_ext,
			'video_width':this.options.video.video_width,
			'video_height':this.options.video.video_height,
			'omedia_id':this.options.video.omedia_id,
			'omedia_aspect_ratio':this.options.video.omedia_aspect_ratio,
			'omedia_autoplay':this.options.video.omedia_autoplay,
			'cover_path':this.options.video.cover_path
		});
		
		if($defined(this.parent)){
		   this.el = video;
		   this.inject('bottom');
		   video.injectInside(this.parent);
		}
		
	},
	
	request: function(){
		window.obray.executing_request = true;
		var str = window.location + ' ';
		var queryString = document.location.search.substring(1,str.length);
		queryString = queryString.replace("action=pages.account","");
		queryString = queryString.replace("action=pages.show","");
		queryString = queryString.replace("action=cart.thank-you","");
		queryString = queryString.replace("content_part_id=","");
		var HTMLRequest = new Request.HTML({'update':this.el,'evalScripts':true,'onComplete':function(){
				if($defined(this.el.getFirst()) && $defined(this.el.getNext())){
					this.el_float = this.el.getFirst().getStyle('float');
					this.el_width = this.el.getFirst().getCoordinates().width;
					var droppable = this.el.getNext();
					droppable.setStyles({'width':this.el_width,'float':this.el_float,'margin':this.el_margin});
				}
				window.obray.executing_request = false;
				//alert('executing request');
				window.obray.chain.callChain();
				//index.cfm?action=pages.getComponentHTML&component_name='+this.options.content_part_type+'&component_type='+this.options.component_type+'&content_part_id='+this.options.content_part_id+'&'+queryString.replace("action=pages.cp_dsp&","")
		}.bind(this)}).post('/cmd/owidgets/getHTML/'+this.options.content_part_type+'/?content_part_id='+this.options.content_part_id + '&' + queryString.replace("action=pages.cp_dsp&",""));
		},
	
	inject: function(position){
		if(this.options.content_part_id == 0 && this.added == false){
			this.add();this.added=true;
		}
		this.el.inject(this.parent,position);
	},
	
	add: function(){
		var content = this.options.siblings();
		if(!(this.options.content_part_type == 'image' && this.options.content_part_id ==0)){
            for(var i=0;i<content.length;++i){
                if(content[i].options.content_order >= this.options.content_order){
                    content[i].options.content_order += 1;
                }
            }
		}
		content[content.length] = this;
	},
	
	del: function(){
		var content = this.options.siblings();
		for(var i=0;i<content.length;++i){
			if(content[i].options.content_order > this.options.content_order){
				content[i].options.content_order -= 1;
			}
		}
		content.erase(this);
		
		window.obray.toolbar.getDroppables().each(function(el){
			if(el.content_area_id == this.options.content_area_id && el.content_order > this.options.content_order){
				--el.content_order;
			}
		}.bind(this))
	},
	
	isFloated: function(){
		
	}
});

// JavaScript Document

Header = new Class({
	Implements: Options,
	
	options: {
		'hasChildren': false,
		'blog':false,
		'content_part':false,
		'onDelete':$empty,
		'onCreate':$empty
	},
	
	initialize: function(header_type,content_part_id,content_area_id,content_parent_id,content_order,text,options){
		//data members
		
		this.setOptions(options);
		this.text = text;
		this.content_part_id = content_part_id;
		this.content_area_id = content_area_id;
		this.content_parent_id = content_parent_id;
		this.content_order = content_order;
		this.content_text = text;
		this.header_type = header_type;
		if(this.text == ''){this.text = 'replace this text';}
		//generate HTML
		this.header = new Element(this.header_type,{'class':'oparagraph'});
		this.textarea = new Element('textarea',{'class':'otextarea'});
		this.header.set('html',this.text);
		//assign events
		this.assignEvents();
		if(Browser.Engine.webkit){ this.edit_offset = 16; } else { this.edit_offset = 0; }
	},
	
	resetStyles: function(){
		this.width = this.header.getSize().x;
		this.height = this.header.getCoordinates().height;
		this.border_left = this.header.getStyle('border-left');
		this.border_right = this.header.getStyle('border-right');
		this.border_top = this.header.getStyle('border-top');
		this.border_bottom = this.header.getStyle('border-bottom');
		this.margin = this.header.getStyle('margin');
		this.padding = this.header.getStyle('padding');
		this.background = this.header.getStyle('background');
		if(this.background == ''){this.background = 'transparent';}
		this.font_family = this.header.getStyle('font-family');
		this.font_size = this.header.getStyle('font-size');
		this.font_weight = this.header.getStyle('font-weight');
		this.color = this.header.getStyle('color');
		this.text_align = this.header.getStyle('text-align');
		this.line_height = this.header.getStyle('line-height');
		//create element
		this.textarea = new Element('textarea');
		//set Styles
		this.textarea.setStyle('width',this.width+5);
		this.textarea.setStyle('height',this.height - this.header.getStyle('padding-top').toInt() - this.header.getStyle('padding-bottom').toInt());
		this.textarea.setStyle('border-left',this.border_left);
		this.textarea.setStyle('border-right',this.border_right);
		this.textarea.setStyle('border-top',this.border_top);
		this.textarea.setStyle('border-bottom',this.border_bottom);
		this.textarea.setStyle('margin',this.margin);
		this.textarea.setStyle('padding',this.padding);
		this.textarea.setStyle('background',this.background);
		this.textarea.setStyle('font-family',this.font_family);
		this.textarea.setStyle('font-weight',this.font_weight);
		this.textarea.setStyle('font-size',this.font_size);
		this.textarea.setStyle('color',this.color);
		this.textarea.setStyle('text-align',this.text_align);
		this.textarea.setStyle('overflow','hidden');
		this.textarea.setStyle('line-height',this.line_height);
		
	},
	
	get: function(){
		return this.header;
	},
	
	assignEvents: function(){
		this.header.addEvent('click',function(){
			this.header.removeEvents();
			this.resetStyles();
			var text = this.header.get('html');
			this.textarea.setProperty('value',text);
			this.header.set('html','')
			this.textarea.inject(this.header);
			this.textarea.focus();
			if(this.content_part_id == 0){
				this.textarea.select();
			}
			this.assignBlur();
		}.bind(this));
	},
	
	assignBlur: function(){
		this.textarea.addEvent('blur',function(){
			var data = '&content_part_id=' + this.content_part_id
					  +'&content_parent_id=' + this.content_parent_id
					  +'&content_part_type=' + this.header_type
					  +'&content_language=' + this.options.content_language
					  +'&content_area_id=' + this.content_area_id
					  +'&content_order=' + this.content_order
					  +'&content_text='+encodeURIComponent(this.textarea.get('value'))
					  +'&blog=' + this.options.blog;
			var updateContent = new Request({'url':'/cmd/opages/updateContent/','data':data,'method':'post','onComplete': function(response){
				this.response = [];
				this.contentParts = [];
				eval(response);
				for(var i=0;i<this.response.length;++i){
					var response_decoded = JSON.decode(this.response[i]);
					this.content_part_id = response_decoded.content_part_id;	
				}
			}.bind(this)}).send();
		}.bind(this));
		
		this.textarea.addEvent('keydown',function(e){
			this.textarea.setStyle('height',this.textarea.getScrollSize().y - this.edit_offset);
			var newChar = e.key;
			if(newChar == 'backspace' && this.textarea.get('value') == ''){
				e.preventDefault();
				//index.cfm?action=pages.deleteContentPart&content_part_id='+this.content_part_id
				var updateContent = new Request({url:'/cmd/opages/deleteContent/?content_part_id='+this.content_part_id,method:'get',onComplete: function(){
						this.options.onDelete();
						this.textarea.removeEvents();
						this.header.getNext().destroy(); //removes droppable
						this.header.destroy();
				}.bind(this)}).send();
			}
		}.bind(this))
		
		this.textarea.addEvent('keyup',function(e){
			this.textarea.setStyle('height',this.textarea.getScrollSize().y - this.edit_offset);
			
		}.bind(this));
	}
	
	
}); // JavaScript Document

Paragraph = new Class({
	Implements: Options,
	
	options: {
		'hasChildren': false,
		'blog': false,
		'onDelete':$empty
	},
	
	initialize: function(content_part_id,content_area_id,content_parent_id,content_order,text,options){
		//data members
		this.setOptions(options);
		this.text = text;
		this.content_part_id = content_part_id;
		this.content_area_id = content_area_id;
		this.content_parent_id = content_parent_id;
		this.content_order = content_order;
		this.content_text = text;
		if(this.text == ''){this.text = 'replace this text';}
		//generate HTML
		this.paragraph = new Element('p',{'class':'oparagraph'});
		this.textarea = new Element('textarea',{'class':'otextarea'});
		this.paragraph.set('html',this.text);
		//set styles
		//assign events
		this.assignEvents();
		if(Browser.Engine.webkit){ this.edit_offset = 4; } else { this.edit_offset = 0; }
	},
	
	resetStyles: function(){
		this.width = this.paragraph.getSize().x;
		this.height = this.paragraph.getCoordinates().height;
		this.border_left = this.paragraph.getStyle('border-left');
		this.border_right = this.paragraph.getStyle('border-right');
		this.border_top = this.paragraph.getStyle('border-top');
		this.border_bottom = this.paragraph.getStyle('border-bottom');
		this.margin = this.paragraph.getStyle('margin');
		this.padding = this.paragraph.getStyle('padding');
		this.background = this.paragraph.getStyle('background');
		if(this.background == ''){this.background = 'transparent';}
		this.font_family = this.paragraph.getStyle('font-family');
		this.font_size = this.paragraph.getStyle('font-size');
		this.font_weight = this.paragraph.getStyle('font-weight');
		this.color = this.paragraph.getStyle('color');
		this.text_align = this.paragraph.getStyle('text-align');
		this.line_height = this.paragraph.getStyle('line-height');
		//create element
		this.textarea = new Element('textarea');
		//set Styles
		this.textarea.setStyle('width',this.width+5);
		this.textarea.setStyle('height',this.height - this.paragraph.getStyle('padding-top').toInt() - this.paragraph.getStyle('padding-bottom').toInt());
		this.textarea.setStyle('border-left','0px solid transparent');
		this.textarea.setStyle('border-right','0px solid transparent');
		this.textarea.setStyle('border-top','0px solid transparent');
		this.textarea.setStyle('border-bottom','0px solid transparent');
		this.textarea.setStyle('background',this.background);
		this.textarea.setStyle('font-family',this.font_family);
		this.textarea.setStyle('font-weight',this.font_weight);
		this.textarea.setStyle('font-size',this.font_size);
		this.textarea.setStyle('color',this.color);
		this.textarea.setStyle('text-align',this.text_align);
		this.textarea.setStyle('overflow','hidden');
		this.textarea.setStyle('line-height',this.line_height);
		this.textarea.setStyles({'display':'inline'});
		
	},
	
	get: function(){
		return this.paragraph;
	},
	
	assignEvents: function(){
		this.paragraph.addEvent('click',function(){
			this.paragraph.removeEvents();
			this.resetStyles();
			var text = this.paragraph.get('html');
			var regex = new RegExp("[<][bB][rR][/]*[>]");
			text_pr = '';
			while(text_pr != text){
				text_pr = text;
				text = text.replace(regex,'\n','gm');
			}
			this.textarea.setProperty('value',text);
			this.paragraph.set('html','')
			this.textarea.inject(this.paragraph);
			this.textarea.focus();
			if(this.content_part_id == 0){
				this.textarea.select();
			}
			this.assignBlur();
		}.bind(this));
	},
	
	assignBlur: function(){
		this.textarea.addEvent('blur',function(){
			//this.saving = new MessageBox({'message':'Saving, please wait...'});
			//this.saving.open('elastic');
			var regex = new RegExp("[\n]");
			var content_text = this.textarea.get('value');
			var content_text_pr = '';
			var data = '&content_part_id=' + this.content_part_id
					  +'&content_parent_id=' + this.content_parent_id
					  +'&content_part_type=p'
					  +'&content_language='+this.options.content_language
					  +'&content_area_id=' + this.content_area_id
					  +'&content_order=' + this.content_order
					  +'&content_text='+encodeURIComponent(content_text)
					  +'&blog=' + this.options.blog;
					  //index.cfm?action=pages.updateObrayContent
			var updateContent = new Request({'url':'/cmd/opages/updateContent/','data':data,'method':'post','onComplete': function(response){
				this.response = [];
				this.contentParts = [];
				eval(response);
				for(var i=0;i<this.response.length;++i){
					var response_decoded = JSON.decode(this.response[i]);
					this.content_part_id = response_decoded.content_part_id;
					
				}
				this.textarea.dispose()
				this.paragraph.set('html',this.textarea.get('value'));
				this.assignEvents();
				//this.saving.close();
			}.bind(this)}).send();
		}.bind(this));
		
		this.textarea.addEvent('keydown',function(e){
			this.textarea.setStyle('height',this.textarea.getScrollSize().y - this.edit_offset);
			var newChar = e.key;
			if(newChar == 'backspace' && this.textarea.get('value') == ''){
				e.preventDefault();

				var updateContent = new Request({'url':'/cmd/opages/deleteContent/?content_part_id='+this.content_part_id,'method':'get','onComplete': function(){
						this.options.onDelete();
						this.textarea.removeEvents();
						this.paragraph.getNext().destroy(); //removes droppable
						this.paragraph.destroy();
				}.bind(this)}).send();
			}
		}.bind(this))
		
		this.textarea.addEvent('keyup',function(e){
			this.textarea.setStyle('height',this.textarea.getScrollSize().y - this.edit_offset);
			
		}.bind(this));
	}
	
	
}); 

List = new Class({
	Implements: Options,
	
	options:{
		'hasChildren':false,
		'blog':false,
		'onDelete':$empty,
		'content_language':'en'
	},
	
	initialize: function(content_part_id,content_area_id,content_parent_id,content_order,options){
		//data memebers
		this.setOptions(options);
		this.content_part_id = content_part_id;
		this.content_area_id = content_area_id;
		this.content_parent_id = content_parent_id;
		this.content_order = content_order;
		
		//generate HTML
		this.list = new Element('ul',{'class':'olist'});
		this.delete_btn = new Element('div',{'class':'delete_btn'});
		this.delete_btn.set('html','X');

		if(this.content_part_id == 0){
			var data = '&content_part_id=' + this.content_part_id
					  +'&content_parent_id=' + this.content_parent_id
					  +'&content_part_type=ul'
					  +'&content_language='+this.options.content_language
					  +'&content_area_id=' + this.content_area_id
					  +'&content_order=' + this.content_order
					  +'&content_text='
					  +'&blog=' + this.options.blog;
			//index.cfm?action=pages.updateObrayContent
			var updateContent = new Request({'url':'/cmd/opages/updateContent/','data':data,'method':'post','onComplete': function(response){
				this.response = [];
				eval(response);
				this.content_part_id = JSON.decode(this.response[0]).content_part_id;
				this.startList();
			}.bind(this)}).send();
		} else {
			//THIS IS NOT WORKING!!!
			if(this.options.hasChildren == false || this.options.hasChildren == 'false'){
				this.startList();
			}
		}
		
		this.list.setStyles({'position':'relative'});
		this.delete_btn.setStyles({'position':'absolute','cursor':'pointer','right':'0px','top':'0px','width':'10px','height':'10px','border':'1px solid #c1c1c1','padding':'3px','text-align':'center','font-family':'arial','background-color':'#444444','color':'#c1c1c1'})
		this.delete_btn.inject(this.list);
		//index.cfm?action=pages.deleteContentPart&content_part_id='+this.content_part_id
		this.delete_btn.addEvent('click',function(){
			var delete_request = new Request({'url':'/cmd/opages/deleteContent/?content_part_id='+this.content_part_id,'onComplete':function(){
				var location = window.location.href.replace(window.location.hash,'');
				var location = location.replace('#','');
				window.location = location;
			}.bind(this)}).send();
		}.bind(this))
		
		
	},
	
	get: function(){
		return this.list;
	},
	
	startList: function(){
		this.startListItem = new ListItem(0,this.content_area_id,this.content_part_id,1,'',{'content_language':this.options.content_language});
		this.startListItem.get().inject(this.list);
	}
}); // JavaScript Document

ListItem = new Class({
	Implements: Options,
	
	options:{
		'blog': false,
		'onDelete':$empty,
		'content_language':'en'
	},
	
	initialize: function(content_part_id,content_area_id,content_parent_id,content_order,text,options){
		//data members
		this.setOptions(options)
		this.content_part_id = content_part_id;
		this.content_area_id = content_area_id;
		this.content_parent_id = content_parent_id;
		this.content_order = content_order;
		
		//genereate HTML
		this.li = new Element('li',{'class':'olistItem'});
		this.li.set('html',text);
		this.createEvents();
	},
	
	get: function(){
		return this.li;
	},
	
	startInput: function(){
		
		var width = this.li.getCoordinates().width;
		var innerText = this.li.innerHTML;
		var new_input = new Element('input',{'type':'text','value':innerText})
		this.li.set('html','');
		new_input.inject(this.li);
		new_input.setStyles({
			'width':width,
			'border':'0px',
			'font-family':this.li.getStyle('font-family'),
			'font-size':this.li.getStyle('font-size'),
			'color':this.li.getStyle('color'),
			'margin':'0px',
			'padding':'0px',
			'background-color':'transparent'
		});
		new_input.focus();
	},
	
	stopInput: function(){
		var temp = this.li.getFirst().getProperty('value');
		this.li.set('html',temp);
	},
	
	createEvents: function(){
		this.li.addEvent('click',function(){
			this.li.removeEvents();
			this.startInput();
			this.li.getFirst().addEvent('keydown',function(e){
				if(e.key == 'enter'){
					var newLi = new ListItem(0,this.content_area_id,this.content_parent_id,parseInt(this.content_order)+1,'',{'content_language':this.options.content_language});
					newLi.get().inject(this.li,'after');
					newLi.li.fireEvent('click');
				} else if(e.key == 'backspace'){
					if(this.li.getFirst().getProperty('value') == ''){
						//index.cfm?action=pages.deleteContentPart&content_part_id='+this.content_part_id
						var updateContent = new Request({url:'/cmd/opages/deleteContent/?content_part_id='+this.content_part_id,method:'get',onComplete: function(){
								this.options.onDelete();
								this.li.destroy();
							}.bind(this)
						}).send();
					}
				}
			}.bind(this))
			this.li.getFirst().addEvent('blur',function(){
				this.saveContent();
				this.stopInput();
				this.createEvents();
			}.bind(this));
		}.bind(this));
	},
	
	saveContent: function(){
		if(this.li.getFirst().getProperty('value') != ''){
			var data = '&content_part_id=' + this.content_part_id
					  +'&content_parent_id=' + this.content_parent_id
					  +'&content_part_type=li'
					  +'&content_language='+this.options.content_language
					  +'&content_area_id=' + this.content_area_id
					  +'&content_order=' + this.content_order
					  +'&content_text='+ encodeURIComponent(this.li.getFirst().getProperty('value'))
					  +'&blog=' + this.options.blog;
			var updateContent = new Request({'url':'/cmd/opages/updateContent/','data':data,'method':'post','onComplete': function(response){
				this.response = [];
				eval(response);
				this.content_part_id = JSON.decode(this.response[0]).content_part_id;
				this.createEvents();
			}.bind(this)}).send();
		}
	}
	
	
}); /*************************************************
	OImage Settings
*************************************************/

OImageSettings = new Class({
	Implements: Options,
	
	options:{
		'oimage_id':0,
		'oimage_width': 1024,
		'oimage_height': 768,
		'oimage_name':'Untitled',
		'oimage_title':'',
		'oimage_description':'',
		'oimage_ext':'jpg',
		'oimage_link':'',
		'oimage_follow':false,
		'oimage_location':'',
		'oimage_resizable':true,
		'onSave': $empty
	},
	
	initialize: function(options){
		this.setOptions(options);
		
		this.box = new sbox({'width':450,'height':300,'sbox_class':'obray-admin-container'});
		this.box.content.setStyles({'padding-left':5,'padding-right':5});
		
		this.header = new BoxHeader({'header':'Update Image'});
		///?action=pages.getOLayoutJSON
		
		this.form = new OForm({'url':'/cmd/oimages/updateOImage/?oimage_id='+this.options.oimage_id,'button':new Element('input',{'type':'button','value':'Update Image'}),'onComplete':function(){
			window.location.reload(true);
		}.bind(this)});
		
		this.oimage_width = new OFHidden({'name':'oimage_width','value':this.options.oimage_width});
		this.form.addElement(this.oimage_width);
		
		this.oimage_height = new OFHidden({'name':'oimage_height','value':this.options.oimage_height});
		this.form.addElement(this.oimage_height);
		
		this.oimage_name = new OFHidden({'name':'oimage_name','value':this.options.oimage_name});
		this.form.addElement(this.oimage_name);
		
		this.oimage_ext = new OFHidden({'name':'oimage_ext','value':this.options.oimage_ext});
		this.form.addElement(this.oimage_ext);
		
		this.title = new OFText({'name':'oimage_title','label':'Image Alt','value':this.options.oimage_title});
		this.form.addElement(this.title);
		
		this.description = new OFText({'text-area':true,'name':'oimage_description','label':'Caption','value':this.options.oimage_description});
		this.form.addElement(this.description);
		
		this.link = new OFText({'name':'oimage_link','label':'Link To','value':this.options.oimage_link});
		this.form.addElement(this.link);
		
		this.follow = new OFCheck({'name':'oimage_follow','label':'Allow search engines to follow this link?','checked':this.options.oimage_follow});
		this.form.addElement(this.follow);
		
		this.header.inject(this.box.content);
		
		this.form.inject(this.header.content);
			
		this.open();
	},
	
	open: function(){
		this.box.open();
	}
});

/*************************************************
	OIMAGES
*************************************************/

OImage = new Class({
	Implements: Options,
	
	options:{
		'oimage_id':0,
		'content_area_id':0,
		'content_part_id':0,
		'resizable':true,
		'max_width':1024,
		'max_height':768,
		'oimage_width': 1024,
		'oimage_height': 768,
		'oimage_name':'Untitled',
		'oimage_title':'',
		'oimage_description':'',
		'oimage_ext':'jpg',
		'oimage_link':'',
		'oimage_follow':false,
		'oimage_location':'',
		'content_order':1,
		'oimage_resizable':true,
		'onDelete':$empty,
		'onSave':$empty,
		'dimension_type':1
	},
	
	initialize: function(options){
		this.setOptions(options);
		
		if(this.options.oimage_location == 'local'){ this.oimage_location = '/assets/images/'; } else { this.oimage_location = window.obray.amazon_location; }
		
		this.is_saved = true;
		
		this.box = new sbox({'width':450,'height':100,'sbox_class':'obray-admin-container'});
		this.header = new BoxHeader({'header':'Upload a Picture'});
		this.img = new Element('img');
		
		this.frame = new Element('div',{'class':'OImage'});
		this.frame.setStyles({'position':'relative','padding':0,'background-image':'url(/obray/images/obray-oimage-bg.jpg)','background-position': (1024/2 - this.options.oimage_width) + 'px ' + (1024/2 - this.options.oimage_height) + 'px'});
					
		if(this.options.oimage_id == 0){ this.loadNewImage(); } else{ this.loadImage(); }
		
		this.handle = new Element('div',{'class':'OImage-handle'});
		this.handle.setStyles({'position':'absolute','bottom':-5,'right':-5,'width':10,'height':10,'background-color':'#fff','border':'1px solid #858585','cursor':'pointer'});
				
	},
	
	/************************************************
		Load New Image
	************************************************/
	
	loadNewImage: function(){
	
		if(!this.upload){
			this.upload = new OFFile({'name':'filedata','max_file_size':(5 * 1024 * 1024),'label':'Select an Image to Upload','uploadSuccess':function(response){
				this.file = response.DATA.SERVERFILE
				this.upload.destroy();
				this.startLoading();
				this.setLoading('Optimizing the image for use with Obray...');
				this.options.oimage_name = response.DATA.SERVERFILENAME;
				this.options.oimage_ext = response.DATA.SERVERFILEEXT;
				var data = '&oimage_name=' + response.DATA.SERVERFILENAME
					     + '&oimage_ext='  + response.DATA.SERVERFILEEXT
					     + '&oimage_resizable=' + this.options.oimage_resizable;
				if(this.options.oimage_resizable == false){ data = data + '&max_height=' + this.options.oimage_height + '&max_width=' + this.options.oimage_width + '&dimension_type=3' } else {
					data = data + '&max_width=' + this.options.max_width + '&max_height=0' + '&dimension_type=1';
				}
				this.optimize = new Request({'url':'/cmd/oimages/optimizeOImage/','data':data,'method':'post','onComplete':function(response){
					this.oimage_location = '/assets/images/';
					this.setLoading('Downloading optimized image to Obray...');
					var json = JSON.decode(response);
					this.options.oimage_width = json.response.DATA.IMAGE_WIDTH;
					this.options.oimage_height = json.response.DATA.IMAGE_HEIGHT;
					this.options.oimage_id = json.response.DATA.OIMAGE_ID;
					this.saveContent();
					// for now we are just going to refresh the page and later we'll figure out the dynamic load
					//var myImage = Asset.images(this.oimage_location + this.file,{'class':'OImage','onComplete':this.loadImage.bind(this) });	
				}.bind(this)}).send();
				
			}.bind(this)});
			this.upload.inject(this.header.content);
		}
		this.box.open();
		this.header.inject(this.box.content);
	},
	
	/************************************************
		Load Image
	************************************************/
	
	loadImage: function(){
		this.createImage();
		this.box.close();
		this.stopLoading();
		this.frame.removeEvents();
		if(this.handle){ this.handle.removeEvents(); }
		if(this.options.oimage_resizable){
			this.frame.makeResizable({
				'handle':this.handle,
				'onDrag':function(){
					var new_dimensions = this.getDimensions(this.frame.getCoordinates().width);
					this.img.setProperty('width',new_dimensions.width);
					this.img.setProperty('height',new_dimensions.height);
					this.frame.setStyles({'height':this.img.getCoordinates().height});
					
				}.bind(this),
				'onComplete':function(){
					var new_dimensions = this.getDimensions(this.frame.getCoordinates().width);
					this.options.oimage_width = new_dimensions.width;
					this.options.oimage_height = new_dimensions.height;
					this.options.max_width = this.options.oimage_width;
					this.setSaveStatus(false);
				}.bind(this)
			});
		}
		this.setSaveStatus(true);
		this.admin = new OWidgetMiniAdmin({'open-element':this.frame});
		if(this.options.oimage_resizable){
			this.admin.addButton('delete-btn','delete',function(){
				this.frame.destroy();
				this.options.onDelete();
			}.bind(this));
		} else{
			this.admin.addButton('add-btn','Upload',this.loadNewImage.bind(this));
		}
		this.admin.addButton('edit-btn','Settings',function(){
			this.settings = new OImageSettings(this.options);
		}.bind(this));
		
	},
	
	/************************************************
		Create Image
	************************************************/
	
	createImage: function(){
		this.file = this.options.oimage_name + '.' + this.options.oimage_ext;
		this.frame.setStyles({'width':this.options.oimage_width,'height':this.options.oimage_height});
		if(this.options.oimag_width > this.options.max_width){ var new_dimensions = this.getDimensions(this.options.max_width); } else { var new_dimensions = this.getDimensions(this.options.oimage_width) }
		this.img.destroy();
		this.img = new Element('img',{'src':this.oimage_location + this.file,'width':new_dimensions.width,'height':new_dimensions.height});
		if(this.options.oimage_name != ""){ this.img.inject(this.frame); }
	},
	
	/************************************************
		Get Dimensions
	************************************************/
	
	getDimensions: function(new_width){
		var new_height = (this.options.oimage_height * new_width) / this.options.oimage_width;
		return {'height':new_height,'width':new_width};
	},
	
	/************************************************
		Start Loading
	************************************************/
	
	startLoading: function(){
		this.load = new Element('img',{'src':'/obray/images/loaders/loader-standard-light.gif'});
		this.load.setStyles({'float':'left','margin-top':5,'margin-right':5});
		this.load.inject(this.header.content);
		this.load_text = new Element('p',{'class':'oloader'});
		this.load_text.setStyles({'float':'left'});
		this.load_text.inject(this.header.content);
	},
	
	/************************************************
		Save Image
	************************************************/
	
	saveImage: function(){
		this.setSaveStatus(true);
		this.startSaving();
		var data = '&oimage_id=' + this.options.oimage_id
				 + '&oimage_name=' + this.options.oimage_name
				 + '&oimage_ext=' + this.options.oimage_ext
				 + '&oimage_title=' + this.options.oimage_title
				 + '&oimage_description=' + this.options.oimage_description
				 + '&oimage_width=' + this.options.oimage_width
				 + '&oimage_height=' + this.options.oimage_height
				 + '&oimage_link=' + this.options.oimage_link
				 + '&oimage_follow=' + this.options.oimage_follow;
		this.save = new Request({'url':'/cmd/oimages/updateOImage/','link':'cancel','data':data,'onComplete':function(){
			var myImage = Asset.images(window.obray.amazon_location + this.file,{'class':'OImage','onComplete':function(){
				// for now we are just going to refresh
				//this.img.destroy();
				//this.createImage();
				//this.stopSaving();
				this.reload.delay(2000)
			}.bind(this) });
		}.bind(this)}).send();
	},
	
	setLoading: function(text){
		this.load_text.set('html',text);
	},
	
	stopLoading: function(){
		try{
		this.load.destroy();
		this.load_text.destroy();
		} catch(err){}
	},
	
	inject: function(el,position){
		this.frame.inject(el,position);
		if(this.options.oimage_resizable){ this.handle.inject(this.frame); }
	},
	
	startSaving: function(){
		this.saving = new Element('img',{'src':'/obray/images/loaders/loader-standard.gif','class':'oimage-saving-container'});
		this.saving.setStyles({'position':'absolute','left':this.options.oimage_width/2-8,'top':this.options.oimage_height/2-8});
		this.saving.inject(this.frame);
		this.handle.setStyles({'display':'none'});
		this.admin.widget_admin_buttons.setStyles({'display':'none'});
	},
	
	stopSaving: function(){
		this.saving.destroy();
		this.handle.setStyles({'display':'block'});
		this.admin.widget_admin_buttons.setStyles({'display':'block'});
	},
	
	setSaveStatus: function(is_saved){
		this.is_saved = is_saved;
		if(!this.is_saved){
			if(!this.save_btn_container){
				this.save_btn_container = new Element('div',{'class':'oimage-save-btn-container obray-admin-container'});
				this.save_btn_container.setStyles({'position':'absolute','right':10,'bottom':10});
				this.save_btn = new Element('input',{'type':'button','value':'Save'});
				this.save_btn.addEvent('click',this.saveImage.bind(this));
				this.save_btn_container.inject(this.frame);
				this.save_btn.inject(this.save_btn_container);
			}
		} else {
			if(this.save_btn_container){ this.save_btn_container.destroy(); }
		}
	},
	
	saveContent: function(){
		var data = '&content_part_id=' + this.options.content_part_id
			  +'&content_parent_id=0'
			  +'&image_id=' + this.options.oimage_id
			  +'&content_part_type=image'
			  +'&content_language=en'
			  +'&content_area_id=' + this.options.content_area_id
			  +'&content_order=' + this.options.content_order
			  +'&content_text=' + '';
		var updateContent = new Request({'url':'/cmd/opages/updateContent/','data':data,'method':'post','onComplete': function(response){
			this.response = [];
			this.contentParts = [];
			eval(response);
			for(var i=0;i<this.response.length;++i){
				var response_decoded = JSON.decode(this.response[i]);
				this.options.content_part_id = response_decoded.content_part_id;	
			}
			this.reload.delay(2000);
		}.bind(this)}).send();
	},
	
	reload: function(){
		window.location.reload(true);
	}

});



/**************************************************************
	
	Embed
	
**************************************************************/

EmbedBtn = new Class({
    Implements: Options,
    
    options:{
        'position':{'x':0,'y':0},
        'embed_code':''
    },
    
    initialize: function(video,options){
        
        this.setOptions(options);
        
        this.video = video;
        this.state = 'closed';
        
        // embed container
        this.embed_container = new Element('div',{'class':'ovideo-embed-container'});
        this.embed_container.setStyles({'left':-185,'top':-76,'position':'absolute','padding':8,'background-image':'url(/obray/images/oplayer/embed-popup.png)','width':216,'height':66,'display':'none'});
        this.embed_container.addEvent('click',function(e){ e.stopPropagation(); });
        
        
        // embed label
        this.embed_label = new Element('label',{'class':'ovideo-embed-label'});
        this.embed_label.setStyles({'width':200,'font-family':'arial','font-size':10,'color':'#fff','padding':5,'text-align':'left'});
        this.embed_label.set('html','COPY THIS EMBED CODE');
        this.embed_label.inject(this.embed_container);
        
        
        // embed input
        this.embed_input = new Element('input',{'type':'text','class':'ovideo-embed-input','value':this.options.embed_code});
        this.embed_input.setStyles({'background-color':'transparent','border':0,'background-image':'url(/obray/images/oplayer/embed-input.png)','width':205,'height':22,'margin-left':4,'font-family':'Courier,Arial'});
        this.embed_input.setProperty('value',this.video.ovideo.getEmbedCode(true));
        this.embed_input.inject(this.embed_container);
        
        this.embed_btn = new Element('div',{'class':'ovideo-embed-btn'});
        this.embed_btn.setStyles({'position':'relative','width':31,'float':'left','font-family':'Arial,Helvetica','color':'#fff','font-size':10,'padding':10,'letter-spacing':-1,'cursor':'pointer','border-left':'2px solid #343434'});
        this.embed_btn.set('html','EMBED');
        
        this.embed_container.inject(this.embed_btn);
        
        this.embed_btn.addEvent('click',function(){
        	if(this.state == 'closed'){
        		this.embed_container.setStyles({'display':'block'});
        		this.state = 'open';
        	} else {
        		this.embed_container.setStyles({'display':'none'});
        		this.state = 'closed';
        	}
        }.bind(this));
        
        this.embed_btn.addEvent('mouseleave',function(){
        	this.embed_container.setStyles({'display':'none'});
        	this.state = 'closed';
        }.bind(this));
        
        this.embed_input.addEvent('mouseup',function(){
            this.embed_input.select();
        }.bind(this))
        
    },
    
    open: function(){
        this.embed_container.setStyles({'display':'block'});
    },
    
    close: function(){
        this.embed_container.setStyles({'display':'none'});
    },
    
    getProperty: function(){
    	return this.embed_btn.getProperty('width')+4;
    },
    
    inject: function(el){
        
        this.embed_btn.inject(el);
        return this;
        
    }
});


/**************************************************************
	
	PLAY BUTTON
	
**************************************************************/

PlayBtn = new Class({
	Implements: Options,
	
	options:{
	
	},
	
	initialize: function(video,options){
		
		this.setOptions(options);
		this.video = video;
		
		this.btn = new Element('div',{'class':'ovideo-play-and-pause-btn'});
        this.btn.setStyles({'float':'left','width':30,'height':30,'background-image':'url(/obray/images/oplayer/play-btn.png)','cursor':'pointer'});
        
        this.btn.addEvent('click',function(){ 
        
        	this.video.toggle();
        	this.toggle('click');
        
         }.bind(this));
        this.btn.addEvent('mouseenter',this.toggle.bind(this,'enter'));
        this.btn.addEvent('mouseleave',this.toggle.bind(this,'leave'));
        
        this.toggle.periodical(250,this);
		
	},
	
	getProperty: function(property){
		switch(property){
			case "width":
				return this.btn.getCoordinates().width;
				break;
		}
	},
	
	toggle: function(event){
		if(this.video.isPaused()){ 
			if(event == 'enter'){
            	this.btn.setStyles({'background-image':'url(/obray/images/oplayer/play-btn-hover.png)'});
            } else {
            	this.btn.setStyles({'background-image':'url(/obray/images/oplayer/play-btn.png)'});
            }
        } else {
        	if(event == 'enter'){
            	this.btn.setStyles({'background-image':'url(/obray/images/oplayer/pause-btn-hover.png)'});
            } else {
            	this.btn.setStyles({'background-image':'url(/obray/images/oplayer/pause-btn.png)'});
            }
        }
	},
	
	inject: function(el){
		
		this.btn.inject(el);
		return this;
		
	}
	
});

/**************************************************************
	
	TIMER
	
**************************************************************/

PlayerTimer = new Class({
	Implements: Options,
	
	options:{
	
	},
	
	initialize: function(video,options){
		
		this.setOptions(options);
		this.video = video;
		this.percent = 0;
		
		this.timer = new Element('div',{'class':'oplayer-timer'});
        this.timer.setStyles({'float':'left','font-family':'Arial,Helvetica','color':'#fff','font-size':10,'width':75,'text-align':'center','padding':10});
        this.timer.set('html','00:00 | 00:00');
        	
        this.set.periodical(1000,this);
	},
	
	set: function(){
		
		var status = this.video.status();
		if(status.state > 2){
			this.timer.set('html',this.format(status.time) + ' | ' + this.format(status.duration));
			this.percent = status.time/status.duration * 100;
		}
		
	},
	
	getProperty: function(property){
		switch(property){
			case "width":		
				return this.timer.getCoordinates().width;
				break;
		}
	},
	
	format: function(time_in_sec){
        var time_string_hr  = time_in_sec / 3600;
        var time_string_min = time_in_sec / 60;
        var time_string_sec = time_in_sec % 60;
        
        (time_string_hr.toInt()  < 10) ? time_string_hr=  ('0' + time_string_hr.toInt())  : time_string_hr=time_string_hr.toInt();
        (time_string_min.toInt() < 10) ? time_string_min= ('0' + time_string_min.toInt()) : time_string_min=time_string_min.toInt();
        (time_string_sec.toInt() < 10) ? time_string_sec= ('0' + time_string_sec.toInt()) : time_string_sec=time_string_sec.toInt();
        
        var time_string = time_string_min + ':' + time_string_sec;
        if(time_string_hr > 0){time_string_hr + ':' + time_string;}
        return time_string;
    },
    
    percentPlayed: function(){ return this.percent; },
    
    inject: function(el){
    
    	this.timer.inject(el);
    	return this;
    
    }
    
    

});

/**************************************************************
	
	SCRUB BAR
	
**************************************************************/

ScrubBar = new Class({
	
	Implements: Options,
	
	options:{
		'width': 317,
		'start': 0,
		'onChange':$empty,
		'onComplete':$empty,
		'enable_scrubbing':true
	},
	
	initialize: function(video,options){
		this.setOptions(options);
		this.video = video;
		this.interval = 0;
		
		this.value = this.options.start;
		this.status = 'not scrubbing';
		
		this.scrub_bar = new Element('div',{'class':'ovideo-scrub-bar'});
        
        this.scrub_bar.setStyles({'float':'left','position':'relative','width':this.options.width,'height':30,'background-color':'#858585','margin-top':1,'margin-bottom':12,'margin-left':3});
        
        this.scrub_progress = new Element('div',{'class':'ovideo-scrub-progress'});
        this.scrub_progress.setStyles({'position':'absolute','top':-1,'left':-1,'height':30,'width':0,'background-color':'#a5a5a5','z-index':10002});
        
        this.scrub_progress_handle = new Element('div',{'class':'ovideo-scrub-handle'});
        this.scrub_progress_handle.setStyles({'position':'absolute','left':-1,'top':-2,'width':7,'height':35,'cursor':'pointer','background-color':'#c5c5c5','margin':0,'padding':0,'z-index':10003});
        this.scrub_progress_handle.addEvent('mousedown',function(){	this.status = 'scrubbing'; }.bind(this));
        this.scrub_progress_handle.addEvent('mouseup',function(){ this.status = 'not scrubbing'; }.bind(this))

        this.scrub_buffer = new Element('div',{'class':'ovideo-scrub-buffer'})
        this.scrub_buffer.setStyles({'position':'absolute','top':-1,'left':-1,'width':0,'height':30,'background-color':'#959595','z-index':10001});
        
        this.scrub_message = new Element('div',{'class':'ovideo-scrub-message'});
        this.scrub_message.setStyles({'position':'absolute','left':(this.options.width-150)/2,'top':-2,'width':150,'height':35,'margin':0,'padding':8,'z-index':10010,'font-size':12,'text-aign':'center','font-family':'Helvetica,Arial','color':'#fff','opacity':0})
        this.scrub_message.set('html','Message goes here.');
        
	},
	
	setBuffer: function(percent){
		this.scrub_buffer.setStyles({'width':this.options.width*percent});
	},
	
	set: function(){
		var status = this.video.status();
		if(status.state > 2){ 
			this.scrub_control.set(status.time/status.duration*1000); 
		}
	},
	
	get: function(){
		return value;
	},
	
	notify: function(message){
		
		this.scrub_message.set('html',message);
		this.scrub_message_fx.pause();
		this.scrub_message_fx.start({'opacity':1,'color':'#fff'});

	},
	
	inject: function(el){
		
		this.scrub_bar.inject(el);
		this.scrub_progress.inject(this.scrub_bar);
		this.scrub_progress_handle.inject(this.scrub_bar);
		this.scrub_buffer.inject(this.scrub_bar);
		this.scrub_message.inject(this.scrub_bar);
		
		this.scrub_message_fx = new Fx.Morph(this.scrub_message,{duration:750,transition: Fx.Transitions.Quint.easeOut,'onComplete':function(){
			this.scrub_message_fx.pause();
			this.scrub_message_fx.start({'opacity':0,'color':'#fff'})
		}.bind(this)});
		
		this.setSlider();
		
		this.toggle();
		
		return this;
	},
	
	toggle: function(){
		
		if(this.interval == 0){
			this.interval = this.set.periodical(1000,this);
		} else {
			$clear(this.interval);
			this.interval = 0;
		}
		
	},
	
	resize: function(width){
		this.options.width = width;
		this.scrub_bar.setStyles({'width':width});
		this.setSlider();
	},
	
	setSlider: function(){
		this.scrub_bar.removeEvents();
		this.scrub_control = new Slider(this.scrub_bar,this.scrub_progress_handle,{
			'mode':'horizontal',
			'steps':1000,
			'snap':false,
			'onChange':function(step){
				this.value = step/1000;
				this.scrub_progress.setStyles({'width':this.options.width*step/1000});
				this.options.onChange(this.value);				
			}.bind(this),
			'onComplete':function(step){
				if(this.options.enable_scrubbing){

					this.value = step/1000;
					this.scrub_progress.setStyles({'width':this.options.width*step/1000});
					this.options.onComplete(this.value);
					this.video.set(this.video.status().duration*this.value);
					
				} else {
					this.notify('Scrubbing is disabled.');
				}
			}.bind(this)
		});
		this.scrub_control.set(this.options.start*1000);
	}
	
})

/**************************************************************
	
	EXPAND
	
**************************************************************/

ExpandBtn = new Class({
	Implements: Options,
	
	options:{
		'click':$empty
	},
	
	initialize: function(options){
	
		this.setOptions(options);
		
		this.expand_btn = new Element('div',{'class':'ovideo-fullscreen-btn'})
        this.expand_btn.setStyles({'float':'left','background-image':'url(/obray/images/oplayer/expand-btn.png)','font-family':'Arial,Helvetica','color':'#fff','font-size':10,'padding':10,'height':10,'width':30,'letter-spacing':-1,'cursor':'pointer','border-left':'2px solid #343434'});
        this.expand_btn.addEvent('mouseenter',function(){ this.expand_btn.setStyles({'background-image':'url(/obray/images/oplayer/expand-btn-hover.png)'}); }.bind(this));
        this.expand_btn.addEvent('mouseleave',function(){ this.expand_btn.setStyles({'background-image':'url(/obray/images/oplayer/expand-btn.png)'}); }.bind(this));
        
        this.expand_btn.addEvent('click',this.options.click);
	},
	
	getProperty: function(property){
		switch(property){
			case "width":		
				return this.expand_btn.getCoordinates().width;
				break;
		}
	},
	
	inject: function(el){
		this.expand_btn.inject(el);
		return this;
	}
});

/**************************************************************
	
	PLAYER
	
**************************************************************/

Player = new Class({
	Implements: Options,
	
	options: {
		'autoplay':false,
		'path':'',
		'width':400,
		'height':300,
		'onEnded':$empty,
		'onPlay':$empty,
		'onLoaded':$empty
	},
	
	initialize: function(options){
	
		this.setOptions(options);
		this.player_element = [];
		this.isFullscreen = false;
		
		/**********************************************
			Create Container
		**********************************************/
		
		this.container = new Element('div',{'class':'oplayer-container'}).setStyles({'position':'relative','width':this.options.width,'height':this.options.height,'overflow':'hidden'});
		this.container.addEvent('click',function(){
			this.video.toggle();
		}.bind(this));
		
		/**********************************************
			Create Overlay
		**********************************************/
		
		this.overlay = new Element('div',{'class':'oplayer-controls-overlay'}).setStyles({'position':'absolute','left':0,'top':0,'height':'100%','width':'100%','z-index':4000});
		if(this.options.cover_path != undefined || this.options.dover_path != ''){ 
			//this.overlay.setStyles({'background-image':'url('+this.options.cover_path+')'}); 
		}
		this.overlay.inject(this.container);
		
		/**********************************************
			Create Cover
		**********************************************/
		
		this.cover = new Element('img',{'src':this.options.cover_path,'width':this.options.width,'height':this.options.height});
		this.cover.inject(this.overlay);
		
		
		/**********************************************
			Create Compatible Video
		**********************************************/
		
		this.video = new CompatibleVideo({'container':this.container,'autoplay':this.options.autoplay,'path':this.options.path,'width':this.options.width,'height':this.options.height,'onEnded':this.options.onEnded,'onPlay':function(){this.overlay.setStyles({'background-image':'none'});this.options.onPlay();}.bind(this),'onLoaded':this.options.onLoaded,'cover':this.cover});
		
		/**********************************************
			Create Control bar
		**********************************************/
		
		this.control_bar = new Element('div',{'class':'ovideo-control-bar','id':this.options.id});
        this.control_bar.setStyles({'position':'absolute','bottom':0,'left':0,'width':'100%','height':30,'background-image':'url(/obray/images/oplayer/control-bar-bg.png)','z-index':4001});
        this.control_bar_fx = new Fx.Morph(this.control_bar,{duration:250,transition: Fx.Transitions.Quint.easeOut});
        this.control_bar.addEvent('click',function(e){ e.stopPropagation(); }.bind(this));
        
        if(this.video.isHTML5 == false){
        
	    	this.overlay.addEvent('mouseenter',function(){ this.control_bar_fx.pause();this.control_bar_fx.start({'height':30}); }.bind(this));
	    	this.overlay.addEvent('mouseleave',function(){ this.control_bar_fx.pause();this.control_bar_fx.start({'height':0}); }.bind(this));
	    	this.control_bar.addEvent('mouseenter',function(){ this.control_bar_fx.pause();this.control_bar_fx.start({'height':30}); }.bind(this));
    	
    	}
        
        
        		
	},
	
	fullscreen: function(){
	
		this.window_size = this.getWindowSize();
		if(this.isFullscreen){
			$$('body').setStyles({'overflow':'scroll'});
			this.container.inject(this.parent).setStyles({'position':'relative','left':0,'top':0,'width':this.options.width,'height':this.options.height});
			this.isFullscreen = false;
			var width = this.options.width;
		} else {
			$$('body').setStyles({'overflow':'hidden'});
			this.parent = this.container.getParent();
			this.container.inject(document.body).setStyles({'position':'absolute','left':0,'top':0,'width':this.window_size.width,'height':this.window_size.height});
			this.isFullscreen = true;
			var width = this.window_size.width;
		}
		
		width -= this.play_btn.getProperty('width');
		width -= this.timer.getProperty('width');
		width -= this.expand.getProperty('width');
		this.scrub.resize(width-3);
		
	},
	
	resize: function(width,height,ratio){
	
		this.options.width = width;
		this.options.height = height;
		
		switch(ratio){
		
			case '16:9':
			
				this.options.height = (9 * width) / 16
				break;
				
			case '16:10':
				
				this.options.height = (10 * width) / 16
				break;
				
			case '4:3':
			
				this.options.height = (3 * width) / 4
				break;
		
		}
		
		this.container.setStyles({'width':this.options.width,'height':this.options.height});
		
		width -= this.play_btn.getProperty('width');
		width -= this.timer.getProperty('width');
		width -= this.expand.getProperty('width');
		this.scrub.resize(width-3);
		
	},
	
	getWindowSize: function(){
    	var viewportwidth;
		var viewportheight;
		
		// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
		
		if (typeof window.innerWidth != 'undefined')
		{
		  viewportwidth = window.innerWidth,
		  viewportheight = window.innerHeight
		}
		
		// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
		
		else if (typeof document.documentElement != 'undefined'
		 && typeof document.documentElement.clientWidth !=
		 'undefined' && document.documentElement.clientWidth != 0)
		{
		   viewportwidth = document.documentElement.clientWidth,
		   viewportheight = document.documentElement.clientHeight
		}
		
		// older versions of IE
		
		else
		{
		   viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
		   viewportheight = document.getElementsByTagName('body')[0].clientHeight
		}
		
		return {width:viewportwidth,height:viewportheight};
    },
	
	inject: function(el){
		
		this.container.inject(el);
		this.control_bar.inject(this.container);
		var width = this.options.width;
		
		/**********************************************
			Play Buttons
		**********************************************/
        
        this.play_btn = new PlayBtn(this.video).inject(this.control_bar);
		width -= this.play_btn.getProperty('width');
		
		/**********************************************
			Timer
		**********************************************/
		
		this.timer = new PlayerTimer(this.video).inject(this.control_bar);
		width -= this.timer.getProperty('width');
		
		/**********************************************
			Scrub Bar
		**********************************************/
		
		this.scrub = new ScrubBar(this.video).inject(this.control_bar);
		
		/**********************************************
			Expand
		**********************************************/
		
		this.expand = new ExpandBtn({'click':this.fullscreen.bind(this)}).inject(this.control_bar);
		width -= this.expand.getProperty('width');
		
		this.scrub.resize(width-3);
		
		
	}

})

/**************************************************************
	
	COMPATIBLE VIDEO
	
**************************************************************/

CompatibleVideo = new Class({
	Implements: Options,
	
	options: {
		'container':new Element('div'),
		'autoplay':false,
		'path':'',
		'width':400,
		'height':300,
		'onEnded':$empty,
		'onPlay':$empty,
		'onLoaded':$empty
		
	},
	
	initialize: function(options){
	
		this.setOptions(options);
		this.ended = false;
		this.started = false;
		
		this.isHTML5 = false;
		
		// For use within normal web clients 
		var isiPad = navigator.userAgent.match(/iPad/i) != null;
		
		// For use within iPad developer UIWebView
		// Thanks to Andrew Hedges!
		var ua = navigator.userAgent;
		var isiPad = /iPad/i.test(ua) || /iPhone OS 3_1_2/i.test(ua) || /iPhone OS 3_2_2/i.test(ua);
		
		if (isiPad){ this.isHTML5 = true; }
		
		if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {
	 		this.isHTML5 = true;
		}

				
		//if( Modernizr.video && Modernizr.video.h264 == 'probably' ){ this.isHTML5 = true; } else { this.isHTML5 = false; }
	
		
	
		if( this.isHTML5 ){
		
			this.ovideo = new Element('video',{'src':this.options.path,'height':'100%','width':'100%'});
			if(this.options.autoplay != 'false'){ this.ovideo.setProperty('autoplay',true); }
            this.ovideo.setStyles({'background-color':'#000','height':'100%','width':'100%'});
        	this.ovideo.inject(this.options.container);
        	    
        	this.ovideo.addEvent('click',function(){
				this.toggle();
			}.bind(this))    
			    
		} else {
			
			if(Browser.Engine.name == 'trident'){ var cachebusting = true; } else { var cachebusting = false; }
			
			this.flash = new Element('div',{'class':'ovideo-flash-wrapper'}).setStyles({'width':'100%','height':'100%','z-index':3999});
			this.flash.inject(this.options.container);
			
            this.ovideo = $f(this.flash,{'src':'/obray/flash/flowplayer.swf','wmode':'opaque','cachebusting':cachebusting},{
                'class':'ovideo',
                'plugins': {'controls': null},
                'clip': { 
                    'url': this.options.path, 
                    'autoPlay': this.options.autoplay, 
                    'autoBuffering': false,
                    'scaling':'fit',
                    'bufferLength':15,
                    'width':this.options.width,
                    'height':this.options.height,
                    'onBegin':function(){
                    	
                    }.bind(this),
                    'onStart':function(){
                    	
                    }.bind(this),
                    'onLoad':function(e){
                        
                    }.bind(this),
                    'onLastSecond':function(){
                    	
                    }.bind(this),
					'onFinish':function() {
						
					}.bind(this)
                },
                'onLoad':$empty,
				'onFinish':function() {
				
				}.bind(this)
            });
            
            
            
		}
		
		
	},
	
	toggle: function(){
		
		if(this.isHTML5){
			if(this.ovideo.paused){
				this.play();
				
			} else {
				this.pause();
			}
		} else {
			if(!this.ovideo.isPlaying()){
				console.log('toggle-play');
				this.ovideo.play();
			} else {
				console.log('toggle-pause');
				this.pause();
			}
		}
		
	},
	
	play: function(){
		
		this.ended = false;
		if(this.isHTML5){
			this.ovideo.play();
		} else {
			this.ovideo.play();
		}
		this.options.cover.setStyles({'display':'none'});
		
	},
	
	pause: function(){
		if(this.isHTML5){
			this.ovideo.pause();
		} else {
			this.ovideo.pause();
		}
	},
	
	isPaused: function(){
		if(this.isHTML5){
			if(!this.ovideo.paused){ this.options.cover.setStyles({'display':'none'}); }
			return this.ovideo.paused;
		} else {
			if(this.ovideo.isPlaying()){ this.options.cover.setStyles({'display':'none'}); }
			return !this.ovideo.isPlaying();
		}
	},
	
	set: function(time){
		
		if(this.isHTML5){
			this.ovideo.currentTime = time;
		} else {
			this.ovideo.seek(time);
		
		}
		
	},
		
	status: function(){
	
		if(this.isHTML5){
			
			/************************************
				VIDEO PROPERTIES
			************************************/
			
			var status = {
				'time':this.ovideo.currentTime,
				'duration':this.ovideo.duration,
				'buffer_start':this.ovideo.buffered.start(0),
				'buffer_end':this.ovideo.buffered.end(0),
				'played':this.ovideo.played.end(0)
			}
			
			/************************************
				NETWORK
			************************************/
			
			status.network = this.ovideo.networkState;
						
			/************************************
				READY STATES
			************************************/
			
			status.state = this.ovideo.readyState;
						
		} else {
			
			try{ var duration = this.ovideo.getClip().fullDuration; } catch(err) { var duration = 0; }
			
			/************************************
				VIDEO PROPERTIES
			************************************/
			
			var temp = this.ovideo.getStatus();
			var status = {
				'time':temp.time,
                'duration': duration,
                'buffer_start':temp.bufferStart,
                'buffer_end':temp.bufferEnd
			}
			
			/************************************
				NETWORK
			************************************/
						
			status.network = 4;
						
			/************************************
				READY STATES
			************************************/
			
			switch( this.ovideo.getState() ){
			
				case -1:
					status.state = 0;
					break;
				case 0:
					status.state = 4;
					break;
				case 1:
					status.state = 2;
					break;
				case 2:
					status.state = 3;
					break;
				case 3: 
					status.state = 4;
					break;
				case 4:
					status.state = 4;
					break;
				case 5:
					status.state = 4
					break;

			}
			
			
		}
		
		if( status.time > 0 && this.started == false){
			this.options.onPlay();
			this.started = true;
		} else if(status.time <= 0 && this.started == true) {
			this.started = false;
		}
		
		if(status.time >= (status.duration-1) && this.ended == false){
			this.options.onEnded();
			this.ended = true;
		} else if(status.time < status.duration-1 && this.ended == true) {
			this.ended = false;
		}
		
		
		return status;
	},
	
	
	
	inject: function(el){
		
	}
	

});

OVideoForm = new Class({
	
	Implements: Options,
	
	options: {
		'content_area_id':0,
		'content_part_id':0,
		'content_order':0,
		'content_text':''
	},
	
	initialize: function(options){
		
		this.setOptions(options);
		
		this.box = new sbox({'sbox_class':'obray-admin-container'});
		
		this.header = new BoxHeader({'header':'Insert New Video'});
		this.header.inject(this.box.content);
		
		this.form = new OForm({'url':'/cmd/opages/updateContent/','onComplete':function(){
			
		}.bind(this)});
		
		this.content_area_id = new OFHidden({'name':'content_area_id','value':this.options.content_area_id});
		this.form.addElement(this.content_area_id);
		
		this.content_part_id = new OFHidden({'name':'content_part_id','value':this.options.content_part_id});
		this.form.addElement(this.content_part_id);
		
		this.content_order = new OFHidden({'name':'content_order','value':this.options.content_order});
		this.form.addElement(this.content_order);
		
		this.content_part_type = new OFHidden({'name':'content_part_type','value':'video'});
		this.form.addElement(this.content_part_type);
		
		this.content_language = new OFHidden({'name':'content_language','value':'en'});
		this.form.addElement(this.content_language);
		
		this.content_text = new OFHidden({'name':'content_text','value':this.options.content_text});
		this.form.addElement(this.content_text);
		
		this.video_file = new OFFile({'upload_url':'/cmd/opieces/omedia/omedia/upload/','label':'Upload Video','name':'file_name','file_types':{'Videos (*.mov, *.mp4, *.flv)':'*.mov; *.mp4; *.flv;'},'file_name':this.options.video_name,'file_ext':this.options.video_ext,'file_size':this.options.video_size,'onUploadSuccess':$empty});
		this.form.addElement(this.video_file);
		
		this.form.inject(this.header.content);
		
		this.box.open();
		
	}

});

OVideo = new Class({
	Implements: [Options],
	
	options: {
		'content_area_id':0,
		'content_part_id':0,
	    'content_order':0,
		'video_id':0,
		'video_title':'',
		'video_description':'',
		'video_width':400,
		'video_height':300,
		'video_image_id':'',
		'video_size':0,
		'video_length':0,
		'video_name':'sample',
		'video_ext':'mp4',
		'video_image_location':'',
		'video_autoplay':false,
		'video_embed':true,
		'video_share':true,
		'share_url':'',
		'omedia_id':0
	},
	
	initialize: function(options){
		// data members
		this.setOptions(options);
						
		this.ometa_data = [
			{'name':'omedia_width','value':this.options.video_width,'type':'hidden','data_type':'integer'},
			{'name':'omedia_height','value':this.options.video_height,'type':'hidden','data_type':'integer'},
			{'label':'Aspect Ratio','name':'omedia_aspect_ratio','type':'select','labels':['16:9 (Video Widescreen Standard)','16:10 (Widescreen Computer Monitor)','4:3 (Traditional TV Format)','Custom (Use to size video arbitrarily)'],'values':['16:9','16:10','4:3'],'data_type':'text'},
			{'label':'Autoplay this video when the page loads?','name':'omedia_autoplay','type':'checkbox','data_type':'text'}
			
		];
		if(this.options.video_id == 0){ 
			this.openVideoForm();
		} else {			
			
			/********************************************
				OVideo Container
			********************************************/
			
			this.container = new Element('div',{'class':'ovideo-container'}).setStyles({'position':'relative','width':this.ometa_data[0].value,'height':this.ometa_data[1].value});
			
			/********************************************
				Player
			********************************************/
			
			this.player = new Player({'path':this.options.path,'width':this.options.video_width,'height':this.options.video_height,'autoplay':this.options.omedia_autoplay,'cover_path':this.options.cover_path});
			this.player.inject(this.container);
			
			/********************************************
				Admin
			********************************************/
			
			this.admin = new OWidgetMiniAdmin({'open-element':this.container});
			this.admin.addButton('delete-btn','Edit',function(){
				
				var confirm = new sboxConfirm({'message':'Are you sure you want to permanently remove this video from the site?','onConfirm':function(){
				
					var delete_r = new Request({'url':'/cmd/opages/deleteContent/','data':'&content_part_id='+this.options.content_part_id,'onComplete':function(){
						
					}.bind(this)}).send();
				
				}.bind(this)}).open();
				
			}.bind(this));
			
			this.admin.addButton('edit-btn','Edit',function(){
				this.openVideoForm();
			}.bind(this));
			
			/********************************************
				Resize
			********************************************/
			
			this.handle = new Element('div',{'class':'ovideo-handle'}).setStyles({'position':'absolute','right':-3,'bottom':-3,'height':10,'width':10,'border':'1px solid black','background-color':'#fff','cursor':'pointer','z-index':4999}).inject(this.container);
			
			
		}
		
		window['player'+this.options.content_part_id] = this.player;
		
	},
	
	openVideoForm: function(){
		if(this.options.video_id != 0){ var width = ',0'; } else { var width = ''; }
		new OMedia({'label':'Video','omedia_height':this.ometa_data[1].value+width,'omedia_width':this.ometa_data[0].value+width,'omedia_id':this.options.video_id,'omedia_object_id':this.options.content_part_id,'omedia_object_type':'content','link':true,'omedia_meta_data':'omedia_video_meta_data','ometa_data':this.ometa_data});
	},
	
	handleWithFlash: function(){
	    
	},
	
	resize: function(){
		var size = this.container.getCoordinates();
		
		this.player.resize(size.width,size.height,this.options.omedia_aspect_ratio);
	},
	
	save: function(){
	
		var size = this.container.getCoordinates();
		
		switch(this.options.omedia_aspect_ratio){
		
			case '16:9':
			
				size.height = (9 * size.width) / 16
				break;
				
			case '16:10':
				
				size.height = (10 * size.width) / 16
				break;
				
			case '4:3':
			
				size.height = (3 * size.width) / 4
				break;
		
		}
		
		this.container.setStyles({'height':size.height});
	
		var size = this.container.getCoordinates();
		var update_r = new Request({'url':'/cmd/opieces/omedia/omedia/update/','data':'&omedia_width='+size.width+'&omedia_height='+size.height+'&omedia_id='+this.options.omedia_id+'&omedia_meta_data=omedia_video_meta_data','onComplete':function(){
			
		}.bind(this)}).send();
		
	},
	
	inject: function(el,position){
	    this.container.inject(el,position);
	    this.container.makeResizable({'handle':this.options.handle,'onDrag':this.resize.bind(this),'onComplete':this.save.bind(this)});
	},
	
	injectAfter: function(el){
		this.container.injectAfter(el);
		this.container.makeResizable({'handle':this.options.handle});
	},
	
	injectInside: function(el){
		this.container.injectInside(el);
		this.container.makeResizable({'handle':this.options.handle});
	}
	
	
});




/***************************
Player = new Class({
    Implements: Options,
    
    options:{
        'content_area_id':0,
		'content_part_id':0,
	    'content_order':0,
		'video_id':0,
		'video_title':'',
		'video_description':'',
		'video_width':500,
		'video_height':282,
		'video_image_id':'',
		'video_size':0,
		'video_length':0,
		'video_name':'sample',
		'video_ext':'mp4',
		'video_autoplay':false,
		'video_embed':true,
		'video_share':true,
		'cover':'/assets/videos/video-cover-image.png',
		'embed_code':'',
		'share_url':'',
		'expand_window':true,
		'background-color':'#000',
		'enable_scrub':true,
		'onFinish':$empty,
		'video_on_amazon':false,
		'amazon_path':'',
		'enable_buffer':false,
		'enable_scrubbing': true,
		'onStart':$empty
    },
    
    initialize: function(options){
        this.setOptions(options);
        this.expanded = false;
        
        this.ovideo_container = new Element('div',{'class':'ovideo-container'});
        this.ovideo_container.setStyles({'position':'relative','left':0,'top':0,'height':this.options.video_height,'width':this.options.video_width});
        
    },
    
    expandVideo: function(){
    	
    	if(this.expanded == false){
	    	var dimensions = this.getWindowSize();
	    	this.ovideo_container.setStyles({'position':'fixed','top':0,'left':0});
	        this.v.setStyles({'width':dimensions.width,'height':dimensions.height});
	        this.ovideo_container.setStyles({'width':dimensions.width,'height':dimensions.height});
			this.controls.control_overlay.setStyles({'width':dimensions.width,'height':dimensions.height});
			this.controls.control_bar.setStyles({'width':dimensions.width});
	   		this.controls.scrubber.scrub_bar.setStyles({'width':dimensions.width-212});
	 		this.controls.scrubber.options.width = dimensions.width - 212;
	 		this.controls.scrubber.setSlider();
	 		this.expanded = true;
 		} else {
 			this.ovideo_container.setStyles({'position':'relative','top':0,'left':0});
	        this.v.setStyles({'width':this.options.video_width,'height':this.options.video_height});
	        this.ovideo_container.setStyles({'width':this.optionsvideo_widthwidth,'height':this.options.video_height});
			this.controls.control_overlay.setStyles({'width':this.options.video_width,'height':this.options.video_height});
			this.controls.control_bar.setStyles({'width':this.options.video_width});
	   		this.controls.scrubber.scrub_bar.setStyles({'width':this.options.video_width-212});
	 		this.controls.scrubber.options.width = this.options.video_width-212;
 			this.controls.scrubber.setSlider();
 			this.expanded = false;
 		}
    	
    },
    
    getWindowSize: function(){
    	var viewportwidth;
		var viewportheight;
		
		// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
		
		if (typeof window.innerWidth != 'undefined')
		{
		  viewportwidth = window.innerWidth,
		  viewportheight = window.innerHeight
		}
		
		// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
		
		else if (typeof document.documentElement != 'undefined'
		 && typeof document.documentElement.clientWidth !=
		 'undefined' && document.documentElement.clientWidth != 0)
		{
		   viewportwidth = document.documentElement.clientWidth,
		   viewportheight = document.documentElement.clientHeight
		}
		
		// older versions of IE
		
		else
		{
		   viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
		   viewportheight = document.getElementsByTagName('body')[0].clientHeight
		}
		
		return {width:viewportwidth,height:viewportheight};
    },
    
	inject: function(el,position){
	    this.ovideo_container.inject(el,position);
	    this.injectOther();
		if(!this.options.enable_scrub) this.controls.setOptions({'enable_scrub':false});
	    this.controls.inject(this.ovideo_container);
		this.ovideo.load();
	},
	
	injectAfter: function(el){
		this.ovideo_container.inject(el,'after');
		this.injectOther();
		this.controls.inject(this.ovideo_container);
		this.ovideo.load();
	},
	
	injectInside: function(el){
		this.ovideo_container.inject(el);
		this.injectOther();
		this.controls.inject(this.ovideo_container);
		this.ovideo.load();	
	},
	
	getPlayer: function(){
	    return this.ovideo_container;
	},
	
	setDimensions: function(width,height){
	    this.ovideo_container_fx.start({'width':width,'height':height});
	},
	
	loadLoader: function(){
		
		this.loader = new Element('div',{'class':'ovideo-loader'});
		this.loader.setStyles({'position':'absolute','color':'#fff','font-family':'Helvetica,Arial','font-size':14,'z-index':10000,'padding':15});
		this.loader.set('html','Loading player, please wait...');
		
	},
	
	supports_video: function() {
	  return !!document.createElement('video').canPlayType;
	},
	
	injectOther: function(){
		

	
		if( Modernizr.video && Modernizr.video.h264 == 'probably' ){
		    this.ovideo = new Element('video',{'id':'OVideo-'+this.options.content_part_id,'autoplay':this.options.video_autoplay,'src':'assets/videos/'+this.options.video_name+'.'+this.options.video_ext,'height':this.options.video_height,'width':this.options.video_width});
            this.ovideo.setStyles({'background-color':this.options['background-color'],'height':this.video_height,'width':this.video_width});
            this.ovideo.inject(this.ovideo_container);
            this.ovideo.addEventListener('ended',function(e){
                this.controls.togglePlayStatus(e);
            }.bind(this));
		} else {
		    this.ovideo = new Element('div',{'id':'OVideo-'+this.options.content_part_id,'class':'OVideo'});
            this.ovideo.setStyles({'height':this.options.video_height,'width':this.options.video_width,'position':'absolute'});
            var path = ''
            if( this.options.video_on_amazon == true){
            	path = this.options.amazon_path;
            } else {
            	path = '/assets/videos/'+this.options.video_name+'.'+this.options.video_ext;
            }
            
            this.loadLoader();
            this.loader.inject(this.ovideo_container);
            
            if(Browser.Engine.name == 'trident'){ var cachebusting = true; } else { var cachebusting = false; }
            
            this.movie = $f(this.ovideo,{'src':'/obray/flash/flowplayer.swf','wmode':'opaque','cachebusting':cachebusting},{
                'class':'ovideo',
                'plugins': {'controls': null},
                'clip': { 
                    'url': path, 
                    'autoPlay': this.options.video_autoplay, 
                    'autoBuffering': false,
                    'scaling':'fit',
                    'bufferLength':15,
                    'onBegin':function(){
                    	this.loader.destroy();
                    	this.controls.updateBuffer.periodical(50,this.controls);
                    }.bind(this),
                    'onStart':function(){
                    	this.controls.autoplay();
                    	this.options.onStart();
                    }.bind(this),
                    'onLoad':function(e){
                        this.controls.togglePlayStatus(e);
                    }.bind(this),
                    'onLastSecond':function(){
                    	//alert('onLastSecon');
                    	this.options.onFinish.delay(250);
                    }.bind(this),
					'onFinish':function() {
						//alert('finished');
						this.options.onFinish.delay(250);
					}.bind(this)
                },
                'onLoad':this.onLoad.bind(this),
				'onFinish':function() {
				}.bind(this)
            });
            this.ovideo.inject(this.ovideo_container);
            this.v = this.ovideo;
            this.ovideo = this.movie;
            
            this.movie.toggleFullscreen();
            
            this.ovideo_container_fx = new Fx.Morph(this.ovideo_container,{'duration':500,'transition':Fx.Transitions.Quint.easeOut});
            //this.ovideo_fx = new Fx.Morph(this.image_btn,{'duration':500,'transition':Fx.Transitions.Quint.easeOut});
		}
		
		this.controls = new PlayerControls({
		    'video_id':this.options.video_id,
		    'width':this.options.video_width,
		    'height':this.options.video_height,
		    'html5':this.isHTML5Compatible(),
		    'video':this.ovideo,
		    'video_name':this.options.video_name,
		    'video_ext':this.options.video_ext,
		    'cover':this.options.cover,
		    'enable_share':this.options.video_share,
		    'enable_embed':this.options.video_embed,
		    'video_image_name':this.options.video_image_name,
		    'video_image_ext':this.options.video_image_ext,
		    'video_image_location':this.options.video_image_location,
		    'embed_code':this.options.embed_code,
		    'share_url':this.options.share_url,
		    'video_autoplay':this.options.video_autoplay,
		    'expand_window':this.options.expand_window,
		    'enable_buffer':this.options.enable_buffer,
		    'enable_scrubbing':this.options.enable_scrubbing,
		    'onExpand':function(){ this.expandVideo(); }.bind(this)
		})
	}
	
	
	
	
});


OVideoSettings = new Class({
    Implements: Options,
    
    options: {
        'video_id':0,
        'video_width':500,
        'video_height':282,
        'video_name':'sample',
        'video_ext':'mp4',
        'video_autoplay':false,
        'video_embed':true,
        'video_share':true,
        'video_title':'',
        'video_descrption':'',
        'video_size':0,
        'onComplete':$empty,
        'video_image_name':'',
        'video_image_id':'',
        'video_image_ext':'',
        'share_url':''
    },
    
    initialize: function(options){
        this.setOptions(options);

        this.video_btn = new Element('input',{'type':'button','value':'Save Video'});
        
        this.settings_form = new OForm({
            'url':'index.cfm?action=videos.saveVideo&fusebox.password=thinkbig&fusebox.load=true&fusebox.%20parse=true&fusebox.execute=true',
            'onComplete':this.options.onComplete
        });
        
        this.settings_form.addElement(new OFFile({'label':'Upload Video','name':'file_name','file_types':{'Videos (*.mov, *.mp4, *.flv)':'*.mov; *.mp4; *.flv;'},'file_name':this.options.video_name,'file_ext':this.options.video_ext,'file_size':this.options.video_size,'onUploadSuccess':$empty}));
		
        this.settings_form.addElement(new OFText({'label':'Dimensions','name':'video_width','blur':function(){ this.settings_form.elements[3].setDimensions(this.settings_form.elements[1].getProperty('value'),this.settings_form.elements[2].getProperty('value')); }.bind(this)}));
        
        this.settings_form.elements[1].text_input.setStyles({'width':50});
        
        this.settings_form.addElement(new OFText({'label':'X','name':'video_height','blur':function(){ this.settings_form.elements[3].setDimensions(this.settings_form.elements[1].getProperty('value'),this.settings_form.elements[2].getProperty('value')); }.bind(this)}));
        
        this.settings_form.elements[2].text_input.setStyles({'width':50});
        
        //this.settings_form.addElement(new OFImage({'label':'Video Thumb','name':'video_image_id','image_width':this.options.video_width,'image_height':this.options.video_height,'image_id':this.options.video_image_id,'image_name':this.options.video_image_name,'image_ext':this.options.video_image_ext}));
        this.settings_form.addElement(new OFText({'label':'Video Title','name':'video_title','value':this.options.video_title}));
        this.settings_form.addElement(new OFText({'label':'Video Description','name':'video_description','text-area':true,'value':this.options.video_description}));
        this.settings_form.addElement(new OFCheck({'label':'Autoplay','name':'video_autoplay','checked':this.options.video_autoplay}));
        this.settings_form.addElement(new OFCheck({'label':'Embed','name':'video_embed','checked':this.options.video_embed}));
        this.settings_form.addElement(new OFCheck({'label':'Share','name':'video_share','checked':this.options.video_share}));
        this.settings_form.addElement(new OFHidden({'value':this.options.video_id,'name':'video_id'}));
        
        
        
    },
    
    inject: function(el){
        this.settings_form.inject(el);
        
    },
    
    setDimensions: function(x,y){
        
    }
});




VideoEmbed = new Class({
    Implements: Options,
    
    options:{
        'position':{'x':0,'y':0},
        'embed_code':''
    },
    
    initialize: function(options){
        this.setOptions(options);
        
        // embed container
        this.embed_container = new Element('div',{'class':'ovideo-embed-container'});
        this.embed_container.setStyles({'position':'absolute','padding':8,'background-image':'url(/obray/images/oplayer/embed-popup.png)','width':216,'height':66,'top':this.options.position.y,'left':this.options.position.x,'display':'none'});
        this.embed_container.addEvent('click',function(e){ e.stopPropagation(); })
        
        // embed label
        this.embed_label = new Element('label',{'class':'ovideo-embed-label'});
        this.embed_label.setStyles({'width':200,'font-family':'arial','font-size':10,'color':'#fff','padding':5,'text-align':'left'});
        this.embed_label.set('html','COPY THIS EMBED CODE');
        
        
        // embed input
        this.embed_input = new Element('input',{'type':'text','class':'ovideo-embed-input','value':this.options.embed_code});
        this.embed_input.setStyles({'background-color':'transparent','border':0,'background-image':'url(/obray/images/oplayer/embed-input.png)','width':205,'height':22,'margin-left':4,'font-family':'Courier,Arial'});
        
        this.embed_input.addEvent('mouseup',function(){
            this.embed_input.select();
        }.bind(this))
    },
    
    open: function(){
        this.embed_container.setStyles({'display':'block'});
    },
    
    close: function(){
        this.embed_container.setStyles({'display':'none'});
    },
    
    inject: function(el){
        this.embed_container.inject(el);
        this.embed_label.inject(this.embed_container);
        this.embed_input.inject(this.embed_container);
    }
});

VideoShare = new Class({
    Implements: Options,
    
    options:{
        'video_id':0,
        'position': {'x':0,'y':0},
        'share_url':'http://www.adventcreative.com'
    },
    
    initialize: function(options){
        this.setOptions(options);
        
        // share container
        this.share_container = new Element('div',{'class':'ovideo-share-container'});
        this.share_container.setStyles({'position':'absolute','padding':8,'background-image':'url(/obray/images/oplayer/share-popup.png)','width':216,'height':170,'top':this.options.position.y,'left':this.options.position.x,'display':'none'});
        this.share_container.addEvent('click',function(e){ e.stopPropagation(); });
        
        // share label
        this.share_label = new Element('label',{'class':'ovideo-share-label'});
        this.share_label.setStyles({'width':200,'font-family':'arial','font-size':10,'color':'#fff','padding':5,'text-align':'left'});
        this.share_label.set('html','EMAIL TO A FRIEND');
        
        
        // share input
        this.share_input = new Element('input',{'class':'ovideo-share-input'});
        this.share_input.setStyles({'background-color':'transparent','border':0,'background-image':'url(/obray/images/oplayer/embed-input.png)','width':205,'height':22,'margin-left':4});
        
        
        // share message
        this.share_message = new Element('div',{'class':'ovideo-share-message'});
        this.share_message.setStyles({'text-align':'center','display':'none','font-family':'Arial,Helvetica','font-face':'bold','font-size':13,'padding-top':15,'padding-bottom':10,'padding-left':5,'font-weight':'bold'});
        this.share_message.set('html','SENT SUCCESSFULLY<br/>');
        
        
        this.send_again_btn = new Element('a');
        this.send_again_btn.setStyles({'font-family':'Arial,Helvetica','font-face':'bold','font-size':11,'color':'#d5d5d5','cursor':'pointer'});
        this.send_again_btn.set('html',' Send Another');
        
        this.send_again_btn.addEvent('click',function(){
            this.share_btn.setStyles({'display':'inline'});
            this.share_input.setStyles({'display':'inline'});
            this.share_message.setStyles({'display':'none'});
            this.share_label.setStyles({'display':'block'});
        }.bind(this));
        
        // share icons
        this.share_icons = new Element('div',{'class':'ovideo-share-icons'});
        this.share_icons.setStyles({'position':'relative','width':206,'padding':3,'border-top':'1px solid #747070','margin-top':10,'margin-left':4,'margin-right':3,'margin-bottom':3});
        
        
        // share email button
        this.share_btn = new Element('img',{'src':'/obray/images/oplayer/email-btn.png'});
        this.share_btn.setStyles({'position':'absolute','top':-34,'left':179,'width':27,'height':22});
        
        this.share_btn.addEvent('click',function(){ 
            var data = '&video_id=' + this.options.video_id
                     + '&email_address=' + this.share_input.getProperty('value');
            this.request = new Request({'url':'index.cfm?action=videos.emailVideo&fusebox.password=thinkbig&fusebox.load=true&fusebox.%20parse=true&fusebox.execute=true','data':data,'method':'post','onComplete':function(){
                this.share_btn.setStyles({'display':'none'});
                this.share_input.setStyles({'display':'none'});
                this.share_message.setStyles({'display':'block'});
                this.share_label.setStyles({'display':'none'});
            }.bind(this)}).send();
        }.bind(this));
        
        this.facebook_btn = new Element('img',{'src':'/obray/images/oplayer/facebook-btn.png'});
        this.facebook_btn.setStyles({'margin':4,'margin-top':10});
        
        this.facebook_btn.addEvent('click',function(){ window.open('http://www.facebook.com/share.php?u=' + encodeURIComponent(this.options.share_url),'_blank'); }.bind(this));
        
        this.twitter_btn = new Element('img',{'src':'/obray/images/oplayer/twitter-btn.png'});
        this.twitter_btn.setStyles({'margin':4,'margin-top':10});
        
        this.twitter_btn.addEvent('click',function(){ window.open('http://www.twitter.com/home?status=' + encodeURIComponent(this.options.share_url),'_blank'); }.bind(this));
        
        // this.youtube_btn = new Element('img',{'src':'/obray/images/oplayer/youtube-btn.png'});
        // this.youtube_btn.setStyles({'margin':4,'margin-top':10});
        // this.youtube_btn.inject(this.share_icons);
        
        this.myspace_btn = new Element('img',{'src':'/obray/images/oplayer/myspace-btn.png'});
        this.myspace_btn.setStyles({'margin':4,'margin-top':10});
        
        this.myspace_btn.addEvent('click',function(){ window.open('https://secure.myspace.com/index.cfm?fuseaction=login.simpleform&featureName=postToV3&dest=http%3a%2f%2fwww.myspace.com%2fModules%2fPostTo%2fPages%2fdefault.aspx%3fu%3d' + encodeURIComponent(this.options.share_url) ) }.bind(this));
        
        this.technorati_btn = new Element('img',{'src':'/obray/images/oplayer/technorati-btn.png'});
        this.technorati_btn.setStyles({'margin':4,'margin-top':10});
        
        this.technorati_btn.addEvent('click',function(){ window.open('http://technorati.com/faves?add=' + encodeURIComponent(this.options.share_url),'_blank'); }.bind(this));
        
        // this.wordpress_btn = new Element('img',{'src':'/obray/images/oplayer/wordpress-btn.png'});
        // this.wordpress_btn.setStyles({'margin':4,'margin-top':10});
        // this.wordpress_btn.inject(this.share_icons);
        
        // this.blogger_btn = new Element('img',{'src':'/obray/images/oplayer/blogger-btn.png'});
        // this.blogger_btn.setStyles({'margin':4,'margin-top':10});
        // this.blogger_btn.inject(this.share_icons);
        
        this.delicious_btn = new Element('img',{'src':'/obray/images/oplayer/delicious-btn.png'});
        this.delicious_btn.setStyles({'margin':4,'margin-top':10});
        
        this.delicious_btn.addEvent('click',function(){ window.open('http://delicious.com/save?jump=yes&url=' + encodeURIComponent(this.options.share_url),'_blank'); }.bind(this));
        
        this.digg_btn = new Element('img',{'src':'/obray/images/oplayer/digg-btn.png'});
        this.digg_btn.setStyles({'margin':4,'margin-top':10});
        
        this.digg_btn.addEvent('click',function(){ window.open('http://digg.com/submit?phase=2&url=' + encodeURIComponent(this.options.share_url),'_blank'); }.bind(this));
        
        this.stumble_btn = new Element('img',{'src':'/obray/images/oplayer/stumble-btn.png'});
        this.stumble_btn.setStyles({'margin':4,'margin-top':10});
        
        this.stumble_btn.addEvent('click',function(){ window.open('http://www.stumbleupon.com/submit?url=' + encodeURIComponent(this.options.share_url),'_blank'); }.bind(this));
    },
    
    open: function(){
        this.share_container.setStyles({'display':'block'});
    },
    
    close: function(){
        this.share_container.setStyles({'display':'none'});
    },
    
    inject: function(el){
        this.share_container.inject(el);
        this.share_label.inject(this.share_container);
        this.share_input.inject(this.share_container);
        
        this.share_message.inject(this.share_container);
        this.send_again_btn.inject(this.share_message);
        
        this.share_icons.inject(this.share_container);
        this.share_btn.inject(this.share_icons);
        this.facebook_btn.inject(this.share_icons);
        this.twitter_btn.inject(this.share_icons);
        this.myspace_btn.inject(this.share_icons);
        this.technorati_btn.inject(this.share_icons);
        this.delicious_btn.inject(this.share_icons);
        this.digg_btn.inject(this.share_icons);
        this.stumble_btn.inject(this.share_icons);
    }
});

VideoVolume = new Class({
    Implements: Options,
    
    options:{
        'position':{'x':0,'y':0},
        'onChange':$empty,
        'volume':75
    },
    
    initialize: function(options){
        this.setOptions(options);
        
        this.volume_container = new Element('div',{'class':'ovideo-volume-container'});
        this.volume_container.setStyles({'display':'none','background-image':'url(/obray/images/oplayer/volume-popup.png)','position':'absolute','left':this.options.position.x,'top':this.options.position.y,'width':28,'height':188});
        this.volume_container.addEvent('click',function(e){
            e.stopPropagation();
        }.bind(this));
        
        this.volume_track = new Element('div',{'class':'ovideo-volume-track'});
        this.volume_track.setStyles({'position':'relative','display':'block','height':154,'width':1,'border':'0px solid #000','margin-left':13,'margin-right':13,'margin-top':11});
        
        
        this.volume_handle = new Element('div',{'class':'ovideo-volume-handle'});
        this.volume_handle.setStyles({'position':'absolute','display':'block','top':0,'left':-2,'width':7,'height':7,'background-color':'#fff','cursor':'pointer'});
        
        this.volume_handle.addEvent('click',addEvent('click',function(e){
            e.stopPropagation();
        }.bind(this)));
        
        this.volume_container.addEvent('mouseleave',function(){
        	this.close();
        }.bind(this))
    },
    
    open: function(){
        this.volume_container.setStyles({'display':'block'});
        if(!this.volume_control){ 
            this.volume_control = new Slider(this.volume_track,this.volume_handle,{'mode':'vertical','steps':100,'onChange':this.options.onChange});
            this.volume_control.set(this.options.volume);
        }
    },
    
    close: function(){
        this.volume_container.setStyles({'display':'none'});
    },
    
    inject: function(el){
        this.volume_container.inject(el);
        this.volume_track.inject(this.volume_container);
        this.volume_handle.inject(this.volume_track);
        
    }
});


// JavaScript Document
PlayerControls = new Class({
    Implements: Options,
    
    options:{
        'video_id':0,
        'width':500,
        'height':282,
        'html5':false,
        'video': new Element('video'),
        'cover':'/assets/videos/video-cover-image.png',
        'enable_embed':true,
        'enable_share':true,
        'video_image_name':'',
        'video_image_ext':'',
        'video_image_location':'',
        'embed_code':'',
        'share_url':'',
        'video_autoplay':'',
        'expand_window':true,
		'enable_scrub':true,
		'enable_buffer':false,
		'enable_scrubbing':true,
		'onExpand':$empty
    },
    
    initialize: function(options){
        this.setOptions(options);
        
        this.play_status = 'stopped';
        this.embed_status = 'closed';
        this.share_status = 'closed';
        this.volume_status = 'closed';
        this.screen_status = 'normal';
                
        if(this.options.video_image_location == "Amazon S3"){ var image_location = window.obray.amazon_location; } else { var image_location = '/assets/images/'; }
        this.video_still = new Element('img',{'src':image_location+this.options.video_image_name+'_standard.'+this.options.video_image_ext,'class':'video-still'});
        this.video_still.setStyles({'position':'absolute','z-index':2997,'top':0,'left':0,'display':'block'});
        
        this.control_overlay = new Element('div',{'class':'ovideo-control-overlay'});
        this.control_overlay.setStyles({'background-image':'url('+this.options.cover+')','background-position':'50% 50%','position':'absolute','overflow':'hidden','top':0,'left':0,'display':'block','width':this.options.width,'height':this.options.height,'z-index':2998});
        this.control_overlay.addEvent('mouseenter',function(){ this.control_bar_fx.pause(); this.control_bar_fx.start({'bottom':0}); }.bind(this));
        this.control_overlay.addEvent('mouseleave',function(){ 
            if(this.embed_status != 'open' && this.share_status != 'open' && this.volume_status != 'open'){
                this.control_bar_fx.pause(); 
                this.control_bar_fx.start({'bottom':-this.control_bar.getCoordinates().height});
            }
        }.bind(this))
        this.control_overlay.addEvent('click',this.togglePlayStatus.bind(this))
        
        this.control_bar = new Element('div',{'class':'ovideo-control-bar','id':this.options.id});
        this.control_bar.setStyles({'position':'absolute','bottom':0,'left':0,'width':this.options.width,'height':30,'background-image':'url(/obray/images/oplayer/control-bar-bg.png)'});
        
        this.control_bar_fx = new Fx.Morph(this.control_bar,{duration:250,transition: Fx.Transitions.Quint.easeOut});
        this.control_bar.addEvent('click',function(e){ e.stopPropagation(); }.bind(this));
        
        this.play_and_pause_btn = new Element('div',{'class':'ovideo-play-and-pause-btn'});
        this.play_and_pause_btn.setStyles({'float':'left','width':30,'height':30,'background-image':'url(/obray/images/oplayer/play-btn.png)','cursor':'pointer'});
        
        this.play_and_pause_btn.addEvent('click',this.togglePlayStatus.bind(this));
        this.play_and_pause_btn.addEvent('mouseenter',function(){
            if(this.play_status == 'stopped'){
                this.play_and_pause_btn.setStyles({'background-image':'url(/obray/images/oplayer/play-btn-hover.png)'});
            } else {
                this.play_and_pause_btn.setStyles({'background-image':'url(/obray/images/oplayer/pause-btn-hover.png)'});
            }
        }.bind(this));
        this.play_and_pause_btn.addEvent('mouseleave',function(){ 
            if(this.play_status == 'stopped'){
                this.play_and_pause_btn.setStyles({'background-image':'url(/obray/images/oplayer/play-btn.png)'});
            } else {
                this.play_and_pause_btn.setStyles({'background-image':'url(/obray/images/oplayer/pause-btn.png)'});
            }
        }.bind(this));
        
        this.scrub_bar_width = 317;
        if(!this.options.enable_embed){this.scrub_bar_width = this.scrub_bar_width - 53;}
        if(!this.options.enable_share){this.scrub_bar_width = this.scrub_bar_width - 52;}
        
        this.scrubber = new ScrubBar({
        	'width':this.options.width-this.scrub_bar_width,
        	'enable_scrubbing':this.options.enable_scrubbing,
        	'onComplete':function(percent){
        		var status = this.getCurrentStatus();
		        // convert the position into the seconds
		        var seconds = percent * status.duration;
        		this.pause();
	        	this.options.video.seek(seconds); 
	        	this.play();
        	}.bind(this)
        });
        
        this.timer = new Element('div',{'class':'ovideo-timer'});
        this.timer.setStyles({'float':'left','font-family':'Arial,Helvetica','color':'#fff','font-size':10,'width':75,'text-align':'center','padding':10});
        this.timer.set('html','00:00 | 00:00');
        
        
        this.embed_btn = new Element('div',{'class':'ovideo-embed-btn'});
        this.embed_btn.setStyles({'position':'relative','width':31,'float':'left','font-family':'Arial,Helvetica','color':'#fff','font-size':10,'padding':10,'letter-spacing':-1,'cursor':'pointer','border-left':'2px solid #343434'});
        this.embed_btn.set('html','EMBED');
        
        this.embed_btn.addEvent('mouseenter',function(){ this.embed_btn.setStyles({'color':'#9b9b9b','background-image':'url(/obray/images/oplayer/btn-hover.png)'}); }.bind(this));
        this.embed_btn.addEvent('mouseleave',function(){ if(this.embed_status == 'closed'){ this.embed_btn.setStyles({'color':'#fff','background-image':'none'}); } }.bind(this));
        this.embed_btn.addEvent('click',this.toggleEmbed.bind(this));
        this.embed_popup = new VideoEmbed({'position':{'y':-84,'x':-170},'embed_code':this.options.embed_code});
        
        
        this.share_btn = new Element('div',{'class':'ovideo-share-btn'});
        this.share_btn.setStyles({'position':'relative','width':30,'float':'left','font-family':'Arial,Helvetica','color':'#fff','font-size':10,'padding':10,'letter-spacing':-1,'cursor':'pointer','border-left':'2px solid #343434'});
        this.share_btn.set('html','SHARE');
        
        this.share_btn.addEvent('mouseenter',function(){ this.share_btn.setStyles({'color':'#9b9b9b','background-image':'url(/obray/images/oplayer/btn-hover.png)'}); }.bind(this));
        this.share_btn.addEvent('mouseleave',function(){  if(this.share_status == 'closed'){ this.share_btn.setStyles({'color':'#fff','background-image':'none'});} }.bind(this)); 
        this.share_btn.addEvent('click',this.toggleShare.bind(this));
        this.share_popup = new VideoShare({'position':{'x':-170,'y':-190},'share_url':this.options.share_url,'video_id':this.options.video_id});
        
        
        this.volume_btn = new Element('div',{'class':'ovideo-volumn-btn'});
        this.volume_btn.setStyles({'position':'relative','float':'left','background-image':'url(/obray/images/oplayer/volume-btn.png)','font-family':'Arial,Helvetica','color':'#fff','font-size':10,'height':10,'width':10,'padding':10,'letter-spacing':-1,'cursor':'pointer','border-left':'2px solid #343434'});
        
        this.volume_btn.addEvent('mouseenter',function(){ this.volume_btn.setStyles({'background-image':'url(/obray/images/oplayer/volume-btn-hover.png)'}); }.bind(this));
        this.volume_btn.addEvent('mouseleave',function(){ this.volume_btn.setStyles({'background-image':'url(/obray/images/oplayer/volume-btn.png)'}); }.bind(this));
        this.volume_btn.addEvent('click',this.toggleVolume.bind(this));
        this.volume_popup = new VideoVolume({'position':{'x':0,'y':-195},'onChange':function(step){
            if(!this.options.html5){ this.options.video.setVolume(100-step); } else { }
        }.bind(this)});
        
        
        if(this.options.expand_window){
            
            this.expand_btn = new Element('div',{'class':'ovideo-fullscreen-btn'})
            this.expand_btn.setStyles({'float':'left','background-image':'url(/obray/images/oplayer/expand-btn.png)','font-family':'Arial,Helvetica','color':'#fff','font-size':10,'padding':10,'height':10,'width':30,'letter-spacing':-1,'cursor':'pointer','border-left':'2px solid #343434'});
            
            this.expand_btn.addEvent('mouseenter',function(){ this.expand_btn.setStyles({'background-image':'url(/obray/images/oplayer/expand-btn-hover.png)'}); }.bind(this));
            this.expand_btn.addEvent('mouseleave',function(){ this.expand_btn.setStyles({'background-image':'url(/obray/images/oplayer/expand-btn.png)'}); }.bind(this));
            //expand window
            
        }
        

        this.buffer = new Element('div',{'class':'ovide-player-buffer'});
        //this.buffer.setStyles({'float':'left','position':'relative','height':30,'width':100,'color':'#fff','font-size':10,'padding-top':10,'font-family':'Helvetica,Arial'});
        
    },
    
    updateBuffer: function(){
    	if(this.options.video.isLoaded()){
	    	var status = this.getCurrentStatus();
	    	if(this.options.enable_buffer){
	        	var buffer = status.buffer_end / status.duration;
	        	this.scrubber.setBuffer(buffer);

	        	var time_left = this.download_speed * ( status.duration - status.buffer_end );
	        	
	        	if( (time_left+15) < status.duration){
	        		this.play();
	        	}

	        }
        }
    },
    
    inject: function(el){
        if( this.options.video_image_name != undefined ){ this.video_still.inject(el); }
        this.control_overlay.inject(el);
        
        this.control_bar.inject(this.control_overlay);
        this.play_and_pause_btn.inject(this.control_bar);
        
        this.timer.inject(this.control_bar);
        if(this.options.enable_buffer){
        	this.buffer.inject(this.control_bar);
        	//this.updateBuffer.periodical(50,this);
        }
        if(this.options.enable_embed){this.embed_btn.inject(this.control_bar);}
        this.embed_popup.inject(this.embed_btn);
        if(this.options.enable_share){this.share_btn.inject(this.control_bar);}
        this.share_popup.inject(this.share_btn);
        
        this.volume_btn.inject(this.control_bar);
        this.volume_popup.inject(this.volume_btn);
        
        
        
        
        
        this.control_bar_fx.pause();
        this.control_bar_fx.start({'bottom':-this.control_bar.getCoordinates().height});
        
        this.scrubber.inject(this.control_bar);
        //this.scrub_control = new Slider(this.scrub_bar,this.scrub_progress_handle,{'mode':'horizontal','steps':1000,'onChange':this.setProgress.bind(this),'snap':false,'onComplete':this.scrub.bind(this)});
        //events
        if(!this.options.html5){

        }
       
        if(this.options.video_autoplay){ 
        	//this.options.video.load(this.togglePlayStatus.bind(this,new Event())) 
        }
        
        if(this.options.expand_window){
        	this.expand_btn.inject(this.control_bar);
        	
        	
        	this.expand_window = new sbox({'scrollable':false,'close':function(){ 
                this.big_player.controls.pause(); 
            }.bind(this)});
            
            //create larger video player
            this.expand_btn.addEvent('click',function(){
                // calculate new height
                this.options.onExpand();
            }.bind(this));
            
        }
    },
    
    play: function(){
        this.options.video.play();
        this.play_and_pause_btn.setStyles({'background-image':'url(/obray/images/oplayer/pause-btn.png)'});
        this.control_overlay.setStyles({'background-image':'url(/obray/images/oplayer/overlay-bg.png)'});

        this.video_still.setStyles({'display':'none'});
        this.play_status = 'playing';
        this.progress_timer_interval = this.updateProgress.periodical(50,this);
    },
    
    pause: function(){
        $clear(this.progress_timer_interval);
        this.options.video.pause();
        this.play_and_pause_btn.setStyles({'background-image':'url(/obray/images/oplayer/play-btn.png)'});
        this.control_overlay.setStyles({'background-image':'url('+this.options.cover+')'});
        this.play_status = 'stopped';
    },
    
    togglePlayStatus: function(e){
        e.stopPropagation();
        if(this.play_status == 'stopped'){ this.play(); } else { this.pause(); }
    },
    
    autoplay: function(){
	    this.play_and_pause_btn.setStyles({'background-image':'url(/obray/images/oplayer/pause-btn.png)'});
        this.control_overlay.setStyles({'background-image':'url(/obray/images/oplayer/overlay-bg.png)'});
        this.video_still.setStyles({'display':'none'});
        this.play_status = 'playing';
        this.progress_timer_interval = this.updateProgress.periodical(50,this);
    },
        
    toggleEmbed: function(){
        if(this.embed_status == 'closed'){
            this.embed_popup.open();
            this.embed_status = 'open';
        } else {
            this.embed_popup.close();
            this.embed_status = 'closed';
        }
    },
    
    toggleShare: function(){
        if(this.share_status == 'closed'){
            this.share_popup.open();
            this.share_status = 'open';
        } else {
            this.share_popup.close();
            this.share_status = 'closed';
        }
    },
    
    toggleVolume: function(){
        if(this.volume_status == 'closed'){
            this.volume_popup.open();
            this.volume_status = 'open';
        } else {
            this.volume_popup.close();
            this.volume_status = 'closed';
        }
    },
	
	getStatus: function() { // Fix to counter the missing getStatus function
		this.getCurrentStatus();
	},
    
    getCurrentStatus: function(){
        if(!this.options.html5){
            var status = this.options.video.getStatus();
            var video_status = {
                'current_time':status.time,
                'duration': this.options.video.getClip().fullDuration,
                'buffer_start':status.bufferStart,
                'buffer_end':status.bufferEnd
            }
        } else {
            var video_status = {
                'current_time':this.options.video.currentTime,
                'duration': this.options.video.duration,
                'buffer_start':0,
                'buffer_end':0
            }
        }
        return video_status;
    },
    
    scrub: function(position){
        // need duration
        var status = this.getCurrentStatus();
        // convert the position into the seconds
        var seconds = position * status.duration/1000;
        // scrub to the specified time
        if(!this.options.html5){ 
        	this.pause();
        	this.options.video.seek(seconds); 
        	this.setProgress(position); 
        	this.play();
        } else { this.options.video.currentTime = seconds; }
    },
    
    updateProgress: function(){
        this.setProgress(false);
    },
    
    timeFormat: function(time_in_sec){
        var time_string_hr  = time_in_sec / 3600;
        var time_string_min = time_in_sec / 60;
        var time_string_sec = time_in_sec % 60;
        
        (time_string_hr.toInt()  < 10) ? time_string_hr=  ('0' + time_string_hr.toInt())  : time_string_hr=time_string_hr.toInt();
        (time_string_min.toInt() < 10) ? time_string_min= ('0' + time_string_min.toInt()) : time_string_min=time_string_min.toInt();
        (time_string_sec.toInt() < 10) ? time_string_sec= ('0' + time_string_sec.toInt()) : time_string_sec=time_string_sec.toInt();
        
        var time_string = time_string_min + ':' + time_string_sec;
        if(time_string_hr > 0){time_string_hr + ':' + time_string;}
        return time_string;
    },
    
    setProgress: function(position){
        // get current time, buffer, duration, etc...
        var status = this.getCurrentStatus();
        // if position isn't defined then set the position based on current time & duration
        if(!position){ var position = (status.current_time/status.duration*1000).toInt(); }
        // determine progres bar width
        var width = (this.scrubber.options.width*(position/1000)).toInt();
        // set progress bar width
        //this.scrubber.set(width+2);
        
        // set scrub handles position
        if(isNaN(position)){position=0;}
        if(this.scrubber.status != 'scrubbing'){ this.scrubber.set(position/1000); }
        // scrub the movie to the correct time
        if(this.options.html5){ this.scrub(position); }
        // get formatted times
        var time_current = this.timeFormat(status.current_time);
        var time_duration = this.timeFormat(status.duration);
        // show formatted times
        this.timer.set('html',time_current + ' | ' + time_duration);
    }
    
    
    
});

****************/ /******************************************************
	
	OUSER MANAGER
	
	DESCRIPTION
		
		This is used to manage ousers. You can search,
		and filter ouser and create new ousers from
		this interface.  They can also be selected
		and that user id will be set as the value
		parameter.
		
******************************************************/

OUserManager = new Class({
	Implements: Options,
	
	options:{
		'title':'Manage Accounts',
		'mode':false,
		'button_text':'',
		'type':'Customer',
		'roles':[],
		'enable_create_login':false,
		'ouser_meta_data':[],
		'enable_select':false,
		'close':$empty,
		'onSelect':$empty
	}, 
	
	initialize: function(options){
		this.setOptions(options);
		
		this.ouser_select = [];
		this.create_role = [this.options.type];
		
		this.box = new sbox({'sbox_class':'obray-admin-container','width':800,'destroy':true,'close':this.options.close,'open':function(){
			this.searchOUsers('',this.options.type);
		}.bind(this)});
		
		this.value = 0;
		
		/**************************************************
			Header
		**************************************************/
		
		
		this.header = new BoxHeader({'header':this.options.title});
		
		
		this.header.inject(this.box.content);
		
		/**************************************************
			Search
		**************************************************/
		
		this.search = new OFText({'name':'keyword','label':'Search ' + this.options.type});
		this.search.inject(this.header.content);
		this.search.addEvent('keyup',function(){ this.searchOUsers(this.search.getProperty('value'),this.options.type); }.bind(this));
		
		/**************************************************
			Roles
		**************************************************/
		
		this.role = new OFSelect({'name':'ouser_role','label':'Role','labels':this.options.roles,'values':this.options.roles,'value':this.options.type,'change':function(){
			this.options.type = this.role.getProperty('value');
			this.add_btn.setProperty('value','Add ' + this.options.type);
			this.select_btn.setProperty('value','Select ' + this.options.type);
			this.options.create_role = [this.options.type];
			this.searchOUsers(this.search.getProperty('value'),this.options.type);
		}.bind(this)});
		
		/**************************************************
			OUsers
		**************************************************/
		
		this.ouser_container = new Element('div',{'class':'ouser-select-container'});
		this.ouser_container.inject(this.header.content);
				
		this.check = new Element('div',{'class':'oaddress-select-check'});
		
		/**************************************************
			Events
		**************************************************/
		
		this.add_btn = new Element('input',{'type':'button','value':'Create New ' + this.options.type});
		this.add_btn.setStyles({'position':'absolute','bottom':10,'right':0});
		this.add_btn.inject(this.box.content);
		
		this.add_btn.addEvent('click',function(){
			this.box.close();
			this.create = new OUserForm({'type':this.options.type,'ouser_meta_data':this.options.ouser_meta_data,'enable_create_login':this.options.enable_create_login,'ouser_role':this.options.type,'close':function(){
				this.box.open();
			}.bind(this)});
		}.bind(this));
		
		this.select_btn = new Element('input',{'type':'button','value':'< Select this ' + this.options.type});
		this.select_btn.setStyles({'position':'absolute','bottom':10,'left':0});
		
		this.select_btn.addEvent('click',function(){
				
			this.options.onSelect(this.value);
			this.box.close();
		}.bind(this))

		this.box.open();	
		
		this.role.inject(this.header.content);
	},
	
	searchOUsers: function(keyword,role){
		
		var data = '&keyword=' + keyword
				 + '&ouser_role=' + role;
		
		this.getOUsers = new Request({'url':'/cmd/ousers/get/?alphabetize=ouser_institution','data':data,'onComplete':function(response){
			this.ouser_container.set('html','')
			this.json = JSON.decode(response).response;
						
			for(var i=0;i<this.json.DATA.QUERY.DATA.OUSER_ID.length;++i){
				this.ouser_select[this.ouser_select.length] = new Element('div',{'class':'ouser-select ogrid-self-clear'});
				if(this.json.DATA.META[this.json.DATA.QUERY.DATA.OUSER_ID[i]].OUSER_INSTITUTION){ var user_company = new Element('div',{'class':'ogrid-1-4 ogrid-float'}).inject(this.ouser_select[this.ouser_select.length-1]).set('html',this.json.DATA.META[this.json.DATA.QUERY.DATA.OUSER_ID[i]].OUSER_INSTITUTION); }
				var user_name = new Element('div',{'class':'ogrid-1-4 ogrid-float'}).inject(this.ouser_select[this.ouser_select.length-1]).set('html',this.json.DATA.QUERY.DATA.OUSER_FIRST_NAME[i] + ' ' + this.json.DATA.QUERY.DATA.OUSER_LAST_NAME[i]);
				var user_email = new Element('div',{'class':'ogrid-1-2 ogrid-float'}).inject(this.ouser_select[this.ouser_select.length-1]).set('html',this.json.DATA.QUERY.DATA.OUSER_EMAIL[i]);
				
				this.ouser_select[this.ouser_select.length-1].inject(this.ouser_container);
				this.ouser_select[this.ouser_select.length-1].ouser_id = this.json.DATA.QUERY.DATA.OUSER_ID[i];
				user_name.addEvent('click',function(ouser_id){
					var card = new OUserCard({'ouser_meta_data':this.options.ouser_meta_data,'enable_create_login':this.options.enable_create_login,'roles':this.options.roles,'onDelete':function(el){ el.destroy(); }.bind(this,this.ouser_select[this.ouser_select.length-1]),'type':this.options.type,'ouser_id':ouser_id,'close':function(){ this.box.open(); }.bind(this)});
					this.box.close();
				}.bind(this,this.json.DATA.QUERY.DATA.OUSER_ID[i]));
			}
			
			this.ouser_select.each(function(el,index){
				if(this.options.enable_select){ el.addEvent('click',function(){ this.check.inject(el);this.value = el.ouser_id;this.select_btn.inject(this.box.content); }.bind(this)); }
				el.addEvent('mouseenter',function(){ el.setStyles({'background-color':'#f5f5f5'}); });
				el.addEvent('mouseleave',function(){ el.setStyles({'background-color':'#ffffff'}); });
			}.bind(this));
			
		}.bind(this)}).send();
		
	}
	
});

/******************************************************
	
	OUSER FORM
	
	DESCRIPTION
		
		This is the create/edit ouser form.  If you
		don't pass in a mode then it will assume
		you want to create a new user.  If you pass
		in 'edit' for the mode it will then update
		the user and the associated meta data.
		
******************************************************/

OUserForm = new Class({
	Implements: Options,
	
	options:{
		'mode':false,
		'button_text':'',
		'type':'Customer',
		'close':$empty,
		'enable_create_login':false,
		'ouser_first_name':'',
		'ouser_last_name':'',
		'ouser_email':'',
		'ouser_role':'',
		'ouser_meta_data':[]
	}, 
	
	initialize: function(options){
		this.setOptions(options);
		for(var i=0;i<this.options.ouser_meta_data.length;++i){	this.options[this.options.ouser_meta_data[i].name] = ''; }
		
		this.ouser_select = [];
		if( this.options.mode == 'edit'){ this.label = 'Edit' } else { this.label = 'Create New'; }
		
		this.box = new sbox({'sbox_class':'obray-admin-container','destroy':true,'close':this.options.close,'height':550});
		
		this.header = new BoxHeader({'header': this.label + ' ' + this.options.ouser_role});
		this.header.inject(this.box.content);
		
		if( this.options.mode == 'edit'){ this.url = '/cmd/ousers/update/' } else { this.url = '/cmd/ousers/add/'; }
		
		this.form = new OForm({'url':this.url,'button':new Element('input',{'type':'button','value': this.label + ' ' + this.options.ouser_role}),'onComplete':function(){ this.box.close();	}.bind(this)});
		
		if(this.options.mode == 'edit'){
			this.getUser = new Request({'url':'/cmd/ousers/get/?ouser_id='+this.options.ouser_id,'onComplete':function(response){
				this.json = JSON.decode(response).response;
				
				this.options.ouser_first_name = this.json.DATA.QUERY.DATA.OUSER_FIRST_NAME[0];
				this.options.ouser_last_name = this.json.DATA.QUERY.DATA.OUSER_LAST_NAME[0];
				this.options.ouser_email = this.json.DATA.QUERY.DATA.OUSER_EMAIL[0];
				this.options.ouser_role = this.json.DATA.QUERY.DATA.OUSER_ROLE[0]
				
				for(var i=0;i<this.options.ouser_meta_data.length;++i){
					this.options[this.options.ouser_meta_data[i].name] = this.json.DATA.META[this.json.DATA.QUERY.DATA.OUSER_ID[0]][this.options.ouser_meta_data[i].name.toUpperCase()];
				}
				
				this.ouser_id = new OFHidden({'name':'ouser_id','value':this.options.ouser_id});
				this.form.addElement(this.ouser_id);
			
				this.writeFields();
			}.bind(this)}).send();
		} else { this.writeFields(); }
		
		this.box.open();	
		
	},
	
	writeFields: function(){
		
		this.meta_fields = [];
		
		this.first_name = new OFText({'label':'First Name','name':'ouser_first_name','value':this.options.ouser_first_name});
		this.form.addElement(this.first_name);
		
		this.last_name = new OFText({'label':'Last Name','name':'ouser_last_name','value':this.options.ouser_last_name});
		this.form.addElement(this.last_name);
		
		this.email = new OFText({'label':'Email address','name':'ouser_email','value':this.options.ouser_email});
		this.form.addElement(this.email);
		
		this.role = new OFHidden({'name':'ouser_role','value':this.options.ouser_role});
		this.form.addElement(this.role);
		
		/**************************************
			Create Login Toggle (if enabled)
		**************************************/
		
		if(this.options.enable_create_login){
			this.login = new OFCheck({'label':'Create Login','name':'create_login','click':function(){ this.passwords.toggle(); }.bind(this)});
			this.form.addElement(this.login);
			
			this.passwords = new BoxToggle();
			
				this.password = new OFText({'label':'Password','name':'ouser_password','type':'password'});
				this.passwords.addElement(this.password);
				this.form.addElement(this.password);
				
				this.password_confirm = new OFText({'label':'Confirm Password','name':'ouser_confirm_password','type':'password'});
				this.passwords.addElement(this.password_confirm);
				this.form.addElement(this.password_confirm);
			
			this.form.addElement(this.passwords);
		}
		
		for(var i=0;i<this.options.ouser_meta_data.length;++i){
			
			if(this.options.ouser_meta_data[i].type == 'text-area'){ 
				var text_area = true; 
				this.meta_fields[this.meta_fields.length] = new OFText({'label':this.options.ouser_meta_data[i].label,'name':this.options.ouser_meta_data[i].name,'text-area':text_area,'value':this.options[this.options.ouser_meta_data[i].name]});
			} else if (this.options.ouser_meta_data[i].type == 'select') { 
				this.meta_fields[this.meta_fields.length] = new OFSelect({'labels':this.options.ouser_meta_data[i].labels,'values':this.options.ouser_meta_data[i].values,'label':this.options.ouser_meta_data[i].label,'name':this.options.ouser_meta_data[i].name,'text-area':text_area,'value':this.options[this.options.ouser_meta_data[i].name]});
			 } else { 
				var text_area = false; 
				this.meta_fields[this.meta_fields.length] = new OFText({'label':this.options.ouser_meta_data[i].label,'name':this.options.ouser_meta_data[i].name,'text-area':text_area,'value':this.options[this.options.ouser_meta_data[i].name]});
			}
			
			this.form.addElement(this.meta_fields[this.meta_fields.length-1]);
		
		}
		
		this.form.inject(this.header.content);
		
	}
	
});

/******************************************************
	
	OUSER CARD
	
	DESCRIPTION
		
		This is used to display the ouser information
		and give options to delete and edit the
		ouser
		
******************************************************/

OUserCard = new Class({
	Implements: Options,
	
	options:{
		'ouser_id':0,
		'mode':false,
		'button_text':'',
		'type':'Customer',
		'close':$empty,
		'onDelete':$empty,
		'roles':[],
		'enable_create_login':false,
		'ouser_meta_data':[]
	}, 
	
	initialize: function(options){
		this.setOptions(options);
		
		this.ouser_select = [];
		this.update = false;
		
		this.box = new sbox({'sbox_class':'obray-admin-container','destroy':true,'open':function(){
			
			this.getOUser();
			
		}.bind(this),'close':function(){
			
			if(this.update){
				this.edit = new OUserForm({'ouser_id':this.options.ouser_id,'mode':'edit','ouser_meta_data':this.options.ouser_meta_data,'enable_create_login':this.options.enable_create_login,'roles':this.options.roles,'close':function(){
					this.update = false;
					this.box.open();
				}.bind(this)});
			} else {
				this.options.close();
			}
			
		}.bind(this)});
		
		this.box.open();
		
	},
	
	getOUser: function(){
		
		/*************************************
			Get OUser information
		*************************************/
		
		this.box.content.set('html','');
		
		this.getUser = new Request({'url':'/cmd/ousers/get/?ouser_id='+this.options.ouser_id,'onComplete':function(response){
			
			this.json = JSON.decode(response).response;
			
			this.header = new BoxHeader({'header': this.json.DATA.QUERY.DATA.OUSER_FIRST_NAME[0] + ' ' + this.json.DATA.QUERY.DATA.OUSER_LAST_NAME[0]});
			this.header.inject(this.box.content);
			
			this.content = new Element('div',{'class':'ouser-card-data'});
			
			// OUSER DATA
			
			for(var key in this.json.DATA.QUERY.DATA){
				if(key != 'OUSER_ID' && key != 'OUSER_FIRST_NAME' && key != 'OUSER_LAST_NAME' && key != 'OUSER_FULL_NAME' && key != 'OUSER_ACTIVE' && key != 'OUSER_META_ID' && key != 'OUSER_CLEARANCE' && key != 'OUSER_PASSWORD' && key != 'OUSER_NAME'){
					var label = key.replace('OUSER_','');
					var el = new Element('div',{'class':'ouser-card-row'}).set('html','<div class="ogrid-2-5-padding ogrid-float ouser-card-label ogrid-vert-padding">' + label + ':</div> <div class="ogrid-3-5-padding ogrid-float ouser-card-value ogrid-vert-padding">' + this.json.DATA.QUERY.DATA[key] + '&nbsp;</div>').inject(this.content);
				}
			} 
			
			this.content.inject(this.header.content);
			
			this.delete_btn = new Element('input',{'type':'button','value':'Delete ' + this.options.type});
			this.delete_btn.setStyles({'position':'absolute','bottom':10,'left':0});
			this.delete_btn.inject(this.box.content);
			this.delete_btn.addEvent('click',function(){ 
				var confirm = new sboxConfirm({'confirm-message':'Are you sure you want to delete this ' + this.options.type + '?','onConfirm':function(){
					this.delete_request = new Request({'url':'/cmd/ousers/delete/?ouser_id='+this.options.ouser_id,'onComplete':function(){
						this.options.onDelete();
						this.box.close();
					}.bind(this)}).send(); 
				}.bind(this)});
				confirm.open();
			}.bind(this));
			
			this.edit_btn = new Element('input',{'type':'button','value':'Edit ' + this.options.type});
			this.edit_btn.setStyles({'position':'absolute','right':0,'bottom':10});
			this.edit_btn.inject(this.box.content);
			this.edit_btn.addEvent('click',function(){
				this.update = true;
				this.box.close();
			}.bind(this));
			
			
			
		}.bind(this)}).send();
	}
	
}); /*******************************************************
    ONav Horizontal
    Multi level style menu
*******************************************************/

ONavHorizontal = new Class({
    Implements: Options,
      
    options:{
		'onav_sub_pages_page_name_hyphenated':'',
		'sub_page_parent_id':0
    },
    
    initialize: function(onav_pages,options){
        this.setOptions(options);
		this.open_index = -1;
		
		// remove onav-hidden class - this class hides menu until javascript has been loaded
		onav_pages.removeClass('onav-hidden');
		
		this.buildSubMenus(onav_pages);
	},
	
	
	
	buildSubMenus: function(el){
	    if($type(el) == 'element'){
			var children = el.getChildren('li');
			var sub_page_container = [];
			var sub_page_container_fx = [];
			var sub_pages = [];
			
			// test for IE7 and IE8 using userAgent
			if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){
				this.ie_version=new Number(RegExp.$1);
				
				if(this.ie_version == 7 || this.ie_version == 8){
					this.ie_fake_psuedo_elements = true;
					var sub_page_container_before = [];
					var sub_page_container_content = [];
					var sub_page_container_after = [];
				}
			}
			
			children.each(function(el,i){
				if(el.getChildren('ul').length > 0){
					
					// remove onav-hidden class for sub pages
					el.getChildren('ul').removeClass('onav-hidden');
					
					// inject divs before and after sub page div - act as fake :before & :after pseudo elements - if browser is ie7 or ie8
					if(this.ie_fake_psuedo_elements){
						// sub page wrapper
						sub_page_container[i] = new Element('div',{'class':'ogrid-self-clear onav-sub-pages-wrapper'});
						sub_page_container[i].inject(el);
					
						// pseudo before sub page container
						sub_page_container_before[i] = new Element('div',{'class':'ogrid-self-clear onav-sub-pages-before'});
						sub_page_container_before[i].inject(sub_page_container[i]);
						
						// main content div for sub page container
						sub_page_container_content[i] = new Element('div',{'id':'onav-sub-pages-'+this.options.sub_page_parent_id,'class':'ogrid-self-clear onav-sub-pages onav-sub-pages-'+this.options.onav_sub_pages_page_name_hyphenated});
						sub_page_container_content[i].inject(sub_page_container[i]);
							
						// pseudo after sub page container
						sub_page_container_after[i] = new Element('div',{'class':'ogrid-self-clear onav-sub-pages-after'});
						sub_page_container_after[i].inject(sub_page_container[i]);
						
						// sub page ul
						sub_pages = el.getChildren('ul');
						sub_pages.addClass('onav-sub-page-ul');
						sub_pages.inject(sub_page_container_content[i]);
					} else {
						// main content div for sub page container
						sub_page_container[i] = new Element('div',{'id':'onav-sub-pages-'+this.options.sub_page_parent_id,'class':'ogrid-self-clear onav-sub-pages onav-sub-pages-'+this.options.onav_sub_pages_page_name_hyphenated});
						sub_page_container[i].inject(el);
					
						// sub page ul
						sub_pages = el.getChildren('ul');
						sub_pages.addClass('onav-sub-page-ul');
						sub_pages.inject(sub_page_container[i]);
					}
					
					// set sub pages FX
					sub_page_container[i].addClass('ogrid-hidden');
					sub_page_container[i].setStyles({'opacity':0,'visibility':'hidden'});
					sub_page_container_fx[i] = new Fx.Morph(sub_page_container[i],{'duration':600,'transition':Fx.Transitions.Quint.easeOut});
					
					//prevent parent link from acting as a link
					var parent_link = [];
					parent_link[parent_link.length] = el.getFirst();
					parent_link[parent_link.length-1].addEvent('click',function(e){ e.preventDefault(); });
					
					// rollover events
					el.addEvents({
						'mouseenter': function(){
							sub_page_container_fx[i].pause();
							sub_page_container[i].removeClass('ogrid-hidden');
							sub_page_container_fx[i].start({'opacity':1,'visibility':'visible'});
						},
						'mouseleave': function(){
							sub_page_container_fx[i].pause();
							var fade_out = function(){
								sub_page_container_fx[i].start({ 'opacity':0, 'visibility':'hidden', 'onComplete':function(){ sub_page_container[i].addClass('ogrid-hidden'); }});
							}
							fade_out.delay(150);
						}
					});
				}
			}.bind(this));
	    }
	}
});





/*******************************************************
    ONav Vertical
    Accordion style menu
*******************************************************/
ONavVertical = new Class({
	Implements: Options,
      
    options:{
        
    },
    
    initialize: function(onav_pages,options){
        this.setOptions(options);
		this.open_index = -1;
		this.buildSubMenus(onav_pages);
	},
	
	buildSubMenus: function(el){
	    if($type(el) == 'element'){
			var children = el.getChildren('li');
			var containers = [];
			var togglers = [];
			var children_bullet = [];
			
			children.each(function(el,i){
				// creates togglers and containers only for list-items that have submenus
				if(el.getChildren('ul').length > 0){
					// toggler
					togglers[togglers.length] = el.getChildren('a');
					togglers[togglers.length-1].addClass('onav-toggler onav-item-closed');
					togglers[togglers.length-1].addEvent('click',function(e){ e.preventDefault(); });
					
					if( togglers[togglers.length-1].getParent().hasClass('selected') ){ this.open_index = togglers.length; }
					
					//container
					containers[containers.length] = el.getChildren('ul');
					containers[containers.length-1].addClass('onav-container');
				} else {
					//children_bullet = new Element('div',{'class':'onav-bullet'});
					//children_bullet.inject(el,'top');
				}
			}.bind(this));
			
			// 'onComplete' resolves the issue where nested accordions don't open properly
			var heightValue='';
			
			var accordion = new Accordion(togglers,containers,{
				'display':this.open_index,
				'alwaysHide':true,
				'onComplete': function() { 
					var element=$(this.elements[this.previous]);
					if(element && element.offsetHeight>0) element.setStyle('height', heightValue);
				},
				'onActive':function(toggler){
					toggler.removeClass('onav-item-closed');
					toggler.addClass('onav-item-open');
				},
				'onBackground':function(toggler){
					toggler.addClass('onav-item-closed');
					toggler.removeClass('onav-item-open');
				}
			});
	    }
	}
});


/********************************************************************

	Icon class:  Creates and Icon for the Obray shelf

********************************************************************/
Icon = new Class({
	Implements: Options,
	
	options:{
		'id':0,
		'label':false
	},
	
	initialize: function(image,parent,options){
		
		//data members
		this.setOptions(options)
		this.parent = parent;
		this.image = image;
		
		//generate HTML
		this.icon_container = new Element('div',{'class':'shelf_icon'});
		this.icon = new Element('div',{'class':'shelf_icon_img'});
		this.icon_label = new Element('div',{'class':'shelf_icon_label'})
		
		//set styles
		this.icon_container.setStyles({'float':'left','position':'relative','width':'128px','height':'128px','background-image':'url(/obray/images/shelf/'+this.image+')','background-repeat':'no-repeat','margin':'5px'});
		this.icon.setStyles({'position':'relative','width':'59px','height':'59px','padding-left':'10px','cursor':'pointer','margin-left':10,'margin-right':10});
		this.icon_label.setStyles({'position':'absolute','bottom':'5px','font-family':'arial','color':'#666666','padding':'5px','text-align':'center','font-size':'14px','width':'118px'});
		
		//set text
		this.icon_label.set('html',this.options.label);
		
		//construct HTML
		this.icon.inject(this.icon_container);
		this.icon_label.inject(this.icon_container);
		this.icon_container.inject(this.parent);
	}
});
/********************************************************************

	IconDrag class:  creates a draggable icon for the Obray shelf

********************************************************************/
DragIcon = new Class({
	
	Extends: Icon,
	
	Implements: Options,
	
	options: {
		
	},
	
	initialize: function(image,parent,getDroppables,type,options){
		
		//data members
		this.parent(image,parent,options);
		
		//set style
		this.icon.setStyle('cursor','move');
		this.droppables = [];
		this.getDroppables = getDroppables;
		this.mouseOverDetectors = [];
		this.droppableTransition = new Fx.Transition(Fx.Transitions.Quad);
		this.type = type;
		
		//add Events
		this.icon.addEvent('mousedown',function(e){
			this.droppables = this.getDroppables();
			$$('.obray-show-help').setStyles({'display':'none'});
			this.droppables.each(function(el,index){
				var position = index;
				this.mouseOverDetectors[position] = new Element('div',{'class':'mouse_over_detectors'});
				
				this.mouseOverDetectors[position].setStyles({'position':'absolute','left':el.getPosition().x,'top':el.getPosition().y,'height':'30px','width':el.getCoordinates().width});
				this.mouseOverDetectors[position].inject('obray');
				this.mouseOverDetectors[position].droppable = this.droppables[position];
				this.mouseOverDetectors[position].fx = new Fx.Tween(this.droppables[position], {transition: this.droppableTransition.easeOut,duration: 200});
			}.bind(this));
			this.icon_draggable = this.icon.clone();
			this.icon_draggable.setStyles({'position':'absolute','left':this.icon.getPosition().x,'top':this.icon.getPosition().y+window.getScroll().y,'cursor':'move','z-index':'2000','opacity':'.5'});
			this.icon_draggable.inject('obray');
			
			var newDrag = new Drag.Move(this.icon_draggable,{handle: this.icon_dgraggable, droppables: this.mouseOverDetectors,
				onEnter: function(el,detector){
					detector.fx.pause();
					detector.fx.start('height','0px','59px');
					detector.setStyle('height','59px');
				}.bind(this),
				onLeave: function(el,detector){
					detector.fx.pause();
					detector.fx.start('height','59px','0px');
					detector.setStyle('height','30px');
				},
				onDrop: function(el,detector){
					if(!detector == false){
						detector.fx.pause();
						detector.fx.start('height','59px','0px');
						detector.setStyle('height','30px');
						this.detector = detector;
						var save = function(response){
							eval(response);
							//index.cfm?action=pages.updateObrayContent&content_part_id=0&content_area_id='+this.detector.droppable.content_area_id+'&image_id='+image_id+'&content_order='+(this.detector.droppable.order+1)+'&content_part_type=image&content_text='
							this.linkProductAndImage = new Request({'url':'/cmd/opages/updateObrayContent/','onComplete':function(){
								var location = window.location.href.replace(window.location.hash,'');
									var location = location.replace('#','');
									window.location = location;
							}.bind(this)}).send();
						}
						
						window.obray.pictureBox = new ImageBox({
							'position':'absolute',
							'width':800,
							'height':712,
							'image_id': 0,
							'image_ext': 'jpg',
							'description':' ',
							'window_height': 413,
							'window_width': detector.getSize().x-30,
							'window_max_width': detector.getSize.x-30,
							'window_max_height': 1000,
							'zoom_level': 0,
							'resizable': false,
							'offset_x': 0,
							'offset_y': 0,
							'onSave': save.bind(this),
							'description_long':' '
						});
						window.obray.pictureBox.open('elastic');
					}
					this.mouseOverDetectors.each(function(el){
						el.destroy();
					});
					this.icon_draggable.destroy();
				}.bind(this)
			});
			newDrag.start(e);
			
		}.bind(this));
	}
	
});

/********************************************************************

	ShelfBox: Create and icon that clicks open sub menu

********************************************************************/
ShelfBox = new Class({
					 
	Implements: Options,
	
	options: {
		'width':200,
		'height':false,
		'top':false,
		'left':false
	},
	
	initialize: function(options){
		
		//data members
		this.setOptions(options);
		
		//generate HTML
		this.box = new Element('div',{'class':'shelf_box'});
		this.box_tl = new Element('div',{'class':'shelf_box_tl'});
		this.box_tr = new Element('div',{'class':'shelf_box_tr'});
		this.box_bl = new Element('div',{'class':'shelf_box_bl'});
		this.box_br = new Element('div',{'class':'shelf_box_br'});
		this.box_t  = new Element('div',{'class':'shelf_box_t'});
		this.box_r  = new Element('div',{'class':'shelf_box_r'});
		this.box_l  = new Element('div',{'class':'shelf_box_l'});
		this.box_bml= new Element('div',{'class':'shelf_box_bml'});
		this.box_mt = new Element('div',{'class':'shelf_box_mt'});
		this.box_bmr= new Element('div',{'class':'shelf_box_bmr'});
		this.box_m  = new Element('div',{'class':'shelf_box_m'});
		
		//set styles
		var tempWidth = (this.options.width/2-17);
		this.box.setStyles({'position':'fixed','top':'0px','left':'0px','z-index':'3000'});
		this.box_tl.setStyles({'float':'left','height':'13px','width':'13px','background-image':'url(/obray/images/shelf/shelf_box_tl.png)'});
		this.box_t.setStyles({'float':'left','height':'13px','width':this.options.width+'px','background-image':'url(/obray/images/shelf/shelf_box_t.png)'});
		this.box_tr.setStyles({'float':'left','height':'13px','width':'13px','background-image':'url(/obray/images/shelf/shelf_box_tr.png)'});
		this.box_l.setStyles({'clear':'both','float':'left','padding-left':'13px','background-image':'url(/obray/images/shelf/shelf_box_l.png)','background-repeat':'repeat-y'});
		this.box_m.setStyles({'background-image':'url(/obray/images/shelf/shelf_box_bg.png)','width':this.options.width+'px'});
		this.box_r.setStyles({'padding-right':'13px','background-image':'url(/obray/images/shelf/shelf_box_r.png)','background-repeat':'repeat-y','background-position':'right'})
		this.box_bl.setStyles({'clear':'both','float':'left','height':'13px','width':'13px','background-image':'url(/obray/images/shelf/shelf_box_bl.png)'});
		this.box_bml.setStyles({'float':'left','height':'13px','width':tempWidth+'px','background-image':'url(/obray/images/shelf/shelf_box_b.png)'});
		this.box_mt.setStyles({'float':'left','height':'26px','width':'34px','background-image':'url(/obray/images/shelf/shelf_box_tail.png)'});
		this.box_bmr.setStyles({'float':'left','height':'13px','width':tempWidth+'px','background-image':'url(/obray/images/shelf/shelf_box_b.png)'});
		this.box_br.setStyles({'float':'left','height':'13px','width':'13px','background-image':'url(/obray/images/shelf/shelf_box_br.png)'});
		if(this.options.height != false){
			this.box_m.setStyles({'height':this.options.height + 'px'});
		}
		
		
		//construct HT
		this.box_tl.inject(this.box);
		this.box_t.inject(this.box);
		this.box_tr.inject(this.box);
		this.box_l.inject(this.box);
		this.box_r.inject(this.box_l);
		this.box_m.inject(this.box_r);
		this.box_bl.inject(this.box);
		this.box_bml.inject(this.box);
		this.box_mt.inject(this.box);
		this.box_bmr.inject(this.box);
		this.box_br.inject(this.box);
		
		this.box.inject('obray');
		
		this.reposition();
		
	},
	
	reposition: function(){
		if(this.options.top != false){this.box.setStyles({'position':'fixed','top':(this.options.top.toInt() - this.box_m.getSize().y.toInt()-26)+'px'});}
		if(this.options.left != false){this.box.setStyles({'position':'fixed','left':(this.options.left.toInt()-this.options.width.toInt()/2+13)+'px'});}
	},
	
	close: function(){
		this.box.destroy();	
	}
});
/********************************************************************

	FontSelector: Create and icon that clicks open sub menu

********************************************************************/
TextPreview = new Class({
	Implements: Options,
	
	options: {
		'type':'p'
	},
	
	initialize: function(parent,droppables,window2,options){
		
		//data members
		this.setOptions(options);
		this.parent = parent;
		this.getDroppables = droppables;
		this.windowObj = window2;
		
		this.mouseOverDetectors = [];
		this.droppableTransition = new Fx.Transition(Fx.Transitions.Quad);
		//generate HTML
		this.text = new Element('div',{'class':'text_preview'});
		this.text_handle = new Element('div',{'class':'text_handle'});
		this.text_box = new Element('div',{'class':'text_box'});
		this.text_container = new Element('div',{'class':'text_container'});
		this.text_end = new Element('div',{'class':'text_end'});
		this.br = new Element('br',{'class':'clear'});
		
		//set styles
		this.text.setStyles({'padding':'3px'});
		this.text_handle.setStyles({'float':'left','width':'24px','height':'37px','background-image':'url(/obray/images/shelf/font_handle.png)','cursor':'move'});
		this.text_box.setStyles({'position':'relative','float':'left','width':'150px','height':'35px','background-color':'#888888','opacity':1,'padding-left':'5px','border':'1px solid white'});
		this.text_end.setStyles({'float':'left','width':'12px','height':'37px','background-image':'url(/obray/images/shelf/font_end.png)'});
		this.text_container.setStyles({'position':'absolute','left':'50%','top':'50%'});
		
		//construct HTML
		this.text_handle.inject(this.text);
		this.text_box.inject(this.text);
		this.text_end.inject(this.text);
		this.br.inject(this.text);
		this.text.inject(this.parent);
		if(this.options.type == 'h1'){
			this.text_box.set('html','<h1>Header 1</h1>');
			this.text_box.getFirst().setStyles({'padding':'0px','margin':'0px'});
		} else if(this.options.type == 'h2'){
			this.text_box.set('html','<h2>Header 2</h2>');
			this.text_box.getFirst().setStyles({'padding':'0px','margin':'0px','margin-top':'8px'});
		} else if(this.options.type == 'h3'){
			this.text_box.set('html','<h3>Header 3</h3>');
			this.text_box.getFirst().setStyles({'padding':'0px','margin':'0px','margin-top':'-2px'});
		} else if(this.options.type == 'h4'){
			this.text_box.set('html','<h4>Header 4</h4>');
			this.text_box.getFirst().setStyles({'padding':'0px','margin':'0px','margin-top':'2px'});
		} else if(this.options.type == 'p'){
			this.text_box.set('html','<p>Paragraph</p>');
			this.text_box.getFirst().setStyles({'padding':'0px','margin':'0px','margin-top':'10px'});
		} else if(this.options.type == 'ul'){
			this.text_box.set('html','<ul><li>List</li></ul>');
			this.text_box.getFirst().setStyles({'padding':'0px','margin':'0px','margin-top':'10px'});
		}
		
		this.text.addEvent('mousedown',function(e){
			this.droppables = this.getDroppables();
			$$('.obray-show-help').setStyles({'display':'block'});
			
			this.droppables.each(function(el,index){
				var position = index;
				this.mouseOverDetectors[position] = new Element('div',{'class':'mouse_over_detectors'});
				this.mouseOverDetectors[position].setStyles({'border':'1px solid white','position':'absolute','left':el.getPosition().x,'top':el.getPosition().y,'height':'30px','width':el.getCoordinates().width});
				this.mouseOverDetectors[position].inject('obray');
				this.mouseOverDetectors[position].droppable = this.droppables[position];
				this.mouseOverDetectors[position].fx = new Fx.Tween(this.droppables[position], {transition: this.droppableTransition.easeOut,duration: 200});
			}.bind(this));
												
			this.text_draggable = this.text.clone();
			this.text_draggable.setStyles({'position':'absolute','left':this.text.getPosition().x+'px','top':(this.text.getPosition().y+window.getScroll().y)+'px','opacity':'.85','z-index':10000});
			this.text_draggable.inject(document.body);
			var newDrag = new Drag.Move(this.text_draggable,{handle: this.tex_handle, droppables: this.mouseOverDetectors,
				onEnter: function(el,detector){
					detector.fx.pause();
					detector.fx.start('height','0px','59px');
					detector.setStyle('height','59px');
				}.bind(this),
				onLeave: function(el,detector){
					detector.fx.pause();
					detector.fx.start('height','59px','0px');
					detector.setStyle('height','30px');
				},
				onDrop: function(el,detector){
					$$('.obray-show-help').setStyles({'display':'none'})
					if(!detector == false){
						detector.fx.pause();
						detector.fx.start('height','59px','0px');
						detector.setStyles('height','30px')
						//alert("order: "+(parseInt(detector.droppable.content_order)+1));
						//alert(detector.droppable.siblings);
						//alert(detector.droppable.siblings.length);
						var newContent = new ContentPartV2(detector.droppable,{
							'content_part_id':0,
							'content_area_id':detector.droppable.content_area_id,
							'content_part_parent_id':detector.droppable.content_parent_id,
							'content_part_type':this.options.type,
							'content_language':window.obray.options.content_language,
							'content_order':(parseInt(detector.droppable.content_order)+1),
							'content_text':'',
							'image':{'image_id':0},
							'video':{'video_id':0},
							'siblings':detector.droppable.siblings
						});
						newContent.inject('after');
						var droppable = new Droppable(newContent.el,newContent,{
							'content_area_id':detector.droppable.content_area_id,
							'content_parent_id':detector.droppable.content_parent_id,
							'content_order':(parseInt(detector.droppable.content_order)+1),
							'siblings':detector.droppable.siblings.bind(detector.droppable.siblings)
						});
						droppable.inject('after');
						window.obray.addDroppable(droppable.get());
						
						this.droppables.each(function(el,index){
							if(el.content_area_id == detector.droppable.content_area_id && el.content_order >= parseInt(detector.droppable.content_order)+1){
								++el.content_order;
							}
						}.bind(this))
						
						
					}
					this.mouseOverDetectors.each(function(el){
						el.destroy();
					});
					this.text_draggable.destroy();
				}.bind(this)
			});
			newDrag.start(e);
			this.windowObj.toggleWindow();
			
		}.bind(this));
	}
})



/********************************************************************

	FontSelector: Create and icon that clicks open sub menu

********************************************************************/
FontSelector = new Class({
	Extends: ShelfBox,
	
	Implements: Options,
	
	options: {
		
	},
	
	initialize: function(droppables,options){
		
		//data members
		this.parent(options)
		
		this.reposition();
		
	}
});


ComponentIcon = new Class({
	Extends: Icon,
	
	options:{
		'label':false,
		'window':false,
		'type':'application'
	},
	
	initialize: function(img,parent,droppables,component_type,options){
		
		//data members
		this.parent(img,parent,options);
		this.getDroppables = droppables;
		this.mouseOverDetectors = [];
		this.droppableTransition = new Fx.Transition(Fx.Transitions.Quad);
		this.component_type = component_type;
		//Add Events
		//add Events
		this.icon_container.addEvent('mousedown',function(e){
			this.options.window.closeWindow();
			this.droppables = this.getDroppables();
			this.droppables.each(function(el,index){
				var position = index;
				this.mouseOverDetectors[position] = new Element('div',{'class':'mouse_over_detectors'});
				this.mouseOverDetectors[position].setStyles({'border':'0px solid black','position':'absolute','left':el.getPosition().x,'top':el.getPosition().y,'height':'30px','width':el.getCoordinates().width});
				this.mouseOverDetectors[position].inject('obray');
				this.mouseOverDetectors[position].droppable = this.droppables[position];
				this.mouseOverDetectors[position].fx = new Fx.Tween(this.droppables[position], {transition: this.droppableTransition.easeOut,duration: 200});
			}.bind(this));
			this.icon_draggable = this.icon_container.clone();
			this.icon_draggable.setStyles({'position':'absolute','left':this.icon_container.getPosition().x,'top':this.icon_container.getPosition().y+window.getScroll().y,'cursor':'move','z-index':'2000','opacity':'.5'});
			this.icon_draggable.inject('obray');
			
			var newDrag = new Drag.Move(this.icon_draggable,{handle: this.icon_dgraggable, droppables: this.mouseOverDetectors,
				onEnter: function(el,detector){
					detector.fx.pause();
					detector.fx.start('height','0px','59px');
					detector.setStyle('height','59px');
				}.bind(this),
				onLeave: function(el,detector){
					detector.fx.pause();
					detector.fx.start('height','59px','0px');
					detector.setStyle('height','30px');
				},
				onDrop: function(el,detector){
					if(!detector == false){
						var newContent = new ContentPartV2(detector.droppable,{
							'content_part_id':0,
							'content_area_id':detector.droppable.content_area_id,
							'content_part_parent_id':detector.droppable.content_parent_id,
							'content_part_type':this.component_type,
							'content_language':window.obray.options.content_language,
							'content_order':(parseInt(detector.droppable.content_order)+1),
							'content_text':'',
							'image':{'image_id':0},
							'video':{'video_id':0},
							'content_parts':[],
							'component_type':this.options.type
						});
						detector.droppable.setStyles({'height':'auto'});
						
					}
					this.mouseOverDetectors.each(function(el){
						el.destroy();
					});
					this.icon_draggable.destroy();
				}.bind(this)
			});
			newDrag.start(e);
		}.bind(this));
		
	},
	
	get: function(){
		return this.icon_container;
	}
})


ShelfWindow = new Class({
	Implements: Options,
	
	options:{
		'window_width':750
	},
	
	initialize: function(options){
		
		//set data members
		this.setOptions(options);
		this.state = 'closed';
		
		//construct HTML
		this.window = new Element('div');
		this.window_tl = new Element('div');
		this.window_t = new Element('div');
		this.window_tr = new Element('div');
		this.window_l = new Element('div');
		this.window_m = new Element('div');
		this.window_r = new Element('div');
		this.window_bl = new Element('div');
		this.window_b = new Element('div');
		this.window_br = new Element('div');
		this.window_close_btn = new Element('div');
		this.br1 = new Element('br',{'class':'clearboth clear'});
		this.br2 = new Element('br',{'class':'clearboth clear'});
		this.br3 = new Element('br',{'class':'clearboth clear'});
		
		//effects
		this.openFx = new Fx.Morph(this.window,{'duration':500,'transition':Fx.Transitions.Quint.easeOut});
		
		//set styles
		this.window.setStyles({'position':'fixed','left':'50%','bottom':99,'overflow':'hidden','height':0,'z-index':5000});
		this.window_tl.setStyles({'float':'left','background-image':'url(/obray/images/shelf/shelf_box_tl.png)','height':28,'width':28});
		this.window_t.setStyles({'float':'left','background-image':'url(/obray/images/shelf/shelf_box_t.png)','height':28,'width':this.options.window_width});
		this.window_tr.setStyles({'float':'left','background-image':'url(/obray/images/shelf/shelf_box_tr.png)','height':28,'width':28});
		this.window_l.setStyles({'float':'left','background-image':'url(/obray/images/shelf/shelf_box_l.png)','width':28});
		this.window_m.setStyles({'float':'left','background-color':'#ffffff','width':this.options.window_width});
		this.window_r.setStyles({'float':'left','background-image':'url(/obray/images/shelf/shelf_box_r.png)','width':28});
		//this.window_bl.setStyles({'float':'left','background-image':'url(/obray/images/shelf/shelf_box_bl.png)','height':28,'width':28});
		//this.window_b.setStyles({'float':'left','background-image':'url(/obray/images/shelf/shelf_box_b.png)','height':28,'width':200});
		//this.window_br.setStyles({'float':'left','background-image':'url(/obray/images/shelf/shelf_box_br.png)','height':28,'width':28});
		this.window_close_btn.setStyles({'background-image':'url(/obray/images/shelf/shelf_box_close_btn.png)','width':30,'height':30,'cursor':'pointer'});
		
		//construct HTML
		this.window_tl.inject(this.window);
		this.window_t.inject(this.window);
		this.window_tr.inject(this.window);
		this.br1.inject(this.window);
		this.window_l.inject(this.window);
		this.window_m.inject(this.window);
		this.window_r.inject(this.window);
		this.br2.inject(this.window);
		//this.window_bl.inject(this.window);
		//this.window_b.inject(this.window);
		//this.window_br.inject(this.window);
		//this.br.clone().inject(this.window);
		this.window_close_btn.inject(this.window_tr);
		
		this.window.inject(document.body);
		
		//add events
		this.window_close_btn.addEvent('click',function(){
			this.closeWindow();
		}.bind(this));
		
	},
	
	openWindow: function(){
		this.openFx.pause();
		var height = this.window_m.getCoordinates().height + 28;
		var middle_height = this.window_m.getCoordinates().height;
		var width = this.options.window_width + 56;
		this.window.setStyles({'margin-left':-(width/2)});
		this.window_l.setStyles({'height':middle_height});
		this.window_r.setStyles({'height':middle_height});
		this.openFx.start({
			'height':height			  
		});
		this.state = 'opened';
	},
	
	closeWindow: function(){
		this.openFx.pause();
		this.openFx.start({
			'height':0			  
		});
		this.state = 'closed';
	},
	
	toggleWindow: function(){
		if(this.state == 'closed'){
			this.openWindow();
		} else {
			this.closeWindow();
		}
	},
	
	getWindow: function(){
		return this.window;
	}
});


ObrayIcon = new Class({
	Implements: Options,
	
	options:{
		'icon_image':false,
		'icon_rollover':false,
		'icon_label':'Icon'
	},
	
	initialize: function(options){
		
		//data members
		this.setOptions(options);
		
		//generate HTML
		this.icon = new Element('div');
		this.icon_image = new Element('div');
		this.icon_label = new Element('div');
		
		//set styles
		this.icon.setStyles({'float':'left','width':97,'height':100});
		this.icon_image.setStyles({'background-image':'url('+this.options.icon_image+')','width':97,'height':75,'cursor':'pointer'});
		this.icon_label.setStyles({'font-family':'Helvetica, Arial','color':'#ffffff','text-align':'center','margin-top':-3});
		
		//set label
		this.icon_label.set('html',this.options.icon_label);
		
		//construct HTML
		this.icon_image.inject(this.icon);
		this.icon_label.inject(this.icon);
		
		//add events
		this.icon_image.addEvent('mouseenter',function(){
			
		}.bind(this))
	},
	
	getIcon: function(){
		return this.icon;
	}
})

LogoutIcon = new Class({
	Extends: ObrayIcon,
	
	options: {
		'icon_label':''
	},
	
	initialize: function(options){
		
		//data members
		this.setOptions(options);
		this.parent(options);
		
		//generate HTML
		this.icon_image.setStyles({'background-image':'url(/obray/images/shelf/icon_logout.png)'});
		
		//addEvent
		this.icon_image.addEvent('click',function(){
			window.location = '/cmd/ousers/logout/';
		});
	}
})

SiteMapIcon = new Class({
	Extends: ObrayIcon,
	
	options: {
		
	},
	
	initialize: function(options){
		
		//data members
		this.setOptions(options);
		this.parent(options);
		
		//generate HTML
		this.icon_image.setStyles({'background-image':'url(/obray/images/shelf/icon_map.png)'});
		
		//add events
		this.icon_image.addEvent('click',function(){
			window.location = '/cmd/map/';
		}.bind(this))
		
	}
})



PicturesIcon = new Class({
	Extends: ObrayIcon,
	
	options: {
		droppables: $empty
	},
	
	initialize: function(options){
		
		//data members
		this.setOptions(options);
		this.parent(options);
		this.getDroppables = this.options.droppables;
		this.mouseOverDetectors = [];
		this.droppables = '';
		this.droppableTransition = new Fx.Transition(Fx.Transitions.Quad);
		
		//generate HTML
		this.icon_image.setStyles({'background-image':'url(/obray/images/shelf/icon_pictures.png)'});
	
		//add Events
		this.icon.addEvent('mousedown',function(e){
			this.droppables = this.getDroppables();
			$$('.obray-show-help').setStyles({'display':'none'});
			this.droppables.each(function(el,index){
				var position = index;
				this.mouseOverDetectors[position] = new Element('div',{'class':'mouse_over_detectors'});
				this.mouseOverDetectors[position].setStyles({'border':'1px solid white','position':'absolute','left':el.getPosition().x,'top':el.getPosition().y,'height':'30px','width':el.getCoordinates().width,'z-index':5002});
				this.mouseOverDetectors[position].inject('obray');
				this.mouseOverDetectors[position].droppable = this.droppables[position];
				this.mouseOverDetectors[position].fx = new Fx.Tween(this.droppables[position], {transition: this.droppableTransition.easeOut,duration: 200});
			}.bind(this));
			this.icon_draggable = this.icon.clone();
			this.icon_draggable.setStyles({'position':'absolute','left':this.icon.getPosition().x,'top':this.icon.getPosition().y+window.getScroll().y,'cursor':'move','z-index':'2000','opacity':'.5'});
			this.icon_draggable.inject('obray');
			
			var newDrag = new Drag.Move(this.icon_draggable,{handle: this.icon_dgraggable, droppables: this.mouseOverDetectors,
				onEnter: function(el,detector){
					detector.fx.pause();
					detector.fx.start('height','0px','59px');
					detector.setStyle('height','59px');
				}.bind(this),
				onLeave: function(el,detector){
					detector.fx.pause();
					detector.fx.start('height','59px','0px');
					detector.setStyle('height','30px');
				},
				onDrop: function(el,detector){
					if(!detector == false){
						detector.fx.pause();
						detector.fx.start('height','59px','0px');
						detector.setStyle('height','30px');
						this.detector = detector;
						
						var height = (detector.droppable.getCoordinates().width*3)/4;				
						var newContent = new ContentPartV2(detector.droppable,{
							'content_part_id':0,
							'content_area_id':detector.droppable.content_area_id,
							'content_part_parent_id':detector.droppable.content_parent_id,
							'content_part_type':'image',
							'content_language':window.obray.options.content_language,
							'content_order':(parseInt(detector.droppable.content_order)+1),
							'content_text':'',
							
							'image':{'oimage_id':0,
							         'max_width':detector.droppable.getCoordinates().width,
							         'content_area_id':this.detector.droppable.content_area_id,
							         'content_order':(parseInt(detector.droppable.content_order)+1),
							         'oimage_width': detector.droppable.getCoordinates().width,
                                     'oimage_height': height,
                                     'oimage_src':'',
                                     'oimage_name':'Untitled',
                                     'oimage_description':'',
                                     'oimage_description_long':'',
                                     'oimage_ext':'jpg',
                                     'oimage_x':0,
                                     'oimage_y':0,
                                     'oimage_zoom':0,
                                     'oimage_link':'',
                                     'oimage_follow':false,
                                     'oimage_thumb_x':0,
                                     'oimage_thumb_y':0,
                                     'content_order':0
							},
							'video':{'video_id':0},
							'siblings':detector.droppable.siblings
						});
						
						newContent.inject('after');
						/***
						var droppable = new Droppable(newContent.el.window.window_container,newContent,{
							'content_area_id':detector.droppable.content_area_id,
							'content_parent_id':detector.droppable.content_parent_id,
							'content_order':(parseInt(detector.droppable.content_order)),
							'content_order_modifier':-1,
							'siblings':detector.droppable.siblings.bind(detector.droppable.siblings)
						});
						
						droppable.inject('after');
						window.obray.addDroppable(droppable.get());
						****/
						
					}
					this.mouseOverDetectors.each(function(el){
						el.destroy();
					});
					this.icon_draggable.destroy();
				}.bind(this)
			});
			newDrag.start(e);
			
		}.bind(this));
	}
})

VideosIcon = new Class({
	Extends: ObrayIcon,
	
	options: {
		droppables: $empty
	},
	
	initialize: function(options){
		
		//data members
		this.setOptions(options);
		this.parent(options);
		this.getDroppables = this.options.droppables;
		this.mouseOverDetectors = [];
		this.droppables = '';
		this.droppableTransition = new Fx.Transition(Fx.Transitions.Quad);
		
		//generate HTML
		this.icon_image.setStyles({'background-image':'url(/obray/images/shelf/icon-video.png)'});
	
		//add Events
		this.icon.addEvent('mousedown',function(e){
			this.droppables = this.getDroppables();
			$$('.obray-show-help').setStyles({'display':'none'});
			this.droppables.each(function(el,index){
				var position = index;
				this.mouseOverDetectors[position] = new Element('div',{'class':'mouse_over_detectors'});
				this.mouseOverDetectors[position].setStyles({'border':'1px solid white','position':'absolute','left':el.getPosition().x,'top':el.getPosition().y,'height':'30px','width':el.getCoordinates().width,'z-index':5002});
				this.mouseOverDetectors[position].inject('obray');
				this.mouseOverDetectors[position].droppable = this.droppables[position];
				this.mouseOverDetectors[position].fx = new Fx.Tween(this.droppables[position], {transition: this.droppableTransition.easeOut,duration: 200});
			}.bind(this));
			this.icon_draggable = this.icon.clone();
			this.icon_draggable.setStyles({'position':'absolute','left':this.icon.getPosition().x,'top':this.icon.getPosition().y+window.getScroll().y,'cursor':'move','z-index':'2000','opacity':'.5'});
			this.icon_draggable.inject('obray');
			
			var newDrag = new Drag.Move(this.icon_draggable,{handle: this.icon_dgraggable, droppables: this.mouseOverDetectors,
				onEnter: function(el,detector){
					detector.fx.pause();
					detector.fx.start('height','0px','59px');
					detector.setStyle('height','59px');
				}.bind(this),
				onLeave: function(el,detector){
					detector.fx.pause();
					detector.fx.start('height','59px','0px');
					detector.setStyle('height','30px');
				},
				onDrop: function(el,detector){
					if(!detector == false){
						detector.fx.pause();
						detector.fx.start('height','59px','0px');
						detector.setStyle('height','30px');
						this.detector = detector;
						
						/***
						video = new OVideo({
							'content_area_id':this.detector.droppable.content_area_id,
							'content_order':(parseInt(detector.droppable.content_order)+1),
							'blog':false
						});
						video.injectAfter(detector.droppable);
						***/
						
						var height = (detector.droppable.getCoordinates().width*3)/4;
						
						var newContent = new ContentPartV2(detector.droppable,{
							'content_part_id':0,
							'content_area_id':detector.droppable.content_area_id,
							'content_part_parent_id':detector.droppable.content_parent_id,
							'content_part_type':'video',
							'content_language':window.obray.options.content_language,
							'content_order':(parseInt(detector.droppable.content_order)+1),
							'content_text':'',
							'image':{'image_id':0},
							'video':{'video_id':0,
							         'video_width':500,
							         'video_height':282,
							         'video_image_id':0,
							         'video_length':0,
							         'video_size':0,
							         'video_name':'',
							         'video_ext':'',
							         'video_title':'',
							         'video_description':'',
							         'video_embed':false,
							         'video_share':false,
							         'video_autoplay':false
							},
							'siblings':detector.droppable.siblings
						});
						newContent.inject('after');
						/***
						var droppable = new Droppable(newContent.el.player.ovideo_container,newContent,{
							'content_area_id':detector.droppable.content_area_id,
							'content_parent_id':detector.droppable.content_parent_id,
							'content_order':(parseInt(detector.droppable.content_order)),
							'content_order_modifier':-1,
							'siblings':detector.droppable.siblings.bind(detector.droppable.siblings)
						});
						droppable.inject('after');
						window.obray.addDroppable(droppable.get());
						***/
					}
					this.mouseOverDetectors.each(function(el){
						el.destroy();
					});
					this.icon_draggable.destroy();
				}.bind(this)
			});
			newDrag.start(e);
			
		}.bind(this));
	},
	
	validDropArea: function(types){
		for(var i=0;i<types.length;++i){
			if(types[i] = this.type){
				return true;
			}
		}
		return false;
	}
})


TextStylesIcon = new Class({
	Extends: ObrayIcon,
	
	options: {
		'droppables':$empty
	},
	
	initialize: function(options){
		
		//data members
		this.setOptions(options);
		this.parent(options);
		this.window = new ShelfWindow();
		this.droppables = this.options.droppables;
		
		//generate HTML
		this.icon_image.setStyles({'background-image':'url(/obray/images/shelf/icon_textStyles.png)'});

		//generate HTML
		this.preview_block = new Element('div',{'class':'text_preview_block'});
		this.h1 = new TextPreview(this.preview_block,this.droppables,this.window,{'type':'h1'});
		this.h2 = new TextPreview(this.preview_block,this.droppables,this.window,{'type':'h2'});
		this.h3 = new TextPreview(this.preview_block,this.droppables,this.window,{'type':'h3'});
		this.h4 = new TextPreview(this.preview_block,this.droppables,this.window,{'type':'h4'});
		this.p  = new TextPreview(this.preview_block,this.droppables,this.window,{'type':'p'});
		this.ul  = new TextPreview(this.preview_block,this.droppables,this.window,{'type':'ul'});
		
		this.h3.text_box.setStyles({'padding-top':'10px','height':'25px'});
		this.h4.text_box.setStyles({'padding-top':'10px','height':'25px'});
		
		//construct HTML
		this.preview_block.inject(this.window.window_m);
		
		//add events
		this.icon_image.addEvent('click',function(){
			this.window.toggleWindow();
		}.bind(this))
		
	}
})

WidgetIcon = new Class({
	Extends: ObrayIcon,
	
	options: {
		'droppables':$empty
	},
	
	initialize: function(options){
		
		//data members
		this.setOptions(options);
		this.parent(options);
		this.components = [];
		this.window = new ShelfWindow();
		this.num_obray_widgets = 0;
		this.num_application_widgets = 0;

		//generate HTML
		this.icon_image.setStyles({'background-image':'url(/obray/images/shelf/icon_widgets_closed.png)'});
		this.components_container = new Element('div',{'class':'components'});
		this.br = new Element('br',{'class':'clear'});
		
		// container for application specific widgets
		this.application_widget_title = new Element('h4',{'class':'application-widget-title'});
		
		this.application_widget_title.setStyles({
			'font-family':'Arial,Helvetica',
			'font-size':14,
			'font-weight':'bold',
			'padding':0,
			'margin':0,
			'margin-top':0
		});
		this.application_widget_title.set('html','Application Widgets')
		this.application_widgets = new Element('div',{'class':'application-widgets-container'});
		this.application_hr = new Element('hr');
		this.application_hr.setStyles({'border-top':0,'border-right':0,'border-left':0,'border-top':1,'border-color':'#f5f5f5'})
		
		// container for assigned obray widgets
		this.obray_widget_title = new Element('h4',{'class':'obray-widget-title'});
		this.obray_widget_title.setStyles({'font-family':'Arial,Helvetica','font-size':14,'font-weight':'bold','padding':0,'margin':0,'margin-top':5});
		this.obray_widget_title.set('html','Obray Widgets')
		this.obray_widgets = new Element('div',{'class':'obray-widgets-container'});
		this.obray_hr = new Element('hr');
		this.obray_hr.setStyles({'border-top':0,'border-right':0,'border-left':0,'border-top':1,'border-color':'#f5f5f5'})
				
		this.window.window_m.setStyles({'height':500,'overflow-y':'scroll'});
		
		//set styles
		this.components_container.setStyles({'padding':'10px','height':'500px','overflow-x':'hidden','overflow-y':'scroll'});
		
		this.getObrayComponents = new Request({'url':'/cmd/owidgets/getWidgets/','method':'post','onComplete':function(response){
            var json = JSON.decode(response);
            // create draggable icon for each widget
            for(var i=0;i<json.response.components.length;++i){
            	if(json.response.components[i] != undefined){              	
	                if(json.response.components[i].component_type == 'obray'){ ++this.num_obray_widgets; var container = this.obray_widgets; } else { ++this.num_application_widgets; var container = this.application_widgets; }
	                this.components[this.components.length] =  new ComponentIcon(json.response.components[i].component_thumbnail,container,this.options.droppables,json.response.components[i].component_name,{'label':json.response.components[i].component_label,'type':json.response.components[i].component_type,'window':this.window});
                }
            }
            // insert application specific widgets if there are any
            if(this.num_application_widgets != 0){
                this.br.inject(this.components_container);
                this.application_hr.clone().inject(this.window.window_m);
                this.application_widget_title.inject(this.window.window_m);
                this.application_hr.inject(this.window.window_m);
                this.application_widgets.inject(this.window.window_m);
                this.br.clone().inject(this.window.window_m);
			}
			// insert assigned obray widgets if there are any
			if(this.num_obray_widgets != 0){
                this.application_hr.clone().inject(this.window.window_m);
                this.obray_widget_title.inject(this.window.window_m);
                this.application_hr.clone().inject(this.window.window_m);
                this.obray_widgets.inject(this.window.window_m);
			}
		}.bind(this)}).send();
		
		
		/*****
		this.getComponents = new Request({'url':'index.cfm?action=pages.getObrayComponents','method':'post','onComplete':function(response){
			
		    eval(response);
		    
		}.bind(this)}).send();
		****/
		
		//add events
		this.icon_image.addEvent('click',function(){ this.window.toggleWindow(); }.bind(this))
		
	}
})


IconGroup = new Class({
	Implements: Options,
	
	options:{
		
	},
	
	initialize: function(options){
		
		//data members
		this.setOptions(options);
		
		//genreate HTML
		this.group = new Element('div');
		this.group_left = new Element('div');
		this.group_middle = new Element('div');
		this.group_right = new Element('div');
		
		//set styles
		this.group_left.setStyles({'float':'left','width':28,'height':95,'background-image':'url(/obray/images/shelf/icon_group_left.png)'});
		this.group_middle.setStyles({'float':'left','height':95,'background-image':'url(/obray/images/shelf/icon_group_middle.png)'});
		this.group_right.setStyles({'float':'left','width':12,'height':95,'background-image':'url(/obray/images/shelf/icon_group_right.png)'});
		
		//construct HTML
		this.group_left.inject(this.group);
		this.group_middle.inject(this.group);
		this.group_right.inject(this.group);
		
	},
	
	getIconGroup: function(){
		return this.group;
	}
})

ShelfTools = new Class({
	Extends: IconGroup,
					   
	Implements: Options,
	
	options:{
		'page_id':0,
		'settings':true,
		'siteMap':true,
		'people':true,
		'templates':false
	},
	
	initialize: function(options){
		this.parent(options);
		//generate HTML
		//this.settings = new SettingsIcon({'icon_label':'Settings'});
		this.siteMap = new SiteMapIcon({'icon_label':'Site Map'});
		//this.people = new PeopleIcon({'icon_label':'People'});
		//this.templates = new TemplatesIcon(this.options.page_id,{'icon_label':'Templates'});
		this.br = new Element('br',{'class':'clearboth'});
		
		//construct HTML
		//if(this.options.settings){this.settings.getIcon().inject(this.group_middle);}
		if(this.options.siteMap){this.siteMap.getIcon().inject(this.group_middle);}
		//if(this.options.people){this.people.getIcon().inject(this.group_middle);}
		//if(this.options.templates){this.templates.getIcon().inject(this.group_middle);}
		this.br.clone().inject(this.group_middle);
	}
})

ShelfContent = new Class({
	Extends: IconGroup,
					   
	Implements: Options,
	
	options:{
		'droppables':$empty,
		'widgets':true
	},
	
	initialize: function(options){
		this.parent(options);
		this.setOptions(options);
		//generate HTML
		this.pictures = new PicturesIcon({'droppables':this.options.droppables,'icon_label':'Pictures'});
		this.videos = new VideosIcon({'droppables':this.options.droppables,'icon_label':'Videos'});
		this.textStyles = new TextStylesIcon({'icon_label':'Text Styles','droppables':this.options.droppables});
		this.widgets = new WidgetIcon({'icon_label':'Site Widgets','droppables':this.options.droppables});
		this.br = new Element('br',{'class':'clearboth'});
		//set styles
		this.group_left.setStyles({'background-image':'url(/obray/images/shelf/icon_group_left_content.png)','margin-left':'20px'})
		//construct HTML
		this.pictures.getIcon().inject(this.group_middle);
		this.videos.getIcon().inject(this.group_middle);
		this.textStyles.getIcon().inject(this.group_middle);
		if(this.options.widgets){ this.widgets.getIcon().inject(this.group_middle); }
		this.br.clone().inject(this.group_middle);
	}
})

/********************************************************************

	Shelf class:  Creates the Obray shelf

********************************************************************/
Shelf = new Class({
	Implements: Options,
	
	options: {
		'id':0,
		'authType': false,
		'settings':true,
		'siteMap':true,
		'people':true,
		'templates':false,
		'widgets':true
	},
	
	initialize: function(options){
		//data memebers
		this.setOptions(options)
		this.dockTransition = new Fx.Transition(Fx.Transitions.Quad);
		this.droppables = [];
		this.icons = [];
		this.groups = [];
		
		//genreate HTML
		this.shelf = new Element('div');
		this.shelf_left = new Element('div');
		this.shelf_middle = new Element('div');
		this.shelf_right = new Element('div');
		this.logout = new LogoutIcon({'icon_label':'Logout'});
		this.tools = new ShelfTools({'page_id':this.options.id,'settings':this.options.settings,'siteMap':this.options.siteMap,'people':this.options.people,'templates':this.options.templates,'widgets':this.options.widgets});
		this.content = new ShelfContent({'droppables':this.getDroppables.bind(this),'widgets':this.options.widgets});
		this.br = new Element('br',{'class':'clearboth'});
		
		//set styles
		this.shelf.setStyles({'position':'fixed','left':0,'bottom':0,'z-index':5000});
		this.shelf_left.setStyles({'float':'left','height':107,'width':19,'background-image':'url(/obray/images/shelf/shelf_left.png)'});
		this.shelf_middle.setStyles({'float':'left','height':96,'width':880,'background-image':'url(/obray/images/shelf/shelf_middle.png)','padding-top':11});
		this.shelf_right.setStyles({'float':'left','height':107,'width':19,'background-image':'url(/obray/images/shelf/shelf_right.png)'});
		
		//construct HTML
		this.logout.getIcon().inject(this.shelf_middle);
		this.tools.getIconGroup().inject(this.shelf_middle);
		this.content.getIconGroup().inject(this.shelf_middle);
		this.br.clone().inject(this.shelf_middle);
		
		this.shelf_left.inject(this.shelf);
		this.shelf_middle.inject(this.shelf);
		this.shelf_right.inject(this.shelf);
		this.shelf.inject(document.body);
		
		this.adjustPosition();
		
	},
	
	addDroppable: function(droppable){
		this.droppables[this.droppables.length] = droppable;
	},
	
	getDroppables: function(){
		return $$('.droppable');
	},
	destroy: function(){
		this.shelf.destroy();
	},
	
	adjustPosition: function(){
		var width = this.shelf.getCoordinates().width;
		this.shelf.setStyles({'position':'fixed','left':'50%','bottom':0,'margin-left':-(width/2)});
	}
}); /*******************************************************
	Droppables
*******************************************************/

Droppable = new Class({
	Implements: Options,
	
	options:{
		'content_area_id':0,
		'content_parent_id':0,
		'content_order':0,
		'content_part':false,
		'siblings':$empty,
		'content_order_modifier':0
	},
	
	initialize: function(parent,content_part,options){
		this.setOptions(options);
		this.parent = parent;
		this.droppable = new Element('div',{'class':'droppable'});	
		this.droppable.content_area_id = this.options.content_area_id;
		this.droppable.content_parent_id = this.options.content_parent_id;
		this.droppable.content_order = this.options.content_order;
		this.droppable.setStyles({'background-color':'#000','opacity':.5});
		this.droppable.siblings = this.options.siblings;
		this.droppable.getContentOrder = function(){ 
			if(content_part == false){
				return 0;
			}else{
				return content_part.options.content_order + this.options.content_order_modifier;
			} 
		}.bind(this);
		//this.droppable.content_part = this.options.content_part;
	},
	
	inject: function(position){
		this.droppable.inject(this.parent,position);
	},
	
	get: function(){
		return this.droppable;
	}
});

/*******************************************************
	Obray v2
*******************************************************/

var ObrayV2 = new Class({
	Implements: Options,
	
	options:{
		'page_id': 0,
		'settings':true,
		'siteMap':true,
		'people':true,
		'templates':false,
		'widgets':true,
		'content_area_object_id':0,
		'amazon_location':'',
		'content_language':'en',
		'ext_parameter':'',
		'content_area_ids':''
	},
	
	initialize: function(options){
		this.setOptions(options);
		
		this.content_areas = [];
		this.missing_areas = [];
		this.chain = new Chain();
		this.callChain = true;
		this.executing_request = false;
		this.amazon_location = this.options.amazon_location;
		
		/****************************************************
			OBRAY CORE: This is where the magic happens
		****************************************************/
		
		var data = '&page_id='+this.options.page_id
				 + '&content_language='+this.options.content_language
				 + '&content_area_object_id='+this.options.content_area_object_id
				 + '&ext_parameter='+this.options.qryStr;
		// get content data
		var time_stamp = Math.round(((new Date()).getTime()-Date.UTC(1970,0,1))/1000);
		this.request = new Request({'url':'/cmd/opages/getContent/?time='+time_stamp,'data':data,'method':'get','onComplete':function(response){
		    response = JSON.decode(response);
		    
			this.toolbar = new Shelf({'id':this.options.page_id,'authType':this.authType,'settings':this.options.settings,'siteMap':this.options.siteMap,'people':this.options.people,'templates':this.options.templates,'widgets':this.options.widgets});
			for(var i=0;i<response.content_areas.length;i++){
				if($defined($(response.content_areas[i].content_area_name))){
					this.content_areas[this.content_areas.length] = new ContentAreaV2({
						'content_area_id':			response.content_areas[i].content_area_id,
						'content_area_name':		response.content_areas[i].content_area_name,
						'content_area_level':		response.content_areas[i].content_area_level,
						'content_part_types':		response.content_areas[i].content_part_types,
						'content_area_width':		response.content_areas[i].content_area_width,
						'content_area_height':		response.content_areas[i].content_area_height,
						'content_parts':			response.content_areas[i].content_parts
					})
				} else {
					// some content areas may be loaded by other content areas (therefore not appearing until that area has been loaded).  We keep track of these so we can find them later.
					this.missing_areas[this.missing_areas.length] = response.content_areas[i];
				}
			}
			this.repeatFind = this.findMissingAreas.periodical(200,this);
			
		}.bind(this)}).send();	
	},
	
	findMissingAreas: function(){
		for(var i=0;i<this.missing_areas.length;i++){
			if($defined($(this.missing_areas[i].content_area_name))){
				this.content_areas[this.content_areas.length] = new ContentAreaV2({
					'content_area_id':			this.missing_areas[i].content_area_id,
					'content_area_name':		this.missing_areas[i].content_area_name,
					'content_area_level':		this.missing_areas[i].content_area_level,
					'content_part_types':		this.missing_areas[i].content_part_types,
					'content_area_width':		this.missing_areas[i].content_area_width,
					'content_area_height':		this.missing_areas[i].content_area_height,
					'content_parts':			this.missing_areas[i].content_parts
				})
				this.missing_areas.erase(this.missing_areas[i]);
			}
		}
		if(this.missing_areas.length == 0){
			//$clear(this.repeatFind);	
		}
	},
	
	addDroppable: function(droppable){
		this.toolbar.addDroppable(droppable);
	},
	
	log:function(obj){
	
		if(console){ console.log(obj) }
		
	}
	
});
OWidgetBarButton = new Class({
    Implements: Options,
    
    options:{
        'button-label':'default',
        'click':$empty
    },
    
    initialize: function(options){
        this.setOptions(options);
        
        this.button = new Element('li',{'class':'owidgetbarbutton'});
        this.button.setStyles({'float':'left','background-image':'none','color':'#858585','display':'block','height':18,'font-size':14,'font-family':'Arial,helvetica','vertical-align':'middle','border-left':'1px solid #454545','border-right':'1px solid #454545','margin':0,'padding':9,'padding-top':9,'margin-top':2,'margin-bottom':2})
        this.button.set('html',this.options['button-label']);
        
        this.button.addEvent('mouseenter',function(){ this.button.setStyles({'color':'#d1d1d1','background-color':'#333333','cursor':'pointer'}); }.bind(this));
        this.button.addEvent('mouseleave',function(){ this.button.setStyles({'color':'#858585','background-color':'transparent','cursor':'pointer'}); }.bind(this));
        
        this.button.addEvent('click',this.options['click']);
    },
    
    inject: function(el,position){
        this.button.inject(el,position);
    },
    
    getCoordinates: function(){
        return this.button.getCoordinates();
    },
    
    setLabel: function(label){
    	this.button.set('html',label);
    },
    
    setStyles: function(styles){
    	this.button.setStyles(styles);
    }
});


OWidgetBar = new Class({
    Implements: Options,
    
    options:{
        'open-element': new Element('div'),
        'title-label':'default',
        'opacity':1,
        'title_div_width':250
        
    },
    
    initialize: function(options){
        this.setOptions(options);
        this.widget_bar_buttons = [];
        
        this.open_element = this.options['open-element'];
        this.open_element.addEvent('mouseenter',function(){
            this.widget_bar.fx.pause();
            this.widget_bar.fx.start({'height':40})
        }.bind(this));
        this.open_element.addEvent('mouseleave',function(){
            this.widget_bar.fx.pause();
            this.widget_bar.fx.start({'height':0})
        }.bind(this));
        
        this.widget_bar = new Element('div',{'class':'oblog-post-bar'});
        this.widget_bar.setStyles({'position':'absolute','top':0,'left':0,'width':'100%','height':0,'background-image':'url(/obray/images/widget/widget-bar.png)','opacity':this.options['opacity'],'overflow':'hidden','-webkit-border-radius':'5px 5px 5px 5px','-moz-border-radius':'5px 5px 5px 5px','z-index':6000})
        this.widget_bar.fx = new Fx.Morph(this.widget_bar,{'duration':600,'transition':Fx.Transitions.Quint.easeOut});
        this.widget_bar.inject(this.open_element,'top');
        
        this.widget_bar_content = new Element('div',{'class':'oblog-post-bar-content'});
        this.widget_bar_content.setStyles({'display':'block','float':'left','color':'#c5c5c5','font-size':12,'font-family':'Arial,Helvetica','padding':5,'width':this.options.title_div_width});
        //this.widget_bar_content.set('html','Blog Post Option for "'+this.options['blog-post-title']+'"');
        this.widget_bar_content.inject(this.widget_bar);
        
        // widget bar title
        this.bar_title = new Element('h2',{'class':'owidget-bar-title'});
        this.bar_title.setStyles({'display':'block','float':'left','font-family':'Arial,Helvetica','color':'#fff','font-weight':'normal','font-size':16,'border':0,'margin':0,'padding':5});
        this.bar_title.set('html',this.options['title-label']);
        this.bar_title.inject(this.widget_bar_content);
        
        this.widget_bar_list = new Element('url',{'class':'owidgetbar-list'});
        this.widget_bar_list.setStyles({'float':'right','margin':0,'padding':0})
        this.widget_bar_list.inject(this.widget_bar);
    },
    
    getContent: function(){
        return this.widget_bar_content;
    },
    
    addButton: function(label,fn){
        this.widget_bar_buttons[this.widget_bar_buttons.length] = new OWidgetBarButton({'button-label':label,'click':fn});
        this.widget_bar_buttons[this.widget_bar_buttons.length-1].inject(this.widget_bar_list);
        return this.widget_bar_buttons[this.widget_bar_buttons.length-1];
    }
});


OWidgetMenuItem = new Class({
    Implements: Options,
    
    options:{
        'item-label':'Default',
        'click-function':$empty,
        'item-icon':''
    },
    
    initialize: function(options){
        this.setOptions(options);
        
        this.menu_item = new Element('li',{'class':'owidgetmenuitem'});
        this.menu_item.setStyles({'display':'block','font-family':'Arial,Helvetica','color':'#858585','list-style':'none','margin':0,'padding':3,'width':194,'-webkit-border-radius':'2px 2px 2px 2px','-moz-border-radius':'2px 2px 2px 2px','background-image':'none'});
        this.menu_item.set('html',this.options['item-label']);
        this.menu_item.addEvent('click',this.options['click-function']);
        this.menu_item.addEvent('mouseenter',function(){ this.menu_item.setStyles({'background-color':'#151515','color':'#ffffff'}); }.bind(this));
        this.menu_item.addEvent('mouseleave',function(){ this.menu_item.setStyles({'background-color':'#000000','color':'#858585'}); }.bind(this));
        if(this.options['item-icon'] != ''){
            this.menu_item_icon = new Element('img',{'src':this.options['item-icon']});
            this.menu_item_icon.setStyles({'margin-bottom':-4,'margin-right':2,'margin-left':-4});
            this.menu_item_icon.inject(this.menu_item,'top');
        }
        
        
    },
    
    inject: function(el,position){
        this.menu_item.inject(el,position);
    }
});


OWidgetMenu = new Class({
    Implements: Options,
    
    options:{
        'content_part_id':0,
        'onDelete':$empty
    },
    
    initialize: function(options){
        this.setOptions(options);
        this.menu_items = [];
        
        this.widget_menu_container = new Element('div',{'class':'owidgetmenu-container'});
        this.widget_menu_container.setStyles({'position':'absolute','z-index':'6000','right':-18,'top':-18,'opacity':0,'cursor':'pointer','background-image':'url(/obray/images/obray-cog.png)','width':35,'height':35,'overflow':'visible'});
        this.widget_menu_container.fx = new Fx.Morph(this.widget_menu_container,{'duration':600,'transition':Fx.Transitions.Quint.easeOut});
        
        this.widget_menu_container.addEvent('mouseenter',function(){ this.widget_menu.fx.pause(); this.widget_menu.fx.start({'opacity':.75}); }.bind(this));
        this.widget_menu_container.addEvent('mouseleave',function(){ this.widget_menu.fx.pause(); this.widget_menu.fx.start({'opacity':0}); }.bind(this));
        
        this.widget_menu = new Element('div',{'class':'owidgetmenu'});
        this.widget_menu.setStyles({'position':'absolute','z-index':'1000','right':20,'top':0,'padding':5,'background-color':'#000000','opacity':0,'width':200,'height':'auto','-webkit-border-radius':'5px 5px 5px 5px','-moz-border-radius':'5px 5px 5px 5px'})
        this.widget_menu.fx = new Fx.Morph(this.widget_menu,{'duration':600,'transition':Fx.Transitions.Quint.easeOut});
        this.widget_menu.inject(this.widget_menu_container);
        
        this.widget_menu_list = new Element('ul');
        this.widget_menu_list.inject(this.widget_menu);
        
    },
    
    fade: function(toggle){
        if(toggle == "in"){
            this.widget_menu_container.fx.pause();
            this.widget_menu_container.fx.start({'opacity':1});
        } else {
            this.widget_menu_container.fx.pause();
            this.widget_menu_container.fx.start({'opacity':0});
        }
    },
    
    inject: function(el,position){
        this.widget_menu_container.inject(el,position);
    },
    
    addMenuItem: function(menu_label,fn){
        this.menu_items[this.menu_items.length] = new OWidgetMenuItem({'item-label':menu_label,'click-function':fn});
        this.menu_items[this.menu_items.length-1].inject(this.widget_menu_list);
    },
    
    enableDelete: function(label){
        this.menu_items[this.menu_items.length] = new OWidgetMenuItem({'item-label':label,'item-icon':'/obray/images/btn-small-delete.png','click-function':function(){
            this.deleteWidget();
        }.bind(this)});
        this.menu_items[this.menu_items.length-1].inject(this.widget_menu_list);
    },
    
    deleteWidget: function(){
        var deletePart = new Request({'url':'/cmd/owidgets/delete/','data':'&content_part_id='+this.options['content_part_id'],'onComplete':function(){
            this.options.onDelete();
            var location = window.location.href.replace(window.location.hash,'');
            var location = location.replace('##','');
            window.location = location;
        }.bind(this)}).send();
    }
});


OWidget = new Class({
    Implements: Options,
    
    options:{
        'widget-container':new Element('div'),
        'content-part-id':0,
        'onDelete':$empty
    },
    
    initialize: function(options){
        this.setOptions(options);
        // assign the passed in container to the local widget object
        this.widget = this.options['widget-container'];
        // add transparent border to widget and set other styles
        this.widget.setStyles({'border':'1px solid transparent','position':'relative','margin-left':-1,'margin-right':-1});
        // show and hide border on mouse events
        
        this.widget_fx = new Fx.Morph(this.widget,{'duration':600,'transition':Fx.Transitions.Quint.easeOut});
        
        this.widget.addEvent('mouseenter',function(){
        	//'border':'1px solid #d5d5d5','margin':-1,
            this.widget.setStyles({'box-shadow':'0px 0px 8px #aaa','border-radius':'3px'});
            this.widget_menu.fade('in');
        }.bind(this));
        this.widget.addEvent('mouseleave',function(){ 
        	//'border':'1px solid transparent',
            this.widget.setStyles({'box-shadow':'0px 0px 0px #000','border-radius':'3px'});
            this.widget_menu.fade('out');
        }.bind(this));
        
        // create widget menu
        this.widget_menu = new OWidgetMenu({'content_part_id':this.options['content_part_id'],'onDelete':this.options.onDelete});
        this.widget_menu.inject(this.widget);
    },
    
    addButton: function(label,fn){
        this.widget_menu.addMenuItem(label,fn);
    },
    
    enableDelete: function(label){
        this.widget_menu.enableDelete(label);
    }
});




/*********************************************
	Mini Edit / Delete Buttons
*********************************************/
OWidgetMiniAdminButton = new Class({
    Implements: Options,
    
    options:{
        'mini-admin-button-label':'default',
		'mini-admin-button':'default-obray-btn',
        'click':$empty,
		'value':''
    },
    
    initialize: function(options){
        this.setOptions(options);
        
        this.mini_admin_button = new Element('li',{'class':'mini-admin-icon'});
        this.mini_admin_button.setStyles({'float':'right','cursor':'pointer','background-image':'none','margin':'0px 2px 0px 2px','padding':0})
        this.mini_admin_button.set('html','<img src="/obray/config/images/'+this.options['mini-admin-button']+'.png" width="23" height="23" alt="'+this.options['mini-admin-button-label']+' Item" title="'+this.options['mini-admin-button-label']+' Item"/>');
        this.mini_admin_button.addEvent('click',this.options['click'].pass(this.options.value));
    },
    
    inject: function(el,position){
        this.mini_admin_button.inject(el,position);
    },
    
    getCoordinates: function(){
        return this.mini_admin_button.getCoordinates();
    },
    
    setLabel: function(label){
    	this.mini_admin_button.set('html',btn_src);
    },
    
    setStyles: function(styles){
    	this.mini_admin_button.setStyles(styles);
    }
});


OWidgetMiniAdmin = new Class({
    Implements: Options,
    
    options:{
        'open-element': new Element('div'),
        'title-label':'default',
		'item-id':0,
        'opacity':1
    },
    
    initialize: function(options){
        this.setOptions(options);
        this.widget_mini_buttons = [];
        
        this.open_element = this.options['open-element'];
        
        this.open_element.addEvent('mouseenter',function(){
            this.widget_admin_buttons.fx.pause();
            this.widget_admin_buttons.fx.start({'opacity':1})
        }.bind(this));
        this.open_element.addEvent('mouseleave',function(){
            this.widget_admin_buttons.fx.pause();
            this.widget_admin_buttons.fx.start({'opacity':0})
        }.bind(this));
        
		//wrapper div
        this.widget_admin_buttons = new Element('div',{'class':'mini-buttons-admin'});
        this.widget_admin_buttons.setStyles({'opacity':0,'overflow':'hidden','height':23,'position':'absolute','top':0,'right':0,'z-index':5100})
        this.widget_admin_buttons.fx = new Fx.Morph(this.widget_admin_buttons,{'duration':600,'transition':Fx.Transitions.Quint.easeOut});
        this.widget_admin_buttons.inject(this.open_element,'top');
        
		this.widget_admin_buttons_list = new Element('ul',{'class':'owidgetbar-list'});
        this.widget_admin_buttons_list.setStyles({'float':'right','margin':0,'padding':0})
        this.widget_admin_buttons_list.inject(this.widget_admin_buttons);
		
    },
    
    getContent: function(){
        return this.widget_admin_buttons_content;
    },
    
    addButton: function(btn_src,btn_label,fn){
        this.widget_mini_buttons[this.widget_mini_buttons.length] = new OWidgetMiniAdminButton({'mini-admin-button':btn_src,'mini-admin-button-label':btn_label,'click':fn});
        this.widget_mini_buttons[this.widget_mini_buttons.length-1].inject(this.widget_admin_buttons_list);
        return this.widget_mini_buttons[this.widget_mini_buttons.length-1];
    }
}); /*******************************************	OAccordion Class*******************************************/OAccordion = new Class({	Implements: Options,		options:{		'open_index':0,		'onToggle':$empty	},		initialize: function(togglers,containers,options){		this.setOptions(options);		this.initialized = false;		togglers.each(function(el,index){			containers[index].isOpen = false;			containers[index].setStyles({'height':0,'overflow':'hidden','visibility':'hidden'});			// close open containers			for(var i=0;i<containers.length;++i){ 				if(containers[i].isOpen && i != index){					containers[i].isOpen = false; 					containers[i].setStyles({'height':containers[i].getCoordinates().height});					togglers[i].fx.pause();					togglers[i].fx.start({'height':0,'overflow':'hidden','visibility':'hidden'});					togglers[i].removeClass('active');					try{					containers[i].getFirst().getChildren('.droppable').each(function(el,index){						el.addClass('droppable-removed');						el.removeClass('droppable');					}.bind(this));					} catch (err) {}				} 			}			el.fx = new Fx.Morph(containers[index],{'duration':600,'transition':Fx.Transitions.Quint.easeOut,'onComplete':function(){        		if(this.container.isOpen){        			this.container.setStyles({'height':'auto','overflow':'visible','visibility':'visible'});        		}        	}.bind(el)});        	el.setStyles({'cursor':'pointer','z-index':3000});			el.addEvent('click',function(e){								el.container = containers[index];				el.container.setStyles({'overflow':'hidden'});								if(e){					if(el.container.getChildren().length >0){e.preventDefault();}				e.stopPropagation();				}				el.addClass('active');												// close open containers				for(var i=0;i<containers.length;++i){ 					if(containers[i].isOpen && i != index){						containers[i].isOpen = false; 						containers[i].setStyles({'height':containers[i].getCoordinates().height});						togglers[i].fx.pause();						togglers[i].fx.start({'height':0,'overflow':'hidden','visibility':'hidden'});						togglers[i].removeClass('active');						try{						containers[i].getFirst().getChildren('.droppable').each(function(el,index){							el.addClass('droppable-removed');							el.removeClass('droppable');													}.bind(this));						} catch(err) {}					} 				}												// open or close container appropriately				if(containers[index].isOpen == false){					containers[index].isOpen = true;					el.fx.pause();					el.fx.start({'height':containers[index].getScrollSize().y,'visibility':'visible'});										// add active class to container					containers[index].addClass('active-container');					try{					containers[index].getFirst().getChildren('.droppable-removed').each(function(el,index){						el.addClass('droppable');						el.removeClass('droppable-removed');					}.bind(this));					} catch (err) {}				} else {					el.removeClass('active');					containers[index].isOpen = false;					containers[index].setStyles({'height':containers[index].getCoordinates().height});					el.fx.pause();					el.fx.start({'height':0,'overflow':'hidden','visibility':'hidden'});										// add active class to container					containers[index].removeClass('active-container');										containers[index].getFirst().getChildren('.droppable').each(function(el,index){						el.addClass('droppable-removed');						el.removeClass('droppable');					}.bind(this));				}				if(this.initialized){ this.options.onToggle(); } else { this.initialized = true; }			}.bind(this));		}.bind(this));				/*** STOPPED WORKING, REASON UNKNOWN - !!!!SHOULD BE WORKING NOW!!!! ****/					if(this.options.open_index != -1){				if(togglers[this.options.open_index]){					togglers[this.options.open_index].fireEvent('click');				}			} else { this.initialized = true; }		}});/*******************************************	OSort Class*******************************************/OSort = new Class({	Implements: Options,		options:{		'container':false,		'sortables':[],		'ids':[],		'x_drag_offset':30,		'y_drag_offset':30,		'save':$empty,		'selector':false,		'offset':{'x':0,'y':0},		'orientation':'horizontal',		'icon_position':{'left':-7,'top':-7}	},		initialize: function(options){		this.setOptions(options);		this.isDragging = false;				this.clone = false;		this.clones = [];				// get dividers		this.dividers = this.options.container.getChildren('.ogrid-divider');				// calculate items per row		if(this.dividers.length != 0){			var i = 0;			while(this.options.sortables[i].getNext().hasClass('ogrid-divider') == false){ ++i;	}			this.items_per_row = i+1;		} else {			this.items_per_row = 1000000;		}				this.options.sortables.each(function(el,index){						// setup ordering variable			el.order = index;			el.id = this.options.ids[index];						//create handle			var position = el.getPosition(this.options.container);			var styles = el.getStyles('margin-left','margin-top');			this.clones[this.clones.length] = el.clone().setStyles({'display':'none','position':'absolute','left':position.x-styles['margin-left'].toInt(),'top':position.y-styles['margin-top'].toInt()}).inject(this.options.container);;			this.clones[this.clones.length-1].reposition = new Fx.Morph(this.clones[this.clones.length-1], {duration: 150, transition: Fx.Transitions.Sine.easeOut});			this.clones[this.clones.length-1].index = index;						el.handle = new Element('div',{'class':'move-handle'}).setStyles({'position':'absolute','left':this.options.icon_position.left,'top':this.options.icon_position.top,'background-image':'url(/obray/images/icon-move.png)','width':16,'height':16,'cursor':'pointer','display':'none'}).inject(el);			el.handle.addEvent('mousedown',function(e){							this.clones.each(function(el,index){ el.setStyles({'display':'block'}); }.bind(this));				this.options.sortables.each(function(el,index){ el.setStyles({'opacity':.01}); }.bind(this));								// set dragging flag				this.isDragging = true;								var position = el.getPosition(this.options.container);				var styles = el.getStyles('margin-left','margin-top','border-top','border-left');									this.clone = el.clone().setStyles({'opacity':.50,'position':'absolute','top':position.y-styles['margin-top'].toInt(),'left':position.x-styles['margin-left'].toInt()});								// create drag object				this.drag_obj = new Drag.Move(this.clone,{'droppables':this.options.sortables,'onEnter':function(obj,droppable){										if(el.order > droppable.order){						el.inject(droppable,'before');						el.getParent().getChildren(this.options.selector).each(function(el,index){ 							el.order = index+1; 						});					} else {						el.inject(droppable,'after');						el.getParent().getChildren(this.options.selector).each(function(el,index){							el.order = index-1; 						});					}										// handle dividers					if(this.dividers.length > 0){						this.options.sortables.each(function(el,index){																				if(el.order % this.items_per_row == 0){								el.inject(this.dividers[(el.order/this.items_per_row)-1],'before'); 							} else if( el.order % this.items_per_row == 1 && el.order >= this.items_per_row ){ 								el.inject(this.dividers[((el.order-1)/this.items_per_row)-1],'after'); 							}													}.bind(this));					}										this.clones.each(function(el,index){												var new_position = this.options.sortables[el.index].getPosition(this.options.container)						var new_styles = this.options.sortables[el.index].getStyles('margin-left','margin-top');						el.reposition.pause();						el.reposition.start({'left':new_position.x-new_styles['margin-left'].toInt(),'top':new_position.y-new_styles['margin-top'].toInt()});											}.bind(this));														}.bind(this),				'onDrop':function(){					this.isDragging = false;					this.clone.destroy();					this.order = [];					this.options.sortables.each(function(el){					  this.order[el.order-1] = el.id;  					}.bind(this));					this.options.save(this.order);					this.clones.each(function(el,index){ el.setStyles({'display':'none'}); }.bind(this));					this.options.sortables.each(function(el,index){ el.setStyles({'opacity':1}); }.bind(this));									}.bind(this)});								this.drag_obj.start(e);							}.bind(this));						el.addEvent('mouseenter',function(){ if(!this.isDragging){ el.handle.setStyles({'display':'block'}); } }.bind(this));			el.addEvent('mouseleave',function(){ el.handle.setStyles({'display':'none'}); }.bind(this));					}.bind(this))			}});/**
 * Swiff.Uploader - Flash FileReference Control
 *
 * @version		3.0
 *
 * @license		MIT License
 *
 * @author		Harald Kirschner <http://digitarald.de>
 * @author		Valerio Proietti, <http://mad4milk.net>
 * @copyright	Authors
 */

Swiff.Uploader = new Class({

	Extends: Swiff,

	Implements: Events,

	options: {
		path: '/obray/config/Swiff.Uploader.swf',
		
		target: null,
		zIndex: 9999,
		
		height: 30,
		width: 100,
		callBacks: null,
		params: {
			wMode: 'opaque',
			menu: 'false',
			allowScriptAccess: 'always'
		},

		typeFilter: null,
		multiple: true,
		queued: true,
		verbose: false,

		url: null,
		method: null,
		data: null,
		mergeData: true,
		fieldName: null,

		fileSizeMin: 1,
		fileSizeMax: null, // Official limit is 100 MB for FileReference, but I tested up to 2Gb!
		allowDuplicates: false,
		timeLimit: (Browser.Platform.linux) ? 0 : 30,

		buttonImage: null,
		policyFile: null,
		
		fileListMax: 0,
		fileListSizeMax: 0,

		instantStart: false,
		appendCookieData: false,
		
		fileClass: null
		/*
		onLoad: $empty,
		onFail: $empty,
		onStart: $empty,
		onQueue: $empty,
		onComplete: $empty,
		onBrowse: $empty,
		onDisabledBrowse: $empty,
		onCancel: $empty,
		onSelect: $empty,
		onSelectSuccess: $empty,
		onSelectFail: $empty,
		
		onButtonEnter: $empty,
		onButtonLeave: $empty,
		onButtonDown: $empty,
		onButtonDisable: $empty,
		
		onFileStart: $empty,
		onFileStop: $empty,
		onFileRequeue: $empty,
		onFileOpen: $empty,
		onFileProgress: $empty,
		onFileComplete: $empty,
		onFileRemove: $empty,
		
		onBeforeStart: $empty,
		onBeforeStop: $empty,
		onBeforeRemove: $empty
		*/
	},

	initialize: function(options) {
		// protected events to control the class, added
		// before setting options (which adds own events)
		this.addEvent('load', this.initializeSwiff, true)
			.addEvent('select', this.processFiles, true)
			.addEvent('complete', this.update, true)
			.addEvent('fileRemove', function(file) {
				this.fileList.erase(file);
			}.bind(this), true);

		this.setOptions(options);

		// callbacks are no longer in the options, every callback
		// is fired as event, this is just compat
		if (this.options.callBacks) {
			Hash.each(this.options.callBacks, function(fn, name) {
				this.addEvent(name, fn);
			}, this);
		}

		this.options.callBacks = {
			fireCallback: this.fireCallback.bind(this)
		};

		var path = this.options.path;
		if (!path.contains('?')) path += '?noCache=' + $time(); // cache in IE

		// container options for Swiff class
		this.options.container = this.box = new Element('span', {'class': 'swiff-uploader-box'}).inject($(this.options.container) || document.body);

		// target 
		this.target = $(this.options.target);
		if (this.target) {
			var scroll = window.getScroll();
			this.box.setStyles({
				position: 'absolute',
				visibility: 'visible',
				zIndex: this.options.zIndex,
				overflow: 'hidden',
				height: 1, width: 1,
				top: scroll.y, left: scroll.x
			});
			
			// we force wMode to transparent for the overlay effect
			this.parent(path, {
				params: {
					wMode: 'transparent'
				},
				height: '100%',
				width: '100%'
			});
			
			this.target.addEvent('mouseenter', this.reposition.bind(this, []));
			
			// button interactions, relayed to to the target
			this.addEvents({
				buttonEnter: this.targetRelay.bind(this, ['mouseenter']),
				buttonLeave: this.targetRelay.bind(this, ['mouseleave']),
				buttonDown: this.targetRelay.bind(this, ['mousedown']),
				buttonDisable: this.targetRelay.bind(this, ['disable'])
			});
			
			this.reposition();
			window.addEvent('resize', this.reposition.bind(this, []));
		} else {
			this.parent(path);
		}

		this.inject(this.box);

		this.fileList = [];
		
		this.size = this.uploading = this.bytesLoaded = this.percentLoaded = 0;
		
		if (Browser.Plugins.Flash.version < 9) {
			this.fireEvent('fail', ['flash']);
		} else {
			this.verifyLoad.delay(1000, this);
		}
	},
	
	verifyLoad: function() {
		if (this.loaded) return;
		if (!this.object.parentNode) {
			this.fireEvent('fail', ['disabled']);
		} else if (this.object.style.display == 'none') {
			this.fireEvent('fail', ['hidden']);
		} else if (!this.object.offsetWidth) {
			this.fireEvent('fail', ['empty']);
		}
	},

	fireCallback: function(name, args) {
		// file* callbacks are relayed to the specific file
		if (name.substr(0, 4) == 'file') {
			// updated queue data is the second argument
			if (args.length > 1) this.update(args[1]);
			var data = args[0];
			
			var file = this.findFile(data.id);
			this.fireEvent(name, file || data, 5);
			if (file) {
				var fire = name.replace(/^file([A-Z])/, function($0, $1) {
					return $1.toLowerCase();
				});
				file.update(data).fireEvent(fire, [data], 10);
			}
		} else {
			this.fireEvent(name, args, 5);
		}
	},

	update: function(data) {
		// the data is saved right to the instance 
		$extend(this, data);
		this.fireEvent('queue', [this], 10);
		return this;
	},

	findFile: function(id) {
		for (var i = 0; i < this.fileList.length; i++) {
			if (this.fileList[i].id == id) return this.fileList[i];
		}
		return null;
	},

	initializeSwiff: function() {
		// extracted options for the swf 
		this.remote('initialize', {
			width: this.options.width,
			height: this.options.height,
			typeFilter: this.options.typeFilter,
			multiple: this.options.multiple,
			queued: this.options.queued,
			url: this.options.url,
			method: this.options.method,
			data: this.options.data,
			mergeData: this.options.mergeData,
			fieldName: this.options.fieldName,
			verbose: this.options.verbose,
			fileSizeMin: this.options.fileSizeMin,
			fileSizeMax: this.options.fileSizeMax,
			allowDuplicates: this.options.allowDuplicates,
			timeLimit: this.options.timeLimit,
			buttonImage: this.options.buttonImage,
			policyFile: this.options.policyFile
		});

		this.loaded = true;

		this.appendCookieData();
	},
	
	targetRelay: function(name) {
		if (this.target) this.target.fireEvent(name);
	},

	reposition: function(coords) {
		// update coordinates, manual or automatically
		coords = coords || (this.target && this.target.offsetHeight)
			? this.target.getCoordinates(this.box.getOffsetParent())
			: {top: window.getScrollTop(), left: 0, width: 40, height: 40}
		this.box.setStyles(coords);
		this.fireEvent('reposition', [coords, this.box, this.target]);
	},

	setOptions: function(options) {
		if (options) {
			if (options.url) options.url = Swiff.Uploader.qualifyPath(options.url);
			if (options.buttonImage) options.buttonImage = Swiff.Uploader.qualifyPath(options.buttonImage);
			this.parent(options);
			if (this.loaded) this.remote('setOptions', options);
		}
		return this;
	},

	setEnabled: function(status) {
		this.remote('setEnabled', status);
	},

	start: function() {
		this.fireEvent('beforeStart');
		this.remote('start');
	},

	stop: function() {
		this.fireEvent('beforeStop');
		this.remote('stop');
	},

	remove: function() {
		this.fireEvent('beforeRemove');
		this.remote('remove');
	},

	fileStart: function(file) {
		this.remote('fileStart', file.id);
	},

	fileStop: function(file) {
		this.remote('fileStop', file.id);
	},

	fileRemove: function(file) {
		this.remote('fileRemove', file.id);
	},

	fileRequeue: function(file) {
		this.remote('fileRequeue', file.id);
	},

	appendCookieData: function() {
		var append = this.options.appendCookieData;
		if (!append) return;
		
		var hash = {};
		document.cookie.split(/;\s*/).each(function(cookie) {
			cookie = cookie.split('=');
			if (cookie.length == 2) {
				hash[decodeURIComponent(cookie[0])] = decodeURIComponent(cookie[1]);
			}
		});

		var data = this.options.data || {};
		if ($type(append) == 'string') data[append] = hash;
		else $extend(data, hash);

		this.setOptions({data: data});
	},

	processFiles: function(successraw, failraw, queue) {
		var cls = this.options.fileClass || Swiff.Uploader.File;

		var fail = [], success = [];

		if (successraw) {
			successraw.each(function(data) {
				var ret = new cls(this, data);
				if (!ret.validate()) {
					ret.remove.delay(10, ret);
					fail.push(ret);
				} else {
					this.size += data.size;
					this.fileList.push(ret);
					success.push(ret);
					ret.render();
				}
			}, this);

			this.fireEvent('selectSuccess', [success], 10);
		}

		if (failraw || fail.length) {
			fail.extend((failraw) ? failraw.map(function(data) {
				return new cls(this, data);
			}, this) : []).each(function(file) {
				file.invalidate().render();
			});

			this.fireEvent('selectFail', [fail], 10);
		}

		this.update(queue);

		if (this.options.instantStart && success.length) this.start();
	}

});

$extend(Swiff.Uploader, {

	STATUS_QUEUED: 0,
	STATUS_RUNNING: 1,
	STATUS_ERROR: 2,
	STATUS_COMPLETE: 3,
	STATUS_STOPPED: 4,

	log: function() {
		if (window.console && console.info) console.info.apply(console, arguments);
	},

	unitLabels: {
		b: [{min: 1, unit: 'B'}, {min: 1024, unit: 'kB'}, {min: 1048576, unit: 'MB'}, {min: 1073741824, unit: 'GB'}],
		s: [{min: 1, unit: 's'}, {min: 60, unit: 'm'}, {min: 3600, unit: 'h'}, {min: 86400, unit: 'd'}]
	},

	formatUnit: function(base, type, join) {
		var labels = Swiff.Uploader.unitLabels[(type == 'bps') ? 'b' : type];
		var append = (type == 'bps') ? '/s' : '';
		var i, l = labels.length, value;

		if (base < 1) return '0 ' + labels[0].unit + append;

		if (type == 's') {
			var units = [];

			for (i = l - 1; i >= 0; i--) {
				value = Math.floor(base / labels[i].min);
				if (value) {
					units.push(value + ' ' + labels[i].unit);
					base -= value * labels[i].min;
					if (!base) break;
				}
			}

			return (join === false) ? units : units.join(join || ', ');
		}

		for (i = l - 1; i >= 0; i--) {
			value = labels[i].min;
			if (base >= value) break;
		}

		return (base / value).toFixed(1) + ' ' + labels[i].unit + append;
	}

});

Swiff.Uploader.qualifyPath = (function() {
	
	var anchor;
	
	return function(path) {
		(anchor || (anchor = new Element('a'))).href = path;
		return anchor.href;
	};

})();

Swiff.Uploader.File = new Class({

	Implements: Events,

	initialize: function(base, data) {
		this.base = base;
		this.update(data);
	},

	update: function(data) {
		return $extend(this, data);
	},

	validate: function() {
		var options = this.base.options;
		
		if (options.fileListMax && this.base.fileList.length >= options.fileListMax) {
			this.validationError = 'fileListMax';
			return false;
		}
		
		if (options.fileListSizeMax && (this.base.size + this.size) > options.fileListSizeMax) {
			this.validationError = 'fileListSizeMax';
			return false;
		}
		
		return true;
	},

	invalidate: function() {
		this.invalid = true;
		this.base.fireEvent('fileInvalid', this, 10);
		return this.fireEvent('invalid', this, 10);
	},

	render: function() {
		return this;
	},

	setOptions: function(options) {
		if (options) {
			if (options.url) options.url = Swiff.Uploader.qualifyPath(options.url);
			this.base.remote('fileSetOptions', this.id, options);
			this.options = $merge(this.options, options);
		}
		return this;
	},

	start: function() {
		this.base.fileStart(this);
		return this;
	},

	stop: function() {
		this.base.fileStop(this);
		return this;
	},

	remove: function() {
		this.base.fileRemove(this);
		return this;
	},

	requeue: function() {
		this.base.fileRequeue(this);
	} 

});


/**
 * FancyUpload - Flash meets Ajax for powerful and elegant uploads.
 * 
 * Updated to latest 3.0 API. Hopefully 100% compat!
 *
 * @version		3.0
 *
 * @license		MIT License
 *
 * @author		Harald Kirschner <http://digitarald.de>
 * @copyright	Authors
 */

var FancyUpload2 = new Class({

	Extends: Swiff.Uploader,
	
	options: {
		queued: 1,
		// compat
		limitSize: 0,
		limitFiles: 0,
		validateFile: $lambda(true)
	},

	initialize: function(status, list, options) {
		this.status = $(status);
		this.list = $(list);

		// compat
		options.fileClass = options.fileClass || FancyUpload2.File;
		options.fileSizeMax = options.limitSize || options.fileSizeMax;
		options.fileListMax = options.limitFiles || options.fileListMax;

		this.parent(options);

		this.addEvents({
			'load': this.render,
			'select': this.onSelect,
			'cancel': this.onCancel,
			'start': this.onStart,
			'queue': this.onQueue,
			'complete': this.onComplete
		});
	},

	render: function() {
		this.overallTitle = this.status.getElement('.overall-title');
		this.currentTitle = this.status.getElement('.current-title');
		this.currentText = this.status.getElement('.current-text');

		var progress = this.status.getElement('.overall-progress');
		this.overallProgress = new Fx.ProgressBar(progress, {
			text: new Element('span', {'class': 'progress-text'}).inject(progress, 'after')
		});
		progress = this.status.getElement('.current-progress')
		this.currentProgress = new Fx.ProgressBar(progress, {
			text: new Element('span', {'class': 'progress-text'}).inject(progress, 'after')
		});
				
		this.updateOverall();
	},

	onSelect: function() {
		this.status.removeClass('status-browsing');
	},

	onCancel: function() {
		this.status.removeClass('file-browsing');
	},

	onStart: function() {
		this.status.addClass('file-uploading');
		this.overallProgress.set(0);
	},

	onQueue: function() {
		this.updateOverall();
	},

	onComplete: function() {
		this.status.removeClass('file-uploading');
		if (this.size) {
			this.overallProgress.start(100);
		} else {
			this.overallProgress.set(0);
			this.currentProgress.set(0);
		}
		
	},

	updateOverall: function() {
		this.overallTitle.set('html', MooTools.lang.get('FancyUpload', 'progressOverall').substitute({
			total: Swiff.Uploader.formatUnit(this.size, 'b')
		}));
		if (!this.size) {
			this.currentTitle.set('html', MooTools.lang.get('FancyUpload', 'currentTitle'));
			this.currentText.set('html', '');
		}
	},
	
	/**
	 * compat
	 */
	upload: function() {
		this.start();
	},
	
	removeFile: function() {
		return this.remove();
	}

});

FancyUpload2.File = new Class({
	
	Extends: Swiff.Uploader.File,

	render: function() {
		if (this.invalid) {
			if (this.validationError) {
				var msg = MooTools.lang.get('FancyUpload', 'validationErrors')[this.validationError] || this.validationError;
				this.validationErrorMessage = msg.substitute({
					name: this.name,
					size: Swiff.Uploader.formatUnit(this.size, 'b'),
					fileSizeMin: Swiff.Uploader.formatUnit(this.base.options.fileSizeMin || 0, 'b'),
					fileSizeMax: Swiff.Uploader.formatUnit(this.base.options.fileSizeMax || 0, 'b'),
					fileListMax: this.base.options.fileListMax || 0,
					fileListSizeMax: Swiff.Uploader.formatUnit(this.base.options.fileListSizeMax || 0, 'b')
				});
			}
			this.remove();
			return;
		}
		
		this.addEvents({
			'start': this.onStart,
			'progress': this.onProgress,
			'complete': this.onComplete,
			'error': this.onError,
			'remove': this.onRemove
		});
		
		this.info = new Element('span', {'class': 'file-info'});
		this.element = new Element('li', {'class': 'file'}).adopt(
			new Element('span', {'class': 'file-size', 'html': Swiff.Uploader.formatUnit(this.size, 'b')}),
			new Element('a', {
				'class': 'file-remove',
				href: '#',
				html: MooTools.lang.get('FancyUpload', 'remove'),
				title: MooTools.lang.get('FancyUpload', 'removeTitle'),
				events: {
					click: function() {
						this.remove();
						return false;
					}.bind(this)
				}
			}),
			new Element('span', {'class': 'file-name', 'html': MooTools.lang.get('FancyUpload', 'fileName').substitute(this)}),
			this.info
		).inject(this.base.list);
	},
	
	validate: function() {
		return (this.parent() && this.base.options.validateFile(this));
	},
	
	onStart: function() {
		this.element.addClass('file-uploading');
		this.base.currentProgress.cancel().set(0);
		this.base.currentTitle.set('html', MooTools.lang.get('FancyUpload', 'currentFile').substitute(this));
	},

	onProgress: function() {
		this.base.overallProgress.start(this.base.percentLoaded);
		this.base.currentText.set('html', MooTools.lang.get('FancyUpload', 'currentProgress').substitute({
			rate: (this.progress.rate) ? Swiff.Uploader.formatUnit(this.progress.rate, 'bps') : '- B',
			bytesLoaded: Swiff.Uploader.formatUnit(this.progress.bytesLoaded, 'b'),
			timeRemaining: (this.progress.timeRemaining) ? Swiff.Uploader.formatUnit(this.progress.timeRemaining, 's') : '-'
		}));
		this.base.currentProgress.start(this.progress.percentLoaded);
	},
	
	onComplete: function() {
		this.element.removeClass('file-uploading');
		
		this.base.currentText.set('html', 'Upload completed');
		this.base.currentProgress.start(100);
		
		if (this.response.error) {
			var msg = MooTools.lang.get('FancyUpload', 'errors')[this.response.error] || '{error} #{code}';
			this.errorMessage = msg.substitute($extend({
				name: this.name,
				size: Swiff.Uploader.formatUnit(this.size, 'b')
			}, this.response));
			var args = [this, this.errorMessage, this.response];
			
			this.fireEvent('error', args).base.fireEvent('fileError', args);
		} else {
			this.base.fireEvent('fileSuccess', [this, this.response.text || '']);
		}
	},

	onError: function() {
		this.element.addClass('file-failed');
		var error = MooTools.lang.get('FancyUpload', 'fileError').substitute(this);
		this.info.set('html', '<strong>' + error + ':</strong> ' + this.errorMessage);
	},

	onRemove: function() {
		this.element.getElements('a').setStyle('visibility', 'hidden');
		this.element.fade('out').retrieve('tween').chain(Element.destroy.bind(Element, this.element));
	}
	
});


/**
 * FancyUpload.Attach - Flash meets Ajax for powerful and elegant uploads.
 *
 * @version     3.0 rc1
 *
 * @license     MIT License
 *
 * @author      Harald Kirschner <mail [at] digitarald [dot] de>
 * @copyright   Authors
 */

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

FancyUpload3.Attach = new Class({

    Extends: Swiff.Uploader,
    
    options: {
        queued: false,
        instantStart: true
    },

    initialize: function(list, selects, options) {
        this.list = $(list);
        this.selects = $(selects) ? $$($(selects)) : $$(selects);
                
        options.target = this.selects[0];
        options.fileClass = options.fileClass || FancyUpload3.Attach.File;
        
        this.parent(options);

        /**
         * Button state
         */
        var self = this;
        
        this.selects.addEvents({
            click: function() {
                return false;
            },
            mouseenter: function() {
                this.addClass('hover');
                self.reposition();
            },
            mouseleave: function() {
                this.removeClass('hover');
                this.blur();
            },
            mousedown: function() {
                this.focus();
            }
        });
        
        if (this.selects.length == 2) {
            this.selects[1].setStyle('display', 'none');
            this.addEvents({
                'selectSuccess': this.onSelectSuccess,
                'fileRemove': this.onFileRemove
            });
        }
    },
    
    onSelectSuccess: function() {
        if (this.fileList.length > 0) {
            this.selects[0].setStyle('display', 'none');
            this.selects[1].setStyle('display', 'inline');
            this.target = this.selects[1];
            this.reposition();
        }
    },
    
    onFileRemove: function() {
        if (this.fileList.length == 0) {
            this.selects[0].setStyle('display', 'inline');
            this.selects[1].setStyle('display', 'none');
            this.target = this.selects[0];
            this.reposition();
        }
    },
    
    start: function() {
        if (Browser.Platform.linux && window.confirm(MooTools.lang.get('FancyUpload', 'linuxWarning'))) return this;
        return this.parent();
    }
    
});

FancyUpload3.Attach.File = new Class({

    Extends: Swiff.Uploader.File,

    render: function() {
        
        if (this.invalid) {
            if (this.validationError) {
                var msg = MooTools.lang.get('FancyUpload', 'validationErrors')[this.validationError] || this.validationError;
                this.validationErrorMessage = msg.substitute({
                    name: this.name,
                    size: Swiff.Uploader.formatUnit(this.size, 'b'),
                    fileSizeMin: Swiff.Uploader.formatUnit(this.base.options.fileSizeMin || 0, 'b'),
                    fileSizeMax: Swiff.Uploader.formatUnit(this.base.options.fileSizeMax || 0, 'b'),
                    fileListMax: this.base.options.fileListMax || 0,
                    fileListSizeMax: Swiff.Uploader.formatUnit(this.base.options.fileListSizeMax || 0, 'b')
                });
            }
            this.remove();
            return;
        }
        
        this.addEvents({
            'open': this.onOpen,
            'remove': this.onRemove,
            'requeue': this.onRequeue,
            'progress': this.onProgress,
            'stop': this.onStop,
            'complete': this.onComplete,
            'error': this.onError
        });
        
        this.ui = {};
        
        this.ui.element = new Element('li', {'class': 'file', id: 'file-' + this.id});
        this.ui.title = new Element('span', {'class': 'file-title', text: this.name});
        this.ui.size = new Element('span', {'class': 'file-size', text: Swiff.Uploader.formatUnit(this.size, 'b')});
        
        this.ui.cancel = new Element('a', {'class': 'file-cancel', text: 'Cancel', href: '#'});
        this.ui.cancel.addEvent('click', function() {
            this.remove();
            return false;
        }.bind(this));
        
        this.ui.element.adopt(
            this.ui.title,
            this.ui.size,
            this.ui.cancel
        ).inject(this.base.list).highlight();
        
        var progress = new Element('img', {'class': 'file-progress', src: '/obray/config/images/progress_bar.gif'}).inject(this.ui.size, 'after');
        this.ui.progress = new Fx.ProgressBar(progress, {
            fit: true
        }).set(0);
                    
        this.base.reposition();

        return this.parent();
    },

    onOpen: function() {
        this.ui.element.addClass('file-uploading');
        if (this.ui.progress) this.ui.progress.set(0);
    },

    onRemove: function() {
        this.ui = this.ui.element.destroy();
    },

    onProgress: function() {
        if (this.ui.progress) this.ui.progress.start(this.progress.percentLoaded);
    },

    onStop: function() {
        this.remove();
    },
    
    onComplete: function() {
        this.ui.element.removeClass('file-uploading');

        if (this.response.error) {
            var msg = MooTools.lang.get('FancyUpload', 'errors')[this.response.error] || '{error} #{code}';
            this.errorMessage = msg.substitute($extend({name: this.name}, this.response));
            
            this.base.fireEvent('fileError', [this, this.response, this.errorMessage]);
            this.fireEvent('error', [this, this.response, this.errorMessage]);
            return;
        }
        
        if (this.ui.progress) this.ui.progress = this.ui.progress.cancel().element.destroy();
        this.ui.cancel = this.ui.cancel.destroy();
        
        var response = this.response.text || '';
        this.base.fireEvent('fileSuccess', [this, response]);
    },

    onError: function() {
        this.ui.element.addClass('file-failed');        
    }

});

//Avoiding MooTools.lang dependency
(function() {
    
    var phrases = {
        'fileName': '{name}',
        'cancel': 'Cancel',
        'cancelTitle': 'Click to cancel and remove this entry.',
        'validationErrors': {
            'duplicate': 'File <em>{name}</em> is already added, duplicates are not allowed.',
            'sizeLimitMin': 'File <em>{name}</em> (<em>{size}</em>) is too small, the minimal file size is {fileSizeMin}.',
            'sizeLimitMax': 'File <em>{name}</em> (<em>{size}</em>) is too big, the maximal file size is <em>{fileSizeMax}</em>.',
            'fileListMax': 'File <em>{name}</em> could not be added, amount of <em>{fileListMax} files</em> exceeded.',
            'fileListSizeMax': 'File <em>{name}</em> (<em>{size}</em>) is too big, overall filesize of <em>{fileListSizeMax}</em> exceeded.'
        },
        'errors': {
            'httpStatus': 'Server returned HTTP-Status #{code}',
            'securityError': 'Security error occured ({text})',
            'ioError': 'Error caused a send or load operation to fail ({text})'
        },
        'linuxWarning': 'Warning: Due to a misbehaviour of Adobe Flash Player on Linux,\nthe browser will probably freeze during the upload process.\nDo you want to start the upload anyway?'
    };
    
    if (MooTools.lang) {
        MooTools.lang.set('en-US', 'FancyUpload', phrases);
    } else {
        MooTools.lang = {
            get: function(from, key) {
                return phrases[key];
            }
        };
    }
    
})();


/**
 * Fx.ProgressBar
 *
 * @version		1.1
 *
 * @license		MIT License
 *
 * @author		Harald Kirschner <mail [at] digitarald [dot] de>
 * @copyright	Authors
 */

Fx.ProgressBar = new Class({

	Extends: Fx,

	options: {
		text: null,
		url: null,
		transition: Fx.Transitions.Circ.easeOut,
		fit: true,
		link: 'cancel'
	},

	initialize: function(element, options) {
		this.element = $(element);
		this.parent(options);
				
		var url = this.options.url;
		if (url) {
			this.element.setStyles({
				'background-image': 'url(' + url + ')',
				'background-repeat': 'no-repeat'
			});
		}
		
		if (this.options.fit) {
			url = url || this.element.getStyle('background-image').replace(/^url\(["']?|["']?\)$/g, '');
			if (url) {
				var fill = new Image();
				fill.onload = function() {
					this.fill = fill.width;
					fill = fill.onload = null;
					this.set(this.now || 0);
				}.bind(this);
				fill.src = url;
				if (!this.fill && fill.width) fill.onload();
			}
		} else {
			this.set(0);
		}
	},

	start: function(to, total) {
		return this.parent(this.now, (arguments.length == 1) ? to.limit(0, 100) : to / total * 100);
	},

	set: function(to) {
		this.now = to;
		var css = (this.fill)
			? (((this.fill / -2) + (to / 100) * (this.element.width || 1) || 0).round() + 'px')
			: ((100 - to) + '%');
		
		this.element.setStyle('backgroundPosition', css + ' 0px').title = Math.round(to) + '%';
		
		var text = $(this.options.text);
		if (text) text.set('text', Math.round(to) + '%');
		
		return this;
	}

});


/*******************************************
	Oform Classes
	Global Widget
*******************************************/
OFormSettings = new Class({
	Implements: Options,
	
	options:{
		'content_part_id':0,
		'oform_highlight_color':'#ffffff',
    	'oform_background_color':'#cccccc',
    	'oform_float_labels_and_fields':true,
    	'oform_show_summary':false,
		'oform_container_class':'oform-container',
		'oform_class':'',
		'oform_label_display':'outside',
		'oform_oncomplete_sbox_show_close_button':false,
		'oform_top_content_area':false
	},
	
	initialize: function(options){
		this.setOptions(options);
		
		// setup box
		this.box = new sbox();
		
		// setup containers
		this.form_container = new Element('div',{'class':'oshop-settings-form-container'});
		this.form_container.setStyles({'padding':10});
		this.form_container.inject(this.box.content);
		this.fields_container = new Element('div',{'class':'oshop-settings-fields-container'}).inject(this.form_container);
		
		this.br = new Element('br',{'class':'clear'});
		//create form
		this.form = new OForm({'button':new Element('input',{'type':'button'}),'btn-label':'&nbsp;','label-width':200,'orientation':'vertical','url':'/index.cfm?action=osettings.UpdateOSettings&fusebox.password=thinkbig&fusebox.load=true&fusebox.%20parse=true&fusebox.execute=true&clear','onComplete':function(){
			window.location.reload(true);
		}.bind(this)});
		this.form.inject(this.box.content);
		
		this.oform_highlight_color = new OFText({'name':'oform_highlight_color','label':'Highlight Color','value':this.options.oform_highlight_color});
		this.form.addElement(this.oform_highlight_color);
		this.oform_highlight_color.inject(this.fields_container);
		
		this.oform_background_color = new OFText({'name':'oform_background_color','label':'Background Color','value':this.options.oform_background_color});
		this.form.addElement(this.oform_background_color);
		this.oform_background_color.inject(this.fields_container);
		
		this.oform_float_labels_and_fields = new OFCheck({'name':'oform_float_labels_and_fields','label':'Put fields and labels on the same line','value':this.options.oform_float_labels_and_fields});
		this.form.addElement(this.oform_float_labels_and_fields);
		this.oform_float_labels_and_fields.inject(this.fields_container);
		
		this.oform_show_summary = new OFCheck({'name':'oform_show_summary_'+this.options.content_part_id,'label':'Show Form Summary','checked':this.options.oform_show_summary});
		this.form.addElement(this.oform_show_summary);
		this.oform_show_summary.inject(this.fields_container);
		
		this.oform_class = new OFText({'name':'oform_container_class_'+this.options.content_part_id,'label':'Form Container Class','value':this.options.oform_container_class});
		this.form.addElement(this.oform_class);
		this.oform_class.inject(this.fields_container);
		
		this.oform_class = new OFText({'name':'oform_class_'+this.options.content_part_id,'label':'Class for Form Specific sBox','value':this.options.oform_class});
		this.form.addElement(this.oform_class);
		this.oform_class.inject(this.fields_container);
		
		this.oform_label_display = new OFSelect({'name':'oform_label_display_'+this.options.content_part_id,'label':'Label Position','labels':['inside','outside'],'values':['inside','outside'],'value':this.options.oform_label_display});
		this.form.addElement(this.oform_label_display);
		this.oform_label_display.inject(this.fields_container);
		
		this.oform_oncomplete_sbox_close_button = new OFCheck({'name':'oform_oncomplete_sbox_show_close_button_'+this.options.content_part_id,'label':'Check to Show Close Button for onComplete Alert Box','checked':this.options.oform_oncomplete_sbox_show_close_button});
		this.form.addElement(this.oform_oncomplete_sbox_close_button);
		this.oform_oncomplete_sbox_close_button.inject(this.fields_container);
		
		this.oform_top_content_area = new OFCheck({'name':'oform_top_content_area_'+this.options.content_part_id,'label':'Content Area ABOVE Form','checked':this.options.oform_top_content_area});
		this.form.addElement(this.oform_top_content_area);
		this.oform_top_content_area.inject(this.fields_container);
	},
		
	open: function(){
		this.box.open();
	}
});



/*******************************************
	Ologin Classes
	Global Widget
*******************************************/
OLoginSettings = new Class({
	Implements: Options,
	
	options:{
		'content_part_id':0,
		'page_id':0,
		'ologin_create_user_enabled':true,
		'ologin_create_user_url':'/login/',
		'ologin_redirect_url':'/account/',
		'ologin_login_title':'Existing User',
		'ologin_label_display':'outside',
		'ologin_username_label':'Username',
		'ologin_password_label':'Password',
		'ologin_forgot_password_input_label':'Enter Your Email Address'
	},
	
	initialize: function(options){
		this.setOptions(options);
		
		// setup box
		this.box = new sbox({'width':600,'height':500,'sbox_class':'obray-admin-container'});
		
		// setup containers
		this.form_container = new Element('div',{'class':'ologin-settings-form-container'});
		this.form_container.setStyles({'padding':10,'width':580});
		
		// main form heading
		this.header = new Element('div',{'class':'settings-header'});
		this.header.setStyles({'font-family':'Helvetica,Arial','font-size':16,'color':'#858585','text-align':'left','margin-bottom':10});
		this.header.set('html','OLogin Widget Settings');
		this.header.inject(this.form_container);
		
		//this.form_container.inject(this.box.content);
		this.fields_container = new Element('div',{'class':'ologin-settings-fields-container'});
		
		this.br = new Element('div',{'class':'clear'});
		
		//create form
		this.form = new OForm({'button':new Element('input',{'type':'button'}),'label-width':225,'btn-label':'&nbsp;','orientation':'vertical','url':'/index.cfm?action=osettings.UpdateOSettings&fusebox.password=thinkbig&fusebox.load=true&fusebox.%20parse=true&fusebox.execute=true&clear','onComplete':function(){
			window.location.reload(true);
		}.bind(this)});
		this.form.inject(this.box.content);
		
		this.create_user_url = new OFText({'label':'Login Form Title','name':'ologin_login_title_'+this.options.content_part_id,'value':this.options.ologin_login_title});
		this.form.addElement(this.create_user_url);
		this.create_user_url.inject(this.fields_container);
		this.br.clone().inject(this.fields_container);
		
		this.label_display_select = new OFSelect({
			'name':'ologin_label_display_'+this.options.content_part_id,
			'padding':3,
			'margin':4,
			'background-color':'#f00000',
			'border':'1px solid #dedede',
			'float':'left',
			'width':70,
			'label':'Label Position',
			'value':this.options.ologin_label_display
		});
		this.label_display_select.addOption('Inside','inside');
		this.label_display_select.addOption('Outside','outside');
		this.form.addElement(this.label_display_select);
		this.label_display_select.inject(this.fields_container);
		this.br.clone().inject(this.fields_container);
		
		this.create_user_enabled = new OFCheck({'label':'Enable Create User Button','name':'ologin_create_user_enabled_'+this.options.content_part_id,'checked':this.options.ologin_create_user_enabled});
		this.form.addElement(this.create_user_enabled);
		this.create_user_enabled.inject(this.fields_container);
		this.br.inject(this.fields_container);
		
		this.create_user_url = new OFText({'label':'Create User Page','name':'ologin_create_user_url_'+this.options.content_part_id,'value':this.options.ologin_create_user_url});
		this.form.addElement(this.create_user_url);
		this.create_user_url.inject(this.fields_container);
		this.br.clone().inject(this.fields_container);
		
		this.redirect_url = new OFText({'label':'Redirect URL','name':'ologin_redirect_url_'+this.options.content_part_id,'value':this.options.ologin_redirect_url});
		this.form.addElement(this.redirect_url);
		this.redirect_url.inject(this.fields_container);
		this.br.clone().inject(this.fields_container);
		
		this.username_label = new OFText({'label':'Label For Username Field','name':'ologin_username_label_'+this.options.content_part_id,'value':this.options.ologin_username_label});
		this.form.addElement(this.username_label);
		this.username_label.inject(this.fields_container);
		this.br.clone().inject(this.fields_container);
		
		this.password_label = new OFText({'label':'Label For Password Field','name':'ologin_password_label_'+this.options.content_part_id,'value':this.options.ologin_password_label});
		this.form.addElement(this.password_label);
		this.password_label.inject(this.fields_container);
		this.br.clone().inject(this.fields_container);
		
		this.forgot_password_input_label = new OFText({'label':'Label For Forgot Password Field','name':'ologin_forgot_password_input_label_'+this.options.content_part_id,'value':this.options.ologin_forgot_password_input_label});
		this.form.addElement(this.forgot_password_input_label);
		this.forgot_password_input_label.inject(this.fields_container);
		this.br.clone().inject(this.fields_container);
		
		//inject form into sbox
		this.fields_container.inject(this.form_container);
		this.form.inject(this.form_container, false);
		this.form_container.inject(this.box.content);
		
	},
		
	open: function(){
		this.box.open();
	}
});

/******************************************************
 	OLOGIN
******************************************************/

OLogin = new Class({
	
	Implements: Options,
	
	options: {
		
		'button':new Element('input',{'type':'button','value':'Login','class':'ologin-login-button'}),
		'btn-value':'Login',
		'btn-label-text-align':'left',
		'redirect':'',
		'username_label':'Username',
		'password_label':'Password',
		'forgot_password_input_label':'Enter Your Email Address',
		'input_class':'ogrid-1-padding',
		'label_class':'ogrid-1'
	},
	
	initialize: function(options){
		//set data members
		this.setOptions(options);
		
		/********************************************
			Login Form
		*******************************************/
		
		this.login_form_wrapper = new Element('div',{'class':'login-form-wrapper oform-container'});
		this.login_form_wrapper.setStyles({'position':'relative'});
		this.login_form = new OForm({'id':'login-form','class':'ologin-form','button':this.options['button'],'btn-value':this.options['btn-value'],'url':'/cmd/ousers/authenticate/','method':'post','onComplete':function(json){
				if(this.options['redirect'] == "") { window.location = json.response.location; } else {	window.location = this.options['redirect'];	}
			}.bind(this),
			'onError': function(json){}
		});
		
		this.user_name = new OFText({'input_id':'user-email','name':'ouser_name','input_wrapper_class':'ogrid-input-1','type':'text','label':this.options.username_label,'input_class':this.options.input_class,'label_class':this.options.label_class});
		this.login_form.addElement(this.user_name);
		
		this.password = new OFText({'input_id':'user-password','name':'ouser_password','input_wrapper_class':'ogrid-input-1','type':'password','label':this.options.password_label,'input_class':this.options.input_class,'label_class':this.options.label_class});
		this.login_form.addElement(this.password);
		
		this.forgot_button = new Element('input',{'type':'button','value':'Forgot Password?','class':'ologin-forgot-password'});
		
		/********************************************
			Forgot Password Form
		********************************************/
		
		this.forgot_form_wrapper = new Element('div',{'class':'forgot-form-wrapper oform-container Ohidden'});
		this.reset = new OForm({'url':'/cmd/ousers/resetPassword/','button':new Element('input',{'type':'button','value':'Reset'})});
		
		this.reset_email = new OFText({'name':'ouser_email','label':'Enter Email Address','input_class':this.options.input_class,'label_class':this.options.label_class});
		this.reset.addElement(this.reset_email);
		
		this.forgot_back_btn = new Element('input',{'type':'button','value':'Back to Login','class':'ologin-back-btn'});
		
		/********************************************
			Events
		********************************************/
		
		this.forgot_button.addEvent('click',function(){	
			this.forgot_form_wrapper.removeClass('Ohidden'); 
			this.login_form_wrapper.addClass('Ohidden');
		}.bind(this));
		
		this.forgot_back_btn.addEvent('click',function(){	
			this.forgot_form_wrapper.addClass('Ohidden'); 
			this.login_form_wrapper.removeClass('Ohidden');
		}.bind(this));
		
	},
	
	setStyles: function(){
		this.container.setStyles(style_options)
	},
	
	inject: function(el,position){
		
		this.login_form_wrapper.inject(el,position);
		this.login_form.inject(this.login_form_wrapper);
		this.forgot_button.inject(this.login_form_wrapper);
		
		this.forgot_form_wrapper.inject(el,position);
		this.reset.inject(this.forgot_form_wrapper);
		this.forgot_back_btn.inject(this.forgot_form_wrapper);
		
    }
});





/*******************************************	OContent Accordion Class	Global Widget*******************************************//****************************	Admin Class	Edit / Delete****************************/OAccordionItem = new Class({    Implements: Options,        options:{    	'content_part_id':0,    	'page_id':0,        'admin_div': new Element('div'),        'oaccordion_title': '',		'oaccordion_id':0,		'item_do':'editItem'    },        initialize: function(options){        this.setOptions(options);				this.oaccordion_item = this.options.admin_div;        this.oaccordion_item.fx = new Fx.Morph(this.oaccordion_item,{'duration':600,'transition':Fx.Transitions.Quint.easeOut,'onComplete':function(){        	this.oaccordion_item.destroy();        }.bind(this)});        this.oaccordion_item_bar = new OWidgetMiniAdmin({'open-element':this.oaccordion_item,'opacity':.85,'title-label':this.options['oaccordion_title']});				// EDIT ITEM //		this.oaccordion_item_bar.addButton('edit-btn','Edit',function(){						this.edit_accordion_item = new OAccordionItems({				'content_part_id':this.options.content_part_id,		        'page_id':this.options.page_id,		        'oaccordion_id':this.options.oaccordion_id,		        'oaccordion_title':this.options.oaccordion_title,		        'item_do':'editItem'			});			this.edit_accordion_item.open();					}.bind(this));		        // DELETE ITEM //        this.oaccordion_item_bar.addButton('delete-btn','Delete Item',function(){			var confirm_bx = new sboxConfirm({'confirm-message':'Are you sure you want to delete this item? This action is permanent.','onConfirm':function(){        		this.delete_post = new Request({'url':'/cmd/owidgets/getHTML/Oaccordion/?content_part_id='+this.options.content_part_id+'&page_id='+this.options.page_id+'&do=deleteItem&oaccordion_id='+this.options.oaccordion_id,'onComplete':function(){        			this.oaccordion_item.fx.start({'opacity':0});					//window.location.reload();        		}.bind(this)}).send();        	}.bind(this)});        	confirm_bx.open();        }.bind(this));    }});/****************************	Create Item Form****************************/OAccordionItems = new Class({    Implements: Options,        options:{        'content_part_id':0,        'page_id':0,        'oaccordion_id':0,        'oaccordion_title':'',        'item_do':'addItem'    },        initialize: function(options){        this.setOptions(options);                this.box = new sbox({'width':500,'height':300,'sbox_class':'obray-admin-container'});                if(this.options.item_do == 'addItem'){        	this.button_value = 'Create New Accordion Item';        } else {        	this.button_value = 'Edit Accordion Item';        }                this.header = new BoxHeader({'header':'Add / Edit An Accordion Item Title'});		this.header.inject(this.box.content);				this.form_container = new Element('div',{'class':'ogrid-1-padding ogrid-self-clear'});		this.form_container.inject(this.box.content);		        this.form = new OForm({        	'button':new Element('input',{'type':'button','value':this.button_value}),        	'url':'/cmd/owidgets/getHTML/Oaccordion/?content_part_id='+this.options.content_part_id+'&page_id='+this.options.page_id+'&do='+this.options.item_do+'&oaccordion_id='+this.options.oaccordion_id,        	'onComplete':function(){        		var reload_request = new Request({'url':'/cmd/owidgets/getHTML/Oaccordion/?content_part_id='+this.options.content_part_id+'&page_id='+this.options.page_id,'onComplete':function(){					window.location.reload();				}.bind(this)}).send();		}.bind(this)});		        this.oaccordion_title = new OFText({'label':'Accordion Item Title','name':'oaccordion_title', 'value':this.options.oaccordion_title,'input_class':'ogrid-1-padding','label_class':'ogrid-1'});		this.form.addElement(this.oaccordion_title);		this.form.inject(this.form_container);    },        open: function(){    	this.box.open();    }});/*******************************************
	Onewsletter Javascript
*******************************************/
addOuploaderMedia = new Class({
	Implements: Options,
	
	options:{
		'content_part_id':0,
		'page_id':0
	}, 
	
	initialize: function(options){
		this.setOptions(options);
		
		this.box = new sbox({'sbox_class':'obray-admin-container','height':275});

		this.header = new BoxHeader({'header':'Upload New Media'});

		this.header.inject(this.box.content);

		this.form = new OForm({'url':'/cmd/owidgets/Ouploader/add/','onComplete':function(response){		
			window.location.reload(true);
		}.bind(this)});
		
		// upload button
		this.file = new OFFile({'upload_url':'/cmd/opieces/omedia/omedia/upload/?requesttimeout=10000','label':'Upload File','name':'upload_file','file_types':{'Files (*.pdf, *.doc, *.docx, *.xls, *.xlsx, *.zip)':'*.pdf; *.doc; *.docx; *.xls; *.xlsx; *.zip'},'onUploadSuccess':$empty});		
		this.form.addElement(this.file);
		
		// link title
		this.title = new OFText({'label':'Enter File Title','name':'omedia_user_title'});
		this.form.addElement(this.title);
		
		// hidden field for content part id
		this.hidden_content_part_id = new OFHidden({'name':'content_part_id','value':this.options.content_part_id})
		this.form.addElement(this.hidden_content_part_id);
		
		this.form.inject(this.header.content);	
		
		this.box.open();
	}
});

updateOuploaderMedia = new Class({
	Implements: Options,
	
	options:{
		'omedia_user_title':'',
		'omedia_id':0
	}, 
	
	initialize: function(options){
		this.setOptions(options);
		
		this.box = new sbox({'sbox_class':'obray-admin-container','height':275});

		this.header = new BoxHeader({'header':'Update Media Title'});

		this.header.inject(this.box.content);

		this.form = new OForm({'url':'/cmd/owidgets/Ouploader/update/','onComplete':function(response){		
			window.location.reload(true);
		}.bind(this)});
		
		// link title
		this.title = new OFText({'label':'Enter File Title','name':'omedia_user_title','value':this.options.omedia_user_title});
		this.form.addElement(this.title);
		
		// hidden field for omedia id
		this.hidden_omedia_id = new OFHidden({'name':'omedia_id','value':this.options.omedia_id})
		this.form.addElement(this.hidden_omedia_id);

		this.form.inject(this.header.content);	
		
		this.box.open();
	}
});





/**********************************    Ocontact Widget Javascript**********************************//**********************************    default-widget Javascript**********************************/ODefaultWidgetSettings = new Class({	Implements: Options,		options:{		'content_part_id':0,		'page_id':0	},		initialize: function(options){				this.setOptions(options);		this.box = new sbox({'width':600,'height':500});				this.form_container = new Element('div',{'class':'settings-container'});		this.form_container.setStyles({'padding':10,'width':580});				this.br = new Element('div',{'class':'clear'});		this.spacer = new Element('div',{'class':'osettings-form-spacer'});				// main form heading		this.header = new Element('div',{'class':'settings-header'});		this.header.setStyles({'font-family':'Helvetica,Arial','font-size':16,'color':'#858585','text-align':'left','margin-bottom':10});		this.header.set('html','Settings');		this.header.inject(this.form_container);				//create form		this.form = new OForm({'background-color':'#1A1A1A','button':new Element('input',{'type':'button'}),'btn-label':'&nbsp;','label-width':225,'orientation':'vertical','url':'?action=osettings.UpdateOSettings&fusebox.password=thinkbig&fusebox.load=true&fusebox.%20parse=true&fusebox.execute=true&clear','onComplete':function(){			window.location.reload(true);		}.bind(this)});				this.default_input = new OFText({'label':'Default Widget Input Field','name':'default_widget_'+this.options.content_part_id,'value':''});		this.form.addElement(this.default_input);		this.default_input.inject(this.form_container);				// inject form		this.form.inject(this.form_container, false);		this.form_container.inject(this.box.content);	},		open: function(){		this.box.open();	}	});/*************************************************	Calendar JS	/components/Acalendar/js/default.js*************************************************/APerson = new Class({	Implements: Options,		options:{		'edit':false,		'button_text':'',		'ouser_campus':'',		'ouser_first_name':'',		'ouser_last_name':'',		'ouser_position':'',		'ouser_email':'',		'ouser_web':'',		'ouser_phone':'',		'ouser_schedule':'',		'ouser_meta_data':'',		'ouser_id':0	}, 		initialize: function(options){		this.setOptions(options);				this.box = new sbox({'sbox_class':'obray-admin-container','destroy':true});				if(this.options.edit){			this.header = new BoxHeader({'header':'Edit Event'});			this.options.button_text = 'Update Event';		} else {			this.header = new BoxHeader({'header':'Create Event'});			this.options.button_text = 'Add Event';		}				this.header.inject(this.box.content);				if(this.options.edit){ this.url = '/cmd/Awidgets/Acontact_staff/update/'; } else { this.url = '/cmd/Awidgets/Acontact_staff/add/'; }				this.form = new OForm({'url':this.url,'button':new Element('input',{'type':'button','value':this.options.button_text}),'onComplete':function(){			window.location.reload(true);		}.bind(this)});				this.campus = new OFHidden({'name':'ouser_campus','value':this.options.ouser_campus});		this.form.addElement(this.campus);				this.ouser_id = new OFHidden({'name':'ouser_id','value':this.options.ouser_id});		this.form.addElement(this.ouser_id);				this.first_name = new OFText({'name':'ouser_first_name','value':this.options.ouser_first_name,'label':'First Name'});		this.form.addElement(this.first_name);				this.last_name = new OFText({'name':'ouser_last_name','value':this.options.ouser_last_name,'label':'Last Name'});		this.form.addElement(this.last_name);				this.position = new OFText({'name':'ouser_position','value':this.options.ouser_position,'label':'Position'});		this.form.addElement(this.position);				this.email = new OFText({'name':'ouser_email','value':this.options.ouser_email,'label':'Email'});		this.form.addElement(this.email);				this.web = new OFText({'name':'ouser_web','value':this.options.ouser_web,'label':'Web'});		this.form.addElement(this.web);				this.phone = new OFText({'name':'ouser_phone','value':this.options.ouser_phone,'label':'Phone Extension'});		this.form.addElement(this.phone);				this.schedule = new OFText({'name':'ouser_schedule','value':this.options.ouser_schedule,'label':'Schedule'});		this.form.addElement(this.schedule);				this.form.inject(this.header.content);						this.box.open();		}	});/*************************************************	Edison Express JS	/components/Aedison-express/js/default.js*************************************************/AEdisonExpressUpload = new Class({	Implements: Options,		options:{		'edit':false,		'content_part_id':0	}, 		initialize: function(options){		this.setOptions(options);				this.box = new sbox({'sbox_class':'obray-admin-container','destroy':true});				if(this.options.edit){			this.header = new BoxHeader({'header':'Edit Event'});			this.options.button_text = 'Update Event';		} else {			this.header = new BoxHeader({'header':'Submit File'});			this.options.button_text = 'Submit File';		}				this.header.inject(this.box.content);				this.url = '/cmd/awidgets/Aedison-express-admin/add/';				this.form = new OForm({'url':this.url,'button':new Element('input',{'type':'button','value':this.options.button_text}),'onComplete':function(){			window.location.reload(true);		}.bind(this)});				// content part id		this.hidden_content_part_id = new OFHidden({'name':'content_part_id','value':this.options.content_part_id});		this.form.addElement(this.hidden_content_part_id);				// upload button		this.file = new OFFile({'upload_url':'/cmd/opieces/omedia/omedia/upload/?requesttimeout=10000','label':'Upload File','name':'upload_file','file_types':{'Files (*.pdf, *.doc, *.docx, *.xls, *.xlsx, *.zip)':'*.pdf; *.doc; *.docx; *.xls; *.xlsx; *.zip'},'onUploadSuccess':$empty});				this.form.addElement(this.file);				// link title		this.title = new OFText({'label':'Enter File Title','name':'omedia_user_title'});		this.form.addElement(this.title);				// doc published date		this.doc_date = new OFDate({'name':'omedia_datetime','label':'Document\'s Published Date'});		this.form.addElement(this.doc_date);				this.form.inject(this.header.content);						this.box.open();		}	});AEdisonExpressDelete = new Class({	Implements: Options,		options:{		'edit':false,		'content_part_id':0,		'file_ids':[],		'file_names':[]	}, 		initialize: function(options){		this.setOptions(options);				this.box = new sbox({'sbox_class':'obray-admin-container','destroy':true});				if(this.options.edit){			this.header = new BoxHeader({'header':'Edit Event'});			this.options.button_text = 'Update Event';		} else {			this.header = new BoxHeader({'header':'Submit File'});			this.options.button_text = 'Delete File';		}				this.header.inject(this.box.content);				this.url = '/cmd/owidgets/Ouploader/delete/';				this.form = new OForm({'url':this.url,'button':new Element('input',{'type':'button','value':this.options.button_text}),'onComplete':function(){			window.location.reload(true);		}.bind(this)});				// content part id		this.hidden_content_part_id = new OFHidden({'name':'content_part_id','value':this.options.content_part_id});		this.form.addElement(this.hidden_content_part_id);						// choose file to send		this.files = new OFSelect({'label':'Choose A File To Delete','name':'omedia_id'});		this.form.addElement(this.files);				if(this.options.file_ids.length > 0){			for(var i=0;i<this.options['file_ids'].length;++i){				this.files.addOption(this.options.file_names[i],this.options.file_ids[i]);			}		}				this.form.inject(this.header.content);						this.box.open();		}	});AEdisonExpressSend = new Class({	Implements: Options,		options:{		'edit':false,		'content_part_id':0,		'file_ids':[],		'file_names':[],		'list':[]	}, 		initialize: function(options){		this.setOptions(options);				this.box = new sbox({'sbox_class':'obray-admin-container','destroy':true});				if(this.options.edit){			this.header = new BoxHeader({'header':'Edit Event'});			this.options.button_text = 'Update Event';		} else {			this.header = new BoxHeader({'header':'Send Email'});			this.options.button_text = 'Send Email';		}				this.header.inject(this.box.content);				this.url = '/cmd/Awidgets/Aedison-express-admin/send/';				this.form = new OForm({'url':this.url,'button':new Element('input',{'type':'button','value':this.options.button_text}),'onComplete':function(){			//window.location.reload(true);		}.bind(this)});				// content part id		this.hidden_content_part_id = new OFHidden({'name':'content_part_id','value':this.options.content_part_id});		this.form.addElement(this.hidden_content_part_id);						// choose file to send		this.files = new OFSelect({'label':'Choose A File To Send','name':'file_id'});		this.form.addElement(this.files);				if(this.options.file_ids.length > 0){			for(var i=0;i<this.options['file_ids'].length;++i){				this.files.addOption(this.options.file_names[i],this.options.file_ids[i]);			}		}						// subscriber list		this.list = new OFSelect({'label':'Choose A Subscription List','name':'list'});		this.form.addElement(this.list);				this.list.addOption('North Campus','north');		this.list.addOption('South Campus','south');						// subject		this.subject = new OFText({'label':'Enter Email Subject','name':'subject'});		this.form.addElement(this.subject);						// message		this.message = new OFText({'text-area':true,'label':'Enter Email Message','name':'message'});		this.form.addElement(this.message);				this.form.inject(this.header.content);						this.box.open();		}	});/*************************************************	Edison Express JS	/components/Aedison-express/js/default.js*************************************************/AEdisonExpress = new Class({	Implements: Options,		options:{		'edit':false,		'content_part_id':0,		'campus':''	}, 		initialize: function(options){		this.setOptions(options);				this.box = new sbox({'sbox_class':'obray-admin-container','destroy':true});				if(this.options.edit){			this.header = new BoxHeader({'header':'Edit Event'});			this.options.button_text = 'Update Event';		} else {			this.header = new BoxHeader({'header':'Submit File'});			this.options.button_text = 'Submit File';		}				this.header.inject(this.box.content);				this.url = '/cmd/owidgets/Ouploader/add/';				this.form = new OForm({'url':this.url,'button':new Element('input',{'type':'button','value':this.options.button_text}),'onComplete':function(){			window.location.reload(true);		}.bind(this)});				this.campus = new OFHidden({'name':'campus','value':this.options.campus});		this.form.addElement(this.campus);				this.hidden_content_part_id = new OFHidden({'name':'content_part_id','value':this.options.content_part_id})		this.form.addElement(this.hidden_content_part_id);				// upload button		this.file = new OFFile({'upload_url':'/cmd/opieces/omedia/omedia/upload/?requesttimeout=10000','label':'Upload File','name':'upload_file','file_types':{'Files (*.pdf, *.doc, *.docx, *.xls, *.xlsx, *.zip)':'*.pdf; *.doc; *.docx; *.xls; *.xlsx; *.zip'},'onUploadSuccess':$empty});				this.form.addElement(this.file);				// link title		this.title = new OFText({'label':'Enter File Title','name':'omedia_user_title'});		this.form.addElement(this.title);				this.doc_date = new OFDate({'name':'omedia_uploaded_datetime','label':'Document\'s Published Date'});		this.form.addElement(this.doc_date);				this.form.inject(this.header.content);						this.box.open();		}	});/*************************************************	Calendar JS	/components/Acalendar/js/default.js*************************************************/ACalendar = new Class({	Implements: Options,		options:{		'edit':false,		'button_text':'',		'campus':'',		'calendar_start_datetime':'',		'calendar_end_datetime':'',		'opost_description':'',		'opost_id':0	}, 		initialize: function(options){		this.setOptions(options);				this.box = new sbox({'sbox_class':'obray-admin-container','destroy':true});				if(this.options.edit){			this.header = new BoxHeader({'header':'Edit Event'});			this.options.button_text = 'Update Event';		} else {			this.header = new BoxHeader({'header':'Create Event'});			this.options.button_text = 'Add Event';		}				this.header.inject(this.box.content);				if(this.options.edit){ this.url = '/cmd/Awidgets/Acalendar/update/'; } else { this.url = '/cmd/Awidgets/Acalendar/add/'; }				this.form = new OForm({'url':this.url,'button':new Element('input',{'type':'button','value':this.options.button_text}),'onComplete':function(){			window.location.reload(true);		}.bind(this)});				this.campus = new OFHidden({'name':'campus','value':this.options.campus});		this.form.addElement(this.campus);				this.opost_id = new OFHidden({'name':'opost_id','value':this.options.opost_id});		this.form.addElement(this.opost_id);				this.datetime_start = new OFDate({'name':'calendar_start_datetime','value':this.options.calendar_start_datetime,'label':'Event START Date'});		this.form.addElement(this.datetime_start);				this.datetime_end = new OFDate({'name':'calendar_end_datetime','value':this.options.calendar_end_datetime,'label':'Event END Date'});		this.form.addElement(this.datetime_end);				this.method = new OFText({'text-area':true,'name':'opost_description','value':this.options.opost_description,'label':'Event Description'});		this.form.addElement(this.method);				this.form.inject(this.header.content);						this.box.open();		}	});/*******************************************
	Onewsletter Javascript
*******************************************/
ANewsletter = new Class({
	
	Implements: Options,
	
	options: {
		'onewsletter_button_value':'Sign Up',
		'page_id':0,
		'content_part_id':0,
		'name_label':'Full Name',
		'email_label':'Email'
	},
	
	initialize: function(options){
		//set data members
		this.setOptions(options);
		
		/********************************************
			Form
		*******************************************/
		
		this.form_container = new Element('div',{'class':'ogrid-1-padding oform-container'});
		this.form = new OForm({'class':'onewsletter-form','button':new Element('input',{'type':'button','value':this.options.onewsletter_button_value,'class':'onewsletter-button'}),'url':'/cmd/Awidgets/Anewsletter/add/','onComplete':function(response){
				// on success
			}.bind(this)
		});
		
		this.full_name = new OFText({'name':'onewsletter_name','type':'text','label':this.options.name_label,'label_class':'ogrid-1','input_class':'ogrid-1-padding'});
		this.form.addElement(this.full_name);
		
		this.email = new OFText({'name':'onewsletter_email','label':this.options.email_label,'label_class':'ogrid-1','input_class':'ogrid-1-padding'});
		this.form.addElement(this.email);
		
		this.north_campus = new OFCheck({'name':'onewsletter_north_campus','label':'North Campus','label_class':'ogrid-1','input_class':'ogrid-1-padding'});
		this.form.addElement(this.north_campus);
		
		this.south_campus = new OFCheck({'name':'onewsletter_south_campus','label':'South Campus','label_class':'ogrid-1','input_class':'ogrid-1-padding'});
		this.form.addElement(this.south_campus);
	},
	
	inject: function(el,position){
		this.form_container.inject(el,position);
		this.form.inject(this.form_container);
    }
});





/*************************************************	Calendar JS	/components/Acalendar/js/default.js*************************************************/ACalendar = new Class({	Implements: Options,		options:{		'edit':false,		'button_text':'',		'campus':'',		'calendar_start_datetime':'',		'calendar_end_datetime':'',		'opost_description':'',		'opost_id':0	}, 		initialize: function(options){		this.setOptions(options);				this.box = new sbox({'sbox_class':'obray-admin-container','destroy':true});				if(this.options.edit){			this.header = new BoxHeader({'header':'Edit Event'});			this.options.button_text = 'Update Event';		} else {			this.header = new BoxHeader({'header':'Create Event'});			this.options.button_text = 'Add Event';		}				this.header.inject(this.box.content);				if(this.options.edit){ this.url = '/cmd/Awidgets/Acalendar/update/'; } else { this.url = '/cmd/Awidgets/Acalendar/add/'; }				this.form = new OForm({'url':this.url,'button':new Element('input',{'type':'button','value':this.options.button_text}),'onComplete':function(){			window.location.reload(true);		}.bind(this)});				this.campus = new OFHidden({'name':'campus','value':this.options.campus});		this.form.addElement(this.campus);				this.opost_id = new OFHidden({'name':'opost_id','value':this.options.opost_id});		this.form.addElement(this.opost_id);				this.datetime_start = new OFDate({'name':'calendar_start_datetime','value':this.options.calendar_start_datetime,'label':'Event START Date'});		this.form.addElement(this.datetime_start);				this.datetime_end = new OFDate({'name':'calendar_end_datetime','value':this.options.calendar_end_datetime,'label':'Event END Date'});		this.form.addElement(this.datetime_end);				this.method = new OFText({'text-area':true,'name':'opost_description','value':this.options.opost_description,'label':'Event Description'});		this.form.addElement(this.method);				this.form.inject(this.header.content);						this.box.open();		}	});

