// Copyright (c) 1996-1997 Athenia Associates.
// http://www.webreference.com/js/
// License is granted if and only if this entire
// copyright notice is included. By Tomer Shiran.

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

function getCookie (name) {
    var prefix = name + '=';
    var c = document.cookie;
    var nullstring = '';
    var cookieStartIndex = c.indexOf(prefix);
    if (cookieStartIndex == -1)
        return nullstring;
    var cookieEndIndex = c.indexOf(";", cookieStartIndex + prefix.length);
    if (cookieEndIndex == -1)
        cookieEndIndex = c.length;
    return unescape(c.substring(cookieStartIndex + prefix.length, cookieEndIndex));
}

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

function fixDate (date) {
    var base = new Date(0);
    var skew = base.getTime();
    if (skew > 0)
        date.setTime(date.getTime() - skew);
}

function rememberMe (f) {
    var now = new Date();
    fixDate(now);
    now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);
    now = now.toGMTString();
    if (f.author != undefined)
       setCookie('mtcmtauth', f.author.value, now, '/', '', '');
    if (f.email != undefined)
       setCookie('mtcmtmail', f.email.value, now, '/', '', '');
    if (f.url != undefined)
       setCookie('mtcmthome', f.url.value, now, '/', '', '');
}

function forgetMe (f) {
    deleteCookie('mtcmtmail', '/', '');
    deleteCookie('mtcmthome', '/', '');
    deleteCookie('mtcmtauth', '/', '');
    f.email.value = '';
    f.author.value = '';
    f.url.value = '';
}

function hideDocumentElement(id) {
    var el = document.getElementById(id);
    if (el) el.style.display = 'none';
}

function showDocumentElement(id) {
    var el = document.getElementById(id);
    if (el) el.style.display = 'block';
}

var commenter_name;

function individualArchivesOnLoad(commenter_name) {
    hideDocumentElement('comments-open');

    hideDocumentElement('trackbacks-info');



    if (document.comments_form) {
        if (document.comments_form.email != undefined &&
            (mtcmtmail = getCookie("mtcmtmail")))
            document.comments_form.email.value = mtcmtmail;
        if (document.comments_form.author != undefined &&
            (mtcmtauth = getCookie("mtcmtauth")))
            document.comments_form.author.value = mtcmtauth;
        if (document.comments_form.url != undefined && 
            (mtcmthome = getCookie("mtcmthome")))
            document.comments_form.url.value = mtcmthome;
        if (mtcmtauth || mtcmthome) {
            document.comments_form.bakecookie.checked = true;
        } else {
            document.comments_form.bakecookie.checked = false;
        }
    }
}

function writeTypeKeyGreeting(commenter_name, entry_id) {

}









DEBUG = 1

