// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

// START SWFUPLOAD HANDLER
function fileQueueError(fileObj, error_code, message) {
	try {
		var error_name = "";
		switch(error_code) {
			case SWFUpload.ERROR_CODE_QUEUE_LIMIT_EXCEEDED:
			alert("Du versuchst, zu viele Dateien auf einmal hochzuladen.");
			break;
		}

		if (error_name !== "") {
			alert(error_name);
			return;
		}

		switch(error_code) {
			
			case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
				alert("Die Datei "+ fileObj.name + " ist zu groß. Die anderen Dateien werden trotzdem hochgeladen...");
			break;
			
			case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
			case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
			default:
				alert("Die Datei "+ fileObj.name + " ist keine gültige Bilddatei. Die anderen Dateien werden trotzdem hochgeladen...");
			break;
		}

		AddImage("/images/" + image_name);

	} catch (ex) { this.debug(ex); }

}

function fileDialogComplete(num_files_selected, num_files_queued) {
	try {
		if (num_files_queued > 0) {
			this.customSettings.total_files = num_files_queued;
			this.customSettings.uploaded_files = 0;
			$(this.customSettings.uploadSpinnerElement).show();
			this.startUpload();
		}
	} catch (ex) { this.debug(ex); }
}

function uploadProgress(fileObj, bytesLoaded) {
	try {
		
		var percent = Math.ceil((bytesLoaded / fileObj.size) * 100)
		$(this.customSettings.currentFilenameElement).innerHTML = '('+fileObj.name+')';
		$(this.customSettings.currentProgressBarElement).style.width = parseInt(percent)+'%';
		$(this.customSettings.currentProgressBarElement).innerHTML = parseInt(percent)+'%';
		$(this.customSettings.currentProgressNumberElement).innerHTML = parseInt(percent)+'%';

	} catch (ex) { this.debug(ex); }
}

function uploadSuccess(fileObj, server_data) {
	try {

		this.customSettings.uploaded_files++;
		var percent = Math.ceil((this.customSettings.uploaded_files / this.customSettings.total_files) * 100)
		$(this.customSettings.totalProgressBarElement).style.width = parseInt(percent)+'%';
		$(this.customSettings.totalProgressBarElement).innerHTML = parseInt(percent)+'%';
		$(this.customSettings.totalProgressNumberElement).innerHTML = parseInt(percent)+'%';

	} catch (ex) { this.debug(ex); }
}

function uploadComplete(fileObj) {
	try {
		if (this.getStats().files_queued > 0) {
			this.startUpload();
		} else {
			Effect.toggle(this.customSettings.uploadBoxElement, 'blind');
			if(this.customSettings.uploadCompleteUrl != null && this.customSettings.uploadCompleteUrl != ''){
				window.location = this.customSettings.uploadCompleteUrl;
			}else{
				window.location.reload( false );
			}
		}
	} catch (ex) { this.debug(ex); }
}

function uploadError(fileObj, error_code, message) {
	var image_name =  "error.gif";
	try {
		switch(error_code) {
			case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED:
			case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED:
			default:
				try {
					alert("Beim Hochladen ist leider ein Fehler aufgetreten.")
				}
				catch (ex) { this.debug(ex); }
			break;
		}

		AddImage("/images/" + image_name);

	} catch (ex) { this.debug(ex); }

}

// END SWFUPLOAD HANDLER

// START CHECK MODIFICATIONS
var mustConfirmLeave = false;
var confirmLeaveMessage = "Du hast schon Eingaben auf dieser Seite gemacht, die verloren gehen würden, wenn Du das machst. Ist das okay?";
function initCheckingForModifications(formToCheck,message) {

		if(message != null){
			confirmLeaveMessage = message;
		}
    var inputs = $$('form#' + formToCheck+ ' input');
    for(var i = 0; i < inputs.length; i++) {
        var type = inputs[i].getAttribute("type");
        if(type == "checkbox" || type == "radio") {
            Event.observe(inputs[i], "change", somethingHasChanged);
        } else {
            Event.observe(inputs[i], "keypress", somethingHasChanged);
        }
    }
    var textareas = $$('form#' + formToCheck+ ' textarea');
    for(var i = 0; i < textareas.length; i++) {
        Event.observe(textareas[i], "keypress", somethingHasChanged);
    }
    var selects = $$('form#' + formToCheck+ ' select');
    for(var i = 0; i < selects.length; i++) {
        Event.observe(selects[i], "change", somethingHasChanged);
    }
 
}
 
