function confirmLinkBox(confirmText){
	if(confirm(confirmText) == false){
		return false;
	}
	
	return true;
}

function dropDown(e, ddBoxId){
	
	if($(e).hasClass('act')){
		//close
		$('#'+ddBoxId).hide();
		$(e).removeClass('act');
	}else{
		//show
		$('#'+ddBoxId).show();
		$(e).addClass('act');
	}
}

var popInValidator = function(){
	
	  var val = true;
	  $(this).find('input[type="text"]:visible,select').each(function(){
			if($(this).val() == ''){
				val = false;
				$(this).attr('class', 'error');
			}else
				$(this).attr('class', '');
				
	  });
	  
	  
	  if(!val){
		  alert('Bitte fülle alle rot eingefärbten Felder aus.')
		  return false;
	  }
	  
	};

function ApplicationForm(formId, jsonFields){
	
	var fields = eval(jsonFields);
	
	var formId = '#'+formId;
	
	function clearField(field){
		 var hElement;
		 if($(field).parent().next().attr('class') == 'helpcol')
			 hElement = $(field).parent().next();
		 else
			 hElement = $(field).parent().parent().next();
		
		$(hElement).attr('class', 'helpcol');
		$(hElement).html('');
	}
	
	function setFieldSuccess(field){
		$(field).parent().next().attr('class', 'helpcol success');
		$(field).parent().next().html('ok');
	}
	
	var fields = fields;
	for(var i=0; i < fields.fields.length; i++){
		var currElement = fields.fields[i];
		
		if(currElement.helpMessage && !currElement.noHover){
			
			$('#'+currElement.id).bind('focus', { msgHelp: currElement.helpMessage}, function(event){
				if($(this).parent().next().attr('class') == 'helpcol'){
					$(this).parent().next().attr('class', 'helpcol help');
					$(this).parent().next().html(event.data.msgHelp);
				}
			});
			
			$('#'+currElement.id).blur(function(){
				if($(this).parent().next().attr('class') == 'helpcol help'){
					clearField(this);
				}
			});
		}
	}
	
	function setFieldError(element, iElement){
		 var hElement;
		 if($('#'+element.id).parent().next().attr('class') == 'helpcol')
			 hElement = $('#'+element.id).parent().next();
		 else
			 hElement = $('#'+element.id).parent().parent().next();
		
		if(iElement.errorImg){
			$(hElement).html(iElement.errorImg);
			showErrorDisplay(iElement.errorMessage);
		}else{
			$(hElement).attr('class', 'helpcol error');
			$(hElement).html(iElement.errorMessage);
		}
	}
	
	function showErrorDisplay(text){
		if($('#errorDisplay').length)
			$('#errorDisplay').remove();
		
		$(formId).prepend('<div id="errorDisplay" class="actionmessage error">'+text+'</div>');
	}
	
	function hideErrorDisplay(){
		$('#errorDisplay').remove();
	}
	
	$(formId).submit(function(){
		var submit = true;
		
		//facebook start form
		if($('#fb') && $('#fb').val() == '1')
			return true;
		
		for(var i=0; i < fields.fields.length; i++){
			
			var currElement = fields.fields[i];
			var value = $('#'+currElement.id).val();
			
			if(currElement.notEmpty){
				if(!value || value.length == 0){
					setFieldError(currElement, currElement);
					submit = false;
					
					continue;
				}else
					clearField($('#'+currElement.id));
			}
			
			if(currElement.handler){
				var re = currElement.handler(value);
				var truefalse = (($.isArray(re)) ? re[0] : re);
				
				if($.isArray(re))
					currElement.errorMessage = re[1];
				
				if(!truefalse){
					
					setFieldError(currElement, currElement);
					submit = false;
					
					continue;
				}else
					clearField($('#'+currElement.id));
			}
			
			if(currElement.checkExp){
				
				if(!currElement.notEmpty && value == "")
					continue;
				
				if(! value.match(currElement.checkExp)){
					setFieldError(currElement, currElement);
					submit = false;
				}else
					clearField($('#'+currElement.id));
				
				continue;
			}
			
			if(currElement.minLength){
				if(value.length < currElement.minLength){
					setFieldError(currElement, currElement);
					submit = false;
					
					continue;
				}else
					clearField($('#'+currElement.id));
			}
			
			if(currElement.maxLength){
				if(value.length > currElement.maxLength){
					setFieldError(currElement, currElement);
					submit = false;
					
					continue;
				}else
					clearField($('#'+currElement.id));
			}
			
			if(currElement.type && value){
				if(currElement.type == 'numeric'){
					
					   var ValidChars = "0123456789.,";
					   var Char;
					   var isValid = true;
					 
					   for (var j = 0; j < value.length; j++){ 
					      Char = value.charAt(j); 
					      if (ValidChars.indexOf(Char) == -1){
					    	  isValid = false;
							  break;
					      }
					   }
					   
					   if(isValid){
						   clearField($('#'+currElement.id));
					   }else{
						   setFieldError(currElement, currElement);
						   submit = false;
					   }					   
					   
				}else if(currElement.type == 'email'){
					
					if(! value.match(/^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/)){
						setFieldError(currElement, currElement);
						submit = false;
					}else
						clearField($('#'+currElement.id));
					
					continue;
				}
			}
		}
		
		if(!submit){
			//$('#wikifit').scrollTop(0);
			$('html, body').animate({scrollTop: Math.max($(formId).offset().top - 50, 0) }, 'slow');
		}
		
		return submit;
	});
}

