var orig=[], pics=[], rates=[], ptime=[], ratePath="", rateExt="", dumpVar=[];

//-- Prototypes --------------------------------------------------------------//

Array.prototype.has = function(needle) {
	for(elm in this) if(this[elm]==needle) return true;
	return false;
}

//-- Form Functions ----------------------------------------------------------//

function checkLogin(main) {
	var allow = true;
	p = (main) ? 'loginpass' : 'smallpass';
	n = (main) ? 'loginname' : 'smallname';
	$(p).removeClassName('inputerror');
	$(n).removeClassName('inputerror');
	if($F(p).strip() == '') {
		$(p).activate().addClassName('inputerror');
		allow = false;
	}
	if($F(n).strip() == '') {
		$(n).activate().addClassName('inputerror');
		allow = false;
	}
	return allow;
}

function checkForgot() {
	var allow = true;
	var inputs = $('forgotForm').getInputs('text');
	inputs.reverse();
	inputs.each(function(n) {
		$(n).removeClassName('inputerror');
		if($F(n).strip()=='') {
			$(n).activate().addClassName('inputerror');
			allow = false;
		}
	});
	return allow;
}

function checkRegister() {
	var allow = true;
	$('registerAgree').up(0).removeClassName('inputerror');
	if(!$F('registerAgree')) {
		$('registerAgree').up(0).addClassName('inputerror');
		$('registerAgree').focus();
		allow = false;
	}
	var inputs = $('registerForm').getInputs('text');
	var passwords = $('registerForm').getInputs('password');
	passwords.reverse();
	passwords.each(function(n) { inputs.splice(1,0,n); });
	inputs.reverse();
	inputs.each(function(n) {
		$(n).removeClassName('inputerror');
		if($F(n).strip()=='') {
			$(n).activate().addClassName('inputerror');
			allow = false;
		}
	});
	return allow;
}

function checkUpload() {
	var allow = true;
	$('uploadform').getElements().each(function(n) {
		if($(n).hasClassName('required') && $(n.id)) {
			if(((n.type=="checkbox") && !n.checked) || !n.value) {
				$(n.id+"Row").addClassName('inputerror');
				allow = false;
			}
		}
	});
	return allow;
}

function errorUpload(msg) {
	$('main').select('div#cookiemessage', 'div#forminfo').each(function(e) { e.remove(); });
 	var div = new Element('div', { 'id': 'cookiemessage' }).update(msg);
 	$('header').insert({after:div});
	if($('uploadform')) $('uploadform').enable();
}

//-- Flash Functions ---------------------------------------------------------//

function getFlashMovie(movieName) {
	var isIE = navigator.appName.indexOf("Microsoft") != -1;
	return (isIE) ? window[movieName] : document[movieName];
}

//-- Category Functions ------------------------------------------------------//

function flipCatList(elm) {
	dls = elm.parentNode.childNodes;
	for(i=0;i<dls.length;i++) {
		if(dls[i].nodeName=="DL") {
			dls[i].className = (dls[i].id==elm.id) ? "active" : "none";
		}
	}
}

//-- Preview Functions -------------------------------------------------------//

function loadpic(url,code,j) {
	Event.observe($(pics[code][j]),'error',function(e) { pics[code][j].src = "/gfx/abh.gif"; });
	pics[code][j].src=url;
}

function changepic(i,code) {
	if(i>=10) i = 0;
	if(pics[code][i].complete) {
		if(pics[code][i].src != "") $(code).src=pics[code][i].src;
		ptime[code] = setTimeout("changepic("+(++i)+",'"+code+"')",750);
	} else {
		ptime[code] = setTimeout("changepic("+(i)+",'"+code+"')",20);
	}
}

function previewScroll(i,e) {
	for(var pt in ptime) timeClear(ptime[pt]);
	var first = true;
	for(var j=0;j<10;j++) {
		if(pics[i.id][j]==1) {
			pics[i.id][j]=new Image();
			var ppexp = /(.+[0-9]{2}\/)([a-z]+)(_[a-z]+)(\.[a-z]+)?$/i;
			var parts = ppexp.exec(i.src.toString());
			var path = parts[1]+"frames/"+parts[2]+"_"+((j==0)?"05":(j*10)+5)+parts[4];
			ptime[i.id] = setTimeout("loadpic('"+path+"','"+i.id+"',"+j+")",j*50);
		}
	}
	changepic(0,i.id);
}

//-- Rating Functions --------------------------------------------------------//

function rateMouseOver(e) {
	timeClear(rates[e[1]][0]);
	for(i=1;i<rates[e[1]].length;i++) {
		$(rates[e[1]][i][0]).src = ratePath+(i<=e[3]?"4":"0")+rateExt;
	}
}

function rateMouseOut(e) {
    rates[e[1]][0] = setTimeout("rateReset("+e[1]+")",1000);
}

function rateClick(e) {
	if(!rates[e[1]]) return false;
	new Ajax.Request(xmlSource+'add-rate', {
		method: 'get',
		parameters: { cid: e[2], rate: e[3] },
		onComplete: function(t) {
			rates[e[1]] = null;
			r = $(e[0]).up().next('span');
			if(t.responseText == "login") {
				window.location.href = "/login";
			} else {
				r.update('<br>'+t.responseText).show();
				new Effect.Fade($(r),{ delay: 5, duration: 0.5 });
			}
		}
	});
}

function rateReset(e) {
	timeClear(rates[e][0]);
	for(i=1;i<rates[e].length;i++) {
		$(rates[e][i][0]).src = rates[e][i][1];
	}
}