function somethingHasChanged(e) {
    if (e.keyCode != Event.KEY_TAB) {
        mustConfirmLeave = true;
    }
}
 
function checkForModifications() {
    if(mustConfirmLeave) {
        if(confirm(confirmLeaveMessage)) {
            return true;
        } else {
            return false;
        }                           
    }
    return true;
}
// END CHECK MODIFICATIONS

// tooltip widget
function toggleTooltip(event, element) { 
  var __x = Event.pointerX(event);
  var __y = Event.pointerY(event);
  //alert(__x+","+__y);
  element.style.top = __y + 5;  
  element.style.left = __x - 40;
  element.toggle();
}

// javascript cookie login hack
var cookie = [];
document.cookie.split(';').each(function(cookiePair){ 
  cookie[unescape(cookiePair.split('=')[0].strip())] = unescape(cookiePair.split('=')[1].strip());
});

if(cookie['logged_in'] == '1') {
	document.write('<style type="text/css" media="screen">.only-logged-out { display:none;}</style>');
}
if(cookie['logged_in'] != '1') {
	document.write('<style type="text/css" media="screen">.only-logged-in { display:none;}</style>');
}

// Set true for first click in login form. Will be false after the click
 var firstClick = true;
// Set the number of email fields in invitation box
 var num_email_fields = 1

// Functions for Feedback-Shoutbox
// Sent Button is disabled and Indicator is shown until ...
   function feedback_sending() {
     $('bt_send').disabled = true;
     Element.show('indicator');
   }

// ... mail sent and everything is set back to start   
   function feedback_sent() {
     $('bt_send').disabled = false;
     Element.hide('indicator');
     Element.hide('feedback-shoutbox');
	 $('feedback_message').value = "";	
   }

// Functions for Invitation-Shoutbox
// new email field is added to the form
   function invitation_add_email_field() {
        num_email_fields++;
        var email_field = "<div id='email_address"+num_email_fields+"'><br><input id='email_addressfield_"+num_email_fields+"' name=\"email_address[]\" style=\"width: 300px;\" type=\"text\" value=\"\" /></div>";
        $('email_fields').insert({before:"<div id='email_address"+num_email_fields+"'><br><input id='email_addressfield_"+num_email_fields+"' name='email_address[]' onblur='ValidateEmail(this.value)' style='width: 300px;' type='text' value='' /></div>"});
        Element.show('link_remove_addressfield'); 
   }
   
// new email field is added to the form
   function invitation_remove_email_field() {
        var element_name = "email_address"+num_email_fields;
        Element.remove(element_name);
        num_email_fields--;
        if (num_email_fields == 1)
        Element.hide('link_remove_addressfield');
   }   

// Sent Button is disabled and Indicator is shown until ...
   function invitation_sending() {
     $('inv_send').disabled = true;
     Element.show('indicator_invitation');
   }

// ... mail sent and everything is set back to start   
   function invitation_sent() {
     $('inv_send').disabled = false;
     Element.hide('indicator_invitation');
     Effect.Fade('invitation-shoutbox');
	 $('invitation_message').value = "";	
   }

  function refresh_search_list(poi_type) {
     if(poi_type == "team"){
      Element.hide('select_for_sport');
      Element.hide('label_for_sport');
      Element.update("label_for_name", "Name oder Stichwort");
     }
     else {
      Element.update("label_for_name", "Name");
      Element.show('select_for_sport');
      Element.show('label_for_sport');
      Element.update("label_for_sport", "Sportart");
     }
  
  }
   
// fix for fixing the problem of "Background Flicker" issue for IE6.   
	function bg_flicker_ie6() { 
		try {
		  document.execCommand('BackgroundImageCache', false, true);
		} catch(e) {}
	 }
	    
// Sent Button is disabled and Indicator is shown until ...
   function BoxSending(boxID) {
     //alert("ajax: not installed");
		 Element.show(boxID+"Loading");
   }

// ... mail sent and everything is set back to start   
   function BoxSent(boxID) {
		 window.history.back();
		 Element.hide(boxID+"Loading");
   }		
   
//Function to preload Images for the Image Swap
function preloadImages() { 
  var d=document; if(d.images){ if(!d.p) d.p=new Array();
    var i,j=d.p.length,a=preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.p[j]=new Image; d.p[j++].src=a[i];}}
}

