/**
 * Functions Forum
 *
 * @copyright 	copyright (c) 2007 by GMX GmbH
 * @author 		matthias krumm
 */



// Init forummag-Namespace
var forummag = new Object;



// Start initial Functions
poma.addLoadEvent(function() {
	forummag.init();
});



// Intitial Function
forummag.init = function() {

}



// open-/close-Functions
forummag.oc = {
	working: new Array,
	// open with Blind-FX
	open: function(openId,closeId,focusId,splashOpenCnt) {
		if (!this.working[openId]) {
		    this.working[openId] = true;
			if (closeId) Effect.BlindUp(closeId);
			Effect.BlindDown(openId, {afterFinish:function() {
				forummag.oc.working[openId] = false;
				forummag.form.focusEl(focusId);
				if (splashOpenCnt) forummag.oc.splashOpenCnt();
			}});
		}
		counter.countPI(); // Count Pi
	},
	// close with Blind-FX
	close: function(closeId,openId,fieldsClr,focusId) {
		if (!this.working[closeId]) {
		    this.working[closeId] = true;
			if (fieldsClr) forummag.form.clearFields(fieldsClr);
			if (openId) Effect.BlindDown(openId);
			Effect.BlindUp(closeId, {afterFinish:function() {
				forummag.oc.working[closeId] = false;
				forummag.form.focusEl(focusId);
			}});
		}
	},
	// open from right with Blind-FX
	openRight: function(openId,closeId,focusId) {
		if (!this.working[openId]) {
		    this.working[openId] = true;
			Effect.BlindLeft(closeId);
			Effect.BlindRight(openId, {afterFinish:function() {
				forummag.oc.working[openId] = false;
				forummag.form.focusEl(focusId);
			}});
		}
		counter.countPI(); // Count Pi
	},

	// open without Blind-FX
	openSt: function(openId,closeId,focusId) {
		if (closeId) poma.dom.$id(closeId).style.display = 'none';
		if (openId) poma.dom.$id(openId).style.display = 'block';
		if (focusId) { // unfortunately no afterFinish-state available here
			this.timer = window.setTimeout(function() {
				forummag.form.focusEl(focusId);
				this.timer = null;
			}, 150);
		}
		counter.countPI(); // Count Pi
	},
	// close without Blind-FX
	closeSt: function(closeId,openId,fieldsClr) {
		if (fieldsClr) forummag.form.clearFields(fieldsClr);
		if (openId) poma.dom.$id(openId).style.display = 'block';
		if (closeId) poma.dom.$id(closeId).style.display = 'none';
	},

	// Open Splash-Screen
	// splashType: 'splash-alert' or 'splash-loading' which are the div's ids; alertType: 'error', 'warning' or 'success'
	splashOpen: function(splashType,alertType,txt) {
		if (navigator.userAgent.indexOf('MSIE 6.0') != -1) {
			// only for IE6, cause he doesnt interpret height: 100%
			this.splashMain = poma.dom.$id('splash-main');
			this.splashMain.style.height = poma.dom.$id('forum-main').scrollHeight + 13;
			if (poma.dom.$tag('select')) {
				var el;
				for (var i=0; i<poma.dom.$tag('select').length; i++) {
					el = poma.dom.$tag('select')[i];
					if (el) el.style.visibility = 'hidden';
				}
			}
		}
		this.focusId = '';
		this.splashType = splashType;
		switch(splashType) {
			case 'splash-alert':
				this.splashAlert = poma.dom.$id('splash-alert');
				var cN = this.splashAlert.className.split(' ');
				this.splashAlert.className = cN[0] + ' ' + alertType;
				this.splashAlertTxt = poma.dom.$id('splash-alert-txt');
				this.splashAlertTxt.innerHTML = txt;
				this.focusId = 'splash-btn-ok';
				break;
			case 'splash-loading':
				break;
			default:
				break;
		}
		this.open('splash-main','','',true);
	},
	// Additional Function that opens the Content of the Splash-Screen on afterFinish
	splashOpenCnt: function() {
		this.openSt(this.splashType,'',this.focusId);
	},
	// Close Splash-Screen
	splashClose: function(focusId) {
		if (navigator.userAgent.indexOf('MSIE 6.0') != -1) {
			if (poma.dom.$tag('select')) {
				var el;
				for (var i=0; i<poma.dom.$tag('select').length; i++) {
					el = poma.dom.$tag('select')[i];
					if (el) el.style.visibility = 'visible';
				}
			}
		}
		this.closeSt(this.splashType);
		this.close('splash-main','','',focusId);
	}
}



