//evtl ins layout??
//var $buoop = {} 
//$buoop.ol = window.onload; 
//window.onload=function(){ 
 //if ($buoop.ol) $buoop.ol(); 
 //var e = document.createElement("script"); 
 //e.setAttribute("type", "text/javascript"); 
 //e.setAttribute("src", "http://browser-update.org/update.js"); 
 //document.body.appendChild(e); 
//} 
// jetzt im layout, weil schwachsinniger code



//var Magistrix.imageHost = "http://images.magistrix.de"
//if (location.host != "www.magistrix.de") {
  //Magistrix.imageHost = ""
//}
//var loadingHTML = '<img src="/images/progress.gif" alt="loading" />';
//var lyric_change_id = null;
//var active_albums = [];



//function writeCookie(key, value)
//{
 //var a = new Date();
 //var expires_in = 1000*60*60*24*90;
 //d = new Date(a.getTime() + expires_in);
 //document.cookie = key+'='+value+'; expires='+d.toGMTString()+';';
//}

//function readCookie(key)
//{
 //a = document.cookie;
 //res = '';
 //while(a != '')
 //{
  //while(a.substr(0,1) == ' '){a = a.substr(1,a.length);}
  //cookiename = a.substring(0,a.indexOf('='));
  //if(a.indexOf(';') != -1)
  //{cookiewert = a.substring(a.indexOf('=')+1,a.indexOf(';'));}
  //else{cookiewert = a.substr(a.indexOf('=')+1,a.length);}
  //if(key == cookiename){res = cookiewert;}
  //i = a.indexOf(';')+1;
  //if(i == 0){i = a.length}
  //a = a.substring(i,a.length);
 //}
  //return(res)
//}

//function destroyCookie(n)
//{
 //document.cookie = n+'=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
//} 


//function listChanged(e){
  //// neues Elternelement
  //parent = $('lyric'+lyric_change_id).parentNode;
  //i      = parent.id.replace(/lyric_list_/, "");
  
  //new Ajax.Request('/admin/lyric/set_album', {
    //method     : 'post', 
    //asynchronous : true, 
    //evalScripts  : true, 
    //parameters   : {
      //lyric_id : lyric_change_id,
      //album_id : active_albums[i*1]
    //}
  //})
  
//}

//function save_album_id(e){
  //// "lyric" abschneiden, um die id zu bekommen
  //lyric_change_id = extract_lyric_id(e)
//}


//function extract_lyric_id(e){
  //// "lyric" von der id des elements abschneiden, um die id als zahl zu bekommen
  //return e.id.substr(5);
//}


//function closeVideoForm(){
  //$('new_video2').hide();
  //$('new_video').show();
//}


//var loadedElements = []

//function loadOrClose(id, url){
  //var e = $(id);
  //var loaded = loadedElements.indexOf(e) != -1
  //if(e.visible() && loaded){
    //Effect.BlindUp(e);
  //}else{
    //var onComplete = function(){ Effect.BlindDown(e) }
    //if (true || loaded) {
      //e.hide();
      //new Ajax.Updater(e, url, {
        //onComplete: onComplete,
        //method: 'get'
      //});
      //loadedElements.push(e);
    //}else{
      //onComplete();
    //}
  //}
//}



/* Video functions -------------------------------------------------------  */

//var videoMover;
//var videoProviders = {
  //1 : '<embed width="425" height="350" src="http://images.magistrix.de/player/player.swf" allowfullscreen="true" flashvars="autostart=true&file=http://www.youtube.com/watch?v=%ID%" />',
  //2 : '<object width="470" height="406" type="application/x-shockwave-flash" data="http://www.myvideo.de/movie/%ID%"><param name="movie" value="http://www.myvideo.de/movie/%ID%"></param></object>'
//}

//function show_video(provider,id){
  
  //if(videoMover)
    //close_video();
  
////  $('lyricText').style.marginRight='280px';

  //var div = document.createElement("div");
  //div.id        = "video";  
  //div.innerHTML = '<a href="javascript:close_video()" id="video-close"></a>' + videoProviders[provider].replace(/%ID%/g,id);
    
  //document.body.appendChild(div);
    
  //move_video(true);
  
  //videoMover = window.setInterval("move_video(false)",40);
