 /*
 * @fileoverview Create an age verification overlay
 *
 * @author PG
 * 	
 */
var ageVerification = function () {

    /*
    * The overlay element, only needs creating once
    *
    * @var Object
    * @private
    */
    var overlay = null;


    /*
    * Legal drinking ages for each country
    *
    * @var Object
    * @public
    */
    var drinkingAges = {
        'canada': 18,
        'china': 18,
        'france': 18,
        'germany': 16,
        'greece': 16,
        'hong Kong': 18,
        'italy': 18,
        'japan': 20,
        'russia': 18,
        'singapore': 18,
        'south korea': 19,
        'spain': 18,
        'taiwan': 18,
        'uk': 18,
        'usa': 21
    };


    /*
    * Form validation error messages
    *
    * @var Object
    * @public
    */
    var errorMessages = {
        dob: "Please enter your date of birth",
        country: "Please select a country",
        language: "Please select a language",
        age: "To enter this site, you must be above the legal drinking age for your country"
    };


    /*
    * Is this IE? (needs separate rules if so)
    * See: http://dean.edwards.name/weblog/2007/03/sniff/
    *
    * @var Bool
    * @private
    */
    var isMSIE = /*@cc_on!@*/false;


    /*
    * If this is IE, what version number is it?
    *
    * @var Int
    * @public
    */
    var vIE = (navigator.appName == 'Microsoft Internet Explorer') ? parseFloat((new RegExp("MSIE ([0-9]{1,}[.0-9]{0,})")).exec(navigator.userAgent)[1]) : -1;



    /*
    * AF modification 22/09/2010 - added automatic overlay content language switch:
    */
    var overlayPath;
    overlayPath = 'http://www.themastersofphotography.com/age-verification/s33/';

    /**
    * The options passed through to this function
    *
    * @var Object
    * @private
    */
    var options = {

        /**
        * The path to the overlay content
        *
        * @var String
        */
        // overlayContentPath: "./AgeVerificationOverlay.aspx",
        overlayContentPath: overlayPath,

        /**
        * Age validation form element to check
        *
        * @var String
        */
        ageValidationForm: "#age-validation",


        /**
        * Submit element to listen for a click on
        *
        * @var String
        */
        submitButton: "#submit input.button",


        /**
        * Checkbox element to listen for a click on
        *
        * @var String
        */
        rememberme: "#remember label",

        /**
        * Dropdown elements to listen for hovers on
        *
        * @var String
        */
        dropDowns: "#location .input-container",

        /**
        * Id to give the new overlay element
        *
        * @var String
        */
        id: 'overlay'
    };


    /**
    * Initialise the functionality
    * 
    * @return void
    * @public
    */
    var init = function (initOptions) {

        // save any options sent through to the intialisation script, if set
        if (!!initOptions) {
            for (var option in options) {
                if (!!initOptions[option] || initOptions[option] === false) {
                    options[option] = initOptions[option];
                }

                // error check, if no element is specified then stop
                if (!options[option] && options[option] !== false && options[option] !== 0) {
                    throw ('Required option not specified: ' + option);
                }
            }
        }


        // remove scrollbars
        $('body').css({
            height: "100%",
            overflow: "hidden"
        });



        // set listeners to validate the overlay on form submit
        $(options.submitButton).bind('click', function (e) {
            return validateOverlay(this);
        });
        $(options.submitButton).bind('keypress', function (e) {
            if (e.keyCode == 13) { // enter
                return validateOverlay(this);
            }
        });
        $('#age-validation').submit( function() { return false; } );


        // set listeners to display the dropdown elements
        // $(options.dropDowns).find('ul').css({opacity:0});
        // $(options.dropDowns).each(function(counter){
        // 	var dropDown = this;
        // 	$(dropDown).find('a').bind('focus', function(e){
        // 		hideDropDown(options.dropDowns, dropDown);
        // 	});
        // });

        // set a mouse listener on the dropdown elements
        // $(options.dropDowns).hover(
        // 	function(e){
        // 		e.preventDefault();
        // 		showDropDown(this);
        // 	},
        // 	function(e){
        // 		e.preventDefault();
        // 		hideDropDown(this);
        // 	}
        // );



        // set a listener on selecting a country/language
        $(options.dropDowns).find('label').bind('mousedown', function (e) {
            //e.preventDefault();
            dropDownSelected($(this).find('input'));
        });
        $(options.dropDowns).find('label').bind('keypress', function (e) {
            if (e.keyCode == 13) { // enter
                //e.preventDefault();
                dropDownSelected($(this).find('input'));
            }
        });

        // display outline around each active (focused) country
        $(options.dropDowns).find('label').bind('click', function (e) {
            $(options.dropDowns).find('label').removeClass('focus');
            $(this).addClass('focus');
        });




        // set listeners on the checkbox element
        $(options.rememberme).bind('click', function (e) {
            if (e.target.nodeName == "INPUT") {
                $(this).blur();
                rememberMe(this);
            }
        });
        $(options.rememberme).bind('focus', function (e) {
            $(this).addClass('focus');
        });
        $(options.rememberme).bind('keypress', function (e) {
            if (e.keyCode == 13) { // enter
                rememberMe(this);
            }
        });


        // Fixes for IE - display issues
        if (isMSIE) {
            $('#age-verification-overlay fieldset, #age-verification-overlay h1').css({
                'zoom': "1"
            });
        }
    };



    /**
    * Create the age verification overlay
    *  
    * @return void
    * @public
    */
    var createOverlay = function (initOptions) {

        // save any options sent through to the intialisation script, if set
        if (!!initOptions) {
            for (var option in options) {
                if (!!initOptions[option] || initOptions[option] === false) {
                    options[option] = initOptions[option];
                }

                // error check, if no element is specified then stop
                if (!options[option] && options[option] !== false && options[option] !== 0) {
                    throw ('Required option not specified: ' + option);
                }
            }
        }

        // condition : check the overlay doesn't already exist
        overlay = $('#age-verification-overlay');
        if (overlay.length < 1) {

            // get overlay contents
            $.get(options.overlayContentPath, function (data) {

                // [SB]
                var verify = $('<div id="verify"></div>');
                $('body').append(verify);
                document.getElementById('verify').innerHTML = data;

                // calculate page height
                var pageHeight = $(document).height();
                overlay = $('#age-verification-overlay');
                $(overlay).css({
                    position: 'absolute',
                    left: '0',
                    top: '0',
                    width: '100%',
                    height: pageHeight + "px",
                    zIndex: '999999'
                });

                init();
            });
        }
    };



    /*
    * Hide the overlay 
    * 
    * @return void
    * @public
    */
    var hideOverlay = function () {
        if (overlay.length > 0) {
            $(overlay).animate({
                opacity: 0
            }, 1000, function () {
                $('#age-verification-overlay').remove();
            });
        }
    };


    /*
    * Check the entered minimum age
    * 
    * @return bool, is the person old enough?
    * @public
    */
    var minimumAge = function () {

//        // find the selected country
        var country = $('select#country option:selected').val();
//
//        // get it's minimum drinking age
        var minimumDrinkingAge = drinkingAges[country];
//        var minimumDrinkingAge = 21; //change request

        // calculate the currently set age, and compare it to the minimum
        var day = $("#dob-day").val();
        var month = $("#dob-month").val();
        var year = $("#dob-year").val();

        var enteredAge = new Date();
        enteredAge.setFullYear(year, month - 1, day);

        var currentDate = new Date();
        currentDate.setFullYear(currentDate.getFullYear() - minimumDrinkingAge);

        // age comparison - too young...
        if ((currentDate - enteredAge) < 0) {
            return false;

            // age comparison - old enough
        } else {
            return true;
        }
    };



    /*
    * Validate the form once it's been submitted
    * 
    * @return void
    * @public
    */
    var validateOverlay = function () {

        // create upper limit for year range
        var currentDate = new Date();
        var rangeYear = currentDate.getFullYear();


        // start validation
        $(options.ageValidationForm).validate({

            // set error HTML container element
            wrapper: "p",

            // set validation rules
            rules: {
                'dob-day': {
                    required: true,
                    minlength: 2,
                    range: [1, 31]
                },
                'dob-month': {
                    required: true,
                    minlength: 2,
                    range: [1, 12]
                },
                'dob-year': {
                    required: true,
                    minlength: 4,
                    range: [1900, rangeYear]
                }
            },


            // set custom error messages
            messages: {
                'dob-day': {
                    required: errorMessages.dob
                },
                'dob-month': {
                    required: errorMessages.dob
                },
                'dob-year': {
                    required: errorMessages.dob
                }
            },

            // group the date of birth fields together
            groups: {
                dob: "dob-day dob-month dob-year"
            },

            // set the placement of the error messages
            errorPlacement: function (error, element) {
                if (element.attr("name") == "dob-day" || element.attr("name") == "dob-month" || element.attr("name") == "dob-year") {
                    //error.insertAfter("fieldset#dob");
                    $("fieldset#dob").append(error);

                } else {
                    error.insertAfter(element);
                }
            },


            // once the form has been submitted successfully...
            submitHandler: function (form) {

                // check the minimum drinking age
                var ageCheck = minimumAge();

                // if the age check has failed, display error message
                if (!ageCheck) {

                    // look for an existing 'error' element
                    var errorElement = $("fieldset#dob p label.error");
                    if (errorElement.length < 1) {
                        $("fieldset#dob").append("<p><label class='error' for='dob' generated='true'>" + errorMessages.age + "</label></p>");

                    } else {
                        $("fieldset#dob p label.error").html(errorMessages.age).css({ display: "block" });
                        $("fieldset#dob p").css({ display: "block" });
                    }

                } else {

                    // condition : if remember me is on, set long term cookie
                    if ($('#remember-me:checked').length > 0) {
                        // first set local domain cooke, then go set macallan.com cookie
                        setCookie('mop_age_verify','1',5000);
                        
                        location.href = 'http://www.blog.themacallan.com/mopageverify.php?setVerification=1&expires=5000&uid='+myCookies['mop_uid'];

                        // condition : if this is the live site, set the cross domain cookie (for the blog age verification)
/*                        if (window.location.href.indexOf("themacallan.com") != -1) {
                            $.cookie('ageVerification', true, { path: '/', expires: 5000, domain: "themacallan.com" });
                            $.cookie('language', $("#language").val(), { path: '/', expires: 5000, domain: "themacallan.com" });
                            $.cookie('country', $("#country").val(), { path: '/', expires: 5000, domain: "themacallan.com" });
                        } else {
                            $.cookie('ageVerification', true, { path: '/', expires: 5000 });
                            $.cookie('language', $("#language").val(), { path: '/', expires: 5000 });
                            $.cookie('country', $("#country").val(), { path: '/', expires: 5000 });
                        }
*/
                        // set session cookie
                    } else {
                        // first set local domain cooke, then go set macallan.com cookie
                        setCookie('mop_age_verify','1');
                        
                        location.href = 'http://www.blog.themacallan.com/mopageverify.php?setVerification=1&expires=5000&uid='+myCookies['mop_uid'];

                        // condition : if this is the live site, set the cross domain cookie (for the blog age verification)
/*                        if (window.location.href.indexOf("themacallan.com") != -1) {
                            $.cookie('ageVerification', true, { path: '/', domain: "themacallan.com" });
                            $.cookie('language', $("#language").val(), { path: '/', domain: "themacallan.com" });
                            $.cookie('country', $("#country").val(), { path: '/', domain: "themacallan.com" });
                        } else {
                            $.cookie('ageVerification', true, { path: '/' });
                            $.cookie('language', $("#language").val(), { path: '/' });
                            $.cookie('country', $("#country").val(), { path: '/' });
                        }
*/
                    }

                    // remove overlay
                    // hideOverlay();
                    //location.reload();
                }
            }
        });
    };



    /**
    * Set remember me state
    *  
    * @return void
    * @public
    */
    var rememberMe = function (element) {
        $(element).toggleClass('selected');
    };



    /**
    * Show dropdown
    *  
    * @return void
    * @public
    */
    // var showDropDown = function(element) {
    // 	$(element).addClass('hover');
    // 	$(element).find('ul').stop().animate({
    // 		opacity:1
    // 	},250);
    // };



    /**
    * Hide dropdown
    *  
    * @return void
    * @public
    */
    // var hideDropDown = function(element, selectedDropdown) {
    // 	$(element).find('ul').stop().animate({
    // 		opacity:0
    // 	},250, function(){
    // 		$(element).removeClass('hover');
    // 		if (selectedDropdown != null) {
    // 			showDropDown(selectedDropdown);
    // 		}
    // 	});
    // };



    /**
    * dropdown element selected, change state
    *  
    * @return void
    * @public
    */
    var dropDownSelected = function (element) {

        // ensure the radio button is now selected
        $(element).attr('checked', true);

        // hide overlay
        var parentDropDown = $(element).parents()[3];
        hideDropDown(parentDropDown);

        // set selected text
        var selectedText = $(element).val();
        $(parentDropDown).find('p span').text(selectedText);
    };



    /**
    * Return value, expose certain methods above
    */
    return {
        init: init,
        createOverlay: createOverlay
    };
} ();
