var inOneYear = (new Date((new Date).getTime()+31536000000)).toGMTString();
var twickitLanguage = 'de';


function rateTwick(inTwickId, inRating, inSum, inCount) {
	$("rating-text" + inTwickId).update("<img src='http://twick.it/html/img/ajax-loader.gif' alt='Bitte warten' />");

	_changeRatingText(inTwickId, inRating, inSum, inCount);
	new Effect.Shake("rating-text" + inTwickId, {"distance":"10"});

	var url = "http://twick.it/inc/ajax/rate_twick.php?secret=&id=" + inTwickId + "&rating=" + inRating;
	new Ajax.Request(url, {
		method: 'get',
	  	onSuccess: function(transport) {
	    	var response = transport.responseText;
	    	if (response) {
	    		var info = response.evalJSON(true);
	    	} else {
	   		 	popup("Es ist ein Fehler aufgetreten. Bitte versuche es erneut.");
	    	}
	  	}	
	});
	
	if(inRating == 1) {
		doDrillDown("Danke. Du findest die Erklärung gut? Dann teile sie mit deinen Freunden. Klick einfach auf Twitter, Facebook oder eins der anderen Bookmark-Symbole in der rechten Spalte.", 5000);
	} else {
		doDrillDown("Danke. Du findest die Erklärung schlecht? Dann versuch doch, einen besseren Twick zu schreiben! Wenn du es nicht kannst, wer dann?", 5000);
	}
}


function _changeRatingText(inId, inRating, inSum, inCount) {
	var text = "";
	if (inCount == 1) {
		if (inSum == 1) {
			text = "1 Punkt bei 1 Bewertung";
		} else {
			text = "-1 Punkt bei 1 Bewertung";
		}
	} else {
		if (inSum == 1) {
			text = "1 Punkt bei {2} Bewertungen";
		} else {
			text = "{1} Punkte bei {2} Bewertungen";
		}
	}
	
	text = text.replace(/\{1\}/, inSum).replace(/\{2\}/, inCount);
	$("rating-text" + inId).update(text);
	$("rating-text" + inId).className = inSum<0 ? "anzahl-schlecht" : "anzahl-gut";
	
	if (inRating == 1) {
		$("thumb-down" + inId).className = "negativ-aus";
		$("thumb-up" + inId).className = "positiv-button";
		$("thumb-down" + inId).onclick = function() {rateTwick(inId, -1, parseInt(inSum)-2, inCount);};
		$("thumb-up" + inId).onclick = function() {doPopup('Du hast diesen Twick bereits als gut bewertet.');};
		$("thumb-up" + inId).blur();
	} else {
		$("thumb-down" + inId).className = "negativ-button";
		$("thumb-up" + inId).className = "positiv-aus";
		$("thumb-down" + inId).onclick = function() {doPopup('Du hast diesen Twick bereits als schlecht bewertet.');};
		$("thumb-up" + inId).onclick = function() {rateTwick(inId, 1, parseInt(inSum)+2, inCount);};
		$("thumb-down" + inId).blur();
	}
}


function addFavorite(inTwickId) {
	var url = "http://twick.it/action/save_favorite.php?add=1&secret=&id=" + inTwickId;
	new Ajax.Request(url, {
		method: 'get',
	  	onSuccess: function(transport) {
	    	var success = transport.responseText;
	    	if (success == "OK") {
	    		$('fav'+inTwickId).className="stern-aktiviert";
	    		$('fav'+inTwickId).onclick = function() {removeFavorite(inTwickId); };
	    		$('fav'+inTwickId).title = "Aus Deinen Favoriten entfernen";
	    		$('fav'+inTwickId).blur();
	    		doDrillDown("Der Twick wurde unter Deinen Favoriten gespeichert.", 5000);
	    	} else {
	   		 	popup("Es ist ein Fehler beim Speichern des Twicks als Favorit aufgetreten.");
	    	}
	  	}	
	});
}