//}

//function move_video(immediately){
  //var offset = offset = (window.innerHeight ? window.innerHeight : document.documentElement.clientHeight) / 2 - 200;
  //offset += window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop;
  //var style = $('video').style;
  //var top = style.top ? parseInt(style.top) : 0;
  
  //if(immediately){
    //style.top = offset + 'px'
  //}else if(top != offset){
    //style.top = offset - ((offset-top)/2).ceil() + 'px';
  //}
//}

//function close_video(){
////  $('lyricText').style.marginRight='';
  //window.clearInterval(videoMover);
  //videoMover = null;
  //$("video").remove();
//}

/* Lyric functions -------------------------------------------------------  */

//function toggleArtistTextSearch(){
  //var e = $('artistTextSearch');
  //e.toggle();
  //if(e.visible()){
    //$('artistTextSearchField').focus();
  //}
//}

//function artist_tip(link,count,image){
  //general_tip(link,image=='' ? null : "http://www.magistrix.de/data/artists/"+image, count + (count==0 ? " Text" : " Texte"))
//}

//function general_tip(link,imageUrl,text){
  
  //var createTip = function(e,html){
    //new Tip(e, html, {
      //stem: 'bottomMiddle',
      //hook: {
        //tip: 'bottomMiddle',
        //target: 'topMiddle'
      //},
      //style: 'protogrey'
    //});
    //e.prototip.show();
  //}
  
  //var html = text;
  
  //if(imageUrl){
    //html = "<img src='" + imageUrl + "' /><br />" + html
    //var img = new Image()
    //img.onload = function(){
      //createTip(link,html);
    //}
    //link.onmouseout = function(){
      //if(!img.completed)img.onload = function(){};
    //}
    //img.src = imageUrl;
  //}else{
    //createTip(link,html);
  //}
//}


/* Lyric functions -------------------------------------------------------  */

function checkDuplicateLyric(e){
  var language_id = e['lyric[language_id]'].value;
  var translated  = checkValue(e['lyric[translated]']);
  var artist_name = e['lyric[artist_name]'].value;
  var lyric_name  = e['lyric[name]'].value;
  var album_name  = e['lyric[album_name]'].value;

  // Bei leerem Interpreten-Namen / Title nicht prüfen
  if(artist_name=='' || lyric_name==''){
    if (artist_name=='' || lyric_name=='') {
      $('lyric_submit_button').disabled = true;
    }
    return;
  }
  
  $('lyric_submit_button').disabled = true;
  
  new Ajax.Request('check_duplicate', {
    method     : 'post', 
    asynchronous : false,
    parameters   : {
      artist_name : artist_name,
      lyric_name  : lyric_name,
      album_name  : album_name,
      language_id : language_id,
      translated  : translated
    }
  });
}

function submitLyricIfNew(e){
  if ($('lyric_text').textLength < 30) {
    alert("Bitte gib noch den Songtext ein. Danke. ;-)");
  }
  else {
    checkDuplicateLyric(e);
    if($('lyric_submit_button').disabled == false) {
      e.submit();
    }
  }
  return false;
}


function quicksearch(e){
  if(e.defaultValue == e.value){
    e.value=''
  }
  
  e.onblur = function(){
    if(e.value==''){
      e.value = e.defaultValue;
    }
  }
}

function check_username()
{
  var username=$('user_name').value;
  
  new Ajax.Updater('username_available', '/users/check_username/'+username, {method: 'get'})
  
}

/* Comment functions -------------------------------------------------------  */

