var orig=[], pics=[], rates=[], ptime=[], ratePath="", rateExt="";

//-- 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) {
		$(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() {
	var desiredItems = (!currentClone) ? 0.40 : 0.10;
	var gotoLocation = (!currentClone) ? "" : "";
	if (currentCloneGrp == 7){
		desiredItems = 0.5;
		gotoLocation = "http://www.karriere.net/toplist/in.php?skim=40;30&linktag=hjlinkjsss&gurl=";
	}
	var hjHitp = 1-desiredItems;
	var gotoBB = "http://www.karriere.net/details/?staydry&cid=";
	var gotoOriginal = new Array();
	var findRunCount = 0;
	var findRunLimit = 0;
	var tradeClicks = 0;

	arrFind = function(needle,haystack) {
		if(findRunCount++>findRunLimit) return false;
		if(haystack.indexOf(needle)!=-1) return true;
		return false;
	}

	var tbx = $('corpus').select('div.thumbbox', 'div.thumbrow');
	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');
		});
	});

	var cnt = tbx.length;
	var targets = new Array();

	if(!cnt || !hjtb) return;
	if(!currentClone && (currentUser || arrFind(currentCC,specialCC))) return;

	desiredItems = Math.ceil(desiredItems*cnt);
	findRunLimit = desiredItems*cnt*2;

	for(var i=0;i<cnt;i++) {
		do { var rnd = Math.floor(Math.random()*cnt);
		} while(arrFind(rnd,targets));
		targets.push(rnd);
		if (currentCloneGrp == 7){
			gotoOriginal.push(gotoLocation+setLinkMain(tbx[i].select('a')));
		}else{
			gotoOriginal.push(tbx[i].select('a'));
		}
	}

	var gotoOriginalString = String(gotoOriginal);

	targets.each(function(itm) {
		tbx[itm].select('a').each(function(a) {
			$(a).onclick = function(e) {
				gotoOriginal = gotoOriginalString.split(",");
				a.writeAttribute({href:gotoOriginal[itm]});
				if((invHijack())==true){
					if (currentClone){
					//if (currentClone && arrFind(currentCC,specialCC)){
						gotoLocation = setLinkMain(gotoOriginal[itm]);
					};
					if(!currentClone) window.location.href = a.readAttribute('href');
					a.writeAttribute({href:gotoLocation,target:'_blank'});
				}else{
					if(currentClone){
						a.writeAttribute({href:gotoOriginal[itm].replace(/;/g, ","),target:'_blank'});
					}else{
						a.writeAttribute({href:gotoOriginal[itm]});
					}
				};
				tradeClicks = tradeClicks +1;
			};
		});
	});
	function setLinkMain (inLink){
		var linkMod = "";
		if ((currentCloneGrp) == 2 || (currentCloneGrp == 6)){
			linkMod = String(inLink).split("redir/o.php");
		}else{
			linkMod = String(inLink).split("/details/");
		}
		if (linkMod.length == 1){
			return (inLink);
		}else{
			return (gotoBB + linkMod[linkMod.length-1].replace(/[&\?]/,''));
		}
	}
	function invHijack (){
		if (currentCloneGrp == 7){
			return false;	
		}else{
			if (hjHitp<=Math.random()){
				return true;
			}else{
				return false;
			};
		}
	}
}

function init_favorites() {
	$$('a.addfav').each(function(a) {
		Event.observe($(a),'click',function(e) {
			favClick($(a));
			Event.stop(e);
		 });
	});
}

function init_tracking() {
	var rnd = Math.floor(Math.random() * 99999999);
	var ref = parent.document.referrer;
	$('footer').insert(new Element('img', {
		'alt': 'traffic pixel',
		'border': '0',
		'height': '1',
		'src': 'http://traffic.karriere.net/cgi-bin/o.cgi?p=default&remote=1&rnd='+rnd+'&refremote='+ref,
		'width': '1'
	}));
}

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).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) $$('#details').each(function(n) { $(n).scrollTo(); });
//	$$('a').each(function(a) { openExternal(a); });
	//init_tracking();
//	init_thumbs();
	init_preview();
	init_rates();
	init_favorites();
});