// Form-Functions
forummag.form = {
	// Validate one or more Field(s) -- Parameter fields is an Array containing the ids of the Input-Fields
	validateFields: function(fields,fieldlabel,deactivate) {
		if (this.fields) { // if the Parameters are set by some other function (e.g. setViolation())
			fields = this.fields;
			fieldlabel = this.fieldlabel;
		}
		var el, val, txt;
		for (var i=0; i<fields.length; i++) {
			el = poma.dom.$id(fields[i]);
			el.blur();
			val = this.trim(el.value);
			if (val == '' || val == ' ' || (el.type == 'checkbox' && !el.checked) ) {
				if (fieldlabel) {
					switch(el.type) {
						case 'checkbox': // Checkbox
							txt = forumValidateFieldsTextChckbx.replace("@@forumValidateFieldsFieldname@@", fieldlabel[i]);
							break;
						case 'select-one': // Select
							txt = forumValidateFieldsTextSlct.replace("@@forumValidateFieldsFieldname@@", fieldlabel[i]);
							break;
						default: // Text, Textarea
							txt = forumValidateFieldsTextTxtfld.replace("@@forumValidateFieldsFieldname@@", fieldlabel[i]);
							break;
					}
				} else {
					txt = forumValidateFieldsTextDef;
				}
				forummag.oc.splashOpen('splash-alert','error',txt);
				this.elId = el.id;
				return false;
			} else {
				if (deactivate) {
					var btn = poma.dom.$id(deactivate);
					btn.disabled = true;
					/*
					*if (btn.src.indexOf('-inactive') == -1) {
					*	btn.src = poma.scrollbox.prototype.convertFilePath(btn.src);
					*}
					*/
				}
			}
		}
	},
	// Function on OK-Button
	btnOk: function() {
		forummag.oc.splashClose(this.elId);
	},
	// Focus Element of validateFields (internal)
	focusEl: function(focusId) {
		if (focusId) {
			poma.dom.$id(focusId).focus();
		}
	},
	// Fields to get cleared
	clearFields: function(fieldsClr) {
		if (fieldsClr) {
			for (var i=0; i<fieldsClr.length; i++) {
				poma.dom.$id(fieldsClr[i]).value = '';
			}
		}
	},
	// Set validateField-Array and focus Textarea
	setViolation: function(val) {
		if (val == 'violation-3') { // fill fields-Array for validateFields()
			this.fields = ['subject','text'];
			this.fieldlabel = ['Art des Versto&szlig;es','Begr&uuml;ndung'];
			poma.dom.$id('text').focus();
		} else {
			this.fields = ['subject'];
		}
	},
	// Maxlength-Function for Textareas
	maxLength: function(field,value,maxlength) {
		if (maxlength != '') {
			if (parseInt(value.length) > parseInt(maxlength)) {
				field.value = value.substring(0, maxlength);
			}
		}
	},
	// Submit a Form onkeyup - IE only
	submitOnKeyUp: function(field) {
		if (poma.useragent.inName('msie', false)) {
			var evt = this.getKeyCode(field.event);
			if (evt == 13) {
				var form = field.parentNode;
				var resp = form.onsubmit();
				if (resp == undefined) {
					form.submit();
				}
			}
		}
	},
	// internal Crossbrowser-Function that returns the keyCode
	getKeyCode: function(event) {
		event = event || window.event;
		return event.keyCode;
	},
	// Trim a String, replace Whitespaces (internal)
	trim: function(str) {
		return str.replace(/(^\s+)([^\s]*)(\s+$)/, '$2');
	},
	//Set Partnerdata
	setPartnerdata: function(inputId, partnerData) {
	    poma.dom.$id(inputId).value = partnerData;
	}
}



// Admin-Functions
forummag.admin = {
	confirm: function(url,txt) {
		var conf = confirm(txt);
		if (conf) {
			window.location = url;
      return false;
    } else {
			return false;
		}
	}
}



