/* - link_block.js - */
// Allow one to set a block element to act as a link
// Produce valid html
// 
// 
// All you need is to register the block element with class="link-block"
// A mouseover effect is set in css
// The link of the block is the first encountered in the block
//
// <div class="link-block">
// <img src="" ... />
// <h1><a href="spam" alt="egg"></h1>
// </div>

// FIXME see in preview_in_cms which contain the same function
function getElementsByClassName2(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}


function gotolinkblock(){
    var aElement = this.getElementsByTagName("a"); 
    if (aElement.length > 0) {
        var target = aElement[0].getAttribute('target');
        if (target == '_blank') { // if it's an external link
            window.open(aElement[0], '', '');
            return false;
        } 
        else {
            window.location.href = aElement[0];
        }
    }
}

function linkblock() {
    // set link-block links
    blocks = getElementsByClassName2('link-block');
    for (var i=0; i<blocks.length; i++) {
	
    	//Explorer hack for mouseover, see suckerfish http://www.alistapart.com/articles/dropdowns/
    	if (window.attachEvent) {
    		blocks[i].onmouseover = function() {this.className+=" sfhover";}
    		blocks[i].onmouseout = function() {this.className=this.className.replace(new RegExp(" sfhover\\b"), "");}
    	}
    	// set link
    	blocks[i].onclick = gotolinkblock;
    }
}

registerPloneFunction(linkblock);