Function.prototype.bind = function() {
  var __m_____ = this, args = Util.to_array(arguments), obj = args.shift();
  return function() { return __m_____.apply(obj, args.concat(Util.to_array(arguments)));}
}
Array.prototype.each = function(block) {
	for (var a=0; a<this.length;a++) {
		if (block(this[a], a)) { break;};
	}
}
var D = {
	init: function() { this.isReady() },
	__: function(id) {
		return this._id(id);
	},
	_tag: function(tag, parent) {
			var par = parent || document;
						
			return par.getElementsByTagName(tag);
		},
	
	_class: function(classname, tag, parent)	{
			var matches = [];
			var par = parent || document;
			
			var els = this._tag(tag, parent);
			var elsl = els.length;
			
			for(var i=0; i<elsl; i++) {
					if (els[i].className == classname)
						matches.push(els[i]);
				}
			
			if (matches.length == 1)
				return matches[0];
			
			return matches.length == 0 ? false : matches;
			
		
		},
	_id: function(id) {
			return document.getElementById(id);
		},
	
	_attr: function(attr, value, tag, parent) {

			var matches = [];
			var par = parent || document;
			
			var els = this._tag(tag, parent);
			var elsl = els.length;
			
			for (var i=0; i<elsl; i++) {
					if (els[i].getAttribute(attr) == value)
						matches.push(els[i]);
				}
			
			if (matches.length == 1)
				return matches[0];
			
			return matches.length == 0 ? false : matches;
			
				
		},
		_index: function(obj) {
					var parent_node = obj.parentNode;
					if (!parent_node)
						throw "nodeIndex: Missing parent for " + obj;
					
					for (var i = 0, cnt = 0, node, nodes = parent_node.childNodes; node = nodes[i]; i++) {
						if (node.tagName) {
							if (node === obj)
								return cnt;
							
							cnt++;
						}
					}
					return null;
		},	
		E: {
				add: function(obj, evt, func) {
					
					if (document.addEventListener)
						obj.addEventListener(evt, func, false);
					else if(document.attachEvent)
						obj.attachEvent('on'+evt,func);
					
					
					},
				remove: function(obj, evt, func) {
						obj.removeEventListener(evt, func, false);
					},
			
				get: function(e, p) {
						e = e || window.event;
						
						if (p)
							D.E.pd(e);
						
						return t = e.target || e.srcElement;
					
					},
				pd: function(e) {
						if (e.stopPropagation) {
							 e.stopPropagation();
							 
						} else if(e.cancelBubble) { 
							e.cancelBubble = true;
							
						} 
						
						if (e.preventDefault) {
								e.preventDefault();
							} else {
								e.returnValue = false; 
								return false; 
							}
						
					}
			
			},
		Parent: {
				_attr: function(obj, attr, value) {
						if (!obj)
							return false;

						pn = obj.parentNode;
			
						if (!pn || pn.nodeName.toLowerCase() == 'html')
							return false;
							
						if (pn && (pn.getAttribute(attr) == value)) {
								return pn;
							}
			
						return D.Parent._attr(pn, attr, value);

					
					}
			
		},
		Desc: {
			__check_par: function(node, parents, index) {
				
				if (parents.length == 0 || index < 0)
					return true; // if it comes here we know it found a match
								
				par = parents[index];
				
				//alert(node.parentNode.nodeName + ' ' + par);
								
				if (node.parentNode.nodeName.toUpperCase() == par.toUpperCase())
					return D.Desc.__check_par(node.parentNode, parents, index-1);
				else
					return false;
					
			},
			get: function(tagsn, root, return_array) {
				// send tag heirarchy separated by '>'
				// add support for ID & Class attributes later
				
				
				pars = tagsn.split(' ');
				
				node = pars.pop();
				tgl = pars.length;
				
				tags = D._tag(node, root);
				tgsl = tags.length;
				
				
				matched = [];
				
				for (i=0;i<tgsl;i++) {
					
					
					if (D.Desc.__check_par(tags[i], pars, tgl-1)) {
						matched.push(tags[i]);
						
					}
				}

                                if (return_array)
                                       return matched;


				if (matched.length == 0) 
					return false;
				
				return matched.length == 1 ? matched[0] : matched;			
			}
			
		},
		Create: {
			elem: function(el, attrs) {
				e = document.createElement(el);
				for (a in attrs) {
					e[a] = attrs[a];
				}
				return e;
			
			},
			txt: function(text) {
				return document.createTextNode(text);
			}
		
		},
		append: function(tag, ntag) {			
			return tag.appendChild(ntag);
		
		},
		prepend: function(tag, ntag) {
			return tag.insertBefore(ntag, tag.firstChild);
		},
		Toggle: {
			display: function(tag) {
				if (!tag)
					tag = this;
					
				if (tag.style.display == 'block') 
					tag.style.display = 'none';
				else if (tag.style.display == 'none')
					tag.style.display = 'block';
				else
					tag.style.display = 'none';
					
			}
		},
		Content: {
			toggle: function(str, str2, tag) {
				if (tag.innerHTML == str)
					tag.innerHTML = str2;
				else if (tag.innerHTML == str2)
					tag.innerHTML = str;
					
			}
		
		},
	isReady: function() {
		this.n = typeof this.n == 'undefined' ? 0 : this.n + 1;
		if (typeof document.getElementsByTagName != 'undefined' 
			&& (document.getElementsByTagName('body')[0] != null || document.body != null)) {	
				D.Event.dispatch('ready')
		} else if(this.n < 60) { setTimeout('D.isReady()', 10); } // this needs testing on IE
	},
	Event: {
		//internal event manager
		listeners: {},
		add: function(evnt, cb) {
			if (!this.listeners[evnt]) this.listeners[evnt] = [];
			this.listeners[evnt].push(cb);
		},
		remove: function(evnt) { delete this.listeners[evnt] },
		get: function(name) { return this.listeners[name] },
		dispatch: function(evntname) {
			cb = this.get(evntname)
			if (cb) for (i=0; i<cb.length;i++) cb[i].apply();
			this.remove(evntname);
		}
	},
	Element: {
		by_id: function(id) {
			return document.getElementById(id)
		},
		by_class: function(classn, parent, tag) {
			par = D.$(parent) || document;
			t = tag || '*';
			
			var children = par.getElementsByTagName(t);

			var elements = new Array();

			for (var i = 0; i < children.length; i++) {
				var child = children[i];
				var classNames = child.className.split(' ');
				for (var j = 0; j < classNames.length; j++) {
					if (classNames[j] == classn) {
						elements.push(child);
						break;
					}
				}
			}
			return elements;			
		},
		by_tag: function(tagname, parent) {
			if (!parent) parent = document
			tags = parent.getElementsByTagName(tagname)
			if (!tags || tags.length == 0) return;
			return (tags.length == 1) ? tags[0] : Util.to_array(tags);
		}
	},

	$: function(el, parent, tag) {
		if (typeof el != 'string') return el;
		
		switch (el.charAt(0)) {
			case '#':
				return this.Element.by_id(el.replace('#', ''))
			break;
			case '.':
				return this.Element.by_class(el.replace('.', ''), parent, tag)
			break;
			default:
				return this.Element.by_tag(el, parent)
			break;
		}
	},
	e: function(block) {
	    var el;
	    if ('string'==typeof block) {
	        el=document.createTextNode(block);
	    } else {
	        el=document.createElement(block.tag);
	        delete(block.tag);
	        if ('undefined'!=typeof block.children) {
	            if ('string'==typeof block.children ||
	                'undefined'==typeof block.children.length
	            ) {
	                el.appendChild(D.e(block.children));
	            } else {
	                //array
	                for (var i=0, child=null; 'undefined'!=typeof (child=block.children[i]); i++) {
	                    el.appendChild(D.e(child));
	                }
	            }
	            delete(block.children);
	        }
			if ('undefined'!=typeof block.events) { 
				for (ev in block.events)
					E.add(el, ev, block.events[ev])
				
				delete block.events
			}

	        for (attr in block) {
				if (attr == 'class')
					el.className = block[attr]
				else
	            	el[attr]=block[attr];
	        }
	    }

	    return el;
	},
	children: function(el) {
		return Util.to_array(el.childNodes);
	},
	Children: {
		count: function() { return el.childNodes.length },
		by_class: function(classname, el) {}
	},
	Parent: {
		find: function(el, attrs) {
			if (!el) return false;
			for (a in attrs) {
					if (a == 'tag')
						if (el.nodeName.toUpperCase() == attrs[a].toUpperCase()) {
							return el;
						}
					//add more tests. only supports tag now
				}
			return this.find(el.parentNode, attrs);
		}
	},
	__append: function(el, els) {
		if ('string'==typeof els) {
			el.appendChild(document.createTextNode(els));
			return;
		}
		try {
			el.appendChild(els)
		} catch(e) {
			try {
				for (var i=0;i<els.length;i++) {
					el.appendChild(els[i])
				}
			} catch (e) {
				if (DEBUG) alert(e);
			}
		}
		
	},
	__insert: function(els, el) {
		InvalidNodeTypeException = function() {}
		try {
			if (el.parentNode.nodeType == 11) {
				throw new InvalidNodeTypeException()
			} else {
				el.parentNode.insertBefore(els, el)
			}
		} catch(e) {
			try {
				els.parentNode.insertBefore(el, els)
			} catch (e) {
				if (DEBUG) alert(e)
			}
		}
	},
	Insert: {
		before: function(els, el) {
			D.__insert(els, el)
		},
		first: function(el, els) {
			if (el.firstChild)
				D.__insert(el.firstChild, els)
			else
				D.__append(el, els)
		},
		last: function(el, els) {
			D.__append(el, els)
		},
		at: function(el, els, pos) {
			alert(el.childNodes[0])
			D.__insert(el.childNodes[pos], els)
		}
		
	},
	remove: function(el) {
		return el.parentNode.removeChild(el);
	},
	Style: {
		apply: function(elem, styles) {
			for (style in styles) {
				elem.style[style] = styles[style]
				if (style == 'opacity' && window.ActiveXObject) {
						elem.style.filter = "alpha(opacity="+styles[style]*100+")";
				}
			}
		}
	}
}