// Availablity-Check
forummag.avail = {
	// check Availability
	checkNick: function(url) {
		var myReq = false;
		poma.dom.$id("agb-box").style.display = "none";
		poma.dom.$id("avail-form-control").style.display = "none";
		poma.dom.$id("successBox").style.display = "none";
		poma.dom.$id("warningBox").style.display = "none";
		poma.dom.$id("errorBox").style.display = "none";
		if (window.XMLHttpRequest) { // Mozilla, Safari,...
			myReq = new XMLHttpRequest();
		} else if (window.ActiveXObject) { // IE
			try {
				myReq = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				try {
					myReq = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e) {}
			}
		}
		if (!myReq) {
			poma.dom.$tag("li", poma.dom.$id("errorBox")).innerHTML = "Ein Fehler ist aufgetreten:\nKann keine XMLHTTP-Instanz erzeugen";
			forummag.oc.open("errorBox");
			return false;
		}
		myReq.onreadystatechange = function() {forummag.avail.requestDone(myReq);};
		myReq.open("GET", url+"?nickName="+poma.dom.$id("nick").value, true);
		myReq.send(null);
	},
	requestDone: function(req) {
		// only if req is "loaded"
		if (req.readyState == 4) {
			// only if "OK"
			if (req.status == 200 || req.status == 304) {
				var results = req.responseText; // var results can be used on screen, when technical response is needed for e.g. bugfixing
				if ("true" == results.trim()) {
					forummag.oc.open("successBox");
					var btn = poma.dom.$id('avail-check-btn');
					if (btn.src.indexOf('-inactive') == -1) {
						btn.src = poma.scrollbox.prototype.convertFilePath(btn.src);
					}
					// alternatively, this is also possible: forummag.oc.splashOpen('splash-alert','success',poma.dom.$id('successBox').innerHTML);
					poma.dom.$id("agb-box").style.display = "block";
					poma.dom.$id("avail-form-control").style.display = "block";
				} else {
					forummag.oc.open("warningBox");
				}
			} else {
				poma.dom.$tag("li", poma.dom.$id("errorBox")).innerHTML = "Ein Fehler ist aufgetreten:\n" +  req.statusText;
				forummag.oc.open("errorBox");
			}
		}
	}
}


/* RATE FOR LIVE VERSION */
forummag.rate = {
	// check Availability
	rate: function(url) {
		//http://meinungen.gmx.net/forum-gmx/rate/117926?rate=up
		var myReq = false;
		if (window.XMLHttpRequest) { // Mozilla, Safari,...
			myReq = new XMLHttpRequest();
		} else if (window.ActiveXObject) { // IE
			try {
				myReq = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				try {
					myReq = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e) {}
			}
		}
		if (url.indexOf("rateId")>-1) {
			var splitted = url.split("?");
            var params = splitted[1].split("&");
            var postIdParam = params[0].split("=");
			var rateParam = params[1].split("=");
		} else {
			var splitted = url.split("/rate/");
            var params = splitted[1].split("?");
			var postIdParam = ['rateId'];
			postIdParam[1] = params[0];
			var rateData = params[1].split("=");
            var rateParam = rateData;
		}
		myReq.onreadystatechange = function() {forummag.rate.requestDone(myReq, postIdParam, rateParam);};
		myReq.open("GET", url, true);
		myReq.send(null);
    },
	requestDone: function(req, postIdParam, rateParam) {
		// only if req is "loaded"
		if (req.readyState == 4) {
			// only if "OK"
            if (req.status == 200 || req.status == 304) {
				var results = req.responseText; // var results can be used on screen, when technical response is needed for e.g. bugfixing
                var splittedresult = results.split(":");
                var topIdName = "top"+postIdParam[1];
                var flopIdName = "flop"+postIdParam[1];
                var topIdHref = "votetop"+postIdParam[1];
                var flopIdHref = "voteflop"+postIdParam[1];
				var alreadyvotedAdviceName = "advice-alreadyvoted"+postIdParam[1];
				var thanksvotedAdviceName = "advice-thanksforvote"+postIdParam[1];
				if(poma.dom.$id(topIdName).innerHTML != splittedresult[0] || poma.dom.$id(flopIdName).innerHTML != splittedresult[1]) {
					poma.dom.$id(topIdName).innerHTML=splittedresult[0];
					poma.dom.$id(flopIdName).innerHTML=splittedresult[1];
					if(rateParam[1] == "up") {
						poma.dom.$id(topIdHref).className = "already-voted";
					} else if(rateParam[1] == "down") {
						poma.dom.$id(flopIdHref).className = "already-voted";
					}
					poma.dom.$id(thanksvotedAdviceName).style.visibility = "visible";
				} else {
					if(poma.dom.$id(thanksvotedAdviceName).style.visibility == "visible") {
						poma.dom.$id(thanksvotedAdviceName).style.visibility = "hidden";
					}
					poma.dom.$id(alreadyvotedAdviceName).style.visibility = "visible";
				}
			} else {
                alert("Es ist ein Fehler aufgetreten. Bitte versuchen Sie es zu einem anderen Zeitpunkt erneut.")
            }
		}
	}
}


// Super Tool
forummag.supertool = {
	activateBox: function(divId, divsCount) {
		/* hide all div-elements */
		var allDivsCount = 5;
		if (divsCount && divsCount > 0) {
			allDivsCount = divsCount;
		}
		for (var i = 1; i < allDivsCount; i++) {
	  		poma.dom.$id("most-discussed-" + i).className = "off";
			poma.dom.$id("most-discussed-link" + i).style.fontWeight = "normal";
		}
		/* show just the one Div Element */
		poma.dom.$id("most-discussed-" + divId).className = "";
		poma.dom.$id("most-discussed-link" + divId).style.fontWeight = "bold";
		counter.countPI(); // Count Pi
	}
}