function removeFavorite(inTwickId) {
	var url = "http://twick.it/action/save_favorite.php?secret=&id=" + inTwickId;
	new Ajax.Request(url, {
		method: 'get',
	  	onSuccess: function(transport) {
	    	var success = transport.responseText;
	    	if (success == "OK") {
	    		$('fav'+inTwickId).className="stern";
	    		$('fav'+inTwickId).onclick= function() {addFavorite(inTwickId); };
	    		$('fav'+inTwickId).blur();
	    		$('fav'+inTwickId).title = "Zu Deinen Favoriten hinzufügen";
	    		doDrillDown("Der Twick wurde aus Deinen Favoriten entfernt.", 5000);
	    	} else {
	   		 	popup("Es ist ein Fehler beim Entfernen des Twicks aus Deinen Favorit aufgetreten.");
	    	}
	  	}	
	});
}


function insertAtCursor(inField, inValue) {
    if (document.selection) {
        inField.focus();
        sel = document.selection.createRange();
        sel.text = inValue;
    } else if (inField.selectionStart || inField.selectionStart == '0') {
        inField.focus();
       
        var startPos = inField.selectionStart;
        var endPos = inField.selectionEnd;
        inField.value = inField.value.substring(0, startPos) + inValue + inField.value.substring(endPos, inField.value.length);
        inField.setSelectionRange(endPos+inValue.length, endPos+inValue.length);
    } else {
        inField.value += inValue;
    }
}


function updateCharCounter(inId) {
	var counterId = "charCounter";
	if (inId != null) {
		counterId += inId;
	}

	var textfieldId = "textfield";
	if (inId != null) {
		textfieldId += inId;
	}

	
	var textLength = $(textfieldId).value.length;
	var charsLeft = 140-textLength;
	$(counterId).update(charsLeft);
	
	if (charsLeft < 0) {
		disableTwickitButton(inId);
		$(counterId).className = "charCounterError";
		$(textfieldId).className = "error";
	} else if (charsLeft == 140) {
		disableTwickitButton(inId);
	} else {
		enableTwickitButton(inId);
		$(counterId).className = "charCounterOK";
		$(textfieldId).className = "ok";
	}
}

function enableTwickitButton(inId) {
	var buttonId = "twickit";
	var formId = "twickit-blase";
	if (inId != null) {
		buttonId += inId;
		formId += inId;
	}
	var button = $(buttonId);
	button.className = "twickitpreview";
	button.onclick = function() { $(formId).submit(); };
};

function disableTwickitButton(inId) {
	var buttonId = "twickit";
	if (inId != null) {
		buttonId += inId;
	}
	var button = $(buttonId);
	button.className = "twickitpreview-off";
	button.onclick = null;
};

var wikipediaTimeout;
function insertWikipediaLink(inTitle) {
	try {
		var url = "http://twick.it/inc/ajax/get_wikipedia_link.php?title=" + encodeURIComponent(inTitle);
	
		new Ajax.Request(url, {
			method: 'get',
		  	onSuccess: function(transport) {
		  		var response = transport.responseText;
		  		if (response) {
			  		var wikipedia = response.evalJSON(true);
			  		var text = "Wikipedia über &quot;" + wikipedia.title + "&quot;:<br />";
			  		text += wikipedia.description + "<br /><a href='" + wikipedia.link + "' target='_blank' class='teaser-link'><img src='html/img/pfeil_weiss.gif'/>Mehr</a><br />";
					$("wikipedia").update(text);
					clearTimeout(wikipediaTimeout);
				} else {
					$("wikipedia-teaser").fade();
				}
		  	}	
		});
		
		wikipediaTimeout = window.setTimeout("$('wikipedia-teaser').fade()", 10000);
	} catch(ignoredException) {}
}