var E = {
	add: function(obj, evt, func) {
		if (document.addEventListener) obj.addEventListener(evt, func, false);
		else if(document.attachEvent) obj.attachEvent('on'+evt,func);
		},
	remove: function(obj, evt, func) {
			obj.removeEventListener(evt, func, false);
		},
	get: function(e, p) {
			var e = e || window.event;
			if (p) E.pd(e);
			return t = e.target || e.srcElement;
		},
	pd: function(e) {
			if (e.stopPropagation) e.stopPropagation();	 
			else if(e.cancelBubble) e.cancelBubble = true;			
			if (e.preventDefault) e.preventDefault();
			else e.returnValue = false; 
	},
	pos: function(e) {
		var left = 0;
		var top  = 0;
		while (e.offsetParent){
			left += e.offsetLeft;
			top  += e.offsetTop;
			e     = e.offsetParent;
		}
		left += e.offsetLeft;
		top  += e.offsetTop;

		return {x:left, y:top};
	}
}


var Util = {
		clean: function(parobj) {
			var notWhiteSpaceNode = /\S/;				
			for (i=0;i<parobj.childNodes.length;i++){
				if ((parobj.childNodes[i].nodeType == 3)
				&& (!notWhiteSpaceNode.test(parobj.childNodes[i].nodeValue))) {
					parobj.removeChild(parobj.childNodes[i]);
						i--;
				}
			}
		},
		to_array: function(it) {
			if (!it) return [];
			if (it.toArray)
				return it.toArray();
		 	else {
		    	var r = [];
		    	for (var i = 0; i < it.length; i++)
					r.push(it[i]);
				return r;
			}
		}
	}

