﻿/*  ---- FOX MOVIES CORE LIBRARY ----
    
COMPONENTS
- jQuery Extensions
- Form validator
- Global document ready instruction
- Email validating RegEx

///////////  EMAIL REGEX ORGINIAL COMMENTS  ///////////////////
<!-- This script and many more are available free online at -->
<!-- The JavaScript Source!! http://javascript.internet.com -->     
///////////////////////////////////////////////////////////////   
        
LAST UPDATED
- 21/10/2011
        
CREATED BY
- James Hay
        
---------------------------------    
*/
var FX = {
    formSaveState: {
        formelementcount: 0,
        formInitMap: {},
        formCurrentMap: {},
        ischanged: false,
        init: function(formid) {
            a = $('#' + formid).find('input[type=checkbox]');
            FX.formSaveState.formelementcount = a.length;
            for (var i = 0; i < a.length; i++) {
                FX.formSaveState.formInitMap[$(a[i]).attr('id')] = {
                    type: 'checkbox',
                    value: ($(a[i]).is(':checked')) ? 1 : 0
                };
                FX.formSaveState.formCurrentMap[$(a[i]).attr('id')] = {
                    type: 'checkbox',
                    value: ($(a[i]).is(':checked')) ? 1 : 0,
                    changed: false
                };
            }
            $('input[type=checkbox]').click(function() {
                var id = $(this).attr('id');
                FX.formSaveState.formCurrentMap[id].value = ($(this).is(':checked')) ? 1 : 0;
            });
            FX.formSaveState.formchangewatch();
        },
        formchangewatch: function() {
            setTimeout(function() {
                var chg = false;
                for (var eleid in FX.formSaveState.formInitMap) {
                    var initVal = FX.formSaveState.formInitMap[eleid].value;
                    var curVal = FX.formSaveState.formCurrentMap[eleid].value;
                    if (curVal != initVal) {
                        chg = true;
                        if (!FX.formSaveState.ischanged) {
                            FX.formSaveState.ischanged = chg;
                            if (typeof (form_statechange) == 'function') {
                                form_statechange();
                            }
                        }
                        break;
                    }
                }
                if (!chg && FX.formSaveState.ischanged) {
                    FX.formSaveState.ischanged = false;
                    if (typeof (form_statechange) == 'function') {
                        form_statechange();
                    }
                }
                FX.formSaveState.formchangewatch();
            }, 200);
        }
    },
    getWindow: function() {
        var dim = { width: $(window).width(), height: $(window).height() };
        var w = $(window).width();
        var h = $(window).height();
        dim.width = w;
        dim.height = h;
        return dim;
    },
    track: function(type, id) {
        if (id != 'undefined' && id != 0) {
            $.ajax({
                beforeSend: function(XMLHttpRequest) {
                    XMLHttpRequest.setRequestHeader("X-Custom-Page-Method", "track");
                },
                type: "POST",
                url: "common.aspx",
                data: '{"type":"' + type + '","id":' + id + '}',
                contentType: "application/json; charset=utf-8",
                dataType: "json"
            });
        }
    },
    extendJquery: function() {
        $.fn.extend({
            toggleCss: function(property, vone, vtwo) {
                if ($(this).css(property) == vone) {
                    $(this).css(property, vtwo);
                }
                else {
                    $(this).css(property, vone);
                }
            },
            toggleAttr: function(attribute, vone, vtwo) {
                var aVal = $(this).attr(attribute);
                if (aVal == vone) {
                    $(this).attr(attribute, vtwo);
                }
                else {
                    $(this).attr(attribute, vone);
                }
            },
            validateForm: function() {
                var f = {
                    empty: function(element) {
                        if (!$.trim(element.val()).length) {
                            return false;
                        }
                        return true;
                    },
                    length: function(element, paramLength) {
                        var l = paramLength.split(',', 2);
                        // TODO: Create error handling
                        if (!isNaN(l[0]) && !isNaN(l[1])) {
                            var length = $.trim(element.val()).length
                            if (length < new Number(l[0]) || length > new Number(l[1])) {
                                return false;
                            }
                            return true;
                        }
                        else {
                            alert('Incorrect length parameter format.');
                            return false;
                        }
                    },
                    email: function(element) {
                        if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(element.val())) {
                            return true;
                        }
                        return false;
                    },
                    match: function(element, paramMatch) {
                        var matchval = $('#' + paramMatch).val();
                        if (element.val() == matchval) {
                            return true;
                        }
                        return false;
                    },
                    number: function(element, param) {
                        var vl = element.val()
                        if (typeof (param) !== 'undefined') {
                            var l = param.split(',', 2);
                            if (l.length == 1) {
                                var max = l[0];
                                if (isNaN(max)) {
                                    alert('Incorrect number parameter format.');
                                    return false;
                                }
                                else if (isNaN(vl)) {
                                    return false;
                                }
                                else if (new Number(vl) > max) {
                                    return false;
                                }
                                else {
                                    return true;
                                }
                            }
                            else if (l.length == 2) {
                                var min = l[0];
                                var max = l[1];
                                if (isNaN(min) || isNaN(max)) {
                                    alert('Incorrect number parameter format.');
                                    return false;
                                }
                                else if (isNaN(vl)) {
                                    return false;
                                }
                                else if (new Number(vl) > max || new Number(vl) < min) {
                                    return false;
                                }
                                else {
                                    return true;
                                }
                            }
                            else {
                                alert('Incorrect number parameter format.');
                                return false;
                            }
                        }
                        else {
                            if (isNaN(element.val())) {
                                return false;
                            }
                            return true;
                        }
                    }
                };
                var a = $(this).find('input,textarea');
                var b = [];
                var e = [];
                var params = [];

                for (var i = 0; i < a.length; i++) {
                    var v = $(a[i]).attr('data-vtype')
                    if (v) {
                        var vtypes = v.split(',');
                        var vparams;
                        var pstring = $(a[i]).attr('data-vparams');
                        if (typeof (pstring) !== 'undefined') {
                            vparams = FX.seperateParameters(pstring);
                        }
                        for (var j = 0; j < vtypes.length; j++) {
                            b.push({
                                id: $(a[i]).attr('id'),
                                vtype: vtypes[j],
                                params: vparams
                            });
                        }
                    }
                }
                a = null;
                for (var i = 0; i < b.length; i++) {
                    switch (b[i].vtype) {
                        case 'empty':
                            var r = f.empty($('#' + b[i].id));
                            if (!r) {
                                e.push(b[i]);
                            }
                            break;
                        case 'length':
                            var r = f.length($('#' + b[i].id), b[i].params.length);
                            if (!r) {
                                e.push(b[i]);
                            }
                            break;
                        case 'email':
                            var r = f.email($('#' + b[i].id));
                            if (!r) {
                                e.push(b[i]);
                            }
                            break;
                        case 'match':
                            var r = f.match($('#' + b[i].id), b[i].params.match);
                            if (!r) {
                                e.push(b[i]);
                            }
                            break;
                        case 'number':
                            var r = f.number($('#' + b[i].id), b[i].params.number);
                            if (!r) {
                                e.push(b[i]);
                            }
                            break;
                        default:
                            break;
                    }
                }
                return e;
            },
            positionPopup: function() {
                var win = FX.getWindow();
                $('#modal_overlay').css({
                    'width': win.width + 'px',
                    'height': win.height + 'px',
                    'top': '0px',
                    'left': '0px'
                });
                var formdim = {
                    width: $(this).outerWidth(),
                    height: $(this).outerHeight()
                };
                // DEBUG
                //alert('Window width: ' + win.width + 'px \n\nWindow height: '
                // + win.height + 'px\n\nElement Id: ' + $(this).attr("id") + '\n\nElement width: '
                // + formdim.width + 'px\n\nElement Height: ' + formdim.height + 'px');
                var toppad = Math.round((win.height - formdim.height) / 2);
                if (toppad > 20) {
                    $(this).css('top', toppad + 'px');
                }
                else {
                    $(this).css('top', '20px');
                }
                var leftpad = Math.round((win.width - formdim.width) / 2);
                if (leftpad > 0) {
                    $(this).css('left', leftpad + 'px');
                }
                else {
                    $(this).css('left', '0px');
                }
            },
            popup: function() {
                var f = {
                    openPopup: function(element) {
                        f.setPopupPosition(element);
                        $('#modal_overlay').show();
                        element.show();
                    },
                    closePopup: function(element) {
                        $('#modal_overlay').hide()
                        element.hide();
                    },
                    createModal: function() {
                        var modal = document.createElement('div');
                        modal.setAttribute('id', 'modal_overlay');
                        $('body').append(modal);
                    },
                    setPopupPosition: function(element) {
                        var win = FX.getWindow();
                        $('#modal_overlay').css({
                            'width': win.width + 'px',
                            'height': win.height + 'px',
                            'top': '0px',
                            'left': '0px'
                        });
                        var formdim = {
                            width: element.outerWidth(),
                            height: element.outerHeight()
                        }
                        var toppad = Math.round((win.height - formdim.height) / 2);
                        if (toppad > 20) {
                            element.css('top', toppad + 'px');
                        }
                        else {
                            element.css('top', '20px');
                        }
                        var leftpad = Math.round((win.width - formdim.width) / 2);
                        if (leftpad > 0) {
                            element.css('left', leftpad + 'px');
                        }
                        else {
                            element.css('left', '0px');
                        }
                    }
                }
                var s = $(this).attr('data-popup');
                if (s != 'open') {
                    if ($('#modal_overlay').length > 0) {
                        f.openPopup($(this));
                    }
                    else {
                        f.createModal();
                        f.openPopup($(this));
                    }
                    $(this).attr('data-popup', 'open');
                }
                else {
                    f.closePopup($(this));
                    $(this).attr('data-popup', 'closed');
                }
            }
        });
    },
    JSEnabled: function() {
        $('#nojs').remove(); // Remove 'Javascript disabled indicator'
        var links = $('a[data-hasjs]');
        for (var i = 0; i < links.length; i++) {
            var linkdata = $(links[i]).attr('data-hasjs');
            $(links[i]).attr('href', linkdata);
            $(links[i]).removeAttr('data-hasjs');
        }
    },
    seperateParameters: function(paramString) {
        var pObject = {};
        var p = paramString.split(';');
        for (var i = 0; i < p.length; i++) {
            if (p[i].indexOf(':') != -1) {
                var pname = p[i].substring(0, p[i].indexOf(':'));
                var pval = p[i].substring(p[i].indexOf(':') + 1);
                pObject[pname] = pval;
            }
        }
        return pObject;
    },
    hashwatch: function() {
        FX.currenthash = window.location.hash;
        FX.previoushash = window.location.hash;
        FX.changehash();
    },
    changehash: function() {
        if (window.location.hash != FX.currenthash) {
            FX.previoushash = FX.currenthash;
            FX.currenthash = window.location.hash;
            if (typeof (window_onhashchange) == 'function') {
                window_onhashchange();
            }
        }
        setTimeout(FX.changehash, 50);
    },
    hashchange: 'indirect',
    currenthash: '',
    previoushash: ''
};
// GLOBAL DOCUMENT READY INSTRUCTION
$(document).ready(function() {
    FX.extendJquery(); // extend jquery // start ticker for watching hashchanges.
    FX.JSEnabled();
    $('.customcheck_off').live('click', function() {
        $(this).attr('class', 'customcheck_on');
    });
    $('.customcheck_on').live('click', function() {
        $(this).attr('class', 'customcheck_off');
    });
    $('#nojs').hide(); // Hide 'Javascript disabled indicator'
    var links = $('a');

    if (typeof (pageinit) == 'function') {
        pageinit(); // If the current page has a 'pageinit' function then run it.
    }
});