function FormField(){
	this.errorMessage = '';
	this.validationRegEx = '';
	this.inputField = null;
	this.messageField = null;	
}

function checkUsername(username){
	$.ajaxSetup({ async: false });
	retValue = false;
	
	$.post( '/ajax', { 'checkUsername' : username }, 
	        function(data){
				
				retValue = (data.existence != 'true');
        
	        }, "json");

     return [retValue, 'Der Benutzername '+username+' ist bereits vergeben. Bitte wähle einen anderen Namen.'];
}

function updateChart(idChart, dataUrl){
		
	$.get(dataUrl, function(data) {
		
		tmp = findSWF(idChart);
    	x = tmp.load( JSON.stringify(data) );
	}, 
	"json");
}

function findSWF(movieName) {
  if (navigator.appName.indexOf("Microsoft")!= -1) {
    return window[movieName];
  } else {
    return document[movieName];
  }
}


function Assessment(){
	this.currentAvg = 0;
	this.count = 0;
	this.url = '';
	
	this.idBase = 'assesment';
	this.star = '/img/stars/star.png';
	this.starEmpty = '/img/stars/star_empty.png';
	this.starHalf = '/img/stars/star_half.png';
	
	this.handler = null;
	
	this.assessmentOptions = new Array("Schlecht","Geht so", "Mittelmäßig", "Gut", "Super");
	
	this.setParameters = function(url, avg, count, handler){
		this.currentAvg = avg;
		this.url = url;
		
		this.handler = handler;
		
		assessment.setCount(count);
		
		$("#stars").hover(
	      function () {

	      }, 
	      function () {
	    	  assessment.releaseHint();
	    	  assessment.reset();
	      }
	    );
		
		assessment.reset();
		
	}
	
	this.releaseHint = function(){
		$('#disass').html('');
	}
	
	this.setCount = function(count){
		this.count = count;
		
		$('#assCount').html('('+count+')');
	}
	
	this.setAvg = function(avg){
		this.currentAvg = avg;
		
		assessment.reset();
	}
	
	this.highlight = function(pos){
		$('#disass').html('<p>Jetzt bewerten:<br/><b>' + this.assessmentOptions[pos - 1]+'</b></p>');
		
		for(var i= 1; i <= pos ;i++){
			$("#"+this.idBase+ (i)).attr("src", this.star);		
		}
		
		for(var j = pos + 1 ;j <= 5; j++){
			$("#"+this.idBase+ (j)).attr("src", this.starEmpty);
		}
	}
	this.reset = function(){
		
		for(i=1; i <= this.currentAvg + 0.5 ;i++){
			$("#"+this.idBase+ (i)).attr("src", 
					((this.currentAvg - i + 1 <=1 && this.currentAvg - i + 1 == 0.5)) ? this.starHalf : this.star);
		}
		
		for(j= Math.round(this.currentAvg) + 1; j<=5; j++){
			$("#"+this.idBase+ (j)).attr("src", this.starEmpty);
		}
	}
	this.setCurrentAvg = function(avg){
		this.currentAvg = avg;
	}
	
	this.saveAssessment = function(value){
		
		$.getJSON( this.url + value,
		        function(data){
			
					if(data.success == 'error'){
						if(data.success = 'not-logged-in'){
							$('#disass').html('<p>Für eine Bewertung musst du <a href="/meinefitness/login">angemeldet</a> sein.</p>');
						}
					}else if(data.success == 'ok'){
						$('#disass').html('<p>Deine Bewertung wurde gespeichert.</p>');
						
						//update assessment-values
						assessment.setAvg(data.avg);
						assessment.setCount(data.count);
						
						if(assessment.handler)
							assessment.handler();
					}		          
		        });
	}
}