function expandPageTitles() {
	var links = $$(".moreinfos");
	for(var i=0; i<links.length; i++) {
		var link = links[i];
		var url = "http://twick.it/inc/ajax/get_page_title.php?url=" + encodeURIComponent(link) + "&id=" + link.id;

		new Ajax.Request(url, {
			asynchronous: true,
			method: 'get',
		  	onSuccess: function(transport) {
		  		var page = transport.responseText.evalJSON(true);
				$(page.id).update(page.title);
		  	}	
		});
	}
}


var more = new Array();
function showMore(inId, inQueryString, inCount) {
	var offset = more[inId];
	if (offset == null) {
		offset = 0;
	}
	offset += inCount;
	
	$(inId + "MoreLink").hide();
	$(inId + "MoreLinkWait").show();

	var url = "http://twick.it/inc/ajax/show_more_" + inId + ".php?" + inQueryString + "&offset=" + offset + "&limit=" + inCount;
	new Ajax.Request(url, {
		method: 'get',
	  	onSuccess: function(transport) {
	  		$(inId + "MoreLinkWait").hide();
	  		var response = transport.responseText;
	  		var status = response.substring(0, 1);
	  		var text = response.substring(1);
	  		
	  		if (text != "") {
	  			var nextContainer = new Element("div", { "class": "dummy-container" }).update(text);
	  			$(inId).appendChild(nextContainer);
	  		}
	  		
	  		if (status == 1) {
	    		$(inId + "MoreLink").show();
	    	} else {
	    		$(inId + "MoreLink").hide();
	    	}
	  	}	
	});
	
	more[inId] = offset;
}

function showEditor(inId) {
	$("twick" + inId).hide();
	$("twick_editor" + inId).show();
}

function hideEditor(inId) {
	$("twick" + inId).show();
	$("twick_editor" + inId).hide();
}


function hover(inId) {
	$(inId + "-link").style.backgroundImage = "url(lang/de/buttons/bt_" + inId + "_hover.png)";
	try {
		alphaBackgrounds();
	} catch(NoIE) {}
}

function reset(inId) {
	$(inId + "-link").style.backgroundImage = "url(lang/de/buttons/bt_" + inId + ".png)";
	try {
		alphaBackgrounds();
	} catch(NoIE) {}
}



var suggestTimeouts;
var prevSearch;
function updateSuggest() {
	if(suggestTimeouts != null) {
		clearTimeout(suggestTimeouts); 
		suggestTimeouts=window.setTimeout("_updateSuggest()", 250);
	} else {
		suggestTimeouts=window.setTimeout("_updateSuggest()", 0);
	}
}


