/*
 * Used to identify video location for conditionals
 */
$.fn.hasParent = function(objs) {
	// ensure that objs is a jQuery array
	objs = $(objs);var found = false;
	$(this[0]).parents().andSelf().each(function() {
		if ($.inArray(this, objs) != -1) {
			found = true;
			return false; // stops the each...
		}
	});
	return found;
}

/*
 * General (CMS)
 */
$(function(){
    // Search submit hover state
    $("#search-submit").hover(function(){
        $(this).attr("src","/images/search-submit-button-hover.png");
    }, function() {
        $(this).attr("src","/images/search-submit-button.png");
    });
    
    // Tooltip hovers
    $("#top ul li a.tooltip").hover(function(){
        $($(this).next()).show();
        $(this).parent().css("marginTop","5px");
    }, function() {
        $(this).next().hide();
        $(this).parent().css("marginTop","6px");
    });
    
    // Setup search helper text
    $('#search-input').focus(function(){
        if($(this).val() == ('Enter search term...')) {
            $(this).val('');
        }
    }).blur(function() {
        if($(this).val() == '') {
            $(this).val('Enter search term...');
        }
    }).blur();

    // Text size selector
    $('.text-size-selector a').click(function(){
        if ($(this).hasClass('mid-text')) {
            $('.page-content p').css("fontSize","14px").css("lineHeight","20px");
        }
        else if ($(this).hasClass('large-text')) {
            $('.page-content p').css("fontSize","16px").css("lineHeight","22px");
        }
        else {
            $('.page-content p').css("fontSize","12px").css("lineHeight","18px");
        }

        $('.text-size-selector a').css("opacity","0.8");
        $(this).css("opacity","1.0");

        return false;
    });

    // Social share modal
    $(".share-modal").live('click',function(){
        ($('#video-url').html() != null && $('#video-url').html() != false) ? loc = $('#video-url').html() : loc = window.location.href.substr(0, window.location.href.indexOf('#'));
        $.nmManual('/popup/share?url='+loc, {
            callbacks: {
                filledContent: function() {
                    Cufon.replace('.share-content h2', {
                        fontFamily: 'Knockout2',
                        hover: true
                    });
                },
                afterShowCont: function() {
                    FB.XFBML.parse();
                }
            }
        });
    });
    
    // Setup titles on all CMS links
    $('.page-content a').each(function(){
       if(!$(this).hasClass('content-button') && $(this).html().indexOf('cufon') != '0') { 
           $(this).attr('title', $(this).text()); 
       }
    });
    
    // Keyboard shortcuts for accessibility
    $(document).bind('keystrokes', {keys: ['alt+0']}, function(event){
        window.location.href = '/';
    });
    $(document).bind('keystrokes', {keys: ['alt+1']}, function(event){
        window.location.href = '/about-the-job';
    });
    $(document).bind('keystrokes', {keys: ['alt+2']}, function(event){
        window.location.href = '/application-process';
    });
    $(document).bind('keystrokes', {keys: ['alt+3']}, function(event){
        window.location.href = '/apply-now';
    });
    $(document).bind('keystrokes', {keys: ['alt+4']}, function(event){
        window.location.href = '/other/contact';
    });
    $(document).bind('keystrokes', {keys: ['alt+5']}, function(event){
        window.location.href = '/registration/login';
    });
    
    //JS form submit for images
    $(".a-act-as-submit, .a-submit").live('click',function(){
        $(this).parents("form").submit();
        return false;
    });
    
    // Setup more info expanders on /about-the-job/possible-careers page
    $('#default-content .possible-careers ul li p').each(function(i){
        //$(this).parent().css("z-index","10");
        $(this)
            .parent()
            .contents().filter(function(){return this.nodeType === 3}) // Looking for text nodes
            .wrap($('<a></a>', {className: 'expand closed', href: '#'} ));
            
        if($(this).parent().children('a').size() > 1) { $(this).parent().children('a:last-child').remove(); }
           
        $(this).absolutize();
            
    }).hide();
    
    $('#default-content .possible-careers ul li a.expand').click(function(){
        var p = $(this).parent().find('p');
        
        /* IE7 tweak - In progress
        var li = $(this).parent();
        var p = li.find('p.' + li.attr('class'));
        
        var ul = li.parents('ul');
        p.insertBefore(ul);
        */
       
        if(p.length > 0) {
            if(p.is(':visible')) {
                $(this).removeClass('open').addClass('closed');
                p.slideUp();
            } else {
                // Close other open bubbles
                var open = $(this).parents('ul').find('a.expand.open');
                open.removeClass('open').addClass('closed');
                open.parent().find('p').slideUp();  

                // Open paragraph in selected anchor
                $(this).removeClass('closed').addClass('open');
                p.slideDown();   
            }
        }
        return false;
    });
    
    // Add names to faq titles
    $('#default-content .faqs ol li strong').each(function(i) {
        $(this).wrap($('<a></a>', {className: 'faq_link', id: 'faq' + (i+1)} ));
    });
 
});

function isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n); }

/*
 * Forms (General)
 */
$(function(){
    
    // Mobile number validator
    $(document).ready(function(){
        // Custom SMS number validator
        jQuery.validator.addMethod("mobile", function(value, element) {
            return /^[0-9]{6,8}$/.test(value);
        }, "Enter a valid number e.g. 1234567");
        
        
        jQuery.validator.addMethod("custom_password", function(value, element) {
            if(value == '') return true;
            
            totalNumbers = 0;
            totalAlphabet = 0;
            
            splitContent = value.split("");
            
            $(splitContent).each(function(){            
                if(isNumber(this))
                {
                    totalNumbers++;
                }
                else
                {
                    totalAlphabet++;
                }
            });
            
            return (totalNumbers < 2 || totalAlphabet < 2) ? false : true;
            
        }, "You need to use at least 8 characters, including at least 2 numbers and 2 letters.");
        
    });
});

/*
 *  Test registration form
 */
$(function(){    
    $('#test_submit').live('click', function(){
        // Do not proceed if form invalid
        if(!$('#test_reg_form').valid()) {
            return false;
        }

        // Save form data
        $.post('/testRegistration/process',
            $('#test_reg_form').serialize(),
            function(data){

                if(data.criminal)
                {
                    window.location = '/admin/default/criminal';
                    return;
                }

                // Show error if present
                if(data.success) {
                    
                    // Display test modal
                    $.nmManual('/popup/test', {
                        callbacks: {
                            filledContent: function() {
                                cufon();
                                resetTest();
                            },
                            afterClose: function() { return window.location.reload(); }
                        }
                    });
                } else {
                    alert(data.error);
                }
            }, "json"
        );
        return false;
    });
    
    // Already logged in - go staight to test
    // Also reloads test if user fails
    $('#test_open, a.restart_test').live('click', function(){
        $.nmManual('/popup/test', {
            callbacks: {
                filledContent: function() {
                    cufon(); 
                    resetTest();
                },
                afterClose: function() { return window.location.reload(); }
            }
        });
        return false;
    });
});

/*
 * Quiz registration form
 */
$(function(){ 
    // Display quiz
    $('a[href="/popup/eligibility"], a[href="/popup/eligibility/"], a.popup-test').click(function(){
        $.nmManual('/popup/quiz', {
            callbacks: {
                filledContent: function() {
                    Cufon.replace('h1, h2, h3, .time, #tally, .html p, .html', {
                        fontFamily: 'Knockout2'
                    });
                },
                afterClose: function() { return window.location.reload(); }
            }
        });
        return false;
    });
    // Submit quiz reg form
    $('#quiz_submit').live('click', function(){
        // Do not proceed if form invalid
        if(!$('#quiz_reg_form').valid()) {
            return false;
        }
        // Save form data
        $.post('/testRegistration/process',
            $('#quiz_reg_form').serialize(),
            function(data){
                if(data.success) {
                    $('#reg_form').hide();
                    $('#quiz').show();
                } else {
                    alert(data.error);
                }
            }, "json"
        );
        return false;
    });
});

