/**
 * the tooltips configuration
 *
 * @var array An array containing tooltip configuration objects
 * @access public
 */
var tooltips = [{
    selector: '.tooltipLink',
    tipClass: 'tooltipLarge'
},{
    selector: '#footer-link-flattr',
    tipClass: 'tooltipSmall'
},{
    selector: '#footer-link-amazon',
    tipClass: 'tooltipSmall'
}];

/**
 * the event-hook configuration
 *
 * @var array An array containing event-hook configuration objects
 * @access public
 */
var hooks = [{
    id: 's',
    events: 'focus blur keydown',
    callback: function(e) {
        manageHint($(this), e);
    }
}];

/**
 * adblocker default
 *
 * @var boolean FALSE as default (ads disabled)
 * @access public
 */
var adsafe = false;


/**
 * jQuery document ready loader
 *
 * This init-method is called when the DOM is ready and processes   
 *
 * @param array $instance The data for the current widget instance
 *
 * @return void
 */
$(document).ready(function() {
    // initialize the tooltips configured previously
    initTooltips();

    // hook events configured peviously
    installHooks();

    // enable smooth scrolling (easing)
    initSmoothScroll();
    
    // enable :focus and :hover for IE < 7
	initPseudoClasses();
    
    // xhtml valid external links
    prepareExternalLinks();
    
    // generate email link (mailto for contact)
    generateEmailLink('kontakt', 'phpfluesterer.de');
    
    // fix the header with the logo menu and fade bg
    //initFixedNavigation();
});


/**
 * init tooltips
 *
 * This method is intend to initialize the previously configure (tooltips Array) tooltips.   
 *
 * @return void
 */
function initTooltips()
{
    $(tooltips).each(function(index) {
        $(this.selector).tooltip({tipClass: this.tipClass});
    });
}

/**
 * install hooks
 *
 * This method is intend to install the hooks for the previously configured events.   
 *
 * @return void
 */
function installHooks()
{
    // install hooks for configured events
    for (hook in hooks) {
        $('#'+hooks[hook].id).bind(hooks[hook].events, hooks[hook].callback)
    }
}

/**
 * serving XHTML-valid external links
 *
 * This method is intend to replace the target of links (unobtrusive) via JavaScript.
 * This source is based on: 
 * http://perishablepress.com/press/2007/11/20/open-external-links-as-blank-targets-via-unobtrusive-javascript/   
 *
 * @return void
 */
function prepareExternalLinks()
{
    $('a[rel~="external"]').each(function(index) {
        this.target = '_blank';
    });
}

/**
 * smooth scroll 
 *
 * This method is intend to implement a smoother scroll effect (easing) for 
 * jumpmarks within pages.
 *
 * @return void
 */
function initSmoothScroll()
{
    $('a[href*=#]').click(function() {   
        // duration in ms
        var duration = 380;

        // easing values: swing | linear
        var easing = 'swing';

        // get / set parameters
        var newHash = this.hash;
               
        if (newHash && newHash.length > 0) {
            var target = $(this.hash).offset().top;
            var oldLocation = window.location.href.replace(window.location.hash, '');
            var newLocation = this;
            
            // make sure it's the same location      
            if(oldLocation+newHash == newLocation) {
                // animate to target and set the hash to the window.location after the animation
                $('html:not(:animated),body:not(:animated)').animate({ scrollTop: target }, duration, easing, function() {
                    // add new hash to the browser location
                    if (!$.browser.msie) {
                        window.location.href = newLocation;
                    }
                });

                // cancel default click action
                return false;
            }
         }
    });
}

/**
 * pseudo-class support for IE < 7
 *
 * This method is intend ensure X-browser compatibility of HOVER (:hover) and FOCUS (:focus).   
 *
 * @return void
 */
function initPseudoClasses()
{
    // get all required inputfields
    $('input,select,textarea').each(function(index){
        // on focus add focus class to element
        $(this).bind('focus', function(){
            $(this).addClass('focus');
        });

        // on blur remove focus class from element
        $(this).bind('blur', function(){
            $(this).removeClass('focus');
        });

        // on hover add hover class to element on release remove it
        $(this).hover(
            function(){
                $(this).addClass('hover');
            },
            function(){ 
                $(this).removeClass('hover');
            }
        );
    });
}