//-- Favorite Functions ------------------------------------------------------//

function favClick(a) {
	var afexp = /^addfav-([0-9]{1,})$/i;
	var parts = afexp.exec(a.id);
	if(!parts[1]) return false;
	new Ajax.Request(xmlSource+'add-favorite', {
		method: 'get',
		parameters: { cid: parts[1] },
		onComplete: function(t) {
			if(t.responseText == "login") {
				window.location.href = "/login";
			} else {
				a.replace(t.responseText);
			}
		}
	});
}

//-- Cookie Functions --------------------------------------------------------//

function createCookie(name,value,days) {
	if(days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i<ca.length;i++) {
		var c = ca[i];
		while(c.charAt(0)==' ') c = c.substring(1,c.length);
		if(c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

//-- General Functions -------------------------------------------------------//

function timeClear(t) {
	if(t && typeof(t)=='number') {
		clearTimeout(t);
		t=0;
	}
}

//-- Init Functions ----------------------------------------------------------//

function init_preview() {
	$$('img.scroll').each(function(n) {
		orig[n.id] = n.src;
		pics[n.id]=new Array(1,1,1,1,1,1,1,1,1,1);
		Event.observe($(n),'mouseover',function(e) { previewScroll(n,e); });
		Event.observe($(n),'mouseout',function(e) {
			for(var pt in ptime) timeClear(ptime[pt]);
			n.src = orig[n.id];
		});
	});
}

function init_rates() {
	var rsexp = /^star-([0-9]{4})-([0-9]{1,})$/i;
	var riexp = /^star-([0-9]{4})-([0-9]{1,})-([0-9]{1})$/i;
	var rpexp = /(.+)[0-9]{1}(\.[a-z]{3})$/i;
	$$('span.ratingStars.active').each(function(s) {
		span = rsexp.exec(s.id);
		rates[span[1]] = new Array();
		s.select('img.rateStar').each(function(i) {
			if(!ratePath || !rateExt) {
				path = rpexp.exec(i.src.toString());
				ratePath = path[1];
				rateExt = path[2];
			}
			img = riexp.exec(i.id);
			rates[span[1]][img[3]] = new Array(i.id,i.src.toString());
			Event.observe($(i),'mouseover',function(e) { rateMouseOver(riexp.exec(Event.element(e).id)); });
			Event.observe($(i),'mouseout',function(e) { rateMouseOut(riexp.exec(Event.element(e).id)); });
			Event.observe($(i),'click',function(e) { rateClick(riexp.exec(Event.element(e).id)); });
 		});
	});
}

function init_thumbs() {

	// Select thumbs and apply rollover
	var tbx = $('corpus').select('div.thumbbox', 'div.thumbrow');
	if(!tbx.length) return;
	tbx.each(function(t) {
		var i = $(t).select('img').first();
		Event.observe(i,'error',function(e) { i.src = gfxSource+"404thumb.png"; });
		Event.observe($(t),'mouseover',function(e) {
			$(t).firstDescendant().addClassName('thumbactive');
		});
		Event.observe($(t),'mouseout',function(e) {
			$(t).firstDescendant().removeClassName('thumbactive');
		});
	});

	// Customized hj
	if(customItems && customRedir) {
		customRegex = /([a-z]+:\/\/)([^\/]+\/)([A-Za-z0-9]+\/)([0-9]{1,})?(.*)/;
		tbx.each(function(itm) {
			itm.select('a:not([target="_blank"])').each(function(a) {
				Event.observe($(a),'click',function(e) {
					if(Math.random()<=customItems) {
						a.writeAttribute({href:a.readAttribute('href').sub(customRegex,customRedir)});
					}
				})
			;})
		;});

	}

}

function init_favorites() {
	$$('a.addfav').each(function(a) {
		Event.observe($(a),'click',function(e) {
			favClick($(a));
			Event.stop(e);
		 });
	});
}

function init_pu(url) {
	if(!url) return;
	var pu = false;
	var uuis = url.replace(/[^A-Z0-9]/gi,'').replace(/^https?/i,'').split("").slice(0,64).reverse().join("");
	function doOpen(url) {
		if(!pu) {
			win = window.open(url, uuis, 'toolbar,status,resizable,scrollbars,menubar,location,height=680,width=790');
			if(win) {
				win.blur();
				pu = true;
			}
		}
		return pu;
	}
	Event.observe($('corpus'),'click',function(e) { if(!readCookie(uuis) && doOpen(url)) createCookie(uuis,1,1); });
}

function openExternal(a) {
	if((a.readAttribute('rel')=='external') || ((a.readAttribute('rel')=='detail')&&blnk)) {
		a.writeAttribute({target:'_blank'});
// 		$(a).onclick = function(e) {
// 			if (e.shiftKey || e.altKey || e.ctrlKey || e.metaKey) {
// 				return true;
// 			} else {
// 				var oWin = window.open(this.getAttribute('href'), '_blank');
// 				if (oWin) {
// 					if (oWin.focus) oWin.focus();
// 					return false;
// 				}
// 				oWin = null;
// 				return true;
// 			}
// 		};
	}
	return a;
}

//-- Global onload -----------------------------------------------------------//
document.observe("dom:loaded", function() {
	$$('input.readonly').each(function(n) { n.onclick = function() { this.activate(); }});
	$$('#logo').each(function(n) { n.onclick = function() { window.location.href = "/"; }});
	if(!window.location.hash && $('top')) $('top').scrollTo();
	init_thumbs();
	init_preview();
	init_rates();
	init_favorites();
	$$('a').each(function(a) { openExternal(a); });
});
