/*********************************************************************************
  *	This script is property of 
  * G8media Advertising, Hamburg (Germany) 
  * http://www.g8media.de 
  * Author: Sascha "w3ksel" Schulz <s.schulz at g8media dot de>
  * Version: 1.2.1
  * 
  * If you want to use it, contact us.
  *
  * [note]
  * to enable this gallery, change the following configs and 
  * run initG8llery() when the window is loaded.
  *
  * [example]
  * window.onload = function(){ initG8llery(); }
  *
**********************************************************************************/






/*********************************************************************************
  * config
**********************************************************************************/

var cnf_g8llery = new Array();

// beginning string in rel attribute of anchors, value has to mach <setPrefix>[cmd=value][...]
cnf_g8llery['relPrefix'] = "g8llery";
// image to display large image by default (if not specified as a command)
cnf_g8llery['idDefaultView'] = "myGallery";
// tags that will be looked up for classname to represent submitted text of large image
cnf_g8llery['txtTags'] = "h2, p";
// tag wrapping whole gallery, specifieces parent node containing elements which will be looked up 
cnf_g8llery['idGalleryWrap'] = "myGallery";
// classname that will be added to current thumbnail (and removed from the previous one)
cnf_g8llery['classActiveThumb'] = "current";


// reads config array
function g8llery_getCfg(handle){
	if(cnf_g8llery[handle])	return cnf_g8llery[handle];
	else						alert("G8llery config error!");
}




/*********************************************************************************
  * helpers, delete if they are already available with same function
**********************************************************************************/

// validates type of variable to ensure it's an array
function is_array(variable){
	if(typeof(variable) == "object" && (variable instanceof Array))
		return true;
	else
		return false;
}
// removes all childes from the given node
function killChilds(node){
	node.innerHtml = '';
	while(node.childNodes[0]){
		node.removeChild(node.childNodes[0]);
	}
}






/*********************************************************************************
  * initiate g8llery
**********************************************************************************/

// disable this method if you call the initialisation manually
// window.onload = function(){ initG8llery(); }

// method has to be called to enable g8llery
function initG8llery(){
	var relItems = g8llery_getRelAnchors();
	g8llery_modifyElements(relItems);
}





/*********************************************************************************
  * config pi
  *
  * DEPRECATED, use g8llery_getCfg() instead!
**********************************************************************************/

function g8llery_getRelPrefix(){
	return g8llery_getCfg('relPrefix');
}
function g8llery_getIdDefaultView(){
	return g8llery_getCfg('idDefaultView');
}
function g8llery_getTxtTags(){
	return g8llery_getCfg('txtTags');
}
function g8llery_getIdGalleryWrap(){
	return g8llery_getCfg('idGalleryWrap');
}
function g8llery_getClassActiveThumb(){
	return g8llery_getCfg('classActiveThumb');
}





/*********************************************************************************
  * core methods
**********************************************************************************/

// returns all anchors having the "rel"-tag with valid pattern
function g8llery_getRelAnchors(){
	var rel = g8llery_getRelPrefix();
	var anchors = document.getElementsByTagName("a");
	var rels = new Array();
	var regex = new RegExp("^"+rel+"(\\[[(special|target|href)=[a-zA-Z0-9\\-\\_\\.\\/\\:]+\\])*$");
	// browse anchors
	for(var i=0; i< anchors.length; i++){
		if(anchors[i].rel && regex.test(anchors[i].rel))
			rels.push(anchors[i]);
	}
	// return matches
	return rels;
}

// attaches an "onclick"-handler to given elements
function g8llery_modifyElements(stack){
	// verify param type
	if(!is_array(stack))		return false;
	// browse stack
	for(var i=0; i<stack.length; i++){
		if(!stack[i].href)		continue;
		// add handler
		stack[i].onclick = g8llery_swapItem;				
	}
	// success
	return true;
}
	
// is called by every "onclick"-handler. swaps image src and texts
function g8llery_swapItem(){
	// get commands
	var cmds = g8llery_getCmds(this.rel);
	// set image target
	var imgTarget = (cmds["target"] && document.getElementById(cmds["target"])) ?
		document.getElementById(cmds["target"]) : document.getElementById(g8llery_getCfg('idDefaultView'));
	// get thumbnails of target
	var thumbnails = g8llery_getThumbnails(imgTarget);
	// get position current thumbnail
	var curPos = g8llery_getThumbPos(imgTarget, thumbnails);
	// define next thumbnail
	if(cmds["special"])	var thumbNext = g8llery_getSpecial(imgTarget, cmds["special"]);
	if(!thumbNext)			var thumbNext = this;
	// define href
	var targetHref = (cmds["href"]) ? cmds["href"] : "";
	
	// swap current item
	if(thumbnails[curPos]) thumbnails[curPos].className = "";
	thumbNext.className = g8llery_getClassActiveThumb();
	g8llery_swapText(thumbNext.title, imgTarget.id);
	imgTarget.src = thumbNext.href;
	g8llery_setLink(imgTarget, targetHref);
	
	// negative return to forbid browser to follow link
	return false;
}