// Quelle: http://aktuell.de.selfhtml.org/tippstricks/javascript/bbcode/
//function form_insertText(input, aTag, eTag) {
  //input.focus();
  //[> für Internet Explorer <]
  //if(typeof document.selection != 'undefined') {
    //[> Einfügen des Formatierungscodes <]
    //var range = document.selection.createRange();
    //var insText = range.text;
    //range.text = aTag + insText + eTag;
    //[> Anpassen der Cursorposition <]
    //range = document.selection.createRange();
    //if (insText.length == 0) {
      //range.move('character', -eTag.length);
    //} else {
      //range.moveStart('character', aTag.length + insText.length + eTag.length);      
    //}
    //range.select();
  //}
  //[> für neuere auf Gecko basierende Browser <]
  //else if(typeof input.selectionStart != 'undefined')
  //{
    //[> Einfügen des Formatierungscodes <]
    //var start = input.selectionStart;
    //var end = input.selectionEnd;
    //var insText = input.value.substring(start, end);
    //input.value = input.value.substr(0, start) + aTag + insText + eTag + input.value.substr(end);
    //[> Anpassen der Cursorposition <]
    //var pos;
    //if (insText.length == 0) {
      //pos = start + aTag.length;
    //} else {
      //pos = start + aTag.length + insText.length + eTag.length;
    //}
    //input.selectionStart = pos;
    //input.selectionEnd = pos;
  //}
  //[> für die übrigen Browser <]
  //else
  //{
    //[> Abfrage der Einfügeposition <]
    //var pos;
    //var re = new RegExp('^[0-9]{0,3}$');
    //while(!re.test(pos)) {
      //pos = prompt("Einfügen an Position (0.." + input.value.length + "):", "0");
    //}
    //if(pos > input.value.length) {
      //pos = input.value.length;
    //}
    //[> Einfügen des Formatierungscodes <]
    //var insText = prompt("Bitte geben Sie den zu formatierenden Text ein:");
    //input.value = input.value.substr(0, pos) + aTag + insText + eTag + input.value.substr(pos);
  //}
//}

//function insertSmilie(e,code){
  //form_insertText(e," " + code + " ",'');
//}

//function comment_insertSmilie(code){
  //insertSmilie($('comment_text'),code);
//}
//function comment_printSmilie(code,path){
  //var img_id="smiley_image_" + Math.floor(Math.random()*1000)

  //document.write('<img id="'+img_id+'" src="' + path +'" onClick="comment_insertSmilie(\'' + code + '\')"> ');
  /*
   * Viele Benutzer probieren, einen Smiley per Drag'n'Drop in das Formular
   * einzufügen statt die Grafiken als Buttons zu nutzen. Die gängigen Browser
   * würden beim Versuch, einen Smiley in das Formular zu droppen,
   * den URL statt den ALT-Text in das Formular einfügen. Dies korrigieren
   * wir, in dem wir aus den Grafiken echte Draggables machen.
   */
  //new Draggable(img_id, {revert:true} );
//}
//function comment_printSmilies(){
  //comment_printSmilie(':)',   Magistrix.imageHost+'/images/smilies/icon_smile.gif');
  //comment_printSmilie(':love',Magistrix.imageHost+'/images/smilies/icon_love.gif');
  //comment_printSmilie('8)',   Magistrix.imageHost+'/images/smilies/icon_cool.gif');
  //comment_printSmilie(':(',   Magistrix.imageHost+'/images/smilies/icon_sad.gif');
  //comment_printSmilie(':((',  Magistrix.imageHost+'/images/smilies/icon_mad.gif');
  //comment_printSmilie(':ow',  Magistrix.imageHost+'/images/smilies/icon_ow.gif');
  //comment_printSmilie(':yes', Magistrix.imageHost+'/images/smilies/icon_yes.gif');
  //comment_printSmilie(':no',  Magistrix.imageHost+'/images/smilies/icon_no.gif');
//}


//function comment_destroy(id){
  //new Ajax.Request('/comments/destroy', {parameters: {id:id},
    //onSuccess : function(){
      //$('comment_'+id+'_row').remove();
    //},
    //onFailure : function(transport){
      //alert(transport.responseText);
    //}
  //});
//}





/* User functions -------------------------------------------------------  */

//function append_user_tip(link){
//  link.onmouseover = null;
//  new Tip(link, {
//    ajax: {
//      url: '/users/tip/' + link.firstChild.data,
//      options: {
//        method: 'get',
//      }
//    },
//    stem: 'bottomMiddle',
//    style: 'protogrey',
//    width: '150px',
//    hook: {
//      tip: 'bottomMiddle',
//      target: 'topMiddle'
//    }
//  });
//}