function init(){
	var labels = $('.boxinlinelabel');
	
	for(var i=0; i < labels.length; i++){
		if($(this).attr('value') != ''){
			$(this).prev().attr('style','display: none');
		}
		
		if($(labels[i]).attr('for') != null){
			$(labels[i]).next()
				.focus(function(){
					$(this).prev().attr('style','display:none');
				})
				.blur(function(){
					if($(this).attr('value') == ''){
						$(this).prev().attr('style','');
					}
				});
			
			if($(labels[i]).next().val() != ''){
				$(labels[i]).attr('style','display:none');
			}
		}
	}
}

$(window).ready(init);

jQuery(document).ready(function($) {
	  $('a[rel*=facebox]').facebox();
	  $('img.help').tipTip({maxWidth: "350px", edgeOffset: 10, defaultPosition: 'right', delay: 100});
	  
	  $('form').each(function(){
		  $(this).submit(function(){
				
			  if (window.event && window.event.keyCode == 13)
			    return false;
			  else
			    return true;
			  
			});
	  });
	  
	  $('input[type="radio"]').each(function(){
		  if($(this).parent().children('input[type="radio"]').length < 2){
			  $(this).parent().css('cursor', 'pointer');
			  $(this).parent().click(function(){
				  //if(!$(this).children('input[type="checkbox"]:first, input[type="radio"]:first').attr('checked'))
				  	$(this).children('input[type="radio"]:first').click();
			  });
		  }
	  });
});


jQuery.fn.enableTr = function() {
	var en = $(this).attr('checked');
	
	$(this).parents('tr:first').find('td').each(function(){
		if(en)
			$(this).removeClass('disabled');
		else
			$(this).addClass('disabled');
		
		$(this).find('input[type="text"],select').each(function(){
			if(en)
				$(this).attr('disabled', '');
			else
				$(this).attr('disabled', 'disabled');
		});
	});
};


jQuery.fn.toogleDiv = function(d) {
	
	var str = (($(this).children('img:first').attr('src') == '/img/bullet_toggle_plus.png') ? '/img/bullet_toggle_minus.png' : '/img/bullet_toggle_plus.png');
	$(this).children('img:first').attr('src', str);
	
	if(str == '/img/bullet_toggle_minus.png') 
		$('#'+d).show(); 
	else 
		$('#'+d).hide();
};

jQuery.fn.changeTab = function(d) {
	var str = (($(this).children('img:first').attr('src') == '/img/bullet_toggle_plus.png') ? '/img/bullet_toggle_minus.png' : '/img/bullet_toggle_plus.png');
	$(this).children('img:first').attr('src', str);
	
	if(str == '/img/bullet_toggle_minus.png') 
		$('#'+d).show(); 
	else 
		$('#'+d).hide();
	
	
	$(this).find('').find('input').each(function(){
		$(this).attr('name', $(this).attr('name').substr(0, $(this).attr('name').lastIndexOf('_') +1) + countUnits);
	});
};

// --- workouts

countUnits = 0;

jQuery.fn.getSetsTable = function() {
	return $(this).parents('.sets:first');
};

jQuery.fn.addSet = function() {
	number = $(this).find('tr').length;
	unitId = $(this).getUnit().attr('id');
	
	$(this).find('tr:last').find('td:last').empty();
	
	$(this).append('<tr><td>'+number+'. Satz</td>'+
				   '<td><input type="text" class="textbox smallbox" name="reps_'+number+'_'+unitId+'" value=""/></td>'+
				   '<td><input type="text" class="textbox smallbox" name="weight_'+number+'_'+unitId+'" value=""/> kg</td><td>&nbsp;</td></tr>');
	
	$(this).addSetButtons();
	
	$(this).getUnit().updateUnitData();
};

jQuery.fn.removeSet = function() {
		
	$(this).find('tr:last').remove();
	
	$(this).addSetButtons( this.find('tr').length > 2);
	
	$(this).getUnit().updateUnitData();
};