/*
 * Stay informed registration
 */
$(function(){    
    $('a[href="/popup/stay-informed"]').click(function(){
        $.nmManual('/popup/stayInformed', {
            callbacks: {
                filledContent: function() {
                    Cufon.replace('h1', {
                        fontFamily: 'Knockout2'
                    });
                },
                afterClose: function() { return window.location.reload(); }
            }
        });
        return false;
    });
    // Submit stay informed reg form
    $('#informed_submit').live('click', function(){
        // Do not proceed if form invalid
        if(!$('#informed_reg_form').valid()) {
            return false;
        }
        // Save form data
        $.post('/popup/stayInformed',
            $('#informed_reg_form').serialize(),
            function(data){ 
                
                if(data == null){
                    alert('Please fill out all of the required fields');
                    return false;
                }
                
                if(data.success) {
                    $('#stay_informed').html($('<p></p>', {html: data.html} ));
                } else {
                    alert(data.error);
                }
            }, "json"
        );
        return false;
    });
});

/*
 * Video registration form
 */
$(function(){    
    $('#video_submit').live('click', function(){
        // Do not proceed if form invalid
        if(!$('#video_reg_form').valid()) {
            return false;
        }

    });
});

/*
 * Edit profile form
 */
$(function(){ 
    // Required to use live on submit button to prevent infinite loop with form submit below
    $('#profile_submit').live('click', function() {
        // Do not proceed if form invalid
        if(!$('#edit_profile').valid()) {
            return false;
        }

        // Check email validity
        $.post('/registration/checkEmail', 
            {
                email: $('#person_email').val()
            },
            function(data) {
                if(data.success) {
                    if(data.unique) {
                        // Remove error message if present
                        var ul = $('#person_email').parent('li').find('ul.error_list');
                        if(ul.length) {
                            ul.remove();
                        }
                        $('#edit_profile').submit();
                    } else {
                        // Display error message
                        $('<ul class="error_list"><li>This email address is already registered.</li></ul>').insertAfter('#person_email');
                    }
                } else {
                    alert('Your session has expired.');
                }
            }, 'json'
        );
        return false;
    });    
});

/*
 * Recruitment steps & checklist profile pages
 */
$(function(){
    // Cancel button - blank inputs and uncheck checkboxes (recruitment steps page)
    $('#recruitment_steps .buttons a.cancel').live('click', function() {
      $('ul.steps').find('input').val('');
      $('ul.steps').find('input[type=checkbox]').attr('checked', false);
    });
    
    // Blank inputs and uncheck checkboxes (checklist page)
    $('#application_steps .buttons a.cancel').live('click', function() {
      $('ul.steps').find('input[type=checkbox].new').attr('checked', false);
    });
    
    // Validate SMS form fields (if present)
    $(document).ready(function(){
        $("#recruitment_steps").validate({
            errorPlacement: function(error, element) {
                error.insertAfter(element);
            }
        });
        // Custom SMS address/date validator
        jQuery.validator.addMethod("address", function(value, element) { 
            // Only validate if user adds address
            if($('#sms_address').val()) {
                return /^[A-Za-z0-9\ \,]*$/.test(value); 
            }
            return true;
        }, "Enter a valid address");
        
        // SMS reminder date validator
        jQuery.validator.addMethod("date", function(value, element) { 
            // Only validate date if address present
            if($('#sms_address').val()) {
                var today = new Date();
                var parts = ($('#sms_date').val()).split('-');
                var time = value.split(':');
                var date = new Date(parts[2], parts[1]-1, parts[0], time[0], time[1]);
                
                if(parts[0] == date.getDate() && parts[1] == (date.getMonth() + 1) && parts[2] == date.getFullYear()){     
                    if(date.getTime() >= today.getTime()) {
                        return true;
                    }
                }
                return false;
            }
            return true;
        }, "Enter a valid date & time");
    });
});