//document.observe("dom:loaded", function() {
//  $$('.userIconF').each(function(link){ append_user_tip(link) });
//  $$('.userIconM').each(function(link){ append_user_tip(link) });
//});


/* Rating functions -------------------------------------------------------  */

/*
 * Bewerten eines Elements
 */

//function ratingField(url,avg,total,locked){
  
  //document.write("<div id='rating'></div>");
  
  //var box = new Starbox('rating', avg, {
    //stars: 5,
    //total: total,
    //className: 'pointy',
    //locked: locked,
    //onRate: function(element, memo){
      //new Ajax.Request(url, {method: 'post', parameters: {rating:memo['rated']}}
    //)},
    //indicator: total==0 ? 'Noch nicht bewertet' : 'Bewertet mit #{average} Sternen <small>(#{total}x bewertet)</small>'
  //});
  
  //$('rating').observe('starbox:changed', starboxChangedText) // observe the mouseover
  //$('rating').observe('starbox:rated',   starboxThankYou) // observe the click
  //$('rating').observe('starbox:left',    starboxLeftText); // observe the mouseout
//}

// when the link is clicked update the restore value
function starboxRatedText() {
  var indicator = this.down('.indicator');
  this.starboxResetText = indicator.innerHTML;
}

// here we restore the indicator on mouseout, if needed
function starboxLeftText() {
  this.down('.indicator').update(this.starboxResetText || '');
}


function starboxChangedText(event) {
  var indicator = this.down('.indicator'),
  pick = (event.memo.rating || 0).round() - 1,
  indicator = this.down('.indicator');
    
  // for restoring, store the indicator text on the star if it was not set before.
  this.starboxResetText = this.starboxResetText || indicator.innerHTML;
  
  this.down('.indicator').update([
    'Langweilig',
  'Geht so',
  'Ok',
  'Spannend',
  'Absolut lesenswert!'
  ][pick]);
}

// Dankeschön
function starboxThankYou(event) {
  var indicator = event.findElement('.starbox').down('.indicator'),
  restore = indicator.innerHTML;
  indicator.update('Vielen Dank für deine Bewertung!');
  (function() { indicator.update(restore) }).delay(2);
}


/*
 * Anzeige einer Bewertung
 */
var starbox_fields = 0;
function showRating(avg){
  starbox_fields = starbox_fields+1;
  var id = "rating"+starbox_fields
  document.write("<div id='"+id+"'></div>");
  new Starbox(id, avg, {locked:true, stars:avg, className: 'dotted'});
}


/* Admin functions -------------------------------------------------------  */



function showCaptcha(public_key){
	if ($('captcha').childNodes.length > 0) {
		// Formular kann abgeschickt werden
		return true;
	}
	
	// reCAPTCHA nachladen
	var script = new Element("script", { type: "text/javascript", src: "http://api.recaptcha.net/js/recaptcha_ajax.js"});
	$$("head")[0].insert(script);
	
	script.onload = function(){
		Recaptcha.create(public_key,
			"captcha", {
			theme: "white",
			lang: "de",
			callback: Recaptcha.focus_response_field
		});
	}
	
	return false;
}


function checkA(e){
/*
  aBoxes[0].style.visibility = 'hidden';
  var checked = e.value;
  for(var i=0; i < bBoxes.length; i++)
    bBoxes[i].style.visibility = bBoxes[i].value > checked ? "visible" : "hidden";
*/
}

function checkB(e){
/*
  var checked = e.value;
  for(var i=0; i < aBoxes.length; i++)
    aBoxes[i].style.visibility = aBoxes[i].value < checked ? "visible" : "hidden";
*/
}


function autofitIframe(frame){
  var innerDoc = (frame.contentDocument) ? frame.contentDocument : frame.contentWindow.document;
  frame.style.height = (innerDoc.body.scrollHeight + 40) + "px"
}








/* Google Web Search */

