Ojay.onDOMReady( function() {
    // preload images
    var contact_on = new Image;
    contact_on.src = "/frontend/img/btn_contact_on.jpg";
    var play_on = new Image;
    play_on.src = "/frontend/img/play_on.jpg";

    // mouseover effect
    $( "#contact" ).on( "mouseover", function( element ) {
       element.setAttributes( {"src": "/frontend/img/btn_contact_on.jpg" } );
    });
    $( "#play" ).on( "mouseover", function( element ) {
       element.setAttributes( {"src": "/frontend/img/btn_play_on.jpg" } );
    });
    $( "#contact" ).on( "mouseout", function( element ) {
       element.setAttributes( {"src": "/frontend/img/btn_contact_off.jpg" } );
    });
    $( "#play" ).on( "mouseout", function( element ) {
       element.setAttributes( {"src": "/frontend/img/btn_play_off.jpg" } );
    });

    // attach event handler
    var form = new ContactForm();
    $( "#contact" ).on( "click", function( element, event ) {
        event.stopEvent();
        form.render();

    });

    $( "#play" ).on( "click", function( element, event ) {
        event.stopEvent();
        $( "#video" ).show();
        $( "#video_close" ).show();
        // create div
        var div = Ojay.HTML.p( { id: "moviez" }, function( html ) {
            html.a( {href: "http://www.adobe.com/go/getflashplayer", target: "_blank"}, "Lt. Lou requires you to download Flash Player 9 to see this movie!" )
        });
        $( "#video" ).setContent( Ojay.HTML.div( div ) );

        var flashvars = {
            xml: "<ray><video width='720' controls='bottom' height='388' autostart='true' src='/store/border.flv' showPlayButtonAtStart='false'/></ray>",
            rayflash_root: "/ray/flash"
        };
        var params = {
            menu: "false",
            wmode: "transparent"
        };

        swfobject.embedSWF("/ray/flash/rayflash.swf", "moviez", "720", "388", "9.0.0", null, flashvars, params );
    });

    $( "#video_close" ).on( "click", function( element, event ) {
        event.stopEvent();
        $( "#video" ).hide();
        $( "#video_close" ).hide();
        $( "#moviez" ).remove();
    });
});

var ContactForm = JS.Class({
    _config: {},

    _validations: [],

    isValidating: false,

    hideForm: function() {
        $( "#contactform" ).hide();
    },

    resetForm: function() {

        this.isValidating = false;
        this._validations.forEach( function( validation ) {
            validation.element.siblings( "div.error" ).removeClass( "active" );
        });
        if( this._config.submit ) {
            this._config.submit.removeClass( "close" );
            this._config.submit.removeClass( "disabled" );
            this._config.submit.node.value = "Send";
        }
        if( this._config.success ) {
            this._config.success.removeClass( "active" );
        }
        if( this._config.wait ) {
            this._config.wait.hide();
        }
        if( this._config.cancel ) {
            this._config.cancel.show();
        }

    },

    validate: function( validation ) {
        var value = validation.element.node.value;
        var result = validation.fn( value );
        if( !result ) {
            validation.element.siblings( "div.error" ).addClass( "active" );
        } else {
            validation.element.siblings( "div.error" ).removeClass( "active" );
        }
        return result;
    },

    saveForm: function() {
        var self = this;

        if( this._config.submit.hasClass( "disabled" ) ) {
            return;
        }

        // validate form
        this.resetForm();
        this.isValidating = true;
        var validElements = this._validations.count( this.validate, this );

        if( validElements != this._validations.length ) return;

        var url =  "/contact";
        var params =  {
            id: "new",
            name: encodeURI( this._config.name.node.value ),
            email: this._config.email.node.value,
            comment: encodeURI( this._config.comment.node.value )
        };
        this._config.submit.addClass( "disabled" );
        this._config.cancel.hide();
        this._config.wait.show();
        Ojay.HTTP.POST( url, params, {
            onSuccess: function( r ) { self.onSuccess( r ); },
            onFailure: function( r ) { self.onFailure( r ); }
        });
    },

    /**
     * the success callback function, used to process the server response and
     * call the appropriate method with the results.
     *
     * @param {Object} event
     * @param {Object} response
     * @param {Object} tr
     */
    onSuccess: function( response ) {
        eval( "var action = " + response.responseText );

        if( action.success ) {
            this._config.success.addClass( "active" );
            this._config.submit.removeClass( "disabled" );
            this._config.submit.addClass( "close" );
            this._config.submit.node.value = "Close";
            this._config.wait.hide();
            $().wait( 3 )._( this ).hideForm();
        }
    },

    /**
     * the failure callback function, used to process a failure while
     * sending a request to the serve rapi.
     *
     * @param {Object} event
     * @param {Object} response
     * @param {Object} tr
     */
    onFailure: function( event, response, tr ) {
        this.resetForm( tr );
    },

    /**
     * render the contact form markup into the document.
     *
     * @return void
     */
    render: function() {

        // get references to the actual elements, and attach
        // event handlers
        var elements = "submit cancel wait name email comment success";
        elements.split( " " ).forEach( function( element ) {
            this._config[element] = $( "#" + element );
        }, this );$

        this._validations = [
                             {element: $( "#name" ), fn: this.isNotEmpty },
                             {element: $( "#email" ), fn: this.isValidEmail }
                             ];

        this.resetForm();
        this._config.name.node.value = "";
        this._config.email.node.value = "";
        this._config.comment.node.value = "";

        $( "#contactform" ).show();

        // assign click handlers
        this._config.submit.on( "click", function( element ) {
            if( element.hasClass( "close" ) ) this.hideForm(); else this.saveForm();
        }, this );
        this._config.cancel.on( "click", this.hideForm, this );


        $( "#name" ).node.focus();

    },

    isNotEmpty: function( value ) {
        return value != "";
    },

    isValidEmail: function( value ) {
        return /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/.test( value );
    },

    forEach: function( subject, fn, scope ) {
        scope = scope || subject;
        var args, i;
        for( i in subject ) {
            if( typeof( subject[i] ) != "function" ) {
                args = [ subject[i], i, subject ];
                fn.apply( scope, args );
            }
        }
    }

});