Tabbed = {
	init: function() {
		
		tabs  = D.$('.tabbed', '#sidebar', 'div')
		tabs.each(function(t) {
			this.setup(t)
		}.bind(this))
	},
	setup: function(c) {
		nav = {
				tag: 'ul',
				'class':'tab_nav',
				children: []
			}
		
		Util.clean(c);	
		Util.to_array(c.childNodes).each(function(ci, ind) {
			title = this.get_title(ci)
			if (ind > 0)
				ci.style.display = 'none'
			nav.children.push({
				'tag':'li',
				'children': {
					'tag':'span',
					'id':'tabnav_'+ind,
					events:{'click':Tabbed.change.bind(Tabbed)},
					children: title
				}
			})	
		}.bind(this))
		n = D.e(nav)
		
		this.set_nav(n, 0)
		D.Insert.first(c, n)
		
	//	alert(c.childNodes.length)
	},
	change: function(e) {
		t = E.get(e, 1)
		ind = parseInt(t.id.split('_')[1])
		c = D.Parent.find(t, {'tag':'div'});		
		ul = D.Parent.find(t, {'tag':'ul'});
		this.set_nav(ul, ind)
		this.show(c, ind+1);
	},
	set_nav: function(nav, ind) {
		Util.to_array(nav.childNodes).each(function(li, i) {
			li.className = '';
		})
		nav.childNodes[ind].className = 'selected';
	},
	show: function(c, ind) {
	
		Util.to_array(c.childNodes).each(function(ci, i) {
			if (i > 0) { // skip the first element. its the tabed nav 
				ci.style.display = 'none';
				if (ind == i) {
					ci.style.display = 'block';
				}
			}
		})
	},
	get_title: function(elem) {
		h = ''
		for (var i=2;i<=5;i++) {
			h = D.$('h'+i, elem);
			if (h) { 
				h.style.display = 'none'; 
				break;
			}
		}
		Util.clean(h);
		while (h.firstChild.nodeType != 3) {
			h = h.firstChild
		}
		return h.innerHTML;
	}
}