/*
 * PAT/PCT video popups
 */
$(function(){ 
    $('a[href="/popup/video/pat"], a[href="/popup/video/pct"]').click(function(event){
        event.preventDefault();
        $.nmManual($(this).attr("href"), {
            callbacks: {
                filledContent: function() {
                    $('.nyroModalCont').addClass('moviePopup');
                },
                afterShowCont: function() {
                    initPlayer(640, 480);
                }
            },
            sizes: {
                minW: 640,
                minH: 550
            }
        });
    });
});

/*
 * VIDEO PLAYER
 */
function initPlayer(width, height, fromBrowser) {
    
    (fromBrowser != null && fromBrowser != false) ? emailURL = fromBrowser : emailURL = window.location;
    
    $('#main_player').mediaelementplayer({
        videoWidth: width,
        videoHeight: height,
        mode: 'shim',
        features: ['playpause','stop','volume','current','progress','duration'],
        error: function(data) {
            alert('An error occurred when playing your video. Please ensure you have flash installed correctly. Alternatively, click the video to open it on your computer.');
        },
        success: function(mediaElement) {
            if($('#player-container').length != 0) {
                mediaElement.addEventListener('ended', function(e) {
                        $.ajax({
                            url: '/loadPoster',
                            success: function(data) {
                                $('#player-container').html(data);
                                Cufon.replace('.knockout' , {
                                    fontFamily: 'Knockout2',
                                    hover: true
                                });
                            }
                        });
                }, false);
                
                mediaElement.addEventListener('stop', function(e) {
                        $.ajax({
                            url: '/loadPoster',
                            success: function(data) {
                                $('#player-container').html(data);
                                Cufon.replace('.knockout' , {
                                    fontFamily: 'Knockout2',
                                    hover: true
                                });
                            }
                        });
                }, false);
            }
            mediaElement.addEventListener('timeupdate', function(e) { }, false);

            $('.mejs-layers').prepend('<div class="video-header"></div>');
            $('.video-header')
                .append('<div class="generated-content"></div>')
                .append('<a href="#" class="video-header-button info"><span>Share</span></a>')
                .append('<div class="information"></div>');
            $('.video-header div.generated-content')
                .append('<span id="generated-title">'+$('#video-title').html()+'</span>')
                .append('<span id="generated-description">'+$('#video-description').html()+'</span>');
            $(".video-header .information")
                .append('<div class="info-title">INFORMATION</div>')
                .append('<div class="info-details"></div>');
            $('.info-details')
                .append('<span class="video-title">'+$('#video-title').html()+'</span>')
                .append('<span class="video-description">'+$('#video-description').html()+'</span>');
            $('.video-description').append('<div class=" video-buttons"></span>');
            $('.video-buttons')
                .append('<a href="#" class="share-button share-modal"><span>Share</span></a>')
                .append('<a href="mailto:friend@email.co.nz?subject=New Cops&amp;body=Check out '+emailURL+' on the New Cops Website!" class="email-button"><span>Email</span></a>');
            $('<span class="seperator"></span>').insertAfter('.mejs-stop-button');
            $('<span class="seperator"></span>').insertAfter('.mejs-volume-button');
            $('<span class="seperator right-controls-start"></span>').insertAfter($('.mejs-duration').parent());
            $('<span class="mejs-button mejs-lightsout-button"><span></span></span>').insertAfter('.right-controls-start');
            if($('#player-container').length == 0) {
                $('<span class="label lights">Lights</span>').insertAfter('.mejs-lightsout-button');
                $('#browser a').live('click',function(){mediaElement.stop();});
            }

            $('.video-header a.info').click(function(){$('.video-header .information').toggle();return false;});
            $("#browser a").click(function(){mediaElement.removeEventListener('timeupdate');mediaElement.removeEventListener('stop');});

            Cufon.replace('.label, #generated-title, #generated-description, .info-title, .info-details' , {
                fontFamily: 'Knockout2',
                hover: true
            });
            
            Cufon.CSS.ready(function() {
                $('.mejs-controls').css('bottom','0px');
                mediaElement.play();
            });
        }
    });
}

