/*
 * Eyefi Behaviour
 *
 * Functions for easy frontend javascripting
 *
 * Documentation can be found on:
 * https://i.eyefi.nl/xiki/ECML/eyefibehaviour
 *
 * Author: Arjan Scherpenisse <arjan@eyefi.nl>
 */

var EB = new Array();

EB.namespaceprefix = "eb:";
EB.scriptprefix = "/js/";

// addEvent and removeEvent are (c) John Resig;
// http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
EB.addEvent = function( obj, type, fn ) {
	if (obj.addEventListener) {
        obj.addEventListener( type, fn, false );
    } else if (obj.attachEvent) {
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); };
		obj.attachEvent( "on"+type, obj[type+fn] );
	} else {
        obj["on"+type] = fn;
    }
};

EB.removeEvent = function( obj, type, fn ) {
	if (obj.removeEventListener) {
		obj.removeEventListener( type, fn, false );
    } else if (obj.detachEvent) {
		obj.detachEvent( "on"+type, obj[type+fn] );
		obj[type+fn] = null;
		obj["e"+type+fn] = null;
	} else {
        obj["on"+type] = null;
    }
};

EB.getElementOptions = function(el, prefix, defaults) {
    if (prefix == null) prefix = EB.namespaceprefix;
    var opts = defaults;
    for (var i=0; i<el.attributes.length; i++) {
        if (el.attributes[i].name.substr(0, prefix.length) == prefix) {
            var n = el.attributes[i].name.substr(prefix.length, el.attributes[i].name.length-prefix.length);
            opts[n] = el.attributes[i].value;
        }
    }
    return opts;
}

EB.includeScript = function(file, type) {
    var head = document.getElementsByTagName("HEAD")[0];
    if (!head) return false;

    var s = document.createElement("SCRIPT");
    if (!type) type = "text/javascript";
    s.setAttribute("type", type);
    s.setAttribute("src", file);
    head.appendChild(s);
}