//Function to find HTML Objects by id
function findObj(n, d) {
  var p,i,x;  
  if(!d) 
    d=document; 
  if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; 
    n=n.substring(0,p);
  }
  if(!(x=d[n])&&d.all) 
    x=d.all[n]; 
  for (i=0;!x&&i<d.forms.length;i++){
    x=d.forms[i][n];
  }
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) 
    x=findObj(n,d.layers[i].document);
  if(!x && d.getElementById) 
    x=d.getElementById(n); 
    
  return x;
}
function restoreSwappedRatingImage(){
  var a=restoreSwappedRatingImage.arguments; 
	var name_string = a[0].toString();
    var avg = document.getElementById(name_string+"_average_rating").firstChild.nodeValue;
    if (avg < 1)
        avg = 8;
    //Alle Bilder "Nullen"	
    	for(u=6;u>=1;u--){
    	   if(avg >= u+1){
        		y=findObj(name_string+"Note"+u);
        	   	if(!y.oSrc) 
        			y.oSrc=y.src; 
        		if(y.src.split("rate"+u+".gif").length != 0){
        		  var imageStrings = y.src.split("rate"+u);
        		  var newImageString = imageStrings[0] + "rate" + u + "_d.gif";
        		  y.src = newImageString;
        		}
    	   }else{
        		y=findObj(name_string+"Note"+u);
        	   	if(!y.oSrc) 
        			y.oSrc=y.src; 
        		if(y.src.split("rate"+u+"_d.gif").length != 0){
        		  var imageStrings = y.src.split("rate"+u);
        		  var newImageString = imageStrings[0] + "rate" + u + ".gif";
        		  y.src = newImageString;
        		}
    	   }
    }  
}
//Function to swap 2 Images
function swapRatingImage() {
  var i,j=0,x,a=swapRatingImage.arguments; 
  document.sr=new Array; 
//Alle Bilder "Nullen"
	var name_string = a[0].toString();
	name_string = name_string.slice(0,(a[0].length-1));
	for(u=6;u>=1;u--){
   		y=findObj(name_string+u);
   	   	if(!y.oSrc) 
   			y.oSrc=y.src; 
   		var imageStrings = y.src.split("rate"+u);
   		var newImageString = imageStrings[0] + "rate" + u + "_d.gif";
   		y.src = newImageString;
	}  
  for(i=0;i<(a.length-2);i+=3)
	   if ((x=findObj(a[i]))!=null){	   
			document.sr[j++]=x; 
			for(u=6;u>=x.name;u--){
//Bildquelle austauschen	
				y=findObj(name_string+u);
			   	if(!y.oSrc) 
					y.oSrc=y.src; 
		      var imageStrings = y.src.split("rate"+u);
	       	  var newImageString = imageStrings[0] + "rate" + u + ".gif";
		      y.src = newImageString;
			}
	   }
}

function setRatingValue(){
    var a=setRatingValue.arguments;
    var tmp = findObj(a[0]);
    tmp.value=a[1];
    var avg = findObj(a[0]+"_average_rating");
    avg.firstChild.data=a[1];
}

function findSwapObj(n, d) { 
  var p,i,x;  
  
  if(!d) 
  	d=document; 
  
  if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; 
	n=n.substring(0,p);
	}
	
  if(!(x=d[n])&&d.all) 
  x=d.all[n]; 
  
  for (i=0;!x&&i<d.forms.length;i++) 
  	x=d.forms[i][n];
  
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) 
  	x=findSwapObj(n,d.layers[i].document);
  
  if(!x && d.getElementById) 
  	x=d.getElementById(n); 
  
  return x;
}

function swapImgRestore() {
  var i,x,a=document.sr; 
  for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) 
  	x.src=x.oSrc;
  	
  var textDiv = document.getElementById("sbs");
  textDiv.firstChild.data = "...";
}

function swapImage() {  
  var i,j=0,x,a=swapImage.arguments; 
  document.sr=new Array; 
  for(i=0;i<(a.length-2);i+=3)
   if ((x=findSwapObj(a[i]))!=null){
   	document.sr[j++]=x; 
	if(!x.oSrc) 
		x.oSrc=x.src; 
//set new image source
    var imageString = x.src.split(".gif")
    var newImageString = imageString[0] + "_active.gif"
	x.src=newImageString;
//display social bookmark service name
    var textDiv = document.getElementById("sbs");
    textDiv.firstChild.data = x.title;
	}
}
// Validierung von Email-Adressen

function isEmailValid(email){
	if ((email==null)||(email=="")){
		return true;
	}
	if (!(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email))) {
		return false;
	} else {
		return true;
	}
}