// Login Area Hide and Show Divs
forummag.logintoptool = {
	hide: function(hideDiv) {
		poma.dom.$id(hideDiv).className = "off";
	},

	show: function(showDiv,focusId) {
		poma.dom.$id(showDiv).className = "expanded-div";
		if(focusId) {
			poma.dom.$id(focusId).focus();
		}
		counter.countPI(); // Count Pi
	},

	hideandshow: function(hideDiv, showDiv, focusId) {
		poma.dom.$id(hideDiv).className = "off";
		poma.dom.$id(showDiv).className = "expanded-div";
		if(focusId) {
			poma.dom.$id(focusId).focus();
		}
		counter.countPI(); // Count Pi
	}
}


forummag.split = {
	cutText: function(div, cnt) {

		var ret = poma.dom.$id(div).innerHTML;
		poma.dom.$id('teaser-alt-link-open').style.display = "block";
		poma.dom.$id('teaser-alt-link-close').style.display = "none";

		if (cnt < ret.length) {
			if (ret.charAt(cnt) != ' ') {
				ret = ret.substr(0, cnt);
				ret = ret.substr(0, ret.lastIndexOf(' '));
			}	else {
				ret = ret.substr(0, cnt);
			}
			var lastpos = ret.length-1;
			if (ret.charAt(lastpos) != '.') {
				// Last Character isn't a dot. We got to add 3 dots.
				ret += '...';
			} else {
				if(ret.charAt(lastpos - 1).toString().search(/^-?[0-9]+$/) == true) {
					// Last Character is a dot, before that comes an integer Character. We got to add 2 dots.
					ret += '..';
				}
			}
		} else {
				ret = ret.substr(0, cnt);
				poma.dom.$id('teaser-alt-link-open').style.display = "none";
				poma.dom.$id('teaser-alt-link-close').style.display = "none";
		}

		poma.dom.$id(div).innerHTML = ret + ' ';
	},

	showText: function(div, text) {
		var newtext = unescape(text);
		poma.dom.$id(div).innerHTML = newtext + ' ';
		poma.dom.$id('teaser-alt-link-open').style.display = "none";
		poma.dom.$id('teaser-alt-link-close').style.display = "block";
		counter.countPI(); // Count Pi
	}

}

function google_ad_request_done(google_ads) {
	var adsRelatedLink = '';
	var adsRelatedSpecialLink = '';
	var banned_words = new Array();
	var ads = 0;
	if (google_ads.length>0) {
		if($ui.browser.msie && $ui.browser.version.indexOf("6.") != -1) {
			adsRelatedLink += '<div class="unit" id="adsense"><div class="index"></div><div class="body"><ul>';
		} else {
			adsRelatedLink += '<div class="unit" id="adsense"><div class="index"></div><div class="body" style="position: relative;"><ul>';
		}
		if (google_ads[0].type == 'text') {
			for(i = 0; ( i < google_ads.length ); ++i) {
				text_ad = google_ads[i].line1 + " " +google_ads[i].line2 + " " +google_ads[i].line3 + " " +google_ads[i].visible_url;
				text_ad = text_ad.toUpperCase();
				for (e = 0; e < banned_words.length; ++e) {
					var pos=text_ad.indexOf(banned_words[e].toUpperCase());
					if (pos > 0) {
						var visible_ad = 0;
					}
				}
				if (visible_ad != 0) {
					var sc_adsense_event = 'event5';
					adsRelatedLink += '<li class="google-ad">';
					adsRelatedLink += '<a href="' + google_ads[i].url + '" target="_blank"><span class="title">' + google_ads[i].line1 +'</span></a><br />';
					adsRelatedLink += '<a href="' + google_ads[i].url + '" rel="nofollow" target="_blank"><span class="text">' + google_ads[i].line2 +'<br />'+ google_ads[i].line3 + "</span></a>";
					adsRelatedLink += '<a href="' + google_ads[i].url + '" rel="nofollow" target="_blank"><span class="link">' + google_ads[i].visible_url + '</span></a>';
					adsRelatedLink += '</li>';
					++ads;
				} else {
					visible_ad = 1;
				}
			}
		}
	adsRelatedLink += '</ul><div class="clear-b"></div><span style="position: absolute; right: 10px; bottom: 5px; color: #999; font-size: 11px;">Ads by Google</span></div></div>';
	document.write(adsRelatedLink);
	}
}