/*
    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.
*/

/*
 * 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']);
    }
});


/*
 * Displays a hovering item over the given element. 
 *  *
 * This function is used by Appbase Javascript utils.
 * Do not change!
 */
function hoverLayer(layerId, element) {
    if(typeof $(layerId) != "undefined") {
        hover = $(layerId);
        hover.style.position = 'absolute';
        
        hover.setStyle({
            left: element.positionedOffset()['left'] - 2 + "px",
            top: element.positionedOffset()['top'] - 4 + "px",
            zIndex: "10"
        });
        
        hover.style.display = 'block';
    }
}

/*
 * Set a layer to display:none
 *
 * This function is used by Appbase Javascript utils.
 * Do not change!
 */
function hideLayer(layerId) {
    if(typeof $(layerId) != "undefined") {
        $(layerId).style.display = 'none';
    }
}

/*
 * Delegate function used by the hovermenu to hide
 * all hovering layers.
 *
 * This function is used by Appbase Javascript utils.
 * Do not change!
 */
var hideAllHovermenuItems = function(id) {
    $$('*.hovermenuitem').each(function(element) { element.hide(); });
}

/*
 * Function to get the mouse position from event
 *
 * This function is used by Appbase Javascript utils.
 * Do not change!
 */
function getMousePosition(event) {
    var pos;

    if (!event) var event = window.event;
	if (event.pageX || event.pageY) 	{
		posx = event.pageX;
		posy = event.pageY;
	}
    else if (event.clientX || event.clientY) 	{
		posx = event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
		posy = event.clientY + document.body.scrollTop + document.documentElement.scrollTop;
	}

	return {x:posx,y:posy};
}

/*
 * Display a hovering popup layer.
 *
 * This function is used by Appbase Javascript utils.
 * Do not change!
 *
 * Layer will be absolute positioned and positioned
 * according to options. Default is to display the
 * popup with a small right offset to the mouse pointer.
 *
 * Options has to be of type Object, and the following
 * assosiated attributes can be used to configure popup:
 *   - x, override the x offset
 *   - y, override the y offset
 *   - fixedPosition, layer will be positioned at the fixed x/y position
 */
function popupLayerEvent(event, layerId, options) {
    if($(layerId) != null) {
        pos = getMousePosition(event);

        if(typeof options == "undefined") {
            var options = new Object();
        }

        var offsetY = 18;
        var offsetX = 14;
        if(typeof options['x'] != "undefined") {
            offsetX = options['x'];
        }

        if(typeof options['y'] != "undefined") {
            offsetY = options['y'];
        }

        var element = $(layerId);

        element.style.display = 'block';
        element.style.position = 'absolute';

        if(typeof options['fixedPosition'] == "undefined" || options['fixedPosition'] == false) {
            element.style.left = pos['x'] + offsetX + 'px';
            element.style.top = pos['y'] + offsetY + 'px';
        }
    }
}

/**
 * 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;
}

/**
 * Called from smallcalendar.php tile template.
 */
function initCalendarPopupLinks() {
    var calendarCloseFunction = function(event) {
            event.stop();
            var popupElementId = event.findElement('a').id.substring(26);
            $(popupElementId).hide();
        }
        
    $$('a.calendar_popup_link').each(function(element) {
        element.observe('click', function(event) {
            event.stop();
            var link = event.findElement('a');
            var popupElementId = link.id.substring(20);
            
            link.observe('click', calendarCloseFunction);
            
            $(popupElementId).setStyle({
                left: link.positionedOffset()['left'] - 11 + "px",
                top: (link.positionedOffset()['top'] + 18) + "px"
            });
            
            $(popupElementId).show();
        });
    });
    
    $$('a.window-close-button').each(function(element) {
        element.observe('click', calendarCloseFunction);
    });
}

/**
 * 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 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;
}

/**
 * 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;
}
            
            