var TT = (function(TT, $) {

    TT.gallery = (function() {

        var SERVICES = {
            studies: pathToRoot+'_WebServices/ContentService.svc/GetCaseStudy',
            people: pathToRoot+'_WebServices/ContentService.svc/GetPerson'
        }

        var TMPL = '<div class="figure">{{if IsImage}}<img src="Asset.axd?FilePath={{html Src}}" />{{else}}<object type="application/x-shockwave-flash" data="{{html Src}}" width="604" height="422"><param name="movie" value="{{html Src}}" /><param name="wmode" value="transparent" /></object>{{/if}}</div><div class="desc">{{html ClientLogoAssetTag}}{{html BusinessChallenge}}{{html Results}}</div>';

        var _reset = {'width': 196, 'height': 141},
            _final = {'width': 606, 'height': 553},
            _initialised = false,
            _container = null,
            _element = null,
            _request = null,
            _loading = false;
            // HTMLElement, src (clicked) element;
            _src = null; 

        return {
            init: function(src) {
                var that = this;
                _initialised = true;
                _container = $('.gallery');
                _element = $('<div id="box"><div class="inner"></div></div>').appendTo('body');
                _element
                    .click(function(e) {
                        if ($(e.target).hasClass('close')) {
                            that.close.apply(that, arguments);
                            return false;
                        }    
                    })
                    .keydown(function(e) {
                        if (e.keyCode === 32) {
                            that.close.apply(that, arguments);
                            return false;
                        }
                    });
                $.template('box', TMPL);
            },
            close: function() {
                _element.css('top', '-999em');
                // focus last gallery item;
                _src.attr('tabindex', -1).get(0).focus();
            },
            load: function(id, src /*jQuery, collection containing src element*/) {
                if (! _loading) {
                    _src = src;
                    _loading = true;
                    _request = $.ajax({
		                type: "GET",
		                url: SERVICES.studies,
		                dataType: "json",
                        data: {id: id, isLive: false}
	                });
                    this.animate(src);
                }
            },
            animate: function(src) {
                if (! _initialised) {
                    this.init(src);    
                }
                var // trap xhr ref in closure; 
                    req = _request,
                    that = this,
                    // clicked element position;
                    dims = src.offset(),
                    // coords to animate to;
                    coords = this.getCoords(src);
                return _element.find('.inner').empty().text('Loading...').end()
                    // reset box dimensions to defaults;
                    .css($.extend({}, _reset, {'top': dims.top, 'left': dims.left}))
                    // animate box into position;
                    .animate($.extend(coords, {
                        'width': _final.width, 'height': _final.height}), 300, 'easeOutCubic',
                        function() {
                            // on animation complete listen for ajax completion;
                            req.success(function(data) {
                                that.render.call(that, data);
                            });
                        });
            },   
            getCoords: function(src) {
                // returns Object, animation values;
                var ret = {}, 
                    pos = src.position(),
                    ofs = _container.offset();
                if (pos.left >= _container.width()/2) {
                    ret.left = (_container.width() - _final.width) + ofs.left;
                }
                /*
                if (pos.top >= _container.height()/2) {
                    ret.top = (_container.height() - HEIGHT-11)+ofs.top;
                }
                */
                ret.top = ofs.top;
                return ret;
            },                                                      
            render: function(data) {
                var elem = _element.find('.inner');
                data = $.extend(data, {
                    Src: data.LargeAsset.FilePath,
                    IsImage: data.Media === "Image"
                });
                elem.empty().hide();
                $.tmpl('box', data).appendTo(elem);
                elem.fadeIn(800)
                    .append('<a class="close" href="#">Close</a>')
                    // move focus to close button, go accessiblity;
                    .find('.close').get(0).focus();
                _loading = false;
            }
        }

    })();

    TT.signup = (function() {

        var SERVICE = pathToRoot + '_WebServices/ContentService.svc/RegisterForNewsletter',
            THANKSMSG = '<p class="msg">Thank you for registering</p>',
            ERRXHR = '<p class="msg">Sorry there appears to have been an error, please try again later</p>',
            ERRINVALID = '<p class="msg">The following doesn\'t appear to be a valid email address</p>';

        var _request = null,
            _target = null;

        return {
            submit: function(value) {
                var that = this;
                if (! _target) {
                   _target = $('.signup');
                }
                _request = $.ajax({
		            type: "POST",
		            url: SERVICE,
		            contentType: "application/json; charset=utf-8",
		            dataType: "json",
		            data: '"'+value+'"'
	            });
                _request.success(function(){
			        that.success.apply(that, arguments);
		        });
		        _request.error(function(){
			        that.error.apply(that, arguments);
		        });
                this.before();
            },
            before: function() {
                return this.setMsg('<p class="msg">Processing...</p>');
            },
            getMsg: function() {
                var msg = _target.find('.msg');
                return msg.length > 0 ? msg : null;
            },
            setMsg: function(message) {
                var msg = this.getMsg();
                if (msg) {
                    msg.replaceWith(message)
                } else {
                    _target.find('h3').after(message);
                };
                return message;
            },
            deleteMsg: function() {
                var msg = this.getMsg();
                if (msg) {
                    msg.remove();
                };
            }, 
            success: function(response) {
                if (response === true) {
                    this.deleteMsg();
                    _target.find('fieldset').replaceWith(THANKSMSG)
                } else {
                    this.addMsg(ERRINVALID);
                };
                return; 
            },
            error: function(response) {
                return _target.find('.msg').replaceWith(ERRXHR);
            }
        }
    })();
    
    $(document).ready(function() {
        
        $('.caseStudyGallery')
            .click(function(e) {
                var el = e.target, id;
                el = el.className.indexOf('box') != -1 ? $(el) : $(el).closest('.box');
                id = el.attr('class').match(/\d+/).pop();
                TT.gallery.load(id, el);
                return false;
            })
            .keydown(function(e) {
                if (e.keyCode === 32) {
                    var id = $(e.target).find('.box').attr('class').match(/\d+/).pop();
                    TT.gallery.load(id, $(e.target));
                    return false;
                }
            });

        $('.signup input[type=image]').click(function () {
            var val = $(this).prev().attr('value');
            TT.signup.submit(val);
            return false;
        });
         
    });

})(TT||{}, jQuery);