jQuery.fn.addSetButtons = function() {
	
	html = ((this.find('tr').length > 2) ? '<a href="javascript:void(0)" onclick="$(this).getSetsTable().removeSet();"><img src="/img/remove.png" alt=""/></a>' : '')+
				'<a href="javascript:void(0)" onclick="$(this).getSetsTable().addSet();"><img src="/img/add.png" alt=""/></a>';
	
	$(this).find('tr:last').find('td:last').append(html);
};

//*****************************************************

jQuery.fn.getUnit = function() {
	return $(this).parents('div:first');
};

jQuery.fn.updateUnitData = function() {
	
	$(this).find('input[name^=sets]').val( $(this).find('.sets').find('tr').length-1 );
};

jQuery.fn.removeUnit = function() {
	$(this).parents('.commentbox').remove().updateWorkoutData();
};

//*****************************************************

jQuery.fn.updateWorkoutData = function() {
	var strIds = '';
	$('#units').find('div').each(function(){
		strIds += $(this).attr('id') + ';';
	});
	$('#ids').val(strIds);
};


function initializeUnits(){
	$('#units').find('div').each(function(){
		
		countUnits++;
		
		$(this).attr('id', countUnits);
		
		$(this).find('input').each(function(){
			$(this).attr('name', $(this).attr('name').substr(0, $(this).attr('name').lastIndexOf('_') +1) + countUnits);
		});
		$(this).find('textarea').each(function(){
			$(this).attr('name', $(this).attr('name').substr(0, $(this).attr('name').lastIndexOf('_') +1) + countUnits);
		});
		
		$(this).find('.sets').children().each(function(){
			if($(this).find('tr').length == 1){
				$(this).addSet();
				initializeUnits();
			}else if($(this).find('tr').find('img').length == 0)
				$(this).addSetButtons();
		});
		
	}).updateWorkoutData();	
}

jQuery.fn.setRowSpans = function(set) {
		var altRowClass = '';
		var $table = $(this);
		var valToReset = '';

		var defaultTdCount = $table.find('tr:first').find('th').length;
		
		$('tr', $table).each(function(column) {
			
			if($(this).find('td').length == 0)
				return;
			
			/*altRowClass = ((altRowClass == 'c1') ? '' : 'c1');
			$tr.attr('class', altRowClass);*/

			if(set){
				//add row-spans
				if($(this).find('td').length == defaultTdCount){
				
					var val = $(this).find('td:first').html();
					var intRowSpan = 0;
					
					$nextTr = $(this).next();
					
					while($nextTr){					
						if(val !== $nextTr.find('td:first').html())
							break;
	
						$nextTr.find('td:first').remove();
						
						$nextTr = $nextTr.next();
						intRowSpan++;
					}
	
					$(this).find('td:first').attr('rowspan', intRowSpan + 1);
				}
			}else{
				//remove rowspans
				if($(this).find('td').length == defaultTdCount){
					$(this).find('td:first').attr('rowspan', 1);
					valToReset = $(this).find('td:first').html();  
				}else{
					$(this).prepend('<td>'+valToReset+'</td>');
				}
			}
		});
};

jQuery.fn.loadCategories = function() {
	if(! $(this).val())
		return;
	
	
	$('#tdCategory').html('<select id="sCategory"></select>');
	$('#sCategory').change(function(){  $(this).loadExercises() });
	
	$.ajax({ async : false, url : '/ajax?unitdata=' + $(this).val() + '-categories', 
	         dataType : 'json', success : function(data){
				$.each(data.categories, function(i, item){
					$('#sCategory').append('<option value="'+item.id+'">'+item.name+'</option>')
		         });		          
	        	}
		  });
	
	if($('#sCategory').val())
		$('#sCategory').loadExercises();
};

jQuery.fn.loadExercises = function(){
	   if( !$(this).val())
	   		return;
	   	
	   	$('#tdExercise').html('<select id="sExercises" style="width:220px"></select>');
	   	
	   	$.getJSON( '/ajax?exercises=' + $(this).val(), 
        function(data){
			$.each(data.exercises, function(i, item){
				$('#sExercises').append("<option value='{\"id\":\""+item.id+"\", \"name\":\""+item.name+"\", \"bildurl\":\""+item.bildurl+"\"}'>"+item.name+"</option>")
	         });		          
        });
};

