/*
   SiteComponents version:
   Id: sitecomponents.js,v 1.19 2009/04/27 12:21:43 kurt Exp 
   Name: SC_6_6_0 
   
   Disclaimer
   
   While we make every effort to ensure that this code is fit for its intended
   purpose, we make no guarantees as to its functionality. CoreTrek AS will
   accept no responsibility for the loss of data or any other damage or
   financial loss caused by use of this code.
   
   Copyright
   
   This programming code is copyright of CoreTrek AS. Permission to run this
   code is given to approved users of CoreTrek's publishing system CorePublish.
   
   This source code may not be copied, modified or otherwise repurposed for use
   by a third party without the written permission of CoreTrek AS.
   
   Contact webmaster@coretrek.com for information.
  
*/

// ============================================================================
// Extensions to protototype.js

/*
 * Register timeout responder to the prototype Ajax requests. This will prevent
 * an Ajax requests running indefinitly when the requested page can not be
 * accessed. The responder will make this behaviour default on all prototype
 * Ajax requests.
 *
 * Timeout is set to 5 seconds
 */
Ajax.Responders.register({
    onCreate: function(request) {
        request['timeoutId'] = window.setTimeout(function() {
            switch(request.transport.readyState) {
                case 0: case 1: case 2: case 3:
                    request.transport.abort();
                    if(request.options['onFailure']) {
                        request.options['onFailure'](request.transport, request.json);
                    }
                    break;
            }
        }, 5000);
    },

    onComplete: function(request) {
        window.clearTimeout(request['timeoutId']);
    }
});

/**
 * Lets extend the prototype.js Element class with some usefull methods
 */
var siteComponentsElementMethods = {
    
    /**
     * Since there are no good ways of getting an invisible element
     * (display:none) size on the Element, we add this our selves.
     */
    getHiddenElementDimensions: function(element) {
        element = $(element);
        
        var visibility = element.getStyle('visibility');
        var display = element.getStyle('display');
        var position = element.getStyle('position');
        
        element.setStyle({ visibility: 'hidden', display: 'block', position: 'absolute' });
        
        var height = element.getHeight();
        var width = element.getWidth();
        
        element.setStyle({ visibility: visibility, display: display, position: position });
        
        return { height: height, width: width };
    },
    
    /**
     * Returns a px value from the elements style definition. The style must be
     * defined with a numeric px value, e.g. 450px (will return 450).
     * Percentages etc. is invalid. If the definition is not set, or the value
     * is invalid the function will return 0.
     */
    getDimensionFromStyle: function(element, style) {
        var styleValue = element.getStyle(style);
        if(styleValue != null) {
            var match = styleValue.match(/^([0-9]+)px$/);
            if(match.length == 2) {
                return parseInt(match[1]);
            } else {
                return 0;
            }
        } else {
            return 0;
        }
    }
    
};

Element.addMethods(siteComponentsElementMethods);

// ============================================================================
// Standalone JavaScript functions

/**
 * Function that return site components config value based on component and
 * config
 *
 * @param component
 * @param parameter
 */
function getSiteComponentsConfig(component, parameter, defaultValue) {
    if(typeof siteComponentsConfig != 'undefined' &&
       typeof siteComponentsConfig[component] != 'undefined' &&
       siteComponentsConfig[component][parameter] != 'undefined') {
       return siteComponentsConfig[component][parameter];
    }
    if(typeof defaultValue != 'undefined') {
        return defaultValue;
    }
    return null;
}

/**
 * Function to invoke an Ajax request for recommending a entity comment post
 *
 * @param int commentId the comment post id to recommend
 */
function recommendCommentPost(commentId) {
    new Ajax.Updater({ success: 'commentpost-rating-' + commentId }, 
    '/xmlhttprequest.php?service=entity.rate', {
        parameters: {
            entity_id: commentId,
            entity_type: 'EntityCommentPost',
            rating: '99'
        }
    });

    return false;
}

/**
 * Function to invoke an Ajax request for agreeing or disagreeing with an
 * article
 *
 * @param int articleId the article in question
 * @param boolean agree true to agree, false to disagree
 */
function articleOpinion(articleId, agree) {
    new Ajax.Updater({ success: 'article-opinion-' + articleId + '-' + (agree?'agree':'disagree') },
        '/xmlhttprequest.php?service=entity.rate', {
        parameters: {
            entity_id: articleId,
            entity_type: 'Article',
            rating: agree?99:1
        }
    });

    return false;
}

/**
 * Resolve the theme name from style includes.
 */
function getThemeName() {
    if(typeof themeName == 'undefined') {
        var stylesheets = $$('link[rel=stylesheet]');
        if(stylesheets.size() > 0) {
            var url = stylesheets[0].readAttribute('href');
            url = url.substring(0, url.lastIndexOf('/'));

            // Set as global variable so we dont have to resolve on every call
            themeName = url.substring(url.lastIndexOf('/') + 1);
        }
    }

    return themeName;
}

/**
 * Regenerate all captchas on page
 */
function regenerateAllCaptchas() {
    var rand = Math.floor(Math.random()*100000);
    $$('div.captcha-image img').each(function(image) {
        image.src = image.src + '&amp;rand=' + rand;
    });
}

/**
 * NOP wrapper for console.log. Adding this removes JavaScript warnings in
 * IE if anyone has forgotten to remove console.log statements.
 *
 * TODO: This will in turn be overridden in debug.js (if debug is enabled).
 * debug.js will display errors if there is any console.log statements left in
 * the code.
 */
 /*
if(typeof console == 'undefined' || typeof console.log != 'function') {
    console = new Object();
    console.log = function(message) { }
}*/
