﻿/*
* ToC:
* 1. Plugins and utilities
*  - $.outerHTML()
*  - $.attrs()
*  - addLoad()
*  - hideAddressBar()
*  - enhanceInputs()
* 2. App functions
*  - 
*/

(function () {
    // 1. Plugins and utilities	

    // jQuery plugins

    // $(':empty') selector only returns true if the element contains no text node, 
    // or whose text node consists exclusively of zero or more spaces and tabs. 
    // This ':notext' selector will return true for elements whose text nodes can also contain line breaks
    // (any whitespace character) and HTML comments.

    $.expr[':'].notext = function (el) {
        return $.trim(el.innerHTML.replace(/<!--.*(?!-->)/, '')).length === 0
    }

    // Cross-browser outerHTML 
    $.fn.outerHTML = function (arg) {
        var $el = this;

        return arg
			? $el.replaceWith(arg)
			: $el.clone().wrap('<b>').parent().html();
    };

    // Return all attributes, optionally filtered by RegExp 
    $.fn.attrs = function (expr, obj) {
        var 
			el = this[0],
			$el = this,
			attrObj = {},
			attrArray = [];

        for (var i = 0, attrs = el.attributes; i < attrs.length; ++i) {
            var attrKey = [
				attrs.item(i).nodeName,
				attrs.item(i).nodeValue
			];

            if (!expr || expr.test(attrKey[0])) {
                attrObj[attrKey[0]] = attrKey[1];
                attrArray.push(attrKey);
            };
        };

        return obj ? attrObj : attrArray;
    };

    // Utility belt 

    // Stack events to execute on page load 
    function addLoad(func) {
        var old = window.onload;
        window.onload = function () {
            func();
            old instanceof Function && old();
        };
    };

    // Scroll to remove the address bar on mobile devices 
    // Modified from: 
    // http://remysharp.com/2010/08/05/doing-it-right-skipping-the-iphone-url-bar/ 
    function hideAddressBar() {
        setTimeout(function () {
            $('html')
				.toggleClass('stretch');
            // Temporarily make the document larger than the viewport to enable scrolling 
            // We don't need to scroll to 0,1. We can avoid all clipping: 
            window.scrollTo(0, 0);
            // Set the document back to normal size now the viewport is scaled: 
            $('html')
				.toggleClass('stretch')
				.css('height', window.innerHeight);
        }, 100)
    };

    // For elements with the data-enhance attribute, 
    // Take data-enhance-* attributes and remove the 
    // 'data-enhance' suffix.
    function html5Inputs() {

        // Only for browsers we know will benefit the user: 
        // BB, iOS, Android display convenient inputs; 
        // Firefox, Opera desktop & Chrome are very creative and unhelpful 
        if (!/^BlackBerry\d| Fennec|Android \d|Opera Mobi|Opera Mini| like Mac OS X/g.test(navigator.userAgent))
            return false;

        $('input[data-enhance]:not([data-enhanced])').each(function () {
            var 
				el = this,
				$el = $(this),
				attrs = $(this).attrs(/^data-enhance-.+/),
				enhancement,
				type;

            // Loop through attributes 
            for (var i = 0; i < attrs.length; ++i) {
                enhancement = attrs[i][0].split('data-enhance-')[1];

                // If the attribute matches data-enhance-* ... 
                if (enhancement)
                    enhancement === 'type'
                // type attribute cannot be changed dynamically 
						? type = attrs[i][1]
                // instantiate the enhancement 
						: $el.attr(enhancement, attrs[i][1]);
            };

            // Set a flag to avoid recursion 
            $el.attr('data-enhanced', 'true');

            // If type was an enhancement... 
            if (type)
            // Change it by modifying the document fragment as a string, 
            // rather than by DOM methods (which is forbidden)
                $el.replaceWith(
					$el.outerHTML().replace(/type="[^"]*"/, 'type="' + type + '"')
				);
        });

        return true;
    };

    // 2. App functions
    addLoad(hideAddressBar);

    // DOM ready 
    $(function () {
        // HTML5 form inputs
        //var html5 = html5Inputs();

        // Age gate validation
        (function LDA() {
            var 
				$form = $('.ageGate_form'),
				$inputs = $form.find('[type=text],[type=number]');

            if (!$form.length) return;

            $inputs
				.each(function () {
				    var 
						$el = $(this),
						val = $el.val().length;

				    if (val) $el.prev('.label').addClass('hide');
				})
				.focus(function () {
				    $(this).prev('.label').addClass('hide');
				})
            // Removed: Agressive input restriction prevents pasting, 
            // Arrow key navigation, modification, etc
            /*
            .keypress(function(e){
            var $el = $(this);
						
            if(e.keyCode == 13) return;

            if($el.val().length >= $el.attr('data-enhance-maxlength')
            || e.keyCode < 48 || e.keyCode > 57){
            e.preventDefault();
            };
            })
            */
				.blur(function () {
				    if (/^\s*$/.test($(this).val()))
				        $(this).prev('.label').removeClass('hide');
				})
				.bind('keyup blur', function () {
				    var 
						$evented = $(this),
						pass = (function () {
						    // Pass by default
						    var pass = true;
						    $inputs.each(function (i) {
						        var 
									$el = $(this),
									val = $el.val(),
									max = ~ ~$el.attr('maxlength');

						        // If it still doesn't match expected char length, fail.
						        if ($el.val().length != max) pass = false;
						    });
						    return pass
						} ());
				    // Manipulate DOM to reflect validation
				    if (pass === true) {
				        $form.addClass('pass');
				        if (Modernizr.touch) setTimeout(function () { $('.inputButtonWrapper', $form).css('visibility', 'visible').css('opacity', '1').css('display', 'block'); }, 0);
				    } else {
				        $form.removeClass('pass');
				        if (Modernizr.touch) setTimeout(function () { $('.inputButtonWrapper', $form).css('visibility', 'hidden').css('opacity', '0').css('display', 'none'); }, 0);
				    }
				});
        } ());

        // Radios & checkboxes graphical enhancements
        (function replaceBooleans() {
            $(':checkbox,:radio').each(function () {
                var 
					$el = $(this),
					$wrap = $('<span class="inputBoolReplace"></span>'),
					$decoration = $('<b></b>');

                $el
					.wrap($wrap)
					.after($decoration)
					.click(function () {
					    $decoration.toggleClass('on')
					});

                if ($el.is(':checked'))
                    $decoration.toggleClass('on');
            });
        } ());

        // Newsletter signup
        (function signUp() {
            var 
				on = 0,
				$link = $('.signUpLink'),
				$signup = $('.signUpWrapper1'),
				$signupEl = $('.signUpWrapper2'),
                $signupemail = $('.signupemail'),
                $signupname = $('.signupname'),
                $submit = $signup.find('.button'),
				reveal = function () {
				    var posX = $link.offset().left + $link.width() - $signupEl.width();

				    $link.addClass('active');
				    $signupEl.css('left', posX + 'px');
				    $signup.show();
				    on = 1;
				    $("body").bind("click", watchClick);
				    $signupemail.focus();
				    return false;
				},
				hide = function () {
				    $link.removeClass('active');
				    $signup.hide();
				    on = 0;
				    $signupemail.blur();
				    $signupname.blur();
				    $("body").unbind("click", watchClick);
				};

            window['signUpHide'] = hide; // expose hide function for use in signup post script below

            function watchClick(el) {
                if ($(el.target).closest("#signUp").length > 0 ||
                    $(el.target).closest(".signUpLink").length > 0) {
                } else {
                    debug.log("hide sign up!");
                    hide();
                };
            };

            $link.click(reveal);
            hide();

            // Form XHR
            //            var 
            //				$form = $('form'),
            //				URL = $form[0].action;

            //            $submit.live('click', function (e) {
            //                e.preventDefault();
            //                $submit.hide();
            //                $.post(URL, $form.serialize(), function (data) {
            //                    $new = $(data).find('.signUpWrapper2');

            //                    $signupEl.html($new.html());
            //                    $submit = $signupEl.find('.button');

            //                    if ($signupEl.find('.errors').eq(0).is(':notext'))
            //                        hide();
            //                })
            //            })
        } ());
    });
} ());