function googleLyricsSearch(text,artist) {
  var gWebSearch = new google.search.WebSearch();
  gWebSearch.setSiteRestriction("www.magistrix.de");
  gWebSearch.setResultSetSize(GSearch.LARGE_RESULTSET);
  gWebSearch.setSearchCompleteCallback(gWebSearch, search_onResults);
  gWebSearch.setQueryAddition("intitle:Songtext inurl:/lyrics/" + (artist != '' ? artist+'/' : ''));
  gWebSearch.execute(text);
  
}

function search_onResults() {
  var results = this.results;
  var output = '';
  
  for (var i = 0; i < results.length; i++) {
    var thisResult = results[i];
    
    var pos = thisResult.title.lastIndexOf('|');
    if(pos > 5)
      thisResult.title = thisResult.title.substr(0,pos-1);
    
    // Wenn wir thisResult.url nicht einmal de-maskieren, dann ist's doppelt maskiert
    // und die Links nutzlos, weil sie dann auf andere Ressourcen zeigen, die ja gar nicht
    // existieren.
    output += "<p>";
    output += "<a href=\"" + unescape(thisResult.url) + "\">" + thisResult.title.replace('<b>Songtext</b>: ','') + "<\/a><br \/>";
    output += thisResult.content + "<br \/>";
//    output += "<span class=\"url\">" + thisResult.url + "<\/span>";
    output += "<\/p>";
  }
  
  if(results.length==0){
    output += "<p>Keine Ergebnisse gefunden<\/p>";
  }
  
  if(results.length==8){
    output += "<p><em>Die Suche ergab mehr als 8 Ergebnisse. Bitte verfeinere deine Suchanfrage.</em></p>";
  }
  
  $("searchresults").innerHTML = output;
}




function AJAX(){
  this.serializeObject = function(obj,prefix){
    var string = "", keystr="";
    for(var key in obj){
      if(typeof obj[key] == "function")
        continue;
      if(string.length>0)
        string += "&";
      keystr = prefix ? prefix+"["+key+"]" : key;
      
      if(typeof obj[key] == "object" || typeof obj[key] == "array")
        string += this.serializeObject(obj[key], keystr);
      else
        string += encodeURIComponent(keystr) + "=" + encodeURIComponent(obj[key]);
    }
    return string;
  }
}



