/* ------------------------------------------------------------------------
 * core.js
 * Copyright (c) Perfect Memorials. All rights reserved.
 * ------------------------------------------------------------------------ */
 
// DOM onload handler - calls init functions
$(document).ready(function(){
    PMTCore.javascriptEnabled();
    PMTCore.setEventHandlers();
    PMTCore.roundMessageCorners();
    // Preload images
    PMTCore.preloadImages(
                            'css/busy.gif',
                            'css/eip-block-helper.png',
                            'css/eip-single-helper-left.gif',
                            'css/eip-single-helper-right.gif'
                         );
});

// -----------------------------------------------------------------------------

var PMTCore = {
    
    DEBUG:           true,
    TRIBUTE_URL:     '',
    
    PATH_IMAGES:     '/images/',
    PATH_CSS:        '/css/',
    PATH_JAVASCRIPT: '/javascript/',
    
    REGEXLIB:        {'shortTitle':'^([a-z0-9\-])+$'},
    
    ajaxInited:      false,
    preloadedImages: [],
    
    javascriptEnabled: function(){
        $('body').removeClass('nojs');
    },
    
    setEventHandlers: function(){
    	// Attach double click protection to forms
        $('form.dblclick-protect').submit(function(){
            return PMTCore.doubleClickProtect(this);
        });
        
    	// Show the login form onclick
    	$('#global-login a').click(function() {
    		$(this).hide();
    		$('#global-login-form').fadeIn('slow', PMTCore.focusUsernameField);
    		return false;
    	});
    	
    	// Attach toggle event handler to hints hide links
        $('.hint a.toggler').click(function(){
            PMTCore.toggleHint(this);
            return false;
        });
    	
        // IE only related JavaScript
        if($.browser.msie){
            // Replicate the CSS pseudo-selector :focus for form inputs and texareas
            $('form input,form textarea').focus(function(){ $(this).addClass('focus'); });
            $('form input,form textarea').blur(function(){ $(this).removeClass('focus'); });
            // PNG Fix (IE 5.5 and 6)
            if($.browser.version >= 5.5 && $.browser.version < 7){
                $.getScript(PMTCore.PATH_JAVASCRIPT + 'lib/jquery/jquery.ifixpng-2.0.js', function(){
                    $('img[@src$=.png], div#footer, .give-feedback, .feedback-thanks, #tribute-photo, #secondary-sidebar dd.photos a.frame, .contrib-photo a.frame, .contrib-photo-comment a.frame, .tribute a.frame, .tribute-alt a.frame, #header #examples a, #main #primary .feature').ifixpng();
                });
            }
        }
    },
    
    initAjax: function(){
        if(PMTCore.ajaxInited){
            return;
        }
        $.ajaxSetup({
            type:     'POST',
            dataType: 'json',
            cache:    false,
            timeout:  20000
        });
        PMTCore.ajaxInited = true;
    },
    
    roundMessageCorners: function(){
    	$('.message').corner('round top 12px');
    	$('.message').corner('round bottom 12px');
    },

    focusUsernameField: function(){
        var fieldRef = $('#top-username');
        if(fieldRef){
            fieldRef.focus();
        }
    },
    
    applyFieldsetLastRow: function(fieldsetId){
        $('#' + fieldsetId + ' .last').removeClass('last');
        var lastRow = $('#' + fieldsetId + ' .row:not(.hide):last');
        lastRow.addClass('last');
    },
    
    doubleClickProtect: function(formElement){
        // Prevent form being resubmitted by keyboard (ENTER key)
        $(document).keypress(function(e){
            var key = e.keyCode;
            return (key != 13);
        });
    	// Disable submit button, change styling and text
    	var $button = $(formElement).find('button.positive');
    	$button.blur();
        $button.attr('disabled', 'disabled');
    	$button.addClass('busy').removeClass('positive');
    	$button.find('span').html('Saving...');
        return true;
    },
    
    reenableSubmit: function(formID, btnText){
    	// Enable submit button, change styling and text
        var $button = $('#' + formID).find('button.busy');
    	$button.removeAttr('disabled');
    	$button.addClass('positive').removeClass('busy');
        $button.find('span').html(btnText);
        return true;
    },
    
    toggleHint: function(anchorElmt){
        $anchorElmt = $(anchorElmt);
        $anchorElmt.blur();
        // Retrieve hint container element
        var hintContainer   = $(anchorElmt).parents('dl.hint');
        // Toggle display of hint
        hintContainer.fadeOut('normal', function(){
            hintContainer.addClass('hide');
        });
        // Save user's hide preference
        var hintShortTitle = $anchorElmt.attr('id');
        if(hintShortTitle){
            // Prepare data
            var data = {hint_short_title:hintShortTitle,save:true};
            // Save preference via AJAX
            PMTCore.initAjax();
            $.ajax({
                url:       '/hide-hint/',
                data:      data
            });
        }
    },
    
    generateShortTitle: function(title){
        title = title.replace(/^[\s\-]*/, "")
                .replace(/[\s\-]*$/, "")
                .replace(/([^a-z0-9\-\s])/gi, "")
                .replace(/\s+/g, " ")
                .replace(/\s/g, "-")
                .replace(/\-+/g, "-")
                .toLowerCase();
        return title;
    },
    
    getRegExp: function(regExpName){
        if(PMTCore.REGEXLIB[regExpName]){
            return new RegExp(PMTCore.REGEXLIB[regExpName]);
        }
        return false;
    },
    
    preloadImages: function(){
        if(!document.createElement){
            return false;
        }
        var index, imgPath;
        for(var i = 0; i < arguments.length; i++){
            index   = PMTCore.preloadedImages.length;
            imgPath = (PMTCore.PATH_IMAGES + arguments[i]);
            PMTCore.preloadedImages[index] = document.createElement('img');
            PMTCore.preloadedImages[index].setAttribute('src', imgPath);
        }
    }

};