/**
 * generates an mailto link for given input
 *
 * This method is intend to replace links with a rel = email with an working mailto: link.   
 *
 * @return void
 */
function generateEmailLink(email, domain)
{
    $('a[rel~="email"]').each(function(index) {
        this.href = 'mailto:'+escape(email + String.fromCharCode(64) + domain);
    });
}


/***********************************************************************************************************************
 * 
 * Forms - manage hints
 * 
 **********************************************************************************************************************/
/**
 * holds the initial hints retrieved from fields
 */
var hints = new Array();
var fadeColor = '#ccc';
var colors = new Array();


function manageHint(elem, e)
{
    // decide what's to handle
    switch(e.type) {

    case 'blur':
        if (_hasInitialValue(elem) || elem.val() == '') {
            // prepare field: 
            _restoreInputFieldFromUserInput(elem);
        }
        
        e.preventDefault();
        
        break;
    case 'keydown':
        if (_hasInitialValue(elem) && e.which != 9) {
            // reset value
            elem.val('');
            
            // change color to visible
            _fadeColor(elem, colors[elem.attr('name')]);
        }
        break;
    default:
    case 'focus':
        if (!_isInitialized(elem)) {
            _initialize(elem);
        }

        if (_hasInitialValue(elem)) { 
            _prepareInputFieldForUserInput(elem);
        }
        
        e.preventDefault();
        
        break;
    }
    
    //e.stopImmediatePropagation();
}

function _restoreInputFieldFromUserInput(elem)
{
    // set cursor to beginning of existing string
    //_setCursor(elem, elem.val().length-1);
    
    _fadeColor(elem, colors[elem.attr('name')], void(0));
    
    elem.val(hints[elem.attr('name')]);
}

function _prepareInputFieldForUserInput(elem)
{    
    // set cursor to beginning of existing string
    _setCursor(elem, 0);
    
    // fade the color to a light grey
    _fadeColor(elem, fadeColor, void(0));
}

function _fadeColor(elem, color, callback)
{
    elem.animate({color: color}, 500, 'linear', callback);
}

function _hasInitialValue(elem)
{
    return (hints[elem.attr('name')] == elem.val());
}


function _setCursor(elem, pos)
{
    elem.setCursorPosition(pos);
}


function _isInitialized(elem)
{
    return !(!hints[elem.attr('name')]);
}


function _initialize(elem)
{
    // ... store if not
    hints[elem.attr('name')] = elem.val();
    colors[elem.attr('name')] = elem.css('color');
}

/***********************************************************************************************************************
 * extending jQuery
 **********************************************************************************************************************/
/**
 * show/hide the category-list
 *
 * This method is intend to show/hide the category-list with an nice jquery effect.   
 *
 * @param object The trigger-object (DOM-Object) which was clicked on
 *
 * @return void
 */
function manageCategorylist(trigger)
{
    // retrieve configuration by given trigger object
    var id               = trigger.id;
    var identifier       = id.split('-');
    var targetIdentifier = '#'+identifier[1]+'-'+identifier[2];
    
    // identifier
    var stringOpened = '&ndash;';
    var stringClosed = '+';
    
    // is currently opened ...
    if ($('#'+id).text() != stringClosed) {
        // ... its opened
        $('#'+id).html(stringClosed);
        $(targetIdentifier).hide('normal');
    } else {
        // ... seems to be closed
        $('#'+id).html(stringOpened);
        $(targetIdentifier).show('normal');
    }
}

/***********************************************************************************************************************
 * extending jQuery
 **********************************************************************************************************************/
/**
 * set cursor position support for jQuery
 *
 * This method is intend to set the cursor-position within an element to a specified position.   
 *
 * @param integer The position to set the cursor to (0 = beginning)
 *
 * @return void
 */
new function($) {
    $.fn.setCursorPosition = function(pos) {
        if ($(this).get(0).setSelectionRange) {
            $(this).get(0).setSelectionRange(pos, pos);
        } else if ($(this).get(0).createTextRange) {
            var range = $(this).get(0).createTextRange();
            range.collapse(true);
            range.moveEnd('character', pos);
            range.moveStart('character', pos);
            range.select();
        }
    }
}(jQuery);