jQuery.fn.addUnit = function(bem) {
	if(!$('#sExercises').val())
		return;
	
	exercise = eval('('+$('#sExercises').val()+')');
	
	id = countUnits++;
	
	hidden = '<input type="hidden" name="type_" value="'+ (($('#sCategory').val() == 'cardio')?'c':'str') +'"/>';
	hidden += '<input type="hidden" name="exercise_id_" value="'+exercise.id+'"/>';
	
	if($('#sCategory').val() != 'cardio'){
		add = '<table class="sets" style="width: auto;"><tr><th width="75">&nbsp;</th><th width="50">WH</th><th width="75">Gewicht</th><th width="75">&nbsp;</th></tr>';
		hidden += '<input type="hidden" value="0" name="sets_">';
	}else{
		add = '<table><tr><td width="75">Dauer:</td><td><input type="text" class="textbox smallbox" name="duration_" value=""/> Min.</td></tr>';
		add += '<tr><td>Entfernung:</td><td><input type="text" class="textbox smallbox" name="distance_" value=""/> km</td></tr></table>'
	}
	
	$('#units').append('<div id="1" class="commentbox'+((id%2==0)?' c1':'')+'"><table><tr><td colspan="2" width="350"><p class="subheadline">'+exercise.name+'</p></td><td align="right"><a href="javascript:void(0)" onclick="$(this).removeUnit();">Entfernen</a></td></tr>'+
						'<tr><td width="115"><img src="'+exercise.bildurl+'" alt="" width="100px"/></td>'+((bem)?'<td width="160">Bemerkungen:<br/><textarea name="bem_"></textarea></td>':'')+'<td>'+hidden+add+'</td></tr></table></div>');
	
	initializeUnits();
};

$(document).ready(initializeUnits); 


//notifications
jQuery.fn.loadNotifications = function(userId){
	
	$('#ulNots').parent().show();
	$('#ulNots').parent().parent().addClass('current');
	
	$('#ulNots').html('');
	
	$.ajax({ async : false, url : '/ajax?notifications=1', 
        dataType : 'json', success : function(data){
			$.each(data.notifications, function(i, item){
				$('#ulNots').append('<li style="padding:2px 3px;"><a href="'+item.href+'"><img src="'+item.image+'" alt="" width="30" class="leftimage"/> '+item.not+'<div class="infotext" style="color:#DDDDDD !important">'+item.created+'</div></a></li>')
	         });		          
       	}
	  });
	
	$(this).html("0");
	$(this).removeClass("newnots");
	
	$('body').click(function(event){
		if(event.target.nodeName != 'A'){
			$('#dNots').hide();
			$('#ulNots').parent().parent().removeClass('current');
			$('body').click(function(){});
		}
	});
};

jQuery.fn.changeTab = function(tabContainerId, newTabId){
    
	//deselect last selected tab
    $.each( $(this).parents('ul:first').children('li'), function(index, value){
	    if($(this).attr('class') == 'selected'){
	    	$(this).attr('class', '');
	    }
    });
   
    $(this).parents('li:first').attr('class', 'selected');
    
    $.each( $('#'+tabContainerId).children(), function(index, value){
        if($(this).attr('id') == newTabId)
        	$(this).show();
        else
            $(this).hide();
    });
};


jQuery.fn.toogleArrow = function(divId) {
	if($('#'+divId).is(':visible')){
		$('#'+divId).hide();
		$(this).find('img:first').attr('src', '/img/bullet_arrow_right.gif');
	}else{
		$('#'+divId).show();
		$(this).find('img:first').attr('src', '/img/bullet_arrow_down.gif');
	}
};


