/*
    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.
*/
// ============================================================================
// 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;
}
/*
 * Get the absolute position of a given element
 *
 * This function is used by Appbase Javascript utils.
 * Do not change!
 */
function getAbsolutePos(el){
    for (var lx=0,ly=0;el!=null;
    lx+=el.offsetLeft,ly+=el.offsetTop,el=el.offsetParent);
    return {x:lx,y:ly}
}

/*
 * Set the layer with the given id to
 * display:block.
 *
 * This function is used by Appbase Javascript utils.
 * Do not change!
 */
function displayLayer(layerId) {
    if(typeof $(layerId) != "undefined") {
        $(layerId).style.display = 'block';
    }
}

/*
 * Set the layer with a given id to
 * display:inline, position:absolute
 *
 * This function is used by Appbase Javascript utils.
 * Do not change!
 */
function hoverLayer(layerId) {
    if(typeof $(layerId) != "undefined") {
        $(layerId).style.display = 'inline';
        $(layerId).style.position = 'absolute';
    }
}

/*
 * 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) {
    hovermenus = $('hovermenu-' + id).getElementsByClassName('hovermenuitem');
    for(i=0;i<hovermenus.length;i++) {
       hovermenus[i].style.display = 'none';
    }
}

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

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


function slideshowFadeFromTo(current, tileId, direction) {
    // Get all slideshow images in this container
	var images  = $$('div#tile'+tileId+' div.slideshow-image');
	
	// Find the next image
	if(direction == 'previous') {
        next = current - 1;
        if(next < 0) {
            next = images.length - 1;
        }
	} else {
	    next = current + 1;
	    if(next >= images.length) {
	       next = 0;
        }
    } 
                
	var currentImage = images[current];
	var nextImage = images[next];
	
	try {
	    new Effect.Appear(nextImage, {
	        duration: 0.5,
	        afterUpdate: function(effect) {
	            // If this is the first frame, we hide the current
	            // image. We do this here to avoid flicker that
	            // occurs when removing image before effect fades in
	            if(effect.currentFrame == 0) {
	                currentImage.hide();
	            }
	        }
	    });
    } catch (e) {
	    // No scriptaculous - hide/show without effect
	    currentImage.hide();
	    nextImage.show();
    }
    
    return next;
}
/**
 * Extend prototype's Hash.toQueryString(), as that always encodes
 * query strings in UTF-8, which is no good for CorePublish domains
 * still using ISO charset.
 */
if(document.characterSet == "ISO-8859-1" || document.charset == 'iso-8859-1') {
    Hash.addMethods( (function() {

        // console.log("overriding Hash.toQueryString()");
       
        function toQueryPair(key, value) {
          if (Object.isUndefined(value)) return key;
          return key + '=' + escape(String.interpret(value));
        }

        return {
               toQueryString : function () {
                return this.inject([], function(results, pair) {
                    var key = escape(pair.key), values = pair.value;

                    if (values && typeof values == 'object') {
                      if (Object.isArray(values))
                        return results.concat(values.map(toQueryPair.curry(key)));
                    } else results.push(toQueryPair(key, values));
                    return results;
                  }).join('&');
                }
            } // end return
    } // end anonymous function
    )() // end function scoping
    );

    Object.extend( String.prototype,
            {
            toQueryParams: function(separator) {
                var match = this.strip().match(/([^?#]*)(#.*)?$/);
                if (!match) return { };
       
                return match[1].split(separator || '&').inject({ }, function(hash, pair) {
                  if ((pair = pair.split('='))[0]) {
                    var key = unescape(pair.shift());
                    var value = pair.length > 1 ? pair.join('=') : pair[0];
                    if (value != undefined) value = unescape(value);
       
                    if (key in hash) {
                      if (!Object.isArray(hash[key])) hash[key] = [hash[key]];
                      hash[key].push(value);
                    }
                    else hash[key] = value;
                  }
                  return hash;
                });
              }
           }
    );
}