/*
 * VIDEO BROWSER & CUSTOM VIDEO PLAYER FUNCTIONALITY
 */
$(function(){

    $(".mejs-lightsout-button").live('click',function(){
        if($(".lightsout").length == 0) {
            $("<div class=\"lightsout\" title=\"Turn the lights back on\"></div>").insertBefore(".lights-stack");
            $(".lightsout").fadeIn("slow");
        }
        else {
            $('.lightsout').fadeOut('slow',function(){
                $('.lightsout').remove();
            });
        }
    });

    $(".lightsout").live('click',function(){
        $(this).fadeOut('slow',function(){
            $(this).remove();
        });
    });

    var itemCount = $("#browser").children().length;
    var current = 1;
    var moving = false;
    updateArrows(); // initially check if we need arrows
    
    $("a.left").click(function(e){
        e.preventDefault();
        
        if(current > 1 && moving == false)
        {
            moving = true;
            current--;
            $("#browser").animate({ marginLeft: '+=139px' }, 500, function(){ moving = false; });
        }
        
        updateArrows();
    });

    $("a.right").click(function(e){
        e.preventDefault();
        
        if(current <= (itemCount - 5) && moving == false)
        {
            moving = true;
            current++;
            $("#browser").animate({ marginLeft: '-=139px' }, 500, function(){ moving = false; });
        }
        
        updateArrows();
    });

    function updateArrows()
    {
        if(current == 1) $("a.left").fadeOut();
        else $("a.left").fadeIn();
        
        if(current == (itemCount - 4) || itemCount < 6) $("a.right").fadeOut();
        else $("a.right").fadeIn();
    }

    if($('video').length != 0) {initPlayer(725, 373);}

    //Load player through browser
    $("#browser a").click(function(event){
        event.preventDefault(); 
        emailURL = window.location+$(this).attr('href');
            
        if($.browser.msie) { window.location = $(this).attr('href');return; }
        
        d = $('#'+$(this).attr('id')+' .meta-description').html();
        t = $('#'+$(this).attr('id')+' .meta-title').html();
        u = $('#'+$(this).attr('id')+' .meta-url').html();
        p = $('#'+$(this).attr('id')+' .meta-poster').html();
        i = $('#'+$(this).attr('id')+' .meta-id').html();
        page = $('#'+$(this).attr('id')+' .meta-page').html();
        
        initial = 'title='+t+'&description='+d+'&url='+u+'&poster='+p;
        (i != null && page != null) ? send=initial+'&id='+i+'&page='+page : send=initial;
        
        $('#main_player').remove();
        $.ajax({
            url: '/loadVideo',
            data: send,
            success: function(data) {$('#video-container').html(data);initPlayer(725, 373, emailURL);}
        });
    });
});

$("#homepage-player a").live('click',function(event){
   
   if($(this).hasClass('more') || $(this).hasClass('email-button')) { return; }
   else { event.preventDefault(); }
   
   if(!$(this).hasParent('.mejs-controls')) {
            d = $(this).parents('.video').children('.meta-description').html();
            t = $(this).parents('.video').children('.meta-title').html();
            u = $(this).parents('.video').children('.meta-url').html();
            p = $(this).parents('.video').children('.meta-poster').html();

            $('#main_player').remove();
            $.ajax({
                url: '/loadVideo',
                data: 'title='+t+'&description='+d+'&url='+u+'&poster='+p,
                success: function(data) {$('#player-container').html(data); initPlayer(568, 292);}
            });
   }
   
});