/*
 * Facebox (for jQuery)
 * version: 1.2 (05/05/2008)
 * @requires jQuery v1.2 or later
 *
 * Examples at http://famspam.com/facebox/
 *
 * Licensed under the MIT:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Copyright 2007, 2008 Chris Wanstrath [ chris@ozmm.org ]
 *
 * Usage:
 *  
 *  jQuery(document).ready(function() {
 *    jQuery('a[rel*=facebox]').facebox() 
 *  })
 *
 *  <a href="#terms" rel="facebox">Terms</a>
 *    Loads the #terms div in the box
 *
 *  <a href="terms.html" rel="facebox">Terms</a>
 *    Loads the terms.html page in the box
 *
 *  <a href="terms.png" rel="facebox">Terms</a>
 *    Loads the terms.png image in the box
 *
 *
 *  You can also use it programmatically:
 * 
 *    jQuery.facebox('some html')
 *
 *  The above will open a facebox with "some html" as the content.
 *    
 *    jQuery.facebox(function($) { 
 *      $.get('blah.html', function(data) { $.facebox(data) })
 *    })
 *
 *  The above will show a loading screen before the passed function is called,
 *  allowing for a better ajaxy experience.
 *
 *  The facebox function can also display an ajax page or image:
 *  
 *    jQuery.facebox({ ajax: 'remote.html' })
 *    jQuery.facebox({ image: 'dude.jpg' })
 *
 *  Want to close the facebox?  Trigger the 'close.facebox' document event:
 *
 *    jQuery(document).trigger('close.facebox')
 *
 *  Facebox also has a bunch of other hooks:
 *
 *    loading.facebox
 *    beforeReveal.facebox
 *    reveal.facebox (aliased as 'afterReveal.facebox')
 *    init.facebox
 *
 *  Simply bind a function to any of these hooks:
 *
 *   $(document).bind('reveal.facebox', function() { ...stuff to do after the facebox and contents are revealed... })
 *
 */