// returns array of commands from string. Will be provied with raw String from "rel"-tag
function g8llery_getCmds(str){
	var regex = new RegExp("((special|target|href)=[a-zA-Z0-9\\-\\_\\.\\/\\:]+)+","g");
	var cmd = str.match(regex);
	var cmds = new Array();
	
	// prevent js from bombing if regex got no match
	if(!cmd)				return cmds;
	
	// browse matches
	for(var i=0; i<cmd.length; i++){
		var pos = cmd[i].indexOf("=");
		var key = cmd[i].substr(0,pos); 
		var value = cmd[i].substr(pos+1, cmd[i].length)
		cmds[key] = value;				
	}	
	return cmds;
}

// returns all anchors of thumbnails, similar to getRelAnchors but excludes "special"-items 
function g8llery_getThumbnails(target){
	var rel = g8llery_getRelPrefix();
	var anchors = document.getElementsByTagName("a");
	var rels = new Array();
	
	// set regular expression to filter elements
	var regexStr = (target.id == g8llery_getIdDefaultView()) ?
		'^'+rel+'(\\[(href=[a-zA-Z0-9\\_\\-\\.\\:\\/]+|target='+target.id+')\\])*$' :
		'^'+rel+'(\\[(href=[a-zA-Z0-9\\_\\-\\.\\:\\/]+|(target='+target.id+')+)\\])+$';
	
	var regex = new RegExp(regexStr);
	for(var i=0; i< anchors.length; i++){
		if(anchors[i].rel && regex.test(anchors[i].rel))
			rels.push(anchors[i]);
	}
	return rels;
}

// returns thumbnail pos in stack by comparing image src's
function g8llery_getThumbPos(cur, stack){
	for(var i=0; i<stack.length; i++){
		if(cur.src == stack[i].href)	return i;
	}
	return false;
}

// returns item used for special tasks such as "next" or "previous"
function g8llery_getSpecial(target, mode){
	var rels = g8llery_getThumbnails(target);
	var pos = g8llery_getThumbPos(target, rels);
	
	switch(mode){
		case "next": // next
		case "++":
			if(false === pos || pos >= rels.length-1)	pos = 0;
			else	pos += 1;
		break;
		
		case "pre": // previous
		case "previous":
		case "--":
			if(false === pos || pos <= 0) 	pos = rels.length -1;
			else	pos -=1;
		break;
		default:
			return false;
	}
	return rels[pos];
}

// swaps texts
function g8llery_swapText(rawText, targetClass){
	var wraps = g8llery_getTextWraps(targetClass);

	var textparts = rawText.split('|');
	for(var i=0; i<wraps.length; i++){
		killChilds(wraps[i]);
		if(textparts[i]){
			var text = document.createTextNode(textparts[i]);
			wraps[i].appendChild(text);
		}
	}
}

// returns text wraps by class name
function g8llery_getTextWraps(classname) {
	var wraps = new Array();
	var tags = new Array();
	var searchTags = g8llery_getCfg('txtTags').split(", ");
	var searchClass = " "+classname+" ";
	
	// set parent node 
	var domNode = (g8llery_getIdGalleryWrap().length > 0 && document.getElementById(g8llery_getIdGalleryWrap())) ?
		 document.getElementById(g8llery_getIdGalleryWrap()) : document;
	
	// repeat search for every searchTag
	for(var i=0; i<searchTags.length; i++){
		tags = domNode.getElementsByTagName(searchTags[i]);
		// compare class names of every found tag
		for(var j=0; j<tags.length; j++){
			var test = " " + tags[j].className + " ";
			if (test.indexOf(searchClass) != -1)
				wraps.push(tags[j]);
		}
	}
	return wraps;
}

// sets link for large image if possible and required 
function g8llery_setLink(target, url){
	var a = target.parentNode;
	if(a.tagName != "A" && a.tagName != "a")		return false;
	if(url.length > 0){
		a.href = url;
		a.target = "_blank";
	}
	else{
		a.removeAttribute("href");
		a.removeAttribute("target");
	}
}
