﻿var mouseTop = 0;


(function($) {
    var imgList = [];
    $.extend({
        preload: function(imgArr, option) {
            var setting = $.extend({
                init: function(loaded, total) { },
                loaded: function(img, loaded, total) { },
                loaded_all: function(loaded, total) { }
            }, option);
            var total = imgArr.length;
            var loaded = 0;

            setting.init(0, total);
            for (var i in imgArr) {
                imgList.push($("<img />")
					.attr("src", imgArr[i])
					.load(function() {
					    loaded++;
					    setting.loaded(this, loaded, total);
					    if (loaded == total) {
					        setting.loaded_all(loaded, total);
					    }
					})
				);
            }

        }
    });
})(jQuery);


/* EVENTS */



(function($) {

    $.Events = {

        INIT_TIMELINE: 'initTimeline',

        ARTICLE_OPEN: 'articleOpen',
        ARTICLE_SCROLL: 'articleScroll',
        ARTICLE_SCROLL_COMPLETE: 'articleScrollComplete',
        ARTICLE_COLLAPSE: 'articleCollapase',
        ARTICLE_ADDRESS: 'articleAddress',

        FILTER: 'filter',

        KEY_UP: 'keyUp',
        KEY_DOWN: 'keyDown',
        KEY_LEFT: 'keyLeft',
        KEY_RIGHT: 'keyRight',

        POINTER_SEEK: 'pointerSeek'


} // Events  

        $.Views = {


} // Views 






    })(jQuery);


    /* ---------------------------------- */

    /* INSTANTIATE */

    (function($) {

        $.fn.Instantiate = function(settings) {

            var config = {};

            if (settings) $.extend(config, settings);

            this.each(function() {

                var $self = $(this),
              $controller = $self.attr('data-controller');

                $self[$controller]();

            });

        }



    })(jQuery);

    /* ---------------------------------- */

    /* Articles */


    (function($) {

        $.Articles = {
            filtered: false,
            filter: '',
            active_id: 0,
            loading: false
        }
        $.fn.Articles = function(settings) {

            var config = {};

            if (settings) $.extend(config, settings);

            this.each(function() {

                var $self = $(this),
            $body = $('body'),
            $articles_scroll = $('#articles-scroll'),
            $articles = $self.find('article'),
            _articles = new Array(),
            $next = $('#arrow-next'),
            $prev = $('#arrow-prev'),
            $fade_next = $('#fade-next'),
            $fade_prev = $('#fade-prev'),
            $indicator = $('#indicator'),
            _active_index = 0,
            _active_id = 0,
            _oldbrowser = $.browser.opera || ($.browser.msie && $.browser.version.indexOf('7.') > -1),
            _devicebrowser = ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))),
            $scroll = ($.browser.mozilla || $.browser.msie) ? $('html') : $body,
            $keyboard = $('<mark/>').attr('id', 'keyboard').appendTo($('#scrolls')),
            $start_article = $self.find('article.autoseek'),
            __START_ID = ($start_article.length > 0) ? $start_article.attr('data-id') : 4;


                $articles.each(function() { _articles.push($(this)) });

                if (_devicebrowser)
                    $indicator.css({ display: 'none' });

                $self
        .Keyboard()
        .bind($.Events.KEY_LEFT, _prev)
        .bind($.Events.KEY_RIGHT, _next);

                $articles.Article();

                $next
        .bind('click', _next)

                $prev
        .bind('click', _prev)

                $body
          .bind($.Events.INIT_TIMELINE,
            function() {

                var init_article = __START_ID;

                if (location.hash) {

                    var hashno = location.hash.replace('#/', ''),
                    found = false;

                    $articles.each(function() {
                        if ($(this).attr('data-number') == hashno) {
                            init_article = $(this).attr('data-id');
                            found = true
                        }
                    })


                }

                if (found) {
                    $body.triggerHandler($.Events.ARTICLE_OPEN, [init_article, found])
                    $body.triggerHandler($.Events.ARTICLE_SCROLL, [init_article, found])
                } else {
                    $body.triggerHandler($.Events.ARTICLE_SCROLL, [init_article, found])
                }


            })
          .bind($.Events.FILTER,
            function(e, id, reset) {

                $.Articles.filter = id;

                _articles = new Array();

                _active_index = 0;

                $articles.each(
                function(i) {

                    if ($(this).hasClass(id) || id == 'all')
                        _articles.push($(this));

                });

                if (reset) {
                    $body.triggerHandler($.Events.ARTICLE_SCROLL, __START_ID)
                } else {

                    $body.triggerHandler($.Events.ARTICLE_SCROLL, _articles[0].attr('data-id'))


                }


            })
          .bind($.Events.ARTICLE_SCROLL,
            function(e, id, auto_open, end) {

                for (var i = 0; i < _articles.length; i++) {

                    if (_articles[i].attr('data-id') == id) {

                        _active_id = id;

                        _active_index = i;

                        _scroll(i, auto_open, end);

                    }

                }

            })

                $(window).bind('resize', _resize);

                function _resize() {

                    if ($(window).width() < 1150) {
                        $fade_next.css({ display: 'none' })
                        $fade_prev.css({ display: 'none' })
                    } else {
                        $fade_next.css({ display: 'block' })
                        $fade_prev.css({ display: 'block' })
                    }


                }
                _resize();

                function _prev(e) {

                    if (!$.Articles.loading) {

                        var index = _active_index - 1,
                  end = false;

                        if (index > 0)
                            if (_articles[index].hasClass('interlude'))
                            index--;

                        if (index < 0) {

                            index = 0;

                            end = -1;

                        }

                        $body.triggerHandler($.Events.ARTICLE_SCROLL, [_articles[index].attr('data-id'), false, end])

                    }

                    e.preventDefault();

                }

                function _next(e) {

                    if (!$.Articles.loading) {

                        var index = _active_index + 1,
                  end = false;

                        if (index < _articles.length)
                            if (_articles[index].hasClass('interlude'))
                            index++;

                        if (index >= _articles.length - 1) {

                            index = _articles.length - 1;

                            end = 1;

                        }

                        $body.triggerHandler($.Events.ARTICLE_SCROLL, [_articles[index].attr('data-id'), false, end])

                    }

                    e.preventDefault();

                }



                function _scroll(index, auto_open, end) {

                    //if (!auto_open)// && _articles.length>3)
                    //index--;

                    if (end) {
                        $self.stop().animate({ left: -(index) * 300 - 100 * end }, 300, 'easeOutQuart', function() {
                            $self.animate({ left: -(index) * 300 - 100 }, 300, 'easeOutQuart', function() {
                                if (auto_open)
                                    $body.triggerHandler($.Events.ARTICLE_SCROLL_COMPLETE, _active_id)
                            });
                        });
                    }
                    else {
                        var move;

                        switch (index) {
                            case 0:
                                move = 35;
                                break;
                            case 1:
                                move = 270;
                                break;
                            case 2:
                                move = 505;
                                break;
                            case 3:
                                move = 625;
                                break;
                            case 4:
                                move = 1220;
                                break;
                            case 5:
                                move = 1455;
                                break;
                            case 6:
                                move = 1690;
                                break;
                            default:
                                break;
                        }

                        $self.stop().animate({ left: -(move) }, 650, 'easeOutQuart', function() {
                            if (auto_open)
                                $body.triggerHandler($.Events.ARTICLE_SCROLL_COMPLETE, _active_id)
                        });
                    }

                }

            });





        }



    })(jQuery);



    (function($) {

        $.fn.Article = function(settings) {

            var config = {};

            if (settings) $.extend(config, settings);

            this.each(function(index) {

                var $self = $(this),
            $body = $('body'),
            $excerpt = $self.find('.excerpt'),
            $id = $self.attr('data-id'),
            $next = $('#arrow-next'),
            $prev = $('#arrow-prev'),
            $number = $self.attr('data-number'),
            $permalink = $self.find('a.permalink'),
            $href = $self.attr('data-permalink'),
            $footer = $self.find('footer'),
            $scroll = ($.browser.mozilla || $.browser.msie) ? $('html') : $body,
            _loaded_detail = false;


                $body
          .bind($.Events.ARTICLE_COLLAPSE,
            function(e) {
                if ($self.hasClass('active'))
                    _close();
            })
          .bind($.Events.ARTICLE_OPEN,
            function(e, id) {

                if (id != $id) {

                    _close()

                } else {

                    $.Articles.loading = true;

                    $.Articles.active_id = $id;

                    $excerpt.css({ display: 'none' })

                    $self.css({ 'background-color': '#F9F5CF' });

                    $self.addClass('_preload')

                }

            })
          .bind($.Events.ARTICLE_SCROLL,
            function(e, id) {


                if ($self.hasClass('active'))
                    _close();


            })
          .bind($.Events.ARTICLE_SCROLL_COMPLETE,
            function(e, id) {

                if (id == $id) {
                    $self.animate({ width: 707 }, 500, 'easeOutQuart', _open)
                    $body.triggerHandler($.Events.ARTICLE_ADDRESS, $number);

                }


            })
          .bind($.Events.FILTER,
            function(e, id) {

                if ($self.hasClass(id) || id == 'all') {

                    if ($self.hasClass('active'))
                        _close();


                    $.Articles.filtered = (id != 'all');

                    $self.css({ display: 'block', opacity: 0 }).animate({ opacity: 1 }, 600, 'easeInOutQuart')

                } else {

                    if ($self.hasClass('active'))
                        _cleanup();

                    $self.css({ display: 'none' });
                }

            });


                $permalink
          .bind('click',
            function(e) {

                if (!$.Articles.loading) {

                    if (!$self.hasClass('in-production')) {
                        $body.triggerHandler($.Events.ARTICLE_OPEN, $id);
                        $body.triggerHandler($.Events.ARTICLE_SCROLL, [$id, true]);
                        $body.triggerHandler($.Events.ARTICLE_ADDRESS, $number);
                    } else {
                        $body.triggerHandler($.Events.ARTICLE_SCROLL, [$id, false]);
                    }

                }

                e.preventDefault();

            });


                function _open() {

                    if (!$self.hasClass('in-production') && !$self.hasClass('interlude'))
                        $.ajax({
                            dataType: 'htm',
                            beforeSend: function() { $self.addClass('_preload') },
                            error: function() { $.Articles.loading = false; _close(); },
                            success: _on_success,
                            data: {
                                xmlhttp: true
                            },
                            url: $href
                        });

                }

                function _close() {

                    $self.find('.full').remove();

                    if ($self.hasClass('active')) {
                        //$self.addClass('_preload')
                        mouseTop = 300;
                        $self.animate({ width: 230 }, 400, 'easeOutQuart', _cleanup)
                        $next.animate({ top: 300 }, 650);
                        $prev.animate({ top: 300 }, 650);
                    }

                }

                function _cleanup() {

                    $self.find('.full').remove();

                    $excerpt.css({ display: 'block' })

                    if ($self.hasClass('active')) {
                        if ($self.hasClass('grid2')) {
                            $self.removeClass('active').removeClass('_preload').css({ width: 480 });
                        } else {
                            $self.removeClass('active').removeClass('_preload').css({ width: 230 });
                        }
                    }
                }

                function _on_success(response) {

                    $.Articles.loading = false

                    _loaded_detail = true;

                    $self
          .addClass('active')
          .removeClass('_preload')

                    if ($.browser.msie)
                        $self.append($(innerShiv(response, false)));
                    else
                        $self.append($(response));



                    $full = $self.find('.full')

                    Cufon.refresh('.BodyCopy1');
                    Cufon.refresh('.BodyCopy3');


                    $self.css({ 'background-color': 'transparent' });

                    /* PROMO */
                    $self.find('[data-controller=PromoHoliday2010]').PromoHoliday2010();



                    $self.find('[data-controller=Collapse]').Collapse();

                    $self.find('[data-controller=Comment]').Comment();

                    $self.find('[data-controller=Video]').Video();

                    $self.find('[data-controller=Sharing]').Sharing({ now: true });

                    $self.find('[data-controller=OmnitureTrack]').OmnitureTrack();

                    $self.css({ height: 'auto' })

                    $scroll.animate({ scrollTop: 0 }, 650, 'easeInOutQuart')

                    mouseTop = 600;
                    $next.animate({ top: 600 }, 650);
                    $prev.animate({ top: 600 }, 650);
                }


            });

        }



    })(jQuery);


    /* ---------------------------------- */

    /* Filter */

    (function($) {

        $.fn.Filter = function(settings) {

            var config = {};

            if (settings) $.extend(config, settings);

            this.each(function() {

                var $self = $(this),
              $body = $('body'),
              $_filter = $self.attr('data-filter');

                $body
            .bind($.Events.FILTER,
              function(e, id) {

                  if (id == $_filter)
                      $self.addClass('active');
                  else
                      $self.removeClass('active');
              });

                $self
            .bind('click',
              function(e) {

                  var reset = ($_filter == 'all') ? true : false;

                  $body.triggerHandler($.Events.FILTER, [$_filter, reset]);

                  e.preventDefault();

              });

            });

        }



    })(jQuery);


    /* ---------------------------------- */

    /* SHELL */

    (function($) {

        $.fn.AddThis = function(settings) {

            var config = {};

            if (settings) $.extend(config, settings);

            this.each(function() {

                var $self = $(this),
              $_script = $self.attr('data-script');

                $.getScript($_script, function() {

                });



            });

        }



    })(jQuery);


    /* ---------------------------------- */

    /* Sharing */

    (function($) {

        $.fn.Sharing = function(settings) {

            var config = {};

            if (settings) $.extend(config, settings);

            this.each(function() {

                var $self = $(this),
              $body = $('body'),
              $url = $self.attr('data-url');


                if (config.now)
                    _addSharing();
                else
                    $(window).bind('load', function() { _addSharing(); });


                function _addSharing() {
                    $mark = $('<mark><a href="http://twitter.com/share" class="twitter-share-button" data-url="' + $url + '" data-count="horizontal">Tweet</a></mark>').appendTo($self);
                    $.getScript('http://platform.twitter.com/widgets.js', function() { });
                    $mark = $('<mark><iframe src="http://www.facebook.com/plugins/like.php?href=' + escape($url) + '&amp;layout=button_count&amp;show_faces=false&amp;width=50&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:100px; height:21px;" allowTransparency="true"></iframe></mark>').appendTo($self)
                }

            });

        }



    })(jQuery);



    /* ---------------------------------- */

    /* SHELL */

    (function($) {

        $.fn.Collapse = function(settings) {

            var config = {};

            if (settings) $.extend(config, settings);

            this.each(function() {

                var $self = $(this),
              $body = $('body');

                $self
            .bind('click',
              function(e) {

                  $body.triggerHandler($.Events.ARTICLE_COLLAPSE)

                  e.preventDefault();

              })

            });

        }



    })(jQuery);

    /* ---------------------------------- */

    /* SHELL */

    (function($) {

        $.fn.Timeline = function(settings) {

            var config = {};

            if (settings) $.extend(config, settings);

            this.each(function() {

                var $self = $(this),
              $body = $('body'),
              $timeline_items = $self.find('ul li');

                $timeline_items.each(
            function(i) {
                if ($(this).attr('data-parent') == 'Timeline')
                    $(this).ArticleProxy({ index: i + 1 })
            });

            });

        }


        $.fn.ArticleProxy = function(settings) {

            var config = {};

            if (settings) $.extend(config, settings);

            this.each(function() {

                var $self = $(this),
            $body = $('body'),
            $a = $self.find('a'),
            $id = $self.attr('data-id')//,
                //$index = $self.attr('data-index');

                $body
          .bind($.Events.FILTER,
            function(e, id) {
                if ($self.hasClass(id) && id != 'all') {
                    $self.addClass('active');
                    $a.addClass('active')
                } else {
                    $a
                .removeClass('active')
                .removeClass('highlight')

                }
            })
          .bind($.Events.ARTICLE_SCROLL,
            function(e, id) {
                if (id == $id) {
                    $body.triggerHandler($.Events.POINTER_SEEK, config.index);
                }
            })


                $self
          .bind('click',
            function(e) {

                if (!$.Articles.loading) {

                    if ($.Articles.filtered && !$self.hasClass($.Articles.filter))
                        $body.triggerHandler($.Events.FILTER, 'all');

                    $body.triggerHandler($.Events.ARTICLE_SCROLL, $id)

                }

                e.preventDefault();

            })


            });

        }





    })(jQuery);


    /* ---------------------------------- */

    /* SHELL */

    (function($) {

        $.fn.Comment = function(settings) {

            var config = {};

            if (settings) $.extend(config, settings);

            this.each(function() {

                var $self = $(this),
            $form = $self.find('form'),
            $body = $('body'),
            $_action = $form.attr('action'),
            $_post_id = $form.find('input[name=comment_post_ID]').val(),
            $_parent = $form.find('input[name=comment_parent]').val(),
            $author = $form.find('input[name=author]'),
            $comment = $form.find('textarea[name=comment]'),
            $submit = $self.find('a#submit'), //$self.find('input[type=submit]'),
            $scroll = ($.browser.mozilla || $.browser.msie) ? $('html') : $body,
            $comments = $('ul.commentlist');

                $submit.bind('click', _submit)

                function _submit(e) {


                    var _author = $author.val(),
              _comment = $comment.val();

                    if (_author == '')
                        _author = "Anonymous";


                    if (_comment.length > 0) {
                        var data = {
                            id: 'commentform',
                            author: _author,
                            comment: _comment,
                            comment_post_ID: $_post_id,
                            comment_parent: $_parent
                        }

                        _before_send();

                        $comments.load(
              $_action + ' ul.commentlist',
              data,
              function() { _on_success() });

                    }

                    e.preventDefault();

                }

                function _before_send() {
                    $self.html('').addClass('_submitting _preload')


                }

                function _on_success(response) {
                    $self.removeClass('_preload').html('Thanks for your comment!')
                    $('ul.commentlist li:last-child').css({ opacity: 0 })
                    $scroll.animate({ scrollTop: $('ul.commentlist').offset().top }, 450, 'easeInOutQuart', _highlight);

                }


                function _highlight() {
                    $('ul.commentlist li:last-child').animate({ opacity: 1 }, 1000, 'easeInOutQuart')
                }


            });

        }



    })(jQuery);


    /* ---------------------------------- */

    /* SHELL */

    (function($) {

        $.fn.Video = function(settings) {

            var config = {};

            if (settings) $.extend(config, settings);

            this.each(function() {

                var $self = $(this),
            $id = $self.attr('data-video');



                function _bind_video() {

                    if ($.browser.msie) {
                        $self.html('<object width="853" height="510"><param name="movie" value="http://www.youtube.com/v/' + $id + '?fs=1&amp;hl=en_US&amp;rel=0&amp;hd=1&amp;autoplay=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/' + $id + '?fs=1&amp;hl=en_US&amp;rel=0&amp;hd=1&amp;autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="853" height="510"></embed></object>');
                    } else {
                        $self.html('<iframe title="YouTube video player" class="youtube-player" type="text/html" width="853" height="510" src="http://www.youtube.com/embed/' + $id + '?rel=0&autoplay=1" frameborder="0"></iframe>');
                    }

                }

                _bind_video();



            });

        }



    })(jQuery);


    /* ---------------------------------- */

    /* SHELL */

    (function($) {

        $.fn.FollowMouse = function(settings) {

            var config = {};

            if (settings) $.extend(config, settings);

            this.each(function() {

                var $self = $(this),
            $next = $('#arrow-next'),
            $prev = $('#arrow-prev'),
            $body = $('body'),
            _BUFFER = 70,
            _offset = 30,
            _top = $next.offset().top,
            _next_active = false,
            _prev_active = false;

                $body
          .bind('mousemove',
            function _on_mousemove(e) {

                if (e.pageX > $(window).width() - _BUFFER) {

                    $next.css({ top: e.pageY - _offset })

                    if (!_next_active)
                        $next.stop()

                    _next_active = true;

                } else {

                    if (_next_active) {
                        $next.stop().animate({ top: mouseTop == 0 ? _top : mouseTop  }, 450, 'easeInOutQuart')
                    }

                    _next_active = false

                }


                if (e.pageX < _BUFFER) {

                    $prev.css({ top: e.pageY - _offset })

                    if (!_prev_active)
                        $prev.stop()

                    _prev_active = true;

                } else {

                    if (_prev_active) {
                        $prev.stop().animate({ top: mouseTop == 0 ? _top : mouseTop }, 450, 'easeInOutQuart')
                    }

                    _prev_active = false

                }



            })


            });

        }



    })(jQuery);




    /* ---------------------------------- */

    /* SHELL */

    (function($) {

        $.fn.Address = function(settings) {

            var config = {};

            if (settings) $.extend(config, settings);

            this.each(function() {

                var $self = $(this),
            $title = $('title');


                $self
          .bind($.Events.ARTICLE_ADDRESS,
            function(e, $id) {
                location.href = '#/' + $id;
                if (!$.browser.msie)
                    document.title = 'Toyota Prius Projects: ' + ($id.length < 4 ? 'No. ' + $id : 'Yr. ' + $id)

            })
          .bind($.Events.ARTICLE_OPEN, _clear)
          .bind($.Events.FILTER, _clear)
          .bind($.Events.ARTICLE_SCROLL, _clear)
          .bind($.Events.ARTICLE_COLLAPSE, _clear)


                function _clear(e) {

                    document.title = 'Toyota Prius Projects';

                    location.href = '#/';

                }

            });

        }



    })(jQuery);

    /* ---------------------------------- */

    /* SHELL */

    (function($) {

        $.fn.SHELL = function(settings) {

            var config = {};

            if (settings) $.extend(config, settings);

            this.each(function() {


            });

        }



    })(jQuery);


    /* ---------------------------------- */

    /* Pointer */

    (function($) {

        $.fn.Pointer = function(settings) {

            var config = {};

            if (settings) $.extend(config, settings);

            this.each(function() {

                var $self = $(this),
            $body = $('body');

                $body
          .bind($.Events.POINTER_SEEK,
            function(e, index) {


                $self.stop().animate({ left: index * 12 - 17 }, 300, 'easeOutQuart')

            })

            });

        }



    })(jQuery);


    /* ---------------------------------- */

    /* LINKS */

    (function($) {


        $.fn.BlankLink = function() {

            this.each(function() {

                var $self = $(this);


                $self
        .attr('target', '_blank')
        .bind('click', on_click);

                function on_click(e) {

                }


            });

        }



    })(jQuery);

    /* ---------------------------------- */

    /* Omniture */

    (function($) {

        $.fn.OmnitureTrack = function(settings) {

            var config = {};

            if (settings) $.extend(config, settings);

            this.each(function() {

                var $self = $(this),
              $body = $('body'),
              $data_omniture = $self.attr('data-omniture'),
              $data_omnitureobject = $self.attr('data-omnitureobject');


                $body.triggerHandler('OMNITURE_TRACK', [$data_omniture, $data_omnitureobject]);



            });

        }



    })(jQuery);


    /* ---------------------------------- */

    /* KEYBOARD */

    (function($) {


        $.fn.Keyboard = function(settings) {

            var config = {};

            if (settings) $.extend(config, settings);

            this.each(function() {

                var $self = $(this),
            $owner = config.owner,
            $body = $('body');

                $(document)
        .bind('keydown', on_keydown)
        .bind('keyup', on_keyup);

                function on_keyup(e) {



                }

                function on_keydown(e) {

                    var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;

                    switch (key) {

                        case 38: //top

                            $self.triggerHandler($.Events.KEY_UP);

                            break;

                        case 39: //right

                            $self.triggerHandler($.Events.KEY_RIGHT);
                            e.preventDefault();

                            break;

                        case 40: ///bottom

                            $self.triggerHandler($.Events.KEY_DOWN);

                            break;

                        case 37: //left

                            $self.triggerHandler($.Events.KEY_LEFT);

                            e.preventDefault();

                            break;


                    } //switch

                } //keydown

            });

            return this;

        } // ARROW-KEYBOARD


    })(jQuery);







    /* ---------------------------------- */

    /* PromoHoliday2010 */

    (function($) {

        $.fn.PromoHoliday2010 = function(settings) {

            var config = {};

            if (settings) $.extend(config, settings);

            this.each(function() {

                var $self = $(this),
              $body = $('body'),
              $url = $self.attr('data-submit'),
              $contents = $self.find('#h2010-contents'),
              $response = $self.find('#h2010-response'),
              $a_preview = $self.find('#h2010-preview'),
              $a_send = $self.find('#h2010-send'),
              $from_name = $self.find('#h2010-from-name'),
              $from_email = $self.find('#h2010-from-email'),
              $to_name = $self.find('#h2010-to-name'),
              $to_email = $self.find('#h2010-to-email'),
              $message = $self.find('textarea'),
              $inputs = $self.find('input,textarea'),
              $to = '';

                $inputs
                .bind('focus',
                  function(e) {
                      if ($(this).val() == $(this).attr('title'))
                          $(this).val('');
                  })
                .bind('blur',
                  function(e) {
                      if ($(this).val() == '')
                          $(this).val($(this).attr('title'));
                  })


                $a_send
                .bind('click',

                  function(e) {


                      if (_validate())
                          _send();
                      else
                          _error()

                      e.preventDefault();

                  });
                $a_preview
                .bind('click',
                  function(e) {

                      if (_validate()) {


                          var url = $url + '&preview_email=true&send_to_friend=true&from_email=' + $from_email.val() + '&from_name=' + $from_name.val() + '&to_email=' + $to_email.val() + '&to_name=' + $to_name.val() + '&message=' + $message.val();

                          var _preview = window.open(url, '_preview', 'width=700,height=700')

                      } else {

                          _error()

                      }

                      e.preventDefault();


                  })

                function _validate() {

                    var validated = true;

                    $inputs.each(

                  function() {

                      if ($(this).val() == '' || $(this).val() == $(this).attr('title')) {

                          validated = false;

                          $(this).addClass('_error');

                      }

                  })

                    return validated;
                }

                function _send() {

                    $.ajax({
                        method: 'POST',
                        dataType: 'html',
                        beforeSend: function() {
                            $to = $to_name.val(),
                    $self.addClass('_sending');
                        },
                        error: function() { },
                        success: _on_success,
                        data: {
                            xmlhttp: true,
                            send_to_friend: true,
                            from_name: $from_name.val(),
                            from_email: $from_email.val(),
                            to_name: $to_name.val(),
                            to_email: $to_email.val(),
                            message: $message.val()
                        },
                        url: $url
                    });
                }

                function _on_success(response) {

                    var json_response = jQuery.parseJSON(response);
                    if (json_response.success == 1) {
                        $self.addClass('_sent').removeClass('_sending');
                        $response.html('Thanks! Your email has been sent to ' + $to + '.')
                    } else {
                        $self.removeClass('_sending')
                        $response.html("We're sorry, but we were unable to deliver your email at this time.<br />Please try again later.");
                    }

                }

                function _error() {
                    alert('Please re-check the fields outlined in red.')
                }





            });

        }



    })(jQuery); 