function loadLyricFavoritesList(current_lyric_id) {
  var infos = window.location.hash.match(/^#with_favorite_list_([0-9]+?)_from_([^ ]+?)$/)
  
  if (infos == undefined) {
		return false;
	}
	
  new Ajax.Request('/lyrics/favorites/show/'+infos[1]+'.json', {
    method       : 'get',
    asynchronous : true,
    parameters   : {
      user : infos[2]
    },
    onSuccess : function(transport){
      var result  = transport.responseJSON
      var area    = $('favorite_navigation');
      
      var f       = document.createElement("form");
      var select  = document.createElement("select");
      var options = select.options;
      select.style.width = "130px";
      
      var current_pos = -1
      result.entries.each(function(entry){
        selected = entry.id==current_lyric_id
        if (selected) {
          current_pos = options.length;
        }
        options[options.length] = new Option(entry.title, entry.url, selected)
      })
      
      select.onchange = function(){
        document.location.href = options[this.selectedIndex].value + window.location.hash;
      }
      
			
      var prev_pos = current_pos - 1
      if (prev_pos < 0) {
        prev_pos = result.entries.length - 1
      }

      var next_pos = (current_pos + 1) % result.entries.length;
      
      
      var navTable = document.createElement("table");
			
			var navTableUserRow = document.createElement("tr");
			
			
			var navTableUserColumn = new Element("th", {'colspan' : '3'}).update('"'+result.name+'" von ' + result.user);
			navTableUserRow.appendChild(navTableUserColumn);
			navTable.appendChild(navTableUserRow);
			
      var navTableRow = document.createElement("tr");

      var navTableLeftColumn   = new Element("td", {'align' : 'right'                    });
      var navTableCenterColumn = new Element("td", {                  'valign' : 'middle'});
      var navTableRightColumn  = new Element("td", {'align' : 'left', 'valign' : 'middle'});

      var backLinkUrl          = result.entries[prev_pos].url + window.location.hash
      var backLink             = new Element("a", {'href' : backLinkUrl})
			var backImage            = new Element("img", {'src' : Magistrix.imageHost+"/images/icons/32/arrow_left_blue.png", 'alt' : 'Zurück'})
			
      backLink.appendChild(backImage);
			
      navTableLeftColumn.appendChild(backLink);
      
      select.style.width = "11em";
      navTableCenterColumn.appendChild(select);
      
      var nextLinkUrl          = result.entries[next_pos].url + window.location.hash
      var nextLink             = new Element("a", {'href' : nextLinkUrl})

      var nextImage            = new Element("img", {'src' : Magistrix.imageHost+"/images/icons/32/arrow_right_blue.png", 'alt' : 'Voor'})
      nextLink.appendChild(nextImage);

      nextLink.appendChild(nextImage);
      navTableRightColumn.appendChild(nextLink);
      
      navTableRow.appendChild(navTableLeftColumn);
      navTableRow.appendChild(navTableCenterColumn);
      navTableRow.appendChild(navTableRightColumn);
      navTable.appendChild(navTableRow);
      f.appendChild(navTable);

      area.appendChild(f);
    }
  });
}


function radioValue(rObj) {
  for (var i=0; i<rObj.length; i++) if (rObj[i].checked) return rObj[i].value;
  return false;
}

function checkValue(rObj) {
  return radioValue(rObj);
}


function addOnLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

function ImageDisplay(){
	this.initialize = function(){
    $$('#body .helpPage img').each(function(image){
			var path_parts = image.src.split("/")
			var image_name = path_parts[path_parts.length - 1]
      if (image_name = image_name.match(/(.+)[_-](mini|huge|square|medium|preview|large|thumb|tiny)(\.[a-z]+)$/)) {
        if (typeof image.up("a") == "undefined") {
	        var full_path_parts = path_parts.slice(0, path_parts.length - 1)
	        full_path_parts.push(image_name[1] + image_name[image_name.length - 1])
	        image_name = full_path_parts.join("/")
					
//					var image_container = new Element("div");
	        var lightview = new Element("a", {className : 'lightview', 'href': image_name, 'title' : "Hier klicken um das Bild zu vergrößern"});
	        image.wrap(lightview);
//					lightview.wrap(image_container);
          
//          var symbol_link = new Element("a", {className : 'lightview', 'href': image_name, 'title' : "Hier klicken um das Bild zu vergrößern"});
//          var symbol      = new Element("img", {"src" : Magistrix.imageHost+'/images/icons/16/view.png', "width":16, "height":16});
//					symbol.wrap(symbol_link);
//					image_container.appendChild(symbol_link);
				}
			}
    });
	}
}

ImageDisplay.getInstance = function() {
  if (typeof ImageDisplay.instance == "undefined") {
    ImageDisplay.instance = new ImageDisplay();
    ImageDisplay.instance.initialize();
  }
  
  return ImageDisplay.instance
}

document.observe("dom:loaded", function(){
  ImageDisplay.getInstance();
});


function REST_Helper(){
  this.initialize = function(){
  };
  
  this.updateParams = function(hash) {
		hash["_method"] = 'put'
    return (new AJAX).serializeObject(hash);
  }
}
REST = new REST_Helper();


function comment_page(page, model, id)
{
	var container = $(model+'Comments')
	if(!container)
	  alert('DIV container comment_frame nicht vorhanden');
	
	new Effect.Opacity(container.down('ul'), { from: 1.0, to: 0.5, duration: 0 });

	new Ajax.Updater(container, '/comments/list/' + id + '/?model=' + model + '&page=' + page , {
		method: 'get', onComplete: function(e){
			$('.relatize').relatizeDate();
		}
	})	
	
	
}

var checked = false;

function checkboxes(){

	var inputs = document.getElementsByTagName('input');
	var checkboxes = [];
	for (var i = 0; i < inputs.length; i++) {
	
		if (inputs[i].type == 'checkbox') {
			if (!checked) {
				inputs[i].checked = true;
				
			}
			else {
				inputs[i].checked = false;
				
			}
		}
		
	}
	if (!checked) {
		checked = true;
	}
	else {
		checked = false;
		
	}
}