function _updateSuggest() {
	var search = document.searchForm.search.value;
	if (search != prevSearch) {
		suggestIndex = -1;
		if (search.length > 1) {
			var url = "http://twick.it/interfaces/api/find_topic.json?limit=13&search=" + search;
		
			new Ajax.Request(url, {
				method: 'get',
			  	onSuccess: function(transport) {
			    	var suggests = transport.responseText.evalJSON(true);
			    	var suggestText = "";
					var query = suggests.query.toQueryParams().search;
					
			    	for (var i=0; i<suggests.topics.length; i++) {
				    	if(i>=12) {
				    		suggestText += "<li style='color:#FFFFFF;'>...</li>";
				    	} else {
				    		var title = suggests.topics[i].title;
				    		var regex = eval("/(" + query + ")/gi");
				    		title = title.replace(regex, "<span>$1</span>");
				    		suggestText += "<li><a href='" + suggests.topics[i].url.replace(/'/g, "%27") + "' id='searchSuggest" + i + "' class='searchSuggest'>" + title + "</a></li>";				    		
				    	}
			    	}
			    	suggestLength = suggests.topics.length;

			    	if (suggestLength > 0) {
			    		$('searchSuggest').update("<ul>" + suggestText + "</ul>");	
				    	$('such-klappfeldinhalt').style.display = "block";
				    } else {
				    	$('searchSuggest').update("<i>Keine Treffer</i>");	
				    	$('such-klappfeldinhalt').fade({duration: 3});
				    }
			  	}	
			});
		} else {
			$('such-klappfeldinhalt').hide();
			$('searchSuggest').update("");
		}	
		prevSearch = search;		
	}
}


var suggestIndex = -1;
var suggestLength = -1;
function searchUpDown(inEvent) {
	var code; //variable to save keystroke
	if (!inEvent) var inEvent = window.event; 
	if (inEvent.keyCode) code = inEvent.keyCode;
	
	if (code == 38) {
		if (suggestIndex > 0) {
			updateSuggestIndex(false);
			suggestIndex--;
			title = $("searchSuggest" + suggestIndex).innerHTML.replace(/<span>(.+?)<\/span>/gi, "$1");
			$("search").value = title;
			prevSearch = $("search").value;
		}	
	} else if (code == 40) {
		if (suggestIndex < suggestLength-1) {
			updateSuggestIndex(true);
			suggestIndex++;
			title = $("searchSuggest" + suggestIndex).innerHTML.replace(/<span>(.+?)<\/span>/gi, "$1");
			$("search").value = title;
			prevSearch = $("search").value;
		}
	} else {
		updateSuggest();
	}
} 

function updateSuggestIndex(inDown) {
	var nextIndex = inDown ? suggestIndex+1 : suggestIndex-1;
	if (suggestIndex >= 0) { 
		$("searchSuggest" + suggestIndex).style.fontWeight="normal";
		$("searchSuggest" + suggestIndex).style.fontSize="12px";
	}
	$("searchSuggest" + nextIndex).style.fontWeight="bold";
	$("searchSuggest" + nextIndex).style.fontSize="14px";
}


function waitPopup() {
	doPopup("<div style='width:100%;text-align: center; font-size:20px;'><img src='http://twick.it/html/img/ajax-loader.gif' /> Bitte warten...</div>", " ", true);
}


function confirmPopup(inText, inLink) {
	doPopup(inText + "<br /><br />", " ", true);
	var myUrl = window.location.href.gsub('http://twick.it', '');
	$("popup-footer").innerHTML += '<div><a href="' + inLink + '" id="popup_yes">Ja</a><a href="javascript:;" onclick="$(\'curtain\').remove(); $(\'popup-kasten\').remove();" id="popup_no">Nein</a></div>';
}

function popup(inText, inTitle, inWithoutOK) {
	Event.observe(
		window, 
		'load', 
		function() {
			doPopup(inText, inTitle, inWithoutOK);
		}
	);
}


function doLoginPopup(inText, inTitle, inWithoutOK) {
	doPopup(inText, inTitle, inWithoutOK);
	var myUrl = window.location.href.gsub('http://twick.it', '');
	$("popup-content").innerHTML += '<br /><br /><form id="loginForm3" action="action/login.php?url='+ myUrl + '" method="post"><label for="login" style="width:80px;display:block;float:left;">Benutzer:&nbsp;</label><input type="text" name="login" id="loginField2" onfocus="this.select()"/><br /><label for="password" style="width:80px;display:block;float:left;">Passwort:&nbsp;</label><input type="password" name="password" id="passwordField2" onfocus="this.select()"/><br /><a href="javascript:;" onclick="$(\'loginForm3\').submit();" class="einloggen-de" style="margin: 5px 0px 0px 80px; float:none;">&nbsp;</a></form>';
	$("popup-content").innerHTML += '<br /><br /><a href="register_form.php">Du hast noch kein Benutzerkonto? Klick hier, um Dich zu registrieren.</a>';
	$("popup_ok").update("Schließen");
}

function doPopup(inText, inTitle, inWithoutOK) {
		var curtain = new Element("div", { "id": "curtain" });
		$$("body")[0].appendChild(curtain);
		fade($("curtain"), 0.6);

		if (!inTitle) {
			inTitle = "Hoppla!";
		}

		var popup = new Element("div", { "class": "popup-kasten", "id": "popup-kasten" });
		var popupHead = new Element("div", { "class": "popup-head" });
		popupHead.appendChild(new Element("h1").update(inTitle));
		var popupBody = new Element("div", { "class": "popup-body", "id": "popup-content" }).update(inText);
		var popupFooter = new Element("div", { "class": "popup-footer", "id": "popup-footer" });
		if (!inWithoutOK) {
			var okHolder = new Element("div", { "style":  "width:100%; text-align:right;" });
			var ok = new Element("a", { "id": "popup_ok", "href": "javascript:;" }).update("OK");
			ok.onclick = 
				function() {
					$$("body")[0].removeChild(curtain);
					$$("body")[0].removeChild(popup);
				};
			okHolder.appendChild(ok);
			popupFooter.appendChild(okHolder);
		}

		popup.appendChild(popupHead);
		popup.appendChild(popupBody);
		popup.appendChild(popupFooter);
		
		$$("body")[0].appendChild(popup);
		
		popup.style.top = ((document.documentElement.clientHeight/2) - (popup.offsetHeight/2)) + "px";
		popup.style.left = ((document.documentElement.clientWidth/2) - (popup.offsetWidth/2)) + "px";
	}


function drillDown(inText, inTimeout) {
	Event.observe(
		window, 
		'load', 
		function() { 
			doDrillDown(inText, inTimeout);
		 }
	);
}


var drilldownTimeouts;
function doDrillDown(inText, inTimeout) {
	if(drilldownTimeouts != null) {
		clearTimeout(drilldownTimeouts);
	} 
	_removeAllDrilldowns();
	
	var drillDown = new Element("div", { "id": "drill-down", "class": "drill-down", "style": "display:none;", "title": "Zum Schließen einfach anklicken"});
	drillDown.onclick = function() {
		this.blindUp();
	};
	
	var drillDownBox = new Element("div", { "id": "drill-down-box"}).update(inText);
	drillDown.appendChild(drillDownBox);

	$("main").appendChild(drillDown);

	fade(drillDown, 0.95);
	drillDown.blindDown();

	drilldownTimeouts=window.setTimeout("_removeAllDrilldowns()", inTimeout);
}


function _removeAllDrilldowns() {
	var drillDowns = $$(".drill-down");
	for (var i=0; i<drillDowns.length; i++) {
		drillDowns[i].blindUp();
	}
}
	

function fade(inObject, inValue) {
    //CSS3
    if (typeof inObject.style.opacity == "string") {
        inObject.style.opacity = inValue;
        //Mozilla Filter Implementation
    } else if (typeof inObject.style.MozOpacity == "string") {
        inObject.style.MozOpacity = inValue;
        //Microsoft Filter Implementation
    } else if (typeof inObject.style.filter == "string") {
        inObject.style.filter = "alpha( opacity = " + inValue * 100 + ")";
    }
}


function evalKeyForSubmit(inEvent, inForm) {  
    if (inEvent && inEvent.which == 13) {
       inForm.submit();  
    } else {
       return true;  
    }
}  


function preloadImage(inSrc) {
	img = new Image();
	img.src = inSrc;
}


function preloadButtonImages() {
	preloadImage("http://twick.it/lang/de/buttons/bt_start_hover.png");
	preloadImage("http://twick.it/lang/de/buttons/bt_benutzer_hover.png");
	preloadImage("http://twick.it/lang/de/buttons/bt_dashboard_hover.png");
	preloadImage("http://twick.it/lang/de/buttons/bt_favoriten_hover.png");
	preloadImage("http://twick.it/lang/de/buttons/bt_blog_hover.png");
	
	preloadImage("http://twick.it/lang/de/buttons/bt_wissensbaum_hover.jpg");
	preloadImage("http://twick.it/lang/de/buttons/bt_suchfeld_hover.jpg");
	preloadImage("http://twick.it/lang/de/buttons/bt_logout_active.jpg");
	preloadImage("http://twick.it/lang/de/buttons/bt_login_active.jpg");
	preloadImage("http://twick.it/html/img/teaser_button_hover.png");
	preloadImage("http://twick.it/html/img/bt_lupe_hover.jpg");
	preloadImage("http://twick.it/html/img/ajax-loader.gif");
	preloadImage("http://twick.it/html/img/stift_hover.gif");
	preloadImage("http://twick.it/html/img/muelleimer_hover.gif");
	preloadImage("http://twick.it/html/img/ansicht_hover.gif");
	preloadImage("http://twick.it/html/img/totenkopf_hover.gif");
}

Event.observe(
	window, 
	'load', 
	preloadButtonImages
);





// Copyright (C) 2005-2008 Ilya S. Lyubinskiy. All rights reserved.
// Technical support: http://www.php-development.ru/
//
// YOU MAY NOT
// (1) Remove or modify this copyright notice.
// (2) Re-distribute this code or any part of it.
//     Instead, you may link to the homepage of this code:
//     http://www.php-development.ru/javascripts/dropdown.php
//
// YOU MAY
// (1) Use this code on your website.
// (2) Use this code as part of another product.
//
// NO WARRANTY
// This code is provided "as is" without warranty of any kind.
// You expressly acknowledge and agree that use of this code is at your own risk.


// ***** Popup Control *********************************************************

// ***** at_show_aux *****

function at_show_aux(parent, child)
{
  var p = document.getElementById(parent);
  var c = document.getElementById(child );

  var top  = (c["at_position"] == "y") ? p.offsetHeight+2 : 0;
  var left = (c["at_position"] == "x") ? p.offsetWidth +2 : 0;

  for (; p; p = p.offsetParent)
  {
    top  += p.offsetTop;
    left += p.offsetLeft;
  }

  c.style.position   = "absolute";
  c.style.top        = top +'px';
  c.style.left       = left+'px';
  c.style.visibility = "visible";
}

// ***** at_show *****

function at_show()
{
  var p = document.getElementById(this["at_parent"]);
  var c = document.getElementById(this["at_child" ]);

  at_show_aux(p.id, c.id);
  clearTimeout(c["at_timeout"]);
}

// ***** at_hide *****

function at_hide()
{
  var p = document.getElementById(this["at_parent"]);
  var c = document.getElementById(this["at_child" ]);

  c["at_timeout"] = setTimeout("document.getElementById('"+c.id+"').style.visibility = 'hidden'", 333);
}

// ***** at_click *****

function at_click()
{
  var p = document.getElementById(this["at_parent"]);
  var c = document.getElementById(this["at_child" ]);

  if (c.style.visibility != "visible") at_show_aux(p.id, c.id); else c.style.visibility = "hidden";
  return false;
}

// ***** at_attach *****

// PARAMETERS:
// parent   - id of the parent html element
// child    - id of the child  html element that should be droped down
// showtype - "click" = drop down child html element on mouse click
//            "hover" = drop down child html element on mouse over
// position - "x" = display the child html element to the right
//            "y" = display the child html element below
// cursor   - omit to use default cursor or specify CSS cursor name

function at_attach(parent, child, showtype, position, cursor)
{
  var p = document.getElementById(parent);
  var c = document.getElementById(child);

  p["at_parent"]     = p.id;
  c["at_parent"]     = p.id;
  p["at_child"]      = c.id;
  c["at_child"]      = c.id;
  p["at_position"]   = position;
  c["at_position"]   = position;

  c.style.position   = "absolute";
  c.style.visibility = "hidden";

  if (cursor != undefined) p.style.cursor = cursor;

  switch (showtype)
  {
    case "click":
      p.onclick     = at_click;
      p.onmouseout  = at_hide;
      c.onmouseover = at_show;
      c.onmouseout  = at_hide;
      break;
    case "hover":
      p.onmouseover = at_show;
      p.onmouseout  = at_hide;
      c.onmouseover = at_show;
      c.onmouseout  = at_hide;
      break;
  }
}
