// 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) {

}

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








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() },
	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'
			
		}
	}
	
}

window.onload = Bookmark.init.bind(Bookmark);

