// global function
(function($) {

    $.modalBox = function(url, image) {

        function parseURL(url) {
            var a =  document.createElement('a');
            a.href = url;
            return {
                source: url,
                protocol: a.protocol.replace(':',''),
                host: a.hostname,
                port: a.port,
                query: a.search,
                params: (function(){
                    var ret = {},
                    seg = a.search.replace(/^\?/,'').split('&'),
                    len = seg.length, i = 0, s;
                    for (;i<len;i++) {
                        if (!seg[i]) { continue; }
                        s = seg[i].split('=');
                        ret[s[0]] = s[1];
                    }
                    return ret;
                })(),
                file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
                hash: a.hash.replace('#',''),
                path: a.pathname.replace(/^([^\/])/,'/$1'),
                relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
                segments: a.pathname.replace(/^\//,'').split('/')
            };
        };

        var closeModal = function() {
            $('div.overlay').fadeOut(function() {
                $(this).remove();
            });
            $('div.modal').fadeOut(function() {
                $(this).remove();
            });

            return false;
        };

        var openModal = function() {

            // get height properies if offered (get these from href params of clicked element)
            var myURL = parseURL(url);

            // get width of modal box (if not specified set default)
            if (myURL.params.w) {
                var width = Number(myURL.params.w);
            }
            else {
                var width = 495;
            }

            // get height of modal box (if not specified set default)
            if (myURL.params.h) {
                var height = Number(myURL.params.h);
            }
            else {
                var height = 493;
            }

            // check that width and height will fit within viewport
            if (height > $(window).height()) {
                height = $(window).height() - 60;
            }
            if (width > $(window).width()) {
                width = $(window).width() - 60;
            }

            // get height and width of modal box for centring modal box - // remove padding from width and height
            var marginLeft = width/2 + 15;
            var marginTop = height/2 + 15;

            // append modal box to body
            var $modal = $('<div class="modal"></div>').css({'margin-top': -marginTop, 'margin-left': -marginLeft, 'width': width, 'height': height}).prependTo('body').fadeIn(250);

            // adjust margin for IE6 as does not support position fixed
            if ($.browser.msie && ($.browser.version === "6.0")) {

                // get the vetical scroll position
                var scrollPos = $(document).scrollTop();

                var temp = scrollPos - marginTop; // remove margin

                $modal.css({'margin-top': temp});       // set margin
            }

            var $overlay = $('<div class="overlay"></div>').insertBefore($modal).css('opacity', '0.8').stop().fadeIn(250);

            $overlay.click(closeModal);

            // check whether link is image
            if (image) {
                // insert image into modal box (set 100% height in case screen resolution is too large)
                $('<img src="' + url + '" height="100%" style="display:block; margin:0 auto;" />').prependTo($modal).load(function() {
                    $modal.css('background-image', 'none');
                });

                // append close button
                $closeBtn = $('<a href="#" class="close">Close</a>').prependTo($modal);

                $closeBtn.click(closeModal);

            }
            else {
                // load AJAX content into modal box
                $modal.load(url + ' #ajax-content', function() {
                    $modal.css('background-image', 'none');

                    // append close button
                    $closeBtn = $('<a href="#" class="close">Close</a>').prependTo($modal);

                    $closeBtn.click(closeModal);
                });
            }
            return false;
        };

        // open modal
        openModal();


        // notes:
        // Find less crude way to determine whether url is an image
        // Find better way to add close button


    };
})(jQuery);



$(document).ready(function() {
    /*===============================
      =========== Modal Box ===========
      ===============================*/
    $('#sub-footer a, #want-more-entries a').click(function() {

        // get URL
        var url = $(this).attr('href');

        if ($(this).hasClass('image')) {
            $.modalBox(url, true);
        }
        else {
            $.modalBox(url);
        }

        return false;
    });

    /*===============================
      ======= Show Extra Inputs =======
      ===============================*/
    var $form = $('#add-friends-page form'); // cache form

    // only run if inputs after the fith pair do NOT have values
    if (!$form.find(':text').filter(':gt(11)').filter('[value]').length) {

        // get last five inputs (in 'name | email' pairs)
        var $extraInputs = $form.find('.field').filter(':gt(11)');

        // insert container around last five inputs
        $extraInputs.wrapAll('<div id="extra-inputs-JS" class="clearfix" />');
        var $extraInputsContainer = $('#extra-inputs-JS'); // cache containing div

        var containerHeight = $extraInputsContainer.height(); // get height of container

        $extraInputsContainer.height(0); // set height to 0

        // insert '+ more names' button
        var $addMoreBtn = $('<a href="#">Add more names</a>').appendTo($form);

        // bind click event to more names button to show contents of containg div
        $addMoreBtn.click(function() {
            // animate height
            $extraInputsContainer.animate({
                height: containerHeight
            }, 500);

            // remove button
            $(this).remove();

            return false;
        });
    }

    /*===============================
      ====== Postcode Validation ======
      ===============================*/
    $('#home-page form').submit(function() {

        // get postcode input
        var $postCodeInput = $('input[name=postcode]', $(this));

        // postcode regex
        //var filter = /^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]? {1,2}[0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)$/i;
        var filter = /^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) {0,1}[0-9][A-Za-z]{2})$/;

        // check that input is not empty and is valid postcode
        if ($postCodeInput.val() === '' || !filter.test($postCodeInput.val())) {

            // remove old error msg
            $(this).find('.error').remove();

            // append error message
            $(this).find('.buttons').after('<span class="error">Please enter a valid Postcode</span>');
            return false;
        }
    });

    /*===============================
      ===== Initial Input Values  =====
      ===============================*/
    /* POSTCODE */
    var $form = $('#home-page form');

    // cache text inputs and change initial color to grey
    var $textInputs = $form.find(':text');

    $textInputs.each(function() {

        var $thisInput = $(this);
        var title = $thisInput.attr('title');

        var value = $thisInput.attr('value');
        if (value === '' || value === title) {
            // set value to title
            $thisInput.css({color: '#9A9A9A', textTransform: 'none'}).attr('value', title);
        }

        // bind focus evernt to remove value if === to  title
        $thisInput.focus(function() {
            if ($thisInput.attr('value') === title) {
                // change color to black
                $thisInput.css({color: '#424242', textTransform: 'uppercase'}).attr('value', '');
            }
        });

        // bind blue event to add title if empty
        $textInputs.blur(function() {
            if ($thisInput.attr('value') === '') {
                // change color to grey
                $thisInput.css({color: '#9A9A9A', textTransform: 'none'}).attr('value', title);
            }
        });
    });


    /* EMAIL / NAME  */
    var $form = $('#add-friends-page form');

    // cache text inputs and change initial color to grey
    var $textInputs = $form.find(':text');

    $textInputs.each(function() {

        var $thisInput = $(this);

        // check whether input is email or name
        if ($thisInput.is('[name*=email]')) {
            var title = 'Email';
        }
        else {
            var title = 'Name';
        }

        var value = $thisInput.attr('value');
        if (value === '' || value === title) {
            // set value to title
            $thisInput.css({color: '#9A9A9A'}).attr('value', title);
        }

        // bind focus evernt to remove value if === to  title
        $thisInput.focus(function() {
            if ($thisInput.attr('value') === title) {
                // change color to black
                $thisInput.css({color: '#424242'}).attr('value', '');
            }
        });

        // bind blue event to add title if empty
        $textInputs.blur(function() {
            if ($thisInput.attr('value') === '') {
                // change color to grey
                $thisInput.css({color: '#9A9A9A'}).attr('value', title);
            }
        });
    });

    // remove initial values on submit (as not to conflict with server side validation)
    $form.submit(function() {

        $textInputs.each(function() {

            $thisInput = $(this);

            // check whether input is email or name
            if ($thisInput.is('[name*=email]')) {
                var title = 'Email';
            }
            else {
                var title = 'Name';
            }
            if ($thisInput.attr('value') === title) {
                $thisInput.attr('value', '');
            }
        });
    });


});
