﻿/* ------------------------------------------------------ */
/* core.js
/* Global JS for the Aubin Cinema website
/* ------------------------------------------------------ */
/* Created: 23/04/2010 (dd/mm/yy)
/* Copyright: Jack Wills Ltd.
/* URL: http://www.aubincinema.com/
/* ------------------------------------------------------ */
var $core = {
    context: false,
    overlay: false,
    overlayOpts: {},

    init: function () {
        this.context = $('#page_container');
        this.overlay = $('#overlay');
        this.overlayOpts = {
            onShow: this.overlayShow,
            onHide: this.overlayHide,
            closeClass: 'close-overlay'
        };

        $('#alert').jqm($.extend({}, this.overlayOpts, { onHide: this.confirmHide, modal: true, trigger: false }));
        $('#confirm').jqm($.extend({}, this.overlayOpts, { onHide: this.confirmHide, modal: true, trigger: false }));

        // trigger an alert whenever links of class alert are pressed.
        this.context.find('.confirm, .alert').each(function () {
            $(this).attr('msg', $(this).attr('title'));
            $(this).attr('title', '');
        });

        this.bindEvents();
        this.prepareNewsletterForm();

        $.prettyLoader({
            animation_speed: 'fast',
            bind_to_ajax: true,
            delay: false,
            loader: '/content/images/prettyLoader/ajax-loader.gif',
            offset_top: 13,
            offset_left: 10
        });
    },

    validateEmailAddress: function (val) {
        return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(val);
    },

    prepareNewsletterForm: function () {
        var base = this;

        this.context.find('#formNewsletter').submit(function (e) {
            e.preventDefault();
            $form = $(this);
            if (base.validateEmailAddress($form.find('input[name="email"]').val())) {
                if ($form.next('span.error').length) {
                    $form.next('span.error').remove();
                }
                $.ajax({
                    type: 'POST',
                    url: '/Newsletter',
                    data: 'email=' + $form.find('input[name="email"]').val(),
                    success: function (data) {
                        if (data == 0) {
                            // FAILED
                        }
                        else {
                            // SUCCESS
                            $form.animate({ opacity: 0 }, { duration: 500, complete: function () {
                                $form.before('<p><span>Thank you for signing up to our newsletter</span></p>');
                                $form.hide();
                            }
                            });
                        }
                    }
                });
            }
            else {
                // Doesn't Validate
                if ($form.next('span.error').length) {
                    $form.next('span.error').remove();
                }
                $form.after('<span class="error">Please enter a valid email address</span>');
            }
        });
    },

    /* ------------------------------------------------------ */
    /* bindEvents
    /* ------------------------------------------------------ */
    bindEvents: function () {
        var self = this;

        // anything with an open-overlay class
        this.context.delegate('.open-overlay', 'click', function (e) {
            e.preventDefault();
            self.onOpenOverlayClick($(this));
        });

        // all submit buttons
        this.context.delegate('button[type=submit]', 'click', function (e) {
            if (!$(this).hasClass('disabled') && !$(this).closest('.confirm').length) {
                self.processing($(this));
                this.form.submit();
                e.preventDefault();
            }
        });

        // print click
        this.context.delegate('#print-ticket, .print-ticket', 'click', function (e) {
            e.preventDefault();
            if (!$(this).hasClass('disabled')) {
                var orderId = ($(this).attr('href').match(/[0-9]+/)) ? $(this).attr('href').match(/[0-9]+/)[0] : '';

                self.processing($(this));
                self.onPrintClick($(this), orderId);
            }
        });

        // anything with an expand-content class
        this.context.delegate('.expand-content', 'click', function (e) {
            e.preventDefault();
            self.onExpandContentClick($(this));
        });

        // anything with an hide-content class
        this.context.delegate('.hide-content', 'click', function (e) {
            e.preventDefault();
            self.onHideContentClick($(this));
        });

        this.context.delegate('.schedule_tabs a', 'click', function (e) {
            e.preventDefault();
            self.repaintForIE();
        });

        this.context.delegate('.confirm, .alert', 'click', function (e) {
            var me = $(this),
                msg = me.attr('msg');

            if (me.attr('name') == 'btnRefundOrder') {
                e.preventDefault();
                confirm(msg, function () {
                    self.processing(me);
                    me.closest('form').trigger('submit');
                });
            }
        });
    },

    processing: function (target) {
        if (target[0].tagName == 'BUTTON') {
            target.attr('disabled', true);
        }

        target.attr('placeholder', target.text());
        target.addClass('disabled').text('Processing...');
    },

    /* ------------------------------------------------------ */
    /* onOpenOverlayClick
    /* ------------------------------------------------------ */
    onOpenOverlayClick: function (target) {
        target = target.closest('.open-overlay');

        var content = $('#' + target.attr('rel')),
            iframe = content.find('iframe');

        if (!content.length) return;
        if (iframe.length) iframe.attr('src', target.attr('href'));

        this.prepareOverlay(content.html());

        if (iframe.length) iframe.attr('src', '');

        this.overlay.addClass(target.attr('rel'));
        this.overlay.jqmShow();
    },


    /* ------------------------------------------------------ */
    /* onExpandContentClick
    /* ------------------------------------------------------ */
    onExpandContentClick: function (target) {
        var content = $('#' + target.attr('rel'));
        if (!content.length) return;

        var duration = 500,
            onTermsPage = target.parents('.about-terms-and-conditions').length;

        content.hide().removeClass('hidden').slideDown(duration, function () {
            target.removeClass('expand-content').addClass('hide-content');

            // expand button on terms and conditions page
            if (onTermsPage) {
                target.text('Back to Top').removeClass('hide-content');
            }
        });

        // re-paint to fix IE8 bug (eugh)
        if (onTermsPage) {
            this.repaintForIE(duration);
        }
    },

    /* ------------------------------------------------------ */
    /* repaintForIE
    /* Temporary fix for re-paint issues in IE8
    /* ------------------------------------------------------ */
    repaintForIE: function (duration) {
        duration = duration || 100;

        if ($.browser.msie && $.browser.version === '8.0') {
            var footer = $('#footer_container');

            footer.css('display', 'none');
            setTimeout(function () { footer.css('display', 'block') }, duration);
        }
    },

    /* ------------------------------------------------------ */
    /* onHideContentClick
    /* ------------------------------------------------------ */
    onHideContentClick: function (target) {
        var content = $('#' + target.attr('rel'));

        if (!content.length) return;

        content.slideUp('slow', function () {
            content.addClass('hidden');
            target.removeClass('hide-content').addClass('expand-content');
        });
    },


    /* ------------------------------------------------------ */
    /* showFeedback
    /* ------------------------------------------------------ */
    showFeedback: function (msg, type, feedback) {
        if (feedback.length) {
            feedback.attr('class', '').addClass('feedback').addClass(type).html('<p>' + msg + '</p>');
        }
    },


    /* ------------------------------------------------------ */
    /* prepareOverlay
    /* ------------------------------------------------------ */
    prepareOverlay: function (html) {
        if (this.overlay.length) {
            if (!this.overlay.hasClass('jqmID1')) {
                this.overlay.jqm(this.overlayOpts);
            }

            if (html) {
                this.overlay.html(html);
            }
        }
    },


    /* ------------------------------------------------------ */
    /* overlayShow
    /* ------------------------------------------------------ */
    overlayShow: function (hash) {
        hash.w.css({
            'margin-left': '-' + hash.w.outerWidth() / 2 + 'px',
            'margin-top': '-' + hash.w.outerHeight() / 2 + 'px'
        })
        hash.o.fadeIn();
        hash.w.fadeIn();
    },


    /* ------------------------------------------------------ */
    /* overlayHide
    /* ------------------------------------------------------ */
    overlayHide: function (hash) {
        hash.o.fadeOut('fast');
        hash.w.fadeOut('fast', function () {
            $(this).html('');
        });
    },

    /* ------------------------------------------------------ */
    /* confirmHide
    /* ------------------------------------------------------ */
    confirmHide: function (hash) {
        hash.o.fadeOut('fast');
        hash.w.fadeOut('fast', function () {
            $(this).find('.message').text('');
        })
    },

    /* ------------------------------------------------------ */
    /* onPrintClick
    /* ------------------------------------------------------ */
    onPrintClick: function (target, orderId) {
        orderId = orderId || $('#orderId').val();

        var updateTarget = function () {
            if (target.hasClass('disabled')) {
                target.removeClass('disabled').text(target.attr('placeholder'));
            }
        };

        $.ajax({
            type: 'POST',
            url: target.attr('href'),
            data: { orderId: orderId },
            success: function (response) {
                var collected = $('#ticket-collected');

                if (response === '1') {
                    if (collected.length) collected.removeClass('error').addClass('success').find('span').text('Yes');
                    updateTarget();
                } else {
                    if (collected.length) collected.removeClass('success').addClass('error').find('span').text('No');
                    updateTarget();
                }
            },
            error: function (response) {
                updateTarget();
            }
        });
    }
};


$(function() {
    $core.init();
});


/* Overriding Javascript's Alert Dialog */
function alert(msg) {
    $('#alert').jqmShow().find('p.message').html(msg);
}

/* Overriding Javascript's Confirm Dialog */

// NOTE; A callback must be passed. It is executed on "cotinue". 
// This differs from the standard confirm() function, which returns
// only true or false!

// If the callback is a string, it will be considered a "URL", and
// followed.

// If the callback is a function, it will be executed.
function confirm(msg, callback) {
    var confirm = $('#confirm');
    confirm.jqmShow().find('p.message').html(msg);
    confirm.find('button.highlight').unbind('click').click(function() {
        (typeof callback == 'string') ? window.location.href = callback : callback();
        confirm.jqmHide();
        return true;
    });
    return false;
}


//Image fader minified version 
function slideSwitch() { var a = $("#slideshow IMG.active"); if (a.length == 0) { a = $("#slideshow IMG:last") } var b = a.next().length ? a.next() : $("#slideshow IMG:first"); a.addClass("last-active"); b.css({ opacity: 0 }).addClass("active").animate({ opacity: 1 }, 1000, function () { a.removeClass("active last-active") }) } $(function () { setInterval("slideSwitch()", 5000) });