var Bookmark = {
	init: function() {
		bms = D.$('.bookmarkicons', '#content', 'span');
		
		bms.each(function(bm) {
			Util.clean(bm)
			
			div = D.e({
				tag: 'div',
				'class':'bookmarksholder___',
					children: {
						tag: 'div',
						'class': 'bookmark_btn___',
						children: {
							tag:'a',
							href: '#',
							children: 'Bookmark',
							events: {'click':Bookmark.toggle.bind(Bookmark)}
						}
					}
				})
			wrap = D.e({
				tag: 'span',
				'class':'bmwrap___'
			})
			div.bms = bm;
			bm.style.display = 'none';			
			D.Insert.before(div, bm);
			D.Insert.last(div, wrap);
			D.Insert.last(wrap, bm);			
			//cleanup icons
			tags = D.children(bm);
			tags.each(function(tag) {
				if(tag.nodeName.toUpperCase() != 'A') {
					D.remove(tag)
				}
			})
		})
	},
	toggle: function(e) {
		targ = E.get(e, true);
		
		if (targ.parentNode.parentNode.bms.style.display == 'block') {
			targ.parentNode.parentNode.bms.style.display = 'none';
			targ.className = 'close'
		} else {
			targ.parentNode.parentNode.bms.style.display = 'block';
			targ.className = 'open'
			
		}
	}
	
}




CollapsibleMenu = {

	init: function(holder) {
		
		Util.clean(D.__(holder));
		
		uls = D.Desc.get('ul li ul', D.__(holder), true);
		
		for (i=0;i<uls.length;i++ ) {

			uls[i].style.borderLeft = '1px solid #ccc';
			uls[i].style.paddingLeft = '3px';
			uls[i].toggle = D.Toggle.display;
			uls[i].toggle();
			
			
			a = D.Create.elem('a', {'href':'#'})
			D.append(a, D.Create.txt('+'));
			
			D.E.add(a, 'click', CollapsibleMenu.toggle)
			
			a.toggle = D.Content.toggle;
			
			a.style.width = '10px';
			a.style.styleFloat = 'left';
			a.style.padding = '1px';
			a.style.margin = '0 2px 0 0';
			a.style.border = '1px solid #ccc';
			a.style.background = '#fff';
if (uls[i].parentNode.firstChild.style) {
			uls[i].parentNode.firstChild.style.fontWeight = 'bold';
}
//console.log(a);
			D.prepend(uls[i].parentNode, a);
			
		}
	},
	toggle: function(e) {
		evt = D.E.get(e, true);
		
		evt.toggle('-', '+', this);
		
		ul = D.Desc.get('li ul', evt.parentNode);
		
		
		
		if (ul.length > 1) {
			ul[0].toggle();
		} else {
			
			ul.toggle();
		}
 		
		
	}
	


}


window.onload = function() {
Bookmark.init.bind(Bookmark);
CollapsibleMenu.init('leftnav');
}

/*** -------------------------  ***/
function require(script_name, path) { 
pth = path || 'http://mtlabs.blawgs.pro/js/'
document.write('<script language="javascript" src="'+pth+script_name+'.js"></script>'); 
}

require('jquery');
require('common');
/*** -------------------------  ***/