(function($) {
  $.facebox = function(data, klass) {
    $.facebox.loading()

    if (data.ajax) fillFaceboxFromAjax(data.ajax)
    else if (data.image) fillFaceboxFromImage(data.image)
    else if (data.div) fillFaceboxFromHref(data.div)
    else if ($.isFunction(data)) data.call($)
    else $.facebox.reveal(data, klass)
  }

  /*
   * Public, $.facebox methods
   */

  $.extend($.facebox, {
    settings: {
      opacity      : 0,
      overlay      : true,
      loadingImage : '/scripts/facebox/loading.gif',
      closeImage   : '/img/close.png',
      imageTypes   : [ 'png', 'jpg', 'jpeg', 'gif' ],
      faceboxHtml  : '\
    <div id="facebox" style="display:none;"> \
      <div class="popup"> \
        <table> \
          <tbody> \
            <tr> \
              <td class="tl"/><td class="b"/><td class="tr"/> \
            </tr> \
            <tr> \
              <td class="b"/> \
              <td class="body"> \
		    	  <a href="#" class="close" style="float:right;padding-bottom:5px"> \
			          <img src="/img/close.gif" title="close" class="close_image" /> \
			      </a> \
                <div class="content" style="clear:both;"> \
                </div> \
              </td> \
              <td class="b"/> \
            </tr> \
            <tr> \
              <td class="bl"/><td class="b"/><td class="br"/> \
            </tr> \
          </tbody> \
        </table> \
      </div> \
    </div>'
    },

    loading: function() {
      init()
      if ($('#facebox .loading').length == 1) return true
      showOverlay()

      $('#facebox .content').empty()
      $('#facebox .body').children().hide().end().
        append('<div class="loading"><img src="'+$.facebox.settings.loadingImage+'"/></div>')

      $('#facebox').css({
        top:	getPageScroll()[1] + (getPageHeight() / 10) + 20,
        left:	385.5
      }).show()

      $(document).bind('keydown.facebox', function(e) {
        if (e.keyCode == 27) $.facebox.close()
        return true
      })
      $(document).trigger('loading.facebox')
    },

    reveal: function(data, klass) {
      $(document).trigger('beforeReveal.facebox')
      if (klass) $('#facebox .content').addClass(klass)
      $('#facebox .content').append(data)
      $('#facebox .loading').remove()
      $('#facebox .body').children().fadeIn('normal')
      //$('#facebox').css('left', $(window).width() / 2 - ($('#facebox table').width() / 2))
      //own modification
      $('#facebox').css('left', 450 - ($('#facebox table').width() / 2))
      
      $(document).trigger('reveal.facebox').trigger('afterReveal.facebox')
    },

    close: function() {
      $(document).trigger('close.facebox')
      return false
    }
  })

  /*
   * Public, $.fn methods
   */

  $.fn.facebox = function(settings) {
    init(settings)

    function clickHandler() {
      $.facebox.loading(true)

      // support for rel="facebox.inline_popup" syntax, to add a class
      // also supports deprecated "facebox[.inline_popup]" syntax
      var klass = this.rel.match(/facebox\[?\.(\w+)\]?/)
      if (klass) klass = klass[1]

      fillFaceboxFromHref(this.href, klass)
      return false
    }

    return this.click(clickHandler)
  }

  /*
   * Private methods
   */

  // called one time to setup facebox on this page
  function init(settings) {
    if ($.facebox.settings.inited) return true
    else $.facebox.settings.inited = true

    $(document).trigger('init.facebox')
    makeCompatible()

    var imageTypes = $.facebox.settings.imageTypes.join('|')
    $.facebox.settings.imageTypesRegexp = new RegExp('\.' + imageTypes + '$', 'i')

    if (settings) $.extend($.facebox.settings, settings)
    $('body').append($.facebox.settings.faceboxHtml)

    var preload = [ new Image(), new Image() ]
    preload[0].src = $.facebox.settings.closeImage
    preload[1].src = $.facebox.settings.loadingImage

    $('#facebox').find('.b:first, .bl, .br, .tl, .tr').each(function() {
      preload.push(new Image())
      preload.slice(-1).src = $(this).css('background-image').replace(/url\((.+)\)/, '$1')
    })

    $('#facebox .close').click($.facebox.close)
    $('#facebox .close_image').attr('src', $.facebox.settings.closeImage)
  }
  
  // getPageScroll() by quirksmode.com
  function getPageScroll() {
    var xScroll, yScroll;
    if (self.pageYOffset) {
      yScroll = self.pageYOffset;
      xScroll = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
      yScroll = document.documentElement.scrollTop;
      xScroll = document.documentElement.scrollLeft;
    } else if (document.body) {// all other Explorers
      yScroll = document.body.scrollTop;
      xScroll = document.body.scrollLeft;	
    }
    return new Array(xScroll,yScroll) 
  }

  // Adapted from getPageSize() by quirksmode.com
  function getPageHeight() {
    var windowHeight
    if (self.innerHeight) {	// all except Explorer
      windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
      windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
      windowHeight = document.body.clientHeight;
    }	
    return windowHeight
  }

  // Backwards compatibility
  function makeCompatible() {
    var $s = $.facebox.settings

    $s.loadingImage = $s.loading_image || $s.loadingImage
    $s.closeImage = $s.close_image || $s.closeImage
    $s.imageTypes = $s.image_types || $s.imageTypes
    $s.faceboxHtml = $s.facebox_html || $s.faceboxHtml
  }

  // Figures out what you want to display and displays it
  // formats are:
  //     div: #id
  //   image: blah.extension
  //    ajax: anything else
  function fillFaceboxFromHref(href, klass) {
    // div
    if (href.match(/#/)) {
      var url    = window.location.href.split('#')[0]
      var target = href.replace(url,'')
      $.facebox.reveal($(target).clone().show(), klass)

    // image
    } else if (href.match($.facebox.settings.imageTypesRegexp)) {
      fillFaceboxFromImage(href, klass)
    // ajax
    } else {
      fillFaceboxFromAjax(href, klass)
    }
  }

  function fillFaceboxFromImage(href, klass) {
    var image = new Image()
    image.onload = function() {
      $.facebox.reveal('<div class="image"><img src="' + image.src + '" /></div>', klass)
    }
    image.src = href
  }

  function fillFaceboxFromAjax(href, klass) {
    $.get(href, function(data) { $.facebox.reveal(data, klass) })
  }

  function skipOverlay() {
    return $.facebox.settings.overlay == false || $.facebox.settings.opacity === null 
  }

  function showOverlay() {
    if (skipOverlay()) return

    if ($('facebox_overlay').length == 0) 
      $("body").append('<div id="facebox_overlay" class="facebox_hide"></div>')

    $('#facebox_overlay').hide().addClass("facebox_overlayBG")
      .css('opacity', $.facebox.settings.opacity)
      .click(function() { $(document).trigger('close.facebox') })
      .fadeIn(200)
    return false
  }

  function hideOverlay() {
    if (skipOverlay()) return

    $('#facebox_overlay').fadeOut(200, function(){
      $("#facebox_overlay").removeClass("facebox_overlayBG")
      $("#facebox_overlay").addClass("facebox_hide") 
      $("#facebox_overlay").remove()
    })
    
    return false
  }

  /*
   * Bindings
   */

  $(document).bind('close.facebox', function() {
    $(document).unbind('keydown.facebox')
    $('#facebox').fadeOut(function() {
      $('#facebox .content').removeClass().addClass('content')
      hideOverlay()
      $('#facebox .loading').remove()
    })
  })

})(jQuery);