function ValidateEmails(email_string){
	if(email_string.search(/,.+/) != -1){	
		var emails = email_string.split(",");
		var valid = true;
		for(var i = emails.length-1; i >=0; i--){
			ValidateEmail(emails[i]);
		}
	}else{
		ValidateEmail(email_string);
	}
}

function ValidateEmail(email){
    var email = trim(email);
    var warning = "Die Mailadresse '"+email+"' weist ein ungültiges Format auf. \nSieh nach, wo der Fehler liegen könnte, ansonsten kann keine Einladung an die Adresse(n) verschickt werden."

	if (isEmailValid(email)){
		return true;
	} else {
    	alert(warning);
		return false;
    }

 }

/* Basic trim-Functions */
 function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
 }
 function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
 }
 function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
 }


// Stuff from Beast

var TopicForm = {
  editNewTitle: function(txtField) {
    $('new_topic').innerHTML = (txtField.value.length > 5) ? txtField.value : 'New Topic';
  }
}

var LoginForm = {
  checkLogin: function(txt) {
    if(txt.value.match(/^https?:\/\//)) {
      $('password_fields').hide();
    } else {
      $('password_fields').show();
    }
  }
}

var EditForm = {
  // show the form
  init: function(postId) {
    $('edit-post-' + postId + '_spinner').show();
    this.clearReplyId();
  },

  // sets the current post id we're editing
  setReplyId: function(postId) {
    $('edit').setAttribute('post_id', postId.toString());
    $('posts-' + postId + '-row').addClassName('editing');
    if($('reply')) $('reply').hide();
  },
  
  // clears the current post id
  clearReplyId: function() {
    var currentId = this.currentReplyId()
    if(!currentId || currentId == '') return;

    var row = $('posts-' + currentId + '-row');
    if(row) row.removeClassName('editing');
    $('edit').setAttribute('post_id', '');
  },
  
  // gets the current post id we're editing
  currentReplyId: function() {
    return $('edit').getAttribute('post_id');
  },
  
  // checks whether we're editing this post already
  isEditing: function(postId) {
    if (this.currentReplyId() == postId.toString())
    {
      $('edit').show();
      $('edit_post_body').focus();
      return true;
    }
    return false;
  },

  // close reply, clear current reply id
  cancel: function() {
    this.clearReplyId();
    $('edit').hide()
  }
}

var ReplyForm = {
  // yes, i use setTimeout for a reason
  init: function() {
    EditForm.cancel();
    $('reply').toggle();
    $('post_body').focus();
    // for Safari which is sometime weird
//    setTimeout('$(\"post_body\").focus();',50);
  }
}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

function promptToRemote(text, param, url) {
 	value = prompt(text + ':');
 	if (value) {
 		new Ajax.Request(url + (url.indexOf('?') == -1 ? '?' : '&') + param + '=' + encodeURIComponent(value), {asynchronous:true, evalScripts:true});
 		return false;
 	}
}

function updatePlusMinusInput(element, increment) {
	var value = parseInt($(element).value);
	
	if (isNaN(value) || value + parseInt(increment) < 0 ) {
		$(element).value = 0
	} else {
		$(element).value = value + parseInt(increment)
	}
}

/* match lineups editor */



function addStartLineupSelector(id,name){
	if(id && name){
		$$('select.start-lineups').each(function(e){
			var selectElement = new Element('option', {value: id}).update(name);
			e.insert(selectElement);
		});
	}
}

function removeStartLineupSelector(id){
	if(id){
		$$('select.start-lineups').each(function(e){
			if(s=e.down('option[value='+id+']')){
				
				if (s.selected){
					var fieldsetRow = e.up('tr');
					var changedCheckbox = fieldsetRow.previous('tr').down('input.checkbox',1)
					var changedCell = changedCheckbox.up('td');
					changedCheckbox.checked = false;
					fieldsetRow.hide();
					changedCell.removeClassName('checked');
				}
				s.remove();
				
			}
			
		});
	}
}

function determineBench(){
	
	var bench = [];
	
	$$('tr.lineup').each(function(tableRow){
		var startCheckbox = tableRow.down('input.checkbox',0); 	// first checkbox
		var changedCheckbox = tableRow.down('input.checkbox',1); // second checkbox
		var missingCheckbox = tableRow.down('input.checkbox',2); // third checkbox
		var userName = tableRow.down('th span').innerHTML;
		
		if(!startCheckbox.checked && !changedCheckbox.checked && !missingCheckbox.checked){
			bench.push(userName);
		}

	});
	
	$('bench-names').innerHTML = bench.sortBy(function(b) { return b; }).join(', ');
	
	
}


function deselectOthers(element){
	var ul = $(element).up('ul');
	var i = 0;
	
	while(e=(ul.down('input[type=checkbox]',i))){
		if(e != element){
			e.checked = false;
		}
		i++;
	}
	
}

function selectLineupBox(element){
	var tableRow = $(element).up('tr');
	var userName = tableRow.down('th span').innerHTML;

	var startCheckbox = tableRow.down('input.checkbox',0); 	// first checkbox
	var changedCheckbox = tableRow.down('input.checkbox',1); // second checkbox
	var missingCheckbox = tableRow.down('input.checkbox',2); // third checkbox

	var membershipField = tableRow.down('input.hidden',0);  // third hidden
	var coordinateLeftField = tableRow.down('input.hidden',1);  // third hidden
	var coordinateRightField = tableRow.down('input.hidden',2); // 4...

	var positionListItem = $('position_'+membershipField.value); 


	var fieldsetRow = tableRow.next();
	var changedCell = changedCheckbox.up('td');
	var missingCell = missingCheckbox.up('td');

	var changedFieldset = fieldsetRow.down('fieldset',0);
	var missingFieldset = fieldsetRow.down('fieldset',1);

	if(element == startCheckbox && element.checked){
		fieldsetRow.hide();
		changedCheckbox.checked = false;
		missingCheckbox.checked = false;
		changedCell.removeClassName('checked');
		missingCell.removeClassName('checked');
		addStartLineupSelector(membershipField.value,userName);
		positionListItem.show();
		
	}else if(element == changedCheckbox && element.checked){
		if(changedFieldset.down('select.start-lineups').down('option') == null){
			alert('Es muss wenigstens ein Spieler in der Startelf aufgestellt sein, damit Auswechselspieler angegeben werden können.');
			element.checked = false;
		}else{
			fieldsetRow.hide();
			changedCell.removeClassName('checked');
			missingCell.removeClassName('checked');
			startCheckbox.checked = false;
			missingCheckbox.checked = false;
			changedCell.addClassName('checked');
			missingCell.removeClassName('checked');
			fieldsetRow.show();
			changedFieldset.show();
			missingFieldset.hide();
			removeStartLineupSelector(membershipField.value);
			positionListItem.hide();
			
		}
	}else if(element == missingCheckbox && element.checked){
		fieldsetRow.hide();
		changedCell.removeClassName('checked');
		missingCell.removeClassName('checked');
		startCheckbox.checked = false;
		changedCheckbox.checked = false;
		changedCell.removeClassName('checked');
		missingCell.addClassName('checked');
		fieldsetRow.show();
		changedFieldset.hide();
		missingFieldset.show();
		removeStartLineupSelector(membershipField.value);
		positionListItem.hide();
		
	}else{
		fieldsetRow.hide();
		changedCell.removeClassName('checked');
		missingCell.removeClassName('checked');
		removeStartLineupSelector(membershipField.value);
		positionListItem.hide();

	}


  determineBench();
	
}

function handleDraggable(draggable){
	var top = parseInt(draggable.style.top);
	var left = parseInt(draggable.style.left);
	
	if(top < 15 || top > 390 || left < -20 || left > 360){
		return true;
	}else{
		$(draggable.id+'_top_field').value = top;
		$(draggable.id+'_left_field').value = left;
		return false;
	}
	
}

function formattedTime(time){
	
	var minutes = time.getMinutes();
	if (minutes < 10) {
	  minutes = "0" + minutes;
	}
	
	var seconds = time.getSeconds();
	if (seconds < 10) {
	  seconds = "0" + seconds;
	}
	
	return time.getHours()+':'+minutes+':'+seconds;
	
}

// START initBlockDoubleSubmit

var formsBlocked = false;
function initBlockDoubleSubmit() {
	var inputs = $$('form');
	for(var i = 0; i < inputs.length; i++) {
		Event.observe(inputs[i], "submit", blockDoubleSubmit);
  }
}
 
function blockDoubleSubmit(e) {
	if(formsBlocked){
		e.target.disable();
		Event.stop(e);
	}else{
		formsBlocked = true;
	}
}
 
Event.observe(window, 'load', function() {
	initBlockDoubleSubmit();
});

// END initBlockDoubleSubmit