var TT = (function (TT, $) {

    TT.signup = (function () {

        var host = window.location.protocol + '//' + window.location.host,
            basePath = window.location.pathname.split('/')[1] +'/';
        if (window.location.host !== "localhost") { basePath = '/'; }

        var SERVICE = host + '/' + basePath + '_WebServices/ContentService.svc/RegisterForNewsletter',
            THANKSMSG = '<p class="signupmsg">Thank you for registering</p>',
            ERRXHR = '<p class="signupmsg error">Sorry there appears to have been an error, please try again later</p>',
            ERRINVALID = '<p class="signupmsg error">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: "GET",
                    url: SERVICE,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: "emailAddress=" + value.emailAddress + "&name=" + value.name
                });
                _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="signupmsg">Processing...</p>');
            },
            getMsg: function () {
                var msg = _target.find('.signupmsg');
                return msg.length > 0 ? msg : null;
            },
            setMsg: function (message) {
                var msg = this.getMsg();
                if (msg) {
                    msg.replaceWith(message)
                } else {
                    _target.find('.errors').html(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);
                    setTimeout(function () { signUpHide() }, 3500);
                } else {
                    this.setMsg(ERRINVALID);
                };
                return;
            },
            error: function (response) {
                return _target.find('.signupmsg').replaceWith(ERRXHR);
            }
        }
    })();

    $(document).ready(function () {
        $('#signUp input[type=submit]').click(function () {
            var signupdata = { emailAddress: $('#signUp .signupemail').attr('value'), name: $('#signUp .signupname').attr('value') }
            TT.signup.submit(signupdata);
            return false;
        });
    });
})(TT || {}, jQuery);