EB.setCookie = function(name, value, expires, path, domain, secure) {
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

EB.getCookie = function(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else
        begin += 2;
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
        end = dc.length;
    return unescape(dc.substring(begin + prefix.length, end));
}

EB.delCookie = function(name, path, domain) {
    if (EB.getCookie(name)) {
        document.cookie = name + "=" + 
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

// get the target element of the last fired event
EB.getEventTarget = function(e) {
    if (!e) e = window.event; 
    return (e.target) ? e.target : e.srcElement;
};

EB.registerAttribute = function(tagname, attribute, callback) {
    if (typeof EB._attributes != "object") EB._attributes = new Array();
    if (typeof EB._attributes[tagname] != "object") EB._attributes[tagname] = new Array();
    EB._attributes[tagname][EB._attributes[tagname].length] = [attribute, callback];
}

EB.processAttributes = function() {
    if (typeof EB._attributes != "object") return;

    for(var tag in EB._attributes) {
        if (typeof EB._attributes[tag] == "function") continue;
        
        var elems = document.getElementsByTagName(tag);
        for (var i=0; i<elems.length; i++) {
            var eventlist = EB._attributes[tag];
            for (var j=0; j<eventlist.length; j++) { 
                if (!elems[i].getAttribute(EB.namespaceprefix+eventlist[j][0])) continue;
                eventlist[j][1](elems[i]);
            }
        }
    }
}


// Preload all images with the eb:src_mouseover behaviour
EB.addHoverImage = function(img) {

    // Check for the eb:src_mouseover tag
    var src_mouseover = img.getAttribute(EB.namespaceprefix+"src_mouseover");
    if (!src_mouseover) return;
        
    // Save the source of the original image
    img.src_original = img.src;

    // Preload the image
    var preloadimg = new Image();
    preloadimg.src = src_mouseover;
        
    // Assign mouseover() and mouseout() functions
    img.EBHoverImageOver = function(e) {
        img.src = img.getAttribute(EB.namespaceprefix+"src_mouseover");
    };
    img.EBHoverImageOut = function(e) {
        img.src = img.src_original;
    };
    
    EB.addEvent(img, "mouseover", img.EBHoverImageOver);
    EB.addEvent(img, "mouseout", img.EBHoverImageOut);
};

/**
 * Add nofocus behaviour to <A> tags with eb:nofocus="true" attribute.
 *
 * Solution: create a small <A> tag, positioned absolute in the left top,
 * and set the focus to this on a mouse release
 */
EB.addNoFocus = function(a) {
    if (!document.getElementById("EB_unfocus_dots")) {
        var e = document.createElement("A");
        e.id = "EB_unfocus_dots";
        e.href = "javascript:;";
        e.style.position = "absolute";
        e.style.top = "0"; e.style.left="0";
        document.body.appendChild(e);
    }
    document.getElementById("EB_unfocus_dots").href = a.href;
    EB.addEvent(a, "click", function() { document.getElementById("EB_unfocus_dots").focus(); } );
}

/**
 * Hover class
 * eb:class_hover="xx";
 */
EB.addHoverClass = function(el) {
    var hoverclass = el.getAttribute(EB.namespaceprefix+"class_mouseover");
    el.EBHoverClassOver = function() {
        if (el.className != hoverclass) {
            el.tmpClassName = el.className;
            el.className = hoverclass;
        }
    };
    el.EBHoverClassOut = function() {
        if (el.className == hoverclass) {
            el.className = el.tmpClassName;
        }
    };
    EB.addEvent(el, "mouseover", el.EBHoverClassOver);
    EB.addEvent(el, "mouseout", el.EBHoverClassOut);
}

/**
 * Link elements
 */
EB.linkEventOver = function(e) {
    var t = EB.getEventTarget(e);
    var linkname = t.getAttribute(EB.namespaceprefix+"link");
    for (var i=0; i<EB.links[linkname].length; i++) {
        var el = EB.links[linkname][i];
        if (el == t) continue;
        if (el.EBHoverImageOver) el.EBHoverImageOver(e);
        if (el.EBHoverClassOver) el.EBHoverClassOver(e);
        if (el.EBDivHrefOver) el.EBDivHrefOver(e);
    }
}

EB.linkEventOut = function(e) {
    var t = EB.getEventTarget(e);
    var linkname = t.getAttribute(EB.namespaceprefix+"link");
    for (var i=0; i<EB.links[linkname].length; i++) {
        var el = EB.links[linkname][i];
        if (el == t) continue;
        if (el.EBHoverClassOut) el.EBHoverClassOut(e);
        if (el.EBHoverImageOut) el.EBHoverImageOut(e);
        if (el.EBDivHrefOut) el.EBDivHrefOut(e);
        
    }
}
EB.addLink = function(x) {
    var linkname = x.getAttribute(EB.namespaceprefix+"link");
    if (typeof EB.links != "object") EB.links = new Array();
    if (typeof EB.links[linkname] != "object") EB.links[linkname] = new Array();

    EB.links[linkname][EB.links[linkname].length] = x;

    EB.addEvent(x, "mouseover", EB.linkEventOver);
    EB.addEvent(x, "mouseout", EB.linkEventOut);
}

/**
 * Toggle elements
 */
EB.toggle = function(id, attribute) {
    if (!attribute) attribute = 'style.display';
    var states = [];
    if (arguments.length < 3) {
        states = ["none", "block"];
    } else {
        var i=0;
        for (i=2;i<arguments.length;i++)
        states[states.length] = arguments[i];
    }
    
    var target = typeof id == "string"?document.getElementById(id):id;
    var l = attribute.split(".");
    var att = eval("target."+attribute);
    if (!att) eval("target."+attribute+" = '"+states[0]+"';");
    
    for (i=0; i<states.length; i++) {
        if (att == states[i]) {
            att = states[(i+1)%states.length];
            eval("target."+attribute+" = att;");
            break;
        }
    }
}

/**
 * Toggle elements in a group: only one open at the same time. 
 */
EB.toggleGroup = function(id) {
    var target = document.getElementById(id);
    if (!target) alert('toggleGroup: unknown element \''+id+'\'');

    group = target.getAttribute(EB.namespaceprefix+"togglegroup");

    if (target.style.display && target.style.display == "block") {
        target.style.display = "none";
        //EB.setCookie("EB_togglegroup_"+group, "-");
    } else {
        for (var i=0; i<EB.togglegroups[group].length; i++) {
            var el = EB.togglegroups[group][i];
            el.style.display = "none";
        }
        target.style.display = "block";
        EB.setCookie("EB_togglegroup_"+group, id);
    }
}

EB.addToggleGroup = function(el) {
    if (!EB._togglestatus) EB._togglestatus = [];
    
    var group = el.getAttribute(EB.namespaceprefix+"togglegroup");
    if (typeof EB.togglegroups != "object") EB.togglegroups = new Array();
    if (typeof EB.togglegroups[group] != "object") EB.togglegroups[group] = new Array();
    EB.togglegroups[group][EB.togglegroups[group].length] = el;

    if (!EB._togglestatus[group] && EB.getCookie("EB_togglegroup_"+group) == el.id) {
        EB.toggleGroup(el.id);
    }
}


/**
 * Initialize scrolling div
 */
EB.initScroller = function(el) {
    if(el.getAttribute(EB.namespaceprefix+"scroller") != "true") return;
	
    if (!EB.scroller) {
        EB.includeScript(EB.scriptprefix+"eb-scroller.js");
        setTimeout(function(){EB.initScroller(el);}, 100);
        return;
    }

    EB.scroller.create(el);
}


// Link to previous page
EB.goBack = function() {
    window.history.go(-1);
}

// Add a bookmark
EB.addFavorite = function(url, title) {
    if (!document.all) {
        alert('Please hit ctrl-b to bookmark this page');
    } else {
        external.AddFavorite(linkUrl,linkTitle);
    }
    return false;
}

// Check browser
EB.checkBrowser = function() {
    if (typeof EB._browser == "object") return EB._browser;
    var b = new Array();
	b.ver=navigator.appVersion; b.dom=document.getElementById?1:0;
	b.mac=(b.ver.indexOf("PPC")!= -1)?1:0; b.win=(b.ver.indexOf("Win")!= -1)?1:0;
	b.ie5=(b.ver.indexOf("MSIE")!= -1 && b.dom && parseInt(b.ver) >= 4)?1:0;
	b.ie4=(document.all && !b.dom)?1:0; b.ie=(b.ie5 || b.ie4);
	b.saf=(b.ver.indexOf("Safari")>-1 && b.mac) ?1:0;
	b.ns6=(b.dom && b.ver.indexOf("MOZILLA")!= -1)?1:0; b.ns4=(document.layers && !b.dom)?1:0; 
	b.ns=(b.ns4 || b.ns6 || b.saf);
	b.eyefi=(b.ie || b.ns);
    EB._browser = b;
	return EB._browser;
}

EB.window = {
    
    /**
     * Center a window.
     * Example:
     * EB.addEvent(window, "load", EB.window.center);
     * this centers a window on load.
     */
    center: function() {
        saw = screen.availWidth;
        sah = screen.availHeight;
        self.moveTo(((saw/2)-380),((sah/2)-220));
    },

    /**
     * Close a window. Doh ;-)
     */
    close: function() {
        window.close();
    },

    /**
     * Link from popup to main window
     * EB.window.openInMain('/index.php');
     */
    openInMain: function(url) {
        opener.parent.location=url;
        opener.focus();
        EB.window.close();
    },

    /**
     * Make the window fullscreen
     */
    fullscreen: function() {
        if (!window.moveTo || !window.resizeTo) return;
        window.moveTo(0,0) 
        window.resizeTo(screen.availWidth,screen.availHeight)
    },

    /**
     * Make a popup window
     * EB.window.popup('aap.php', 320, 240);
     * EB.window.popup('aap.php', 320, 240, ['location','resizable']); // resizablepopup with location bar
     */
    popup: function(url, w, h, opts) {
        var all_options = {'toolbar': false, 'location': false, 'directories': false,
                           'status': false, 'menubar': false,
                           'scrolling': false, 'scrollbars': false, 'resizable': false};
        if (typeof opts == "object") {
            for (var j=0; j<opts.length; j++) all_options[opts[j]] = true;
        }
        s = "";
        for (var i in all_options) s += i+"="+(all_options[i]?"yes":"no")+",";
        if (w) s += "width="+w+",";
        if (h) s += "height="+h+",";
        s = s.substr(0,s.length-1);
        window.open(url,'pop',s);        
    }
};


// ATTRIBUTE REGISTRATIE GEDEELTE
EB.registerAttribute("IMG", "src_mouseover", EB.addHoverImage);
EB.registerAttribute("INPUT", "src_mouseover", EB.addHoverImage);
EB.registerAttribute("A", "class_mouseover", EB.addHoverClass);
EB.registerAttribute("A", "nofocus", EB.addNoFocus);

EB.registerAttribute("DIV", "togglegroup", EB.addToggleGroup);
EB.registerAttribute("UL", "togglegroup", EB.addToggleGroup);
EB.registerAttribute("IFRAME", "togglegroup", EB.addToggleGroup);

EB.registerAttribute("A", "link", EB.addLink);
EB.registerAttribute("IMG", "link", EB.addLink);

EB.registerAttribute("DIV", "scroller", EB.initScroller);

// LOAD GEDEELTE
EB.addEvent(window, "load", EB.processAttributes);

var date = new Date();
function showYear() {
	document.write(date.getFullYear());
}