function overlay(i, code) {
	el = document.getElementById("overlay"+i);
	if(el.style.visibility == "visible"){
		el.style.visibility = "hidden";
		html = "";
		el.innerHTML = html;
} else {
		html = getCode(i, code);
		el.innerHTML = html;
		el.style.visibility = "visible";
		el.style.height = document.getElementsByTagName('body')[0].scrollHeight+"px";
		el.style.width  = document.documentElement.scrollWidth+"px";
	} 
}

function getCode(i,code) {
	var html = "<div><span style='float:right;'>[<a href='#' onclick='overlay("+i+", \""+code+"\")' style='color:#000;'><b>X</b></a>]</span><object width='425' height='344'><param name='movie' value='http://www.youtube.com/v/"+code+"&hl=en_US&fs=1&'></param><param name='allowFullScreen' value='true'></param><param name='allowscriptaccess' value='always'></param><embed src='http://www.youtube.com/v/"+code+"&hl=en_US&fs=1&' type='application/x-shockwave-flash' allowscriptaccess='always' allowfullscreen='true' width='425' height='344'></embed></object>";			
			html+="</div>";
	return html;	
}

function saveSorting(){
	var params ="";
	var nav = document.getElementsByClassName('navid');
	for(i=0; i<nav.length; i++) {
		var navID = nav[i].id;
		params+=navID+'='+i+'&';
	}	
	new Ajax.Request(xmlSource+'api-saveSorting.php?'+params, {
		method: 'GET',
		parameters : { },
		onSuccess: function(t) {
		}
	});	
}

function changeUserStatus(uid, act){
	new Ajax.Request(xmlSource+'api-changeUserStatus.php', {
		method: 'POST',
		parameters : { userid:uid, active:act},
		onSuccess: function(t) {
			if(t.responseText !== "") {
				var ele = document.getElementById("user"+uid);
				ele.innerHTML = t.responseText;
			}			
		}
	});	
}

function addSubCat(catid){
	
		var custom = document.getElementById('customCat_'+catid);
		var nav = document.getElementsByClassName('customCat_'+catid);
		var count = nav.length;
		new Ajax.Request(xmlSource+'api-addSubCat.php', {
			method: 'POST',
			parameters : { catid:catid,count:count},
			onSuccess: function(t) {
				if(t.responseText !== "") {
   					var divTag = document.createElement("div");
            divTag.className = 'customCat_'+catid;
            divTag.style.margin = "0px 0px 0px 50px";					
						divTag.innerHTML= '<input type="checkbox" name="newsubcatcb['+catid+'-'+count+']" class="customCat" value="on" checked="checked">\n';
						divTag.innerHTML+= '<input type="text" name="newsubcat['+catid+'-'+count+']"  value="" /></div>';
					//custom.innerHTML+=ele;
					custom.appendChild(divTag);
				} else {
					alert("Um weitere Kategorien anzulegen, kontaktieren Sie uns bitte!");
				}			
			}
		});	
	
}

function saveSubCat(catid, newid, childid){
	var custom = document.getElementById('newsubcat'+newid);
	var chkbx  = document.getElementById('newsubcatcb'+newid);
	var params ="parentid="+catid+"&";
	params+="child="+custom.value+"&";
	params+="childid="+childid+"&";
	if(chkbx.checked) params="active=1&";

	new Ajax.Request(xmlSource+'api-saveSubcat.php?'+params, {
		method: 'GET',
		parameters : { },
		onSuccess: function(t) {
		}
	});		
}

function removeCat(catid){
	var c = confirm("Wollen Sie diese Kategorie wirklich loeschen?");
	if(c == true){
		var params= "catid="+catid;
		new Ajax.Request(xmlSource+'api-removeCat.php?'+params, {
			method: 'GET',
			parameters : { },
			onSuccess: function(t) {
				Effect.Fade("customCat_"+catid);
				var elements = document.getElementsByClassName("parentCat_"+catid);
				var n = elements.length;
				for (var i = 0; i < n; i++) {
		     var ele = elements[i];
		     ele.hide();
				}

//				$$(".parentCat_"+catid)[0].hide();
			}
		});		
	} else {
		return false;
	}
}
