/*************************
* Clear Login Fields     *
*************************/

jQuery.fn.clear = function() {
	var defaultVal = $('.form_head_login .user').val();
	$('.form_head_login .user').focus(function(){
	   if($(this).attr('value') == 'Login-Name'){
		$(this).attr({value: ''});
	   }
	});
	$('.form_head_login .user').blur(function(){
		var currentVal = $('.form_head_login .user').val();
		if (currentVal == '' || currentVal == defaultVal) {
			$(this).val(defaultVal);
		};
	});
	$('.form_head_login .placeholder_pw').focus(function(){
		$(this).hide();
		$('.hidden_element_pw').show();
		$('.hidden_element_pw').focus();
	});
	
	$('.form_head_login .hidden_element_pw').focusout(function(){
		var currentValPW = $('.hidden_element_pw').val();
		if (currentValPW == '') {
			$(this).hide();
			$('.placeholder_pw').show();
		}
	});
	
};
$(window).load(function(){
	$().clear();
});


/*************************
* Slider User Box/Form   *
*************************/
$(document).ready(function()
{
    $(".slide").click(function()
        {
            if( $(this).children('img').attr("src") == '/src/icon_minimize.gif' )
            {
                $(this).children('img').attr({src: '/src/icon_enlarge.gif'});
                $(this).parents().eq(1).find(".user_box_content").slideUp('slow');
                $(this).parents().eq(1).find(".user_box_content").attr({style: 'display:none'});
            }
            else
            {
                $(this).children('img').attr({src: '/src/icon_minimize.gif'});
                $(this).parents().eq(1).find(".user_box_content").slideDown('slow');
                $(this).parents().eq(1).find(".user_box_content").attr({style: 'display:block'});
            }
       }
    );
});

/*************************
* Suche Forms            *
*************************/

$(document).ready(function() {
	
	$("input[name='zip']").each(function() {
		akt=$(this);
		disableZip(akt);
	});
	
	function disableZip(akt) {			
		var zipVal = $(akt).val();
		if ( (zipVal.length < 5) || ( isNaN(zipVal) ) ) {
			$(akt).parents().eq(1).find("select[name='radius']").attr({disabled: 'disabled'});
		} else {
			$(akt).parents().eq(1).find("select[name='radius']").removeAttr("disabled");
		};		
	}
	
	$("input[name='zip']").keyup(function() {
		akt=$(this);
		disableZip(akt);
	});



	$("input[name='zip']").keyup(function() {
		var zipVal = $(this).val();
		if ( (zipVal.length < 5) || ( isNaN(zipVal) ) ) {
			$("select[name='zip_radius']").attr({disabled: 'disabled'});
		} else {
			$("select[name='zip_radius']").removeAttr("disabled");
		};
	});
	
	$("input[name='zip']").focusout(function() {
		var zipVal = $(this).val();
		if ( (zipVal.length < 5) || ( isNaN(zipVal) ) ) {
			$("select[name='zip_radius']").attr({disabled: 'disabled'});
		} else {
			$("select[name='zip_radius']").removeAttr("disabled");
		};
	});	

});

$(document).ready(function() {
	$(".field_1").toggle(function(){
		$(this).children('img').attr({src: '/src/icon_enlarge.gif'});
		$(".fieldset_1").slideUp('fast');
	},function(){
		$(this).children('img').attr({src: '/src/icon_minimize.gif'});
		$(".fieldset_1").slideDown('fast');
	});

	$(".field_2").toggle(function(){
		$(this).children('img').attr({src: '/src/icon_enlarge.gif'});
		$(this).parents().eq(1).find(".fieldset_2").slideUp('fast');
	},function(){
		$(this).children('img').attr({src: '/src/icon_minimize.gif'});
		$(this).parents().eq(1).find(".fieldset_2").slideDown('fast');
	});
});

/*************************
* Facebox                *
*************************/
/*
* 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')
* jQuery.facebox('some html', 'my-groovy-style')
*
* 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, an image, or the contents of a div:
*
* jQuery.facebox({ ajax: 'remote.html' })
* jQuery.facebox({ ajax: 'remote.html' }, 'my-groovy-style')
* jQuery.facebox({ image: 'stairs.jpg' })
* jQuery.facebox({ image: 'stairs.jpg' }, 'my-groovy-style')
* jQuery.facebox({ div: '#box' })
* jQuery.facebox({ div: '#box' }, 'my-groovy-style')
*
* 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
* afterClose.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, klass)
    else if (data.image) fillFaceboxFromImage(data.image, klass)
    else if (data.div) fillFaceboxFromHref(data.div, klass)
    else if ($.isFunction(data)) data.call($)
    else $.facebox.reveal(data, klass)
  }

  /*
* Public, $.facebox methods
*/

  $.extend($.facebox, {
    settings: {
      opacity : 0.5,
      overlay : true,
      loadingImage : '/src/loading_singles_klein.gif',
      closeImage : '/src/icon_modal_close.gif',
      imageTypes : [ 'png', 'jpg', 'jpeg', 'gif' ],
      faceboxHtml : '\
<div id="facebox" style="display:none;"> \
<div class="popup"> \
<table> \
<tbody id="facebox-tbody"> \
<tr> \
<td class="tl"/><td class="b"/><td class="tr"/> \
</tr> \
<tr> \
<td class="b"/> \
<td class="facebox_head"> \
<a href="#" class="close"> \
<img src="/src/icon_modal_close.gif" title="Schließen" class="close_image" /> \
</a></td>\
<td class="b"/> \
</tr> \
<tr> \
<td class="b"/> \
<td class="body"> \
<div class="content"> \
</div> \
<div class="footer"> \
</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),
        left: $(window).width() / 2 - 205
      }).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))
      $(document).trigger('reveal.facebox').trigger('afterReveal.facebox')
    },

    close: function() {
      $(document).trigger('close.facebox')
      return false
    }
  })

  /*
* Public, $.fn methods
*/

  $.fn.facebox = function(settings) {
    if ($(this).length == 0) return

    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.bind('click.facebox', 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').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,'')
      if (target == '#') return
      $.facebox.reveal($(target).html(), 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()
      $(document).trigger('afterClose.facebox')
    })
  })

})(jQuery);

/*************************
* UI-Slider extra        *
*************************/
$(document).ready(function() {
   /* if ($('select#weightMin').length > 0) {
        $('select#weightMin, select#weightMax').selectToUISlider({labels:2, tooltipSrc:'value'});
        //fixToolTipColor();
    }

    if ($('select#heightMin').length > 0) {
        $('select#heightMin, select#heightMax').selectToUISlider({labels:2, tooltipSrc:'value'});
        //fixToolTipColor();
    }

    if ($('select#ageMin').length > 0) {
        $('select#ageMin, select#ageMax').selectToUISlider({labels:2, tooltipSrc:'value'});
        //fixToolTipColor();
    } */

    if ($('select#height').length > 0) {
        $('#height').selectToUISlider({labels:2, tooltipSrc:'value'}).next();
        //fixToolTipColor();
    }

    if ($('select#weight').length > 0) {
        $('#weight').selectToUISlider({tooltipSrc:'value'}).next();
        //fixToolTipColor();
    }

    function fixToolTipColor(){
        $('.ui-tooltip-pointer-down-inner').each(function(){
            var bWidth = $('.ui-tooltip-pointer-down-inner').css('borderTopWidth');
            var bColor = $(this).parents('.ui-slider-tooltip').css('backgroundColor')
            $(this).css('border-top', bWidth+' solid '+bColor);
        })
    }
});

 /*************************
* Cockpit                  *
*************************/





/**********************************************
* Mein Profil                                 *
**********************************************/
/* Mein Profil - Fragen */
function openAnswer(questionId){
    $('#answerForm_'+questionId).fadeIn('slow');
}

function closeAnswer(questionId) {
    $('#answerForm_'+questionId).fadeOut('fast');
}

function saveAnswer(question_id) {
    var answer_content  = $('#answer_'+question_id).val();
    var arrow_edit      = $('#arrow_edit_answer_' + question_id);

    $.ajax({
        type: "POST",
        timeout: 7000,
        data: {questionId:question_id, answer:answer_content},
        url: "/MeinProfil/Fragen/speichern",
        success: function(result) {
            result = jQuery.parseJSON(result);

            if (result.ok) {
                closeAnswer(question_id);

                if (answer_content.length > 0)
                    arrow_edit.html('bearbeiten');
                else
                    arrow_edit.html('ändern');

                changeProgressBars(result);
            }
        }
    })
}

function changeProgressBars(values) {
    var progressBarQuestions  = $("span[rel='progress_questions']");
    var progressBarOverall    = $('.myprofile_right .teaser strong');

    var progressBarQuestionsText  = progressBarQuestions.html();
    var progressBarQuestionsValue = progressBarQuestionsText.substring(0, progressBarQuestionsText.lastIndexOf('%'));

    if (values.completeness.questions.css > 0) {
        if (progressBarQuestions.attr('class', 'myprofile_progress'))
            progressBarQuestions.addClass('myprofile_progress');

            progressBarQuestions
                .removeClass('progress_' + progressBarQuestionsValue)
                .addClass('progress_' + values.completeness.questions.css)
                .html(values.completeness.questions.value + '%');
    }
    else {
        progressBarQuestions.removeClass().html(values.completeness.questions.value + '%');
    }

    progressBarOverall.html(values.completeness.overall.value + '%');
}

function countSigns(question_id){
    if($('#answer_'+question_id).val().length > 1000) {
        alert('Es sind nur 1000 Zeichen erlaubt');
        $('#answer_'+question_id).val( $('#answer_'+question_id).val().substr(0,1000));
    }
    $('#signCount_'+question_id).html(1000 - $('#answer_'+question_id).val().length);

}

/* Mein Profil - Interessen */
$(document).ready(function() {

    $('.tab_navi li a').click(function(event) {
    	$(this).addClass('active');
		$(".tab_navi li a").not(this).removeClass('active');
		$(this).blur();
		$('#tab_content > div').css('display', 'none');
        $('#content_' + this.id).fadeIn('fast');
        event.preventDefault();
    });

});

/* Mein Profil - Kontakte / Kontaktanfragen */
$(document).ready(function() {
	$('.confirm_request').click(function(event) {
	    var request_id = $(this).parents(".handle_requests").attr('id');
		$("#"+request_id+" input[name='todo']").val("annehmen");
		$("#"+request_id).submit();
	    event.preventDefault();
	});
	$('.ignore_request').click(function(event) {
	    var request_id = $(this).parents(".handle_requests").attr('id');
		$("#"+request_id+" input[name='todo']").val("ignorieren");
		$("#"+request_id).submit();
	    event.preventDefault();
	});
});

/* Mein Profil - Profildaten */
$(document).ready(function() {
    setSliderStatus('height');
    setSliderStatus('weight');
	$('input:checkbox[name="show_height"]').change(function() {
	  setSliderStatus('height');
	});
	$('input:checkbox[name="show_weight"]').change(function() {
	  setSliderStatus('weight');
	});
});

function setSliderStatus(param){
  if($('input:checkbox[name="show_'+param+'"]').attr('checked') == true ) {
	    $('select[name="attribute['+param+']"]').prepend('<option value="0" label="0">0</option>');
		$('select[name="attribute['+param+']"]').val('0');
		$('#'+param+' + .ui-slider').slider('disable');
	  }
	  else {
	    $('#'+param+' + .ui-slider').slider('enable');
	    $('select[name="attribute['+param+']"] option[value="0"]').remove();
		var valuetext = ($('#handle_'+param).attr('aria-valuetext'));
	    $('select[name="attribute['+param+']"]').val(valuetext);
	    $('select[name="'+param+'"] option[value="'+valuetext+'"]').attr('selected','selected');
	}
}


jQuery.fn.chgNotice = function() {

	var chgNoticeStr = '<form ><input type="hidden" id="profil_id" name="profil_id" value="" /><h3>Notiz:</h3><textarea id="notiz" style="overflow: hidden;" name="notiz"  scrollbar="no"></textarea><p class="sign_count">Noch <span id="signCount">300</span> Zeichen zur Verf&uuml;gung</p><a href="javascript:void(0);" id="notiz_speichern" title="Notiz speichern"><img src="/src/button_speichern.gif" alt="Notiz speichern" /></a></form>';

	$('a[rel*=notizTrigger]').click(function(){
	 	jQuery.facebox(chgNoticeStr);
	 	$().handleNotice();
	  	$('textarea#notiz').val('');
		$('#profil_id').val($(this).attr('id'));
		$('#notiz').val($('#description_' + $(this).attr('id')).html());
		$('#signCount').html(80 - $('#notiz').val().length);

	});

	jQuery.fn.handleNotice = function() {

			$('#signCount').html(80 - $('#notiz').val().length);

			$('#notiz', $('#facebox')[0]).live('keyup', function() {
				if($('#facebox #notiz').val().length > 80) {
					alert('Es sind nur 80 Zeichen erlaubt');
					$('#notiz_speichern').attr({disabled: 'disabled'});
				  $('#facebox #notiz').val( $('#facebox #notiz').val().substr(0,80));
			  }
				$('#facebox #signCount').html(80 - $('#facebox #notiz').val().length);
			});


			if ( $('#confirmed_contacts').hasClass('active') ){
				$('#notiz_speichern').click(function() {
					$.ajax({
						type: "POST",
						timeout: 7000,
						data: {notiz:$('#notiz').val(), profil_id:$('#profil_id').val()},
						url: "/MeinProfil/Kontakte/notizspeichern",
						success: function(result) {
							$('#description_'+$('#profil_id').val()).html(result);
							// jQuery.trim(result);
							jQuery(document).trigger('close.facebox');
							}
						})
					});

				$('#newMessageLayer').empty();

			} else if ( $('#delete_favs').hasClass('search_form') ){
				$('#notiz_speichern').click(function() {
					$.ajax({
						type: "POST",
						timeout: 7000,
						data: {notiz:$('#notiz').val(), profil_id:$('#profil_id').val()},
						url: "/MeinProfil/Favoriten/speichern",
						success: function(result) {
							$('#description_'+$('#profil_id').val()).html(result);
							jQuery.trim(result);
							jQuery(document).trigger('close.facebox');
							}
						})
					});
			} else {
				return false;
			}

	};

};

$(document).ready(function(){
		$().chgNotice();
});

jQuery.fn.delContact = function() {
	$('#delete_contact').live('click', function() {
	  	if ($('input:checked').length >= 1) {
			var delContactStr = '<h3>Kontakte löschen</h3><div class="hold_delete"><p>Möchten Sie die Kontakte wirklich löschen?</p><a href="#" id="abort" class="close" title="Abbrechen"><img src="/src/btn_nein.gif" alt="Abbrechen" /></a><a href="javascript:void(0);" id="confirm" title="Bestätigen"><img src="/src/btn_ja.gif" alt="Bestätigen" /></a></div>';
			jQuery.facebox(delContactStr);
			$('#confirm').live('click', function() {
				$('#delete_contacts_form').submit();
				jQuery(document).trigger('close.facebox');
			});
			$('#abort').live('click', function() {
				jQuery(document).trigger('close.facebox');
			});
	  	} else {
			var delNoContactStr = '<h3>Kontakte löschen</h3><div class="hold_delete_no"><p>Sie haben keine Kontakte ausgewählt.</p><a href="javascript:void(0);" class="close" title="Schließen"><img src="/src/btn_abbrechen.gif" alt="Schließen" /></a></div>';
			jQuery.facebox(delNoContactStr);
			$('.close').live('click', function() {
				jQuery(document).trigger('close.facebox');
			});
	  	}
	});
};
$(document).ready(function(){
	$().delContact();
});

jQuery.fn.delFavs = function() {

	$('#delete_favs_trigger').live('click', function() {

	  	if ($('input:checked').length >= 1) {

			var delFavsStr = '<h3>Favoriten löschen</h3><div class="hold_delete"><p>Möchten Sie den/ die Favorit(en) wirklich löschen?</p><a href="#" id="abort" class="close" title="Abbrechen"><img src="/src/btn_nein.gif" alt="Abbrechen" /></a><a href="javascript:void(0);" id="confirm" title="Bestätigen"><img src="/src/btn_ja.gif" alt="Bestätigen" /></a></div>';

			jQuery.facebox(delFavsStr);

			$('#confirm').live('click', function() {
				$('#delete_favs').submit();
				jQuery(document).trigger('close.facebox');
			});

			$('#abort').live('click', function() {
				jQuery(document).trigger('close.facebox');
			});

	  	} else {

			var delNoFavsStr = '<h3>Favoriten löschen</h3><div class="hold_delete_no"><p>Sie haben keine Favoriten ausgewählt.</p><a href="javascript:void(0);" class="close" title="Schließen"><img src="/src/btn_abbrechen.gif" alt="Schließen" /></a></div>';

			jQuery.facebox(delNoFavsStr);

			$('.close').live('click', function() {
				jQuery(document).trigger('close.facebox');
			});
	  	}

	});

};
$(document).ready(function(){
	$().delFavs();
});

/* Mein Profil - Interessen */

jQuery.fn.handleBubbles = function() {

	// Close Tooltip
	$('.close_add_to_contacts').live('click', function(event) {
		$(this).parents(".div_message").hide('fast');
		$(this).parents(".tooltip_content").html('');
		event.preventDefault();
	});

	// Add To Contacts Gäste
	$("a[rel='link_zukontakten']").click(function(){
	    $(".tooltip_content").empty();
	    $(this).children(".div_message").fadeIn('slow');
	    $(this).blur();
	    $.get("/Profil/addtocontacts/profile/" + $('#guest_profile_id').val()+"/description/"+$('#description').val(), function(text){
	    	$(".tooltip_content").html(text);
	    });
	    $(this).children(".div_message").delay(5000).fadeOut('slow');
	    $(this).parents(".tooltip_content").html('');
	});

	/*
	// Add To Contacts Fremdprofil
	$("a[rel='zukontakten']").click(function(){
	    $(".tooltip_content").empty();
	    $(this).children(".div_message").fadeIn('slow');
	    $(this).blur();
	    $.get("/Profil/addtocontacts/profile/"+$('#profile_id').val()+"/description/"+$('#description').val(), function(text){
	    	$(".tooltip_content").html(text);
	    });
	    $(this).children(".div_message").delay(5000).fadeOut('slow');
	    $(this).parents(".tooltip_content").html('');
	});


	// Block User
	$("a[rel='link_blocken']").click(function(){
	    $(".tooltip_content").empty();
	    $(this).children(".div_message").fadeIn('slow');
		$(this).blur();
		$.get("/Profil/blocken/profile/" + $('#guest_profile_id').val(), function(text){
			$(".tooltip_content").html(text);
	    });
	    $(this).children(".div_message").delay(5000).fadeOut('slow');
	    $(this).parents(".tooltip_content").html('');
	});
*/

	// Stupsel back
	/*
	$("a[rel='link_zurueckstupseln']").click(function(){
	    $(".tooltip_content").empty();
	    $(this).children(".div_message").fadeIn('slow');
		$(this).blur();
	    $.ajax({
	      type: "POST",
	      timeout: 7000,
	      data: {guestprofile:$('#guest_profile_id').val()},
	      url: "/MeineKontakte/Stupselliste/zurueckstupseln",
	      success: function(result) {
	        var retStatus;
	        if (result)
	            retStatus = 'Erfolgreich zurückgestupselt!';
	        else
	        	retStatus = 'Fehler! Bitte versuchen Sie es später noch einmal.';

	        $(".tooltip_content").html(retStatus);
	      }
	    })
	    $(this).children(".div_message").delay(5000).fadeOut('slow');
	});
/*
	// Stupsel
	$("a[rel='link_stupseln']").click(function(){
	    $(".tooltip_content").empty();
	    $(this).children(".div_message").fadeIn('slow');
		$(this).blur();
        $.get("/Profil/stupseln/profile/"+$('#profile_id').val(), function(text){
        	$(".tooltip_content").html(text);
        });
	    $(this).children(".div_message").delay(5000).fadeOut('slow');
	    $(this).parents(".tooltip_content").html('');
    });
*/
	$("a[rel='link_abschicken']").click(function() {
	    $.ajax({
            type: "POST",
            timeout: 7000,
            data: {receiver:$('#guest_profile_id').val(),subject:'Neue Nachricht', content:$('#' + this.name).val()},
            url: "/Postfach/Neuenachricht",
            success: function(result) {
                var sm_retStatus;

                switch (result) {
                    case 'true':
                        sm_retStatus = 'Nachricht wurde erfolgreich versandt.';
                        $('#message_' + $('#guest_profile_id').val()).val('');
                        break;
                    case '"noPlus"':
                        window.location = '/MeinProfil/Plusmitgliedschaft';
                        break;
					case '"noContent"':
                        sm_retStatus = 'Nachricht kann nicht gesendet werden. Bitte geben Sie eine Nachricht vor dem Versenden ein.';
                        break;
                    default:
                        sm_retStatus = 'Fehler! Bitte versuchen Sie es später noch einmal.';
                        break;
                }

                if (sm_retStatus) {
                    $('#arrow_' + $('#guest_profile_id').val()).fadeOut(function() {
                        $('#sm_sentStatus_' + $('#guest_profile_id').val())
                            .html(sm_retStatus)
                            .fadeIn('slow')
                            .delay(1000)
                            .fadeOut(function() {
                                $('#arrow_' + $('#guest_profile_id').val()).fadeIn(100);
                            })
                    })
                }
            }
	    });
	    //$(this).children(".div_message").show('fast');
	});

/*
	// Favoriten
	$("a[rel='link_zufavoriten']").click(function(){
	    $(".tooltip_content").empty();
	    $(this).children(".div_message").fadeIn('slow');
		$(this).blur();
        $.get("/Profil/addtofavorites/profile/"+$('#profile_id').val(), function(text){
        	$(".tooltip_content").html(text);
        });
	    $(this).children(".div_message").delay(5000).fadeOut('slow');
	    $(this).parents(".tooltip_content").html('');
    });



	$("a[rel='link_melden']").click(function(){
	    $(".tooltip_content").empty();
	    $(this).children(".div_message").css('left');
	    $(this).children(".div_message").fadeIn('slow');
		$(this).blur();
        $.get("/Profil/melden/profile/[{$profileData.profile_id}]/cid/[{$profileData.cid}]", function(text){
        	$(".tooltip_content").html(text);
        });
	    $(this).children(".div_message").delay(5000).fadeOut('slow');
	    $(this).parents(".tooltip_content").html('');
    });
*/
// neue mit Bubbles

	// add to contacts new




	$("a[rel='link_zufavoriten']").live('click', function(){
		$(this).blur();
		var target = $(this).next('div').find('.tooltip_content_new');
	    $.get("/Profil/addtofavorites/profile/"+$('#profile_id').val(), function(text){
	    	$(target).html(text);
	    });
	});

	$("a[rel='link_blocken']").click(function(){
		$(this).blur();
		art = $(this).attr('class');
//		var target = $(this).next('div').find('.tooltip_content_new');
	    $.get("/Profil/blocken/profile/"+$('#profile_id').val(), function(text){
	    	if (art == 'show_profile_block_profile') {
	//    		$(target).html(text);
	    	} else if (art == 'stupselliste_blocken') {
	    		document.location.href="/MeineKontakte/Stupselliste";
	    	} else {
	    		document.location.href="/Postfach";
	    	}
	    });
	});
	
	$("a[rel='link_blocken_detail']").click(function(){
		id = $(this).children().attr('class');
	    $.get("/Profil/blocken/profile/"+id, function(){
	    document.location.href="/Postfach"; 
	    });
	});

	
	$("a[rel='link_aussortieren']").live('click', function(event){
			$(this).blur();
			var profileId = $('#profile_id').val();
			var target = $(this).next('div').find('.tooltip_content_new');
			if (profileId != null ) {
				$.get("/Cockpit/index/sortout/profileId/"+profileId, function(result){
					if (result == 1){
					  $(target).html('Dieses Profil wird Ihnen hier nicht mehr angezeigt!');
					  //partnervorschlag aktualisieren
				      sortOut();
					}
					else {
					  $(target).html('Hat nicht geklappt');
					}
				});
			}
	});
	
	$("a[rel='link_zurueckstupseln']").click(function(){
		$(this).blur();
		var target = $(this).next('div').find('.tooltip_content_new');
	    $.ajax({
		      type: "POST",
		      timeout: 7000,
		      data: {guestprofile:$('#guest_profile_id').val()},
		      url: "/MeineKontakte/Stupselliste/zurueckstupseln",
		      success: function(result) {
		        var retStatus;
		        if (result)
		            retStatus = 'Erfolgreich zurückgestupselt!';
		        else
		        	retStatus = 'Fehler! Bitte versuchen Sie es später noch einmal.';

		        $(target).html(retStatus);
		      }
		 })		
	});

};
$(document).ready(function(){
	$().handleBubbles();
});


/* Einstellungen - Interessen */
jQuery.fn.chgEmail = function() {
	$('#chg_email_trigger').click(function(event){
		var chgEmailStr = '<div id="chg_email_layer"><form id="form_change_email" action="" method="post"><h3>Ihre E-Mail Adresse lautet: <span></span></h3><br /><p>Neue E-Mail-Adresse</p><input class="facebox_form_txt" id="email1" name="email1" type="text" value=""/><br /><br /><p>E-Mail-Adresse wiederholen</p><input class="facebox_form_txt" id="email2" name="email2" type="text" value=""/><br /><br /><div class="floatbox facebox_wrap_error"><div class="facebox_error" id="sentStatus"></div><div class="right"><input type="image" src="/src/button_speichern.gif" value="Speichern" /></div></div></form></div>';
		jQuery.facebox(chgEmailStr);
		$('#form_change_email h3 span').text($(this).attr('name'));
		$().chgEmailAction();
		event.preventDefault();
	});

	jQuery.fn.chgEmailAction = function() {
		      //Submit
		      $('#facebox #form_change_email').submit(function() {
		          var email1    = $('#facebox #email1').val();
		          var email2    = $('#facebox #email2').val();

		          $.ajax({
		              type: "POST",
		              timeout: 7000,
		              data: {email1:email1, email2:email2},
		              url: "/MeinProfil/Benachrichtigungen/email",
		              success: function(result) {
			                if (result == true) {
		                      $('#facebox #form_change_email').fadeOut(100);
		                      var result = 'Email-Adresse wurde geändert';
		                      $('#email_address').html(email1);
		                      $.facebox.close();
			                } else {
		                  $('#facebox #sentStatus').fadeIn(100).html(result);
			                }
		              }
		          })
		          return false;
		      });
	};
};

$(document).ready(function(){
	$().chgEmail();
});

/* Einstellungen - Matching */

function blockForm(form) { 
	if (form == 'state'){ 
		if ($('#formState').val() != '0') {
			$('#formZip').val('');
			$('#formZip').attr("disabled","disabled");
			$('#formRadius').attr("disabled","disabled");
		}else {
			$('#formZip').removeAttr("disabled");
			$('#formRadius').removeAttr("disabled");			
		}
	}
	if (form == 'zip'){
		zipLength = $('#formZip').val().length;
		if (zipLength > '0'){
			$('#formState').attr("disabled","disabled");
			$('#formState').val('0');
		} else {
			$('#formState').removeAttr("disabled");
		}	
	}
}

$(document).ready(function()
		{

		if(document.sucheForm && document.sucheForm.zip.value.length < 5)
		       {
		           document.sucheForm.radius.disabled = true;
		        }
		});



/*************************
* Fremdprofil            *
*************************/

$("a[rel='link_no_login']").live('click', function(event) {
	var noLoginStr = '<div class="show_profile_no_login_layer"><h3>Um diese Funktion nutzen zu können müssen Sie eingeloggt sein!</h3><p class="show_profile_no_login_intro"><strong>Ihre Vorteile im Überblick</strong></p><ul class="show_profile_no_login_ul"><li><strong>Verlieben: </strong>Über 2,0 Millionen Singles warten auf Sie – bis 3.000 neue Singles täglich.</li><li><strong>Finden statt suchen: </strong>Partnervorschläge nach Ihren persönlichen Suchkriterien.</li><li><strong>Stupseln: </strong>Per virtuellem Kuss Kontakt zu anderen Singles aufnehmen.</li></ul><div class="floatbox"><div class="right"><a href="/Registrierung/Index/index/cookie/fssuu/key/callback" title="Jetzt einloggen oder kostenlos registrieren"><img src="/src/btn_kostenlosregistrieren.gif" alt="Jetzt einloggen oder kostenlos registrieren" width="185" height="24" /></a></div></div></div>';
	jQuery.facebox(noLoginStr);
	event.preventDefault();
});


$("a[rel='link_award']").live('click', function(event) {
	jQuery.facebox($('.show_profile_awards_layer').html());
	event.preventDefault();
});

$("a[rel='link_forum_award']").live('click', function(event) {
	jQuery.facebox($('.show_profile_forum_awards_layer').html());
	event.preventDefault();
});


$('.show_profile_gb_textarea').live('keyup', function() {
    var maxSignCount    = 500;
    var actualSignCount = $(this).val().length;

    if (actualSignCount <= maxSignCount) {
        $('.signCount_gb').html(maxSignCount - actualSignCount);
    }
    else {
        alert('Es sind nur ' + maxSignCount + ' Zeichen erlaubt');
        $(this).val($(this).val().substr(0, maxSignCount));
    }
});


$(document).ready(function() {
   $('.user_img_50 .show_profile_small_pic').click(function(event){
     var currentImg = ($(this).children('img').attr('src'));
     var currentDesc = ($(this).attr('name'));
     var currentHref = ($(this).attr('href'));
     var currentNr = ($(this).attr('id'));
     currentNr = currentNr.replace(/picNr/, "picBigNr");
     $(this).attr('longdesc', currentHref);
     currentImg = ($(this).attr('rel'));
     $('#bigpicture').attr({src: currentImg, name: currentDesc, longdesc: currentHref});
     $('#bigpicture').attr('class',currentNr);
     event.preventDefault();
   });


});

/*************************
* Admin                  *
*************************/
$(document).ready(function() {
    $('#div_logos > *').click(function(eventObject){
        $('#div_logos > *').css('border', '3px solid white');
        $(this).css('border', '3px solid red');
        $('#admin_logo_url').val($(this).attr('title'));
    });
});

/*************************
* Hilfebubbles           *
*************************/
/*
 * jQuery Tools 1.2.3 - The missing UI library for the Web
 *
 * [tooltip, tooltip.slide, tooltip.dynamic]
 *
 * NO COPYRIGHTS OR LICENSES. DO WHAT YOU LIKE.
 *
 * http://flowplayer.org/tools/
 *
 * File generated: Sat Jul 03 10:58:08 GMT 2010
 */
(function(f){function p(a,b,c){var h=c.relative?a.position().top:a.offset().top,e=c.relative?a.position().left:a.offset().left,i=c.position[0];h-=b.outerHeight()-c.offset[0];e+=a.outerWidth()+c.offset[1];var j=b.outerHeight()+a.outerHeight();if(i=="center")h+=j/2;if(i=="bottom")h+=j;i=c.position[1];a=b.outerWidth()+a.outerWidth();if(i=="center")e-=a/2;if(i=="left")e-=a;return{top:h,left:e}}function t(a,b){var c=this,h=a.add(c),e,i=0,j=0,m=a.attr("title"),q=n[b.effect],k,r=a.is(":input"),u=r&&a.is(":checkbox, :radio, select, :button, :submit"),
s=a.attr("type"),l=b.events[s]||b.events[r?u?"widget":"input":"def"];if(!q)throw'Nonexistent effect "'+b.effect+'"';l=l.split(/,\s*/);if(l.length!=2)throw"Tooltip: bad events configuration for "+s;a.bind(l[0],function(d){clearTimeout(i);if(b.predelay)j=setTimeout(function(){c.show(d)},b.predelay);else c.show(d)}).bind(l[1],function(d){clearTimeout(j);if(b.delay)i=setTimeout(function(){c.hide(d)},b.delay);else c.hide(d)});if(m&&b.cancelDefault){a.removeAttr("title");a.data("title",m)}f.extend(c,{show:function(d){if(!e){if(m)e=
f(b.layout).addClass(b.tipClass).appendTo(document.body).hide().append(m);else if(b.tip)e=f(b.tip).eq(0);else{e=a.next();e.length||(e=a.parent().next())}if(!e.length)throw"Cannot find tooltip for "+a;}if(c.isShown())return c;e.stop(true,true);var g=p(a,e,b);d=d||f.Event();d.type="onBeforeShow";h.trigger(d,[g]);if(d.isDefaultPrevented())return c;g=p(a,e,b);e.css({position:"absolute",top:g.top,left:g.left});k=true;q[0].call(c,function(){d.type="onShow";k="full";h.trigger(d)});g=b.events.tooltip.split(/,\s*/);
e.bind(g[0],function(){clearTimeout(i);clearTimeout(j)});g[1]&&!a.is("input:not(:checkbox, :radio), textarea")&&e.bind(g[1],function(o){o.relatedTarget!=a[0]&&a.trigger(l[1].split(" ")[0])});return c},hide:function(d){if(!e||!c.isShown())return c;d=d||f.Event();d.type="onBeforeHide";h.trigger(d);if(!d.isDefaultPrevented()){k=false;n[b.effect][1].call(c,function(){d.type="onHide";k=false;h.trigger(d)});return c}},isShown:function(d){return d?k=="full":k},getConf:function(){return b},getTip:function(){return e},
getTrigger:function(){return a}});f.each("onHide,onBeforeShow,onShow,onBeforeHide".split(","),function(d,g){f.isFunction(b[g])&&f(c).bind(g,b[g]);c[g]=function(o){f(c).bind(g,o);return c}})}f.tools=f.tools||{version:"1.2.3"};f.tools.tooltip={conf:{effect:"toggle",fadeOutSpeed:"fast",predelay:0,delay:30,opacity:1,tip:0,position:["top","center"],offset:[0,0],relative:false,cancelDefault:true,events:{def:"mouseenter,mouseleave",input:"focus,blur",widget:"focus mouseenter,blur mouseleave",tooltip:"mouseenter,mouseleave"},
layout:"<div/>",tipClass:"tooltip"},addEffect:function(a,b,c){n[a]=[b,c]}};var n={toggle:[function(a){var b=this.getConf(),c=this.getTip();b=b.opacity;b<1&&c.css({opacity:b});c.show();a.call()},function(a){this.getTip().hide();a.call()}],fade:[function(a){var b=this.getConf();this.getTip().fadeTo(b.fadeInSpeed,b.opacity,a)},function(a){this.getTip().fadeOut(this.getConf().fadeOutSpeed,a)}]};f.fn.tooltip=function(a){var b=this.data("tooltip");if(b)return b;a=f.extend(true,{},f.tools.tooltip.conf,a);
if(typeof a.position=="string")a.position=a.position.split(/,?\s/);this.each(function(){b=new t(f(this),a);f(this).data("tooltip",b)});return a.api?b:this}})(jQuery);
(function(d){var i=d.tools.tooltip;d.extend(i.conf,{direction:"up",bounce:false,slideOffset:10,slideInSpeed:200,slideOutSpeed:200,slideFade:!d.browser.msie});var e={up:["-","top"],down:["+","top"],left:["-","left"],right:["+","left"]};i.addEffect("slide",function(g){var a=this.getConf(),f=this.getTip(),b=a.slideFade?{opacity:a.opacity}:{},c=e[a.direction]||e.up;b[c[1]]=c[0]+"="+a.slideOffset;a.slideFade&&f.css({opacity:0});f.show().animate(b,a.slideInSpeed,g)},function(g){var a=this.getConf(),f=a.slideOffset,
b=a.slideFade?{opacity:0}:{},c=e[a.direction]||e.up,h=""+c[0];if(a.bounce)h=h=="+"?"-":"+";b[c[1]]=h+"="+f;this.getTip().animate(b,a.slideOutSpeed,function(){d(this).hide();g.call()})})})(jQuery);
(function(g){function j(a){var c=g(window),d=c.width()+c.scrollLeft(),h=c.height()+c.scrollTop();return[a.offset().top<=c.scrollTop(),d<=a.offset().left+a.width(),h<=a.offset().top+a.height(),c.scrollLeft()>=a.offset().left]}function k(a){for(var c=a.length;c--;)if(a[c])return false;return true}var i=g.tools.tooltip;i.dynamic={conf:{classNames:"top right bottom left"}};g.fn.dynamic=function(a){if(typeof a=="number")a={speed:a};a=g.extend({},i.dynamic.conf,a);var c=a.classNames.split(/\s/),d;this.each(function(){var h=
g(this).tooltip().onBeforeShow(function(e,f){e=this.getTip();var b=this.getConf();d||(d=[b.position[0],b.position[1],b.offset[0],b.offset[1],g.extend({},b)]);g.extend(b,d[4]);b.position=[d[0],d[1]];b.offset=[d[2],d[3]];e.css({visibility:"hidden",position:"absolute",top:f.top,left:f.left}).show();f=j(e);if(!k(f)){if(f[2]){g.extend(b,a.top);b.position[0]="top";e.addClass(c[0])}if(f[3]){g.extend(b,a.right);b.position[1]="right";e.addClass(c[1])}if(f[0]){g.extend(b,a.bottom);b.position[0]="bottom";e.addClass(c[2])}if(f[1]){g.extend(b,
a.left);b.position[1]="left";e.addClass(c[3])}if(f[0]||f[2])b.offset[0]*=-1;if(f[1]||f[3])b.offset[1]*=-1}e.css({visibility:"visible"}).hide()});h.onBeforeShow(function(){var e=this.getConf();this.getTip();setTimeout(function(){e.position=[d[0],d[1]];e.offset=[d[2],d[3]]},0)});h.onHide(function(){var e=this.getTip();e.removeClass(a.classNames)});ret=h});return a.api?ret:this}})(jQuery);

$(document).ready(function() {

	// myprofile_box col2

	$('.myprofile_box_show_bubbles_stupsel').tooltip({
		position: 'top right',
		offset: [0,-30]
	});

	$('.myprofile_box_show_bubbles_contacts').tooltip({
		position: 'top right',
		offset: [0,-30]
	});

	// show_profile

	$('.show_profile_link_stupsel').tooltip({
		position: 'top right',
		offset: [0,-20],
		event: 'click'
	});

	$('.show_profile_link_sms').tooltip({
		position: 'top right',
		offset: [0,-20]
	});
	
	$('.show_profile_link_chat_no_login').tooltip({
		position: 'top right',
		offset: [0,-20]
	});	

	$('.show_profile_add_as_contact').tooltip({
		cancelDefault: false,
		position: 'top right',
		offset: [0,-20],
		event: 'click'
	});

	$('.show_profile_add_as_fav').tooltip({
		cancelDefault: false,
		position: 'top right',
		offset: [0,-20],
		event: 'click'
	});

	$('.show_profile_block_profile').tooltip({
		position: 'top right',
		offset: [0,-20]
	});	
	
	$('.show_no_chat').tooltip({
		position: 'top right',
		offset: [0,-20]
	});		
	


	// Cockpit

	$("body").live("mouseover",function(){
		$(".cockpit_btn").tooltip({
			position: 'top right',
			offset: [-10,-30]
		});
	});
	

	$('#draggable_area').tooltip({
		position: 'top right',
		offset: [0,-20]
	});	
	
	
	
	$('.show_profile_add_as_fav').tooltip({
		cancelDefault: false,
		position: 'top right',
		offset: [0,-20],
		event: 'click'
	});
	
	$('.cockpit_btn_add_to_favs_no_bubbles').tooltip({
		cancelDefault: false,
		position: 'top right',
		offset: [0,-20],
		event: 'click'
	});
	
	// Landingpage
	
	$('.link_lp_help').tooltip({
		position: 'top right',
		offset: [0,-20]
	});	
	
	// Nachrichten
	
	$('.mail_block_user').tooltip({
		position: 'top right',
		offset: [0,-20]
	});
	
	// Mein Profil - Stupselliste
	
	$('.stupselliste_zurueckstupseln').tooltip({
		position: 'top right',
		offset: [0,-40]
	});
	
	$('.stupselliste_blocken').tooltip({
		position: 'top right',
		offset: [0,-40]
	});	
		
	$('.stupselliste_add_to_contacts').tooltip({
		position: 'top right',
		offset: [0,-40]
	});
	
	$('.stupselliste_delete_poke').tooltip({
		position: 'top right',
		offset: [0,-40]
	});
	
	

});


/*****************************
* BrokenImages rausschmeißen *
******************************/
/**
 * Weichenfunktion welche zur Renderengine spezifischen Funktion verweist.
 * Renderengines siehe: http://de.wikipedia.org/wiki/HTML-Rendering
 */
function IsImageOk(img)
{
//	alert('IsImageOk');
    /**
     *Neue Funktion fuer spaeteren browsercheck
     */

    if( (CheckBrowserName('MSIE')) )
        return IsImageOkMSIE(img);

    else if( (CheckBrowserName('firefox')) )
        return IsImageOkFirefox(img);

    else if( (CheckBrowserName('opera')) )
        return IsImageOkOpera(img);

    else if( (CheckBrowserName('safari')) )
        return IsImageOkSafari(img);

    else
        return true;

/**
 *Originalfunktion vor dem auslagern in Renderenginespezifische Funktionen
 */
/*
    // During the onload event, IE correctly identifies any images that
    // weren't downloaded as not complete. Others should too. Gecko-based
    // browsers act like NS4 in that they report this incorrectly.
    if (!img.complete)
    {
        return false;
    }

    // However, they do have two very useful properties: naturalWidth and
    // naturalHeight. These give the true size of the image. If it failed
    // to load, either of these should be zero.
    if (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) {
        return false;
    }

    // No other way of checking: assume it's ok.
    return true;
*/
}

/**
* Broken Image Check Function for Browsers with Trident Renderengine
*/
function IsImageOkMSIE(img)
{
    // During the onload event, IE correctly identifies any images that
    // weren't downloaded as not complete. Others should too. Gecko-based
    // browsers act like NS4 in that they report this incorrectly.
    if (!img.complete)
    {
        return false;
    }
    else
        return true;
}

/**
* Broken Image Check Function for Browsers with Gecko Renderengine
*/
function IsImageOkFirefox(img)
{
    // However, they do have two very useful properties: naturalWidth and
    // naturalHeight. These give the true size of the image. If it failed
    // to load, either of these should be zero.
    if (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0)
    {
        return false;
    }
    else
        return true;
}

/**
* Broken Image Check Function for Browsers with Presto/Elektra Renderengine
*/
function IsImageOkOpera(img)
{
    return true;    //Bisher kein Test vorhanden
}

/**
* Broken Image Check Function for Browsers with Webkit Renderengine
*/
function IsImageOkSafari(img)
{
    return true;    //Bisher kein Test vorhanden
}

/**
 * Testet ob der uebergebene Name in der Browserkennung steht
 */
function CheckBrowserName(name)
{
    var agent = navigator.userAgent.toLowerCase();
    if (agent.indexOf(name.toLowerCase())>-1)
    {
        return true;
    }
    return false;
}

/**
 * Funktion die aufgerufen wird, wenn der DOM-Baum im Browser fertig gebaut wurde
 * Wird außerden in Cockpt/snippet-suggestion.tpl benutzt. Achtung
 */
$(window).load(function()
{
    for (var i = 0; i < document.images.length; i++)
    {
        if (!IsImageOk(document.images[i]) &&
            (document.images[i].src.search(/pics.singles.freenet.de/)>0) )  //document.[...].search > 0 == suchstring wurde gefunden
        {
            document.images[i].src = "/src/avatar_special_120.jpg";
        }
    }
})


/*************************
* Nachrichten            *
*************************/
jQuery.fn.clearArchiv = function() {
	var defaultArchivVal = $('#addFolderName').val();
	$('#addFolderName').focus(function(){
		$(this).attr({value: ''});
	});
	$('#addFolderName').blur(function(){
		var currentArchivVal = $('#addFolderName').val();
		if (currentArchivVal == '' || currentArchivVal == defaultArchivVal) {
			$(this).val(defaultArchivVal);
		};
	});
};

$(document).ready(function(){
	$().clearArchiv();

    $('#checkAll').click(function() {
        var target = $(this).attr('rel');
        $("input[name='" + target + "']")
            .attr('checked', $('#checkAll')
            .is(':checked'));
    });
});

is_online = 0;
is_new = 0;
function setNewMessageDefaultValues(profileId, nickname, hasImage, online, isnew) {
    $('#multiple_profile_id').val(profileId);
    $('#multiple_profile_nickname').attr('name', nickname);
    $('#multiple_profile_has_image').attr('name', hasImage);
    is_online = online;
    is_new = isnew;
}

$("a[rel='link_spamInfo']").live('click', function(event) {
	jQuery.facebox($('.show_spam_layer').html());
	event.preventDefault();
});

/*************************
* rechte Seite Mein Profil  *
*************************/

$("a[rel='show_status_layer']").die('click').live('click', function(event) {
	showTextInDialog('show_status_layer','Ihr persönlicher Status:',320);
	showStatus();
})

function showStatus(){

 //$.facebox(function(){ 
	$.ajax({
        type: "GET",
        timeout: 7000,
        url: "/Ajax/Index/task/profilstatus/mode/get/",
        success: function(result) {
           var wants = result.wants;
           var is = result.is;
		   var i;
		   var j;
		   var htmlWants ="<select name='status_wants'>";
		   var htmlIs ="<select name='status_is'>";
		   var selectedIs = result.selected.is;
		   var selectedWants = result.selected.wants;
		   for(i=0;i<is.length;i++){
		     var setSelectIs = '';
		     //if(selectedIs == i){setSelectIs = " selected='selected'"}
		     htmlIs += "<option value='"+is[i].id+"'"+setSelectIs+">"+is[i].name+"</option>";
		   }
		     htmlIs += "</select>";
		   //$("#facebox select[name='status_is']").html(htmlIs);
		   $(".ui-dialog .status_wait").remove();
		   $(".ui-dialog select[name='status_is']").remove();
		   $(".ui-dialog select[name='status_wants']").remove();
		   $(".ui-dialog label[for='status_is']").after(htmlIs);
		   for(j=0;j<wants.length;j++){
		    var setSelectWants = '';
		   // if(selectedWants == j){setSelectWants = " selected='selected'"}
		    htmlWants += "<option value='"+wants[j].id+"'"+setSelectWants+">"+wants[j].name+"</option>";
		   }
		   htmlWants += "</select>";
		   //$("#facebox select[name='status_wants']").html(htmlWants); 
		   $(".ui-dialog label[for='status_wants']").after(htmlWants); 
		   //$.facebox(htmlIs+htmlWants); 
		   
		
   		   var selectedIs = result.selected.is;
		   var selectedWants = result.selected.wants;
		   $(".ui-dialog select[name='status_wants'] option[value="+selectedWants+"]").attr("selected", true);
		   $(".ui-dialog select[name='status_is'] option[value="+selectedIs+"]").attr("selected", true); 
		   
		} 
	});    	
	//event.preventDefault();
// });
}

$("#saveStatus").die('click').live('click', function(event) {
 var statusIsSelected = $(".ui-dialog select[name='status_is']").attr('value');
 var statusIsSelectedText = $(".ui-dialog select[name='status_is'] option:selected").text();
 var statusWantsSelected = $(".ui-dialog select[name='status_wants']").attr('value');
 var statusWantsSelectedText = $(".ui-dialog select[name='status_wants'] option:selected").text(); 
 $.ajax({
  type: "POST",
  timeout: 7000,
  url: "/Ajax/Index/task/profilstatus/mode/set/is/"+statusIsSelected+"/wants/"+statusWantsSelected,
  success: function(result){
    $('.status_is').text(statusIsSelectedText).attr('title', statusIsSelectedText);
    $('.status_wants').text(statusWantsSelectedText).attr('title', statusWantsSelectedText);
	$('.status_search_is').attr('href', '/Suche/Statussuche/instant/statusis/'+statusIsSelected);
	$('.status_search_wants').attr('href', '/Suche/Statussuche/instant/statuswants/'+statusWantsSelected);
  }
 });
 dialogClose();
 //event.preventDefault();
});

/*************************
* rechte Seite Countdown  *
*************************/


/*
 * jquery-counter plugin
 *
 * Copyright (c) 2009 Martin Conte Mac Donell <Reflejo@gmail.com>
 * Dual licensed under the MIT and GPL licenses.
 * http://docs.jquery.com/License
 */
jQuery.fn.countdown = function(userOptions)
{
  // Default options
  var options = {
    stepTime: 60,
    // startTime and format MUST follow the same format.
    // also you cannot specify a format unordered (e.g. hh:ss:mm is wrong)
    format: "dd:hh:mm:ss",
    startTime: "01:12:32:55",
    digitImages: 6,
    digitWidth: 53,
    digitHeight: 77,
    timerEnd: function(){},
    image: "digits.png"
  };
  var digits = [], interval;

  // Draw digits in given container
  var createDigits = function(where) 
  {
    var c = 0;
    options.startTime = options.startTime.split('');
    options.format = options.format.split('');

    // Iterate each startTime digit, if it is not a digit
    // we'll asume that it's a separator
    for (var i = 0; i < options.startTime.length; i++)
    {
      if (parseInt(options.startTime[i]) >= 0) 
      {
        elem = $('<div id="cnt_' + i + '" class="cntDigit" />').css({
          height: options.digitHeight * options.digitImages * 10, 
          float: 'left', background: 'url(\'' + options.image + '\')',
          width: options.digitWidth});
        digits.push(elem);
        margin(c, -((parseInt(options.startTime[i]) * options.digitHeight *
                              options.digitImages)));
        digits[c].__max = 9;
        // Add max digits, for example, first digit of minutes (mm) has 
        // a max of 5. Conditional max is used when the left digit has reach
        // the max. For example second "hours" digit has a conditional max of 4 
        switch (options.format[i]) {
          case 'h':
            digits[c].__max = (c % 2 == 0) ? 2: 9;
            if (c % 2 == 0)
              digits[c].__condmax = 4;
            break;
          case 'd': 
            digits[c].__max = 9;
            break;
          case 'm':
          case 's':
            digits[c].__max = (c % 2 == 0) ? 5: 9;
        }
        ++c;
      }
      else 
        elem = $('<div class="cntSeparator"/>').css({float: 'left'})
                .text(options.startTime[i]);

      where.append('<div>');
      where.append(elem)
      where.append('</div>');
    }
  };
  
  // Set or get element margin
  var margin = function(elem, val) 
  {
    if (val !== undefined)
      return digits[elem].css({'marginTop': val + 'px'});

    return parseInt(digits[elem].css('marginTop').replace('px', ''));
  };

  // Makes the movement. This is done by "digitImages" steps.
  var moveStep = function(elem) 
  { 
    digits[elem]._digitInitial = -(digits[elem].__max * options.digitHeight * options.digitImages);
    return function _move() {
      mtop = margin(elem) + options.digitHeight;
      if (mtop == options.digitHeight) {
        margin(elem, digits[elem]._digitInitial);
        if (elem > 0) moveStep(elem - 1)();
        else 
        {
          clearInterval(interval);
          for (var i=0; i < digits.length; i++) margin(i, 0);
          options.timerEnd();
          return;
        }
        if ((elem > 0) && (digits[elem].__condmax !== undefined) && 
            (digits[elem - 1]._digitInitial == margin(elem - 1)))
          margin(elem, -(digits[elem].__condmax * options.digitHeight * options.digitImages));
        return;
      }

      margin(elem, mtop);
      if (margin(elem) / options.digitHeight % options.digitImages != 0)
        setTimeout(_move, options.stepTime);

      if (mtop == 0) digits[elem].__ismax = true;
    }
  };

  $.extend(options, userOptions);
  this.css({height: options.digitHeight, overflow: 'hidden'});
  createDigits(this);
  interval = setInterval(moveStep(digits.length - 1), 1000);
};


/*************************
* Statussuche  *
* *************************/
$(document).ready(function() {
	$('.status_info').click(function() {
		var htmlStr = '<h3>Was ist die Statussuche?</h3><p>Suchen Sie nach Singles, die den gleichen Status in dem einen oder dem anderen Feld <br />angegeben haben. Bleibt der Eintrag auf "egal", wird das Feld in der Suche nicht berücksichtigt. <br />Die Eingaben in diesen Feldern ändern nicht Ihren eigenen Status.</p>';
		jQuery.facebox(htmlStr);
	});
});


/*********************
 * Kontaktformular *
* ****************** */
$(document).ready(function() {
		$("#Beschreibung").keyup(function()	{
			var box=$(this).val();
			var main = box.length *100;
			var value= (main / 145);
			var count= 145 - box.length;
	
			if(box.length <= 145)
			{
				$('#count').html(count);
			} else {
			alert(' Full ');
			}
			return false;
		});

});

function setSubject(index) {
	//alert('Hello: ' + index);
	var contactOption = '';
	
	$('.form_contact span').removeClass('add_txt disabled').addClass('add_txt enabled');
	
	switch (index) {
    case '1':
    	contactOption = '<option value="0">Bitte auswählen...</option>' + 
    			 '<option value="Fragen zur Bestellung">Fragen zur Bestellung</option>';
    	urlFunction = 'bestellung';
      break;
    case '2':
    	contactOption = '<option value="0">Bitte auswählen...</option>' + 
    			 '<option value="Widerruf einer Bestellung">Widerruf einer Bestellung</option>';
    	urlFunction = 'widerruf';
      break;  
    case '3': 
    	contactOption = '<option value="0">Bitte auswählen...</option>' +
    			 '<option value="1">Fehler Report</option>' +
				 '<option value="2">Sperrliste</option>';
    	urlFunction = 'funktionen';
      break;
    case '4': 
    	contactOption = '<option value="0">Bitte auswählen...</option>' +
    		'<option value="1">Daten(Anschrift, Zahlungsdaten etc.) ändern</option>' +
			'<option value="2">Weitere Vertragsfragen</option>' + 
			'<option value="3">Upgrade Ihres Dienstes</option>' + 
			'<option value="4">Reklamationen</option>' + 
			'<option value="5">Passwort vergessen / ändern</option>' + 
			'<option value="6">Profil löschen</option>';
    	urlFunction = 'vertrag';
    	break;
    case '5': 
    	contactOption = '<option value="0">Bitte auswählen...</option>' +
    		'<option value="1">Mahnungsnachfragen</option>' +
			'<option value="2">Allgemeine Rechnungsanfragen</option>' + 
			'<option value="3">Keine Rechnung erhalten</option>';
    	urlFunction = 'rechnung';
    	break;
    case '6': 
    	contactOption = '<option value="0">Bitte auswählen...</option>' +
    		'<option value="1">Meine Erfolgsstory</option>';
    	urlFunction = 'stories';
    	break;
    case '7': 
    	contactOption = '<option value="0">Bitte auswählen...</option>' +
    		'<option value="1">Anfrage</option>';
    	urlFunction = 'tipps';
    	break;
	default:
	    contactOption = '';
    	urlFunction = '';
		break;
	}
	
//	alert(option);
	
	// set 'contactForm' to ''
//	$("#contactForm").html = '';
	document.getElementById("contactForm").innerHTML = '';
	
	var newHTML = '<select class="settings_form_select enabled" id="subject" name="subject">' + contactOption + '</select>';
	$("#contactSubject").html(newHTML);
	
	
	
	// build form
	$('#contactSubject select').change(function() {
		//alert('change: ' + urlFunction);
		//alert('subject: ' + $("#subject").attr('value'));
			$.ajax({
				type: "POST",
				timeout: 700000,
				dataType: 'html',
				data: {subject:$("#subject").attr('value')},
				url: "/Hilfe/Kontaktform/" + urlFunction,
				success: function(result) {
					$('#contactForm').html(result);
//					alert('load was performed');
				},
				error: function(XMLHttpRequest, textStatus, errorThrown){
                    alert(XMLHttpRequest.readyState);
				}
			});
	});
}

function checkLength() {
	maxLength = 3000;
	length = $("#Beschreibung").val().length;
//	alert('length: ' + length);
	currentLength = maxLength - length;
	currentLength = this.addCommas(currentLength);
	var newHTML = '<label class="optional" for="wordlength">(max. 3.000 Zeichen, verbleiben ' + currentLength + ')</label>';
	$("#wordlength-label").html(newHTML);
	
}

function addCommas(nStr)
{
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + '.' + '$2');
  }
  return x1 + x2;
}

/*************************
*      FAQ               *
*************************/

$(document).ready(function() {
//	$('.singlesFAQ .frn_contentNavi ul li a').unbind('click');
//	$('.singlesFAQ .frn_contentNavi ul li ul li a').bind('click');
	
	/*$('.singlesFAQ .frn_contentNavi').children().children().children('a').click(function() {
		$('.singlesFAQ .frn_contentNavi li').removeClass('active');
		$(this).parent().addClass('active');
		return false;
	}); */
	
	function frnContentNavi() {
    actTimeout = window.setTimeout("",0);
    var contentNaviInit = function(obj) {
        initRootObj = obj ? obj : '.frn_contentNavi';
        $("a", initRootObj).click(function () {
            openToggler = $(this).hasClass('open');
            unfoldingObj = $(this).next('ul', initRootObj);// Element, das this folgt
            closeUnfoldingEven = (!openToggler ? ($('a, ul',$(this).parents('ul').eq(0)).removeClass('open')) : function() {return false});
            unfoldingObj.toggleClass('open').removeClass(openToggler ? 'active' : '').addClass(!openToggler ? 'active' : '').blur().parents('ul').eq(0).removeClass(!openToggler ? 'active' : '').addClass(openToggler ? 'active' : '');
            $(this).toggleClass('open');
            return ($(this).hasClass('go') ? true : false);
        });
        $("a.initialopen").removeClass('initialopen').addClass('open').next('ul').addClass('open active').parents('ul').addClass('open');
    }
    contentNaviInit();
    $(".frn_hilfe_produktauswahl").appendTo("body");
}
var frnContentNaviObj = new frnContentNavi();
// Content-Ausklapper
os = ".freelinks--frn_unfolding";
    $(os+"_toggler, "+os+"_toggler_map").live('click',function () {
 $($("[class*='frn_unfolding'][class!='freelinks--frn_unfolding_toggler'][class!='freelinks--frn_unfolding_toggler_map']")[$("."+$(this).attr('class')).index(this)]).toggle();
     });
});


/******************************
******* Cookie Plugin  ********
******************************/

/**
* jQuery Cookie plugin
*
* Copyright (c) 2010 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};

/******************************
* rechte Spalte Besucherliste *
******************************/
$('.user_box').ready(function() {
	$('#rVisits').click(function(){
		$.cookie('vistitorBox', '1', {path: '/' });
		$('#boxMyVisits').hide();
		$('#boxVisits').show();	
	});
	$('#rMyVisits').click(function(){		
		$.cookie('vistitorBox', '2', {path: '/' });
		$('#boxVisits').hide();
		$('#boxMyVisits').show();			
	});
});




/******************************
*** allgemeiner Ajax Aufruf ***
******************************/
/**
 * check if reqType is set
 * @param {Object} reqType
 * @return string
 */
function checkReqType(reqType){
    if (typeof(reqType) == 'undefined') {
        reqType = 'json';
    }

    return reqType;
}

/**
 * checks if param is set
 * otherwise retrun an empty string
 * @param {Object} reqParam
 */
function checkReqParam(reqParam){
    if (typeof(reqParam) == 'undefined') {
        reqParam = '';
    }

    return reqParam;
}

function HttpRequest(reqMethod, reqUrl, reqHandler, reqType, reqErrorHandler, reqEntity) {
	var type = checkReqType(reqType);
	var entity = checkReqParam(reqEntity);
	
	$.ajax({
		type: reqMethod,
		dataType: type,
		url: reqUrl,
		data: entity,
		success: function(data, textStatus, XMLHttpRequest){
			if (typeof(reqHandler) != 'undefined') {
				reqHandler(XMLHttpRequest.responseText, XMLHttpRequest, '');
			}
		}
	});

}


/******************************
** rechte Seite Online Tipps **
******************************/
function showOnlineTipp(data) {
data = $.parseJSON(data); 
	
		row='0';
		shtml = '';

			end = data.countProfiles-1;
			if (end > 4) {end = 4;}
			if (data.countProfiles > '0') {
				for (var i = 0; i <= end; i++){
					
					if (row == 0) {shtml += '<div class="user_img rowBack"> ';} else {shtml += '<div class="user_img"> ';}
					shtml += '<a title="'+data.profiles[i].nickname+', '+data.profiles[i].age+'" href="'+data.profiles[i].link+'" class="cockpit_useronline_profiles">';
					shtml += '<img width="80" height="80" alt="'+data.profiles[i].nickname+'" src="'+data.profiles[i].image+'">';
					if (data.profiles[i].isOnline == '1') {shtml += '<span class="status_1"></span>';}
                                        if (data.profiles[i].bDay == '1') {shtml += '<span class="bDay_1"></span>';}
					if (data.profiles[i].isNew == '1') {shtml += '<span class="new_1"></span>';}
					if (data.profiles[i].isKissed == true) {shtml += '<span class="kiss_pic_small"></span>';}
					shtml += '</a>';
					if (data.profiles[i].sex == '5')
						{
							shtml += '<div class="mHead">';
						} else {
							shtml += '<div class="fHead">';
						}
					shtml += '<a href="'+data.profiles[i].link+'" class="red">'+data.profiles[i].nickname+'</a></div>';
					shtml += '<div class="mBody">'+data.profiles[i].age+' Jahre<br />';
					shtml += data.profiles[i].city+'<br />';
					shtml += data.profiles[i].stateName+'<br />';
					shtml += '</div></div>';
		
					row ++;
					if (row == '2') { row = '0';}
				}
				shtml += '<div class="clear"></div>';
			} else {
				shtml = '<div style="padding-left:10px;">Bitte ändern Sie Ihre Sucheinstellungen.</div>';
			}
				shtml += '<div class="wrap_view_all">  <span class="clearfix">';
				if (data.countProfiles < '6'){
					shtml += '<a title="Alle ansehen" href="/'+data.link+'" class="view_all">Alle Online-Singles anzeigen';
				} else {
					shtml += '<a title="Weitere ansehen" href="/'+data.link+'" class="view_all">Weitere Online-Singles anzeigen';
				}
				shtml += '</a></span></div>';
			$('.wrap_online_user').html(shtml);
}

$(document).ready(function() {
	if ( $('div.onlineTipp').length > 0 ) {
		HttpRequest('POST', '/Ajax/Index/task/searchonline/', showOnlineTipp, 'json', '');
		
		$('.onlineTipp .closeEW').click( function() {
			$('.onlineTipp .editWindow').fadeOut('fast');
		});
		
		$('.onlineTipp .editBtn').click( function() {
			$('.onlineTipp .editWindow').fadeIn('fast');
		});
		
		$('.onlineTipp .saveEW').die().live('click', function() {
			$('.wrap_online_user').html('<div class="loading"></div>');
	
			var sex = $(".onlineTipp select[name='sex']").val();
			var agestart = $(".onlineTipp select[name='agestart']").val();
			var agestop = $(".onlineTipp select[name='agestop']").val();
			var zip = $(".onlineTipp input[name='zip']").val();
			var radius = $(".onlineTipp select[name='radius']").val();	
			
			var newURL = '/Ajax/Index/task/searchonline/filter/1/sex/'+sex+'/agestart/'+agestart+'/agestop/'+agestop+'/zip/'+zip+'/radius/'+radius;
			
			HttpRequest('POST', newURL, showOnlineTipp, 'json', '');	
			
			$('.onlineTipp .view_all').attr('href','/Suche/Gespeichertesuche/online/filter/1/sex/'+sex+'/agestart/'+agestart+'/agestop/'+agestop+'/zip/'+zip+'/radius/'+radius);
			
			$('.onlineTipp .editWindow').fadeOut('fast');
		});
	};		
});

/******************************
****** Reiter umschalten ******
******************************/
$(document).ready(function() {	
	$('.searchSelect ul li').live('click', function(){
		$(this).parent().children('li').removeClass('current');
		$(this).addClass('current');	
		$('.searchSelect ul li a').blur();
	});
});


/******************************
********** UI Dialog **********
******************************/
function dialogLoad(html, titel, width, addClass) {
	$("div[aria-labelledby='ui-dialog-title-dialogWrapper'], #dialogWrapper").remove();
	dialogHTML = '<div id="dialogWrapper">'+html+'</div>';

	$("#dialogBox").empty();
	$("#dialogBox").append(dialogHTML);
	$("#dialogWrapper" ).dialog({
		autoOpen: false,
	    modal: true,
	    resizable: false,
	    draggable: true,
		width: width,
		minHeight: 50,
		hide: 'fade',	
		dialogClass: addClass,
		title: titel		  
	});
	$("#dialogWrapper" ).dialog('open');
	
	$('.ui-widget-overlay').live('click',function(){	
//		dialogClose();
	});	
	
}


function dialogClose(){
	 $("#dialogWrapper" ).dialog('close');
};

$('.layerClose').die().live('click', function() {
	$("#dialogWrapper" ).dialog('close');       
})

/* bo Text in Dialog */
function showTextInDialog(showMessage, titel, width, addClass) {
	$("div[aria-labelledby='ui-dialog-title-dialogWrapper'], #dialogWrapper").remove();
	layerHTML = $('#'+showMessage+'').html(); 	
	dialogHTML = '<div id="dialogWrapper">'+layerHTML+'</div>';
	$("#dialogBox").empty();
	$("#dialogBox").append(dialogHTML);
	
	$('#dialogWrapper').dialog({
		autoOpen: false,
		modal: true,
		resizable: false,
		draggable: false,
		width: width,	
		minHeight: 50,
		hide: 'fade',
		dialogClass: addClass,
		title: titel		
    });
    
   $('#dialogWrapper').dialog('open'); 
   
	$('.ui-widget-overlay').live('click',function(){	
		dialogClose();
	});
	
}

var btnTarget;

/******************************
********** Stupseln ***********
******************************/
function stupselLayer(data){
	antwort = data.match(/Leider nicht möglich.+/);
	html  = '<div>'+data+'</div>';
//	html += '<div><div class="dialogCheck stup"><input type="checkbox" name="checkit" /> Diesen Hinweis nicht mehr anzeigen. </div>';
	html += '<div class="diaBtn">'
	html += '<a href="javascript:void(0);" class="sBtn bRight closeStubLayer" title="Absenden">';
	html += '<div class="leftBtn">';
	html += '<div class="rightBtn">';
	html += '<div class="centerBtn " style="font-weight:normal;">Schließen</div>';
	html += '</div>';
	html += '</div>';
	html += '</a>';
	html += '</div>';
//	html += '</div>';

	if (antwort == null) {
		layerInfo = 'Erfolgreich geküsst (virtueller Kuss)';
	} else {	
		layerInfo = 'Virtueller Kuss';
		data = 'noKiss';
	}	
	var ownProf = $('a#stupselLayer').attr('class');
	if ($('a#stupselLayer').attr('class') == 'own_profile') {
		layerInfo = 'Virtueller Kuss';
		data = 'noKiss';
	}
	
	dialogLoad(html, layerInfo)
	stupselNoLayer(data);
}

$("a#stupselLayer").live('click', function(){
	$(this).blur();
	HttpRequest('GET', '/Profil/stupseln/profile/'+$('#profile_id').val()+'/nickname/'+$('#profileName').val(), stupselLayer, 'text', '');	
});

function stupselNoLayer(data){
	$('.stupseln .activeBtn').fadeIn('slow').fadeOut(10000);
	//$('.stupseln .activeStupsel').fadeIn('slow').fadeOut(10000);
	if (data != 'noKiss') {
		valentinstags_kuss_aktion();
	}
}

$("a#stupselNoLayer").live('click', function(){
	$(this).blur();
	HttpRequest('GET', '/Profil/stupseln/profile/'+$('#profile_id').val()+'/nickname/'+$('#profileName').val(), stupselNoLayer, 'text', '');	
});

$('.closeStubLayer').live('click', function(){
	
//	if ($(this).parents().eq(1).children('.dialogCheck').children('input').is(":checked") == true) {	
//		HttpRequest('POST', '/Ajax/Index/task/layerstupseln/','' , '', '');
//		$('#stupselLayer').attr('id', 'stupselNoLayer')
//		stupUseLayer = 0;
//	}
	dialogClose();
})

function valentinstags_kuss_aktion() {
	var anzahl = $('.kiss_pic').attr('class');
	anzahl = anzahl.split(" ");
	anzahl = anzahl[0].substring(5);
	if (anzahl == 0) {
		$('.kiss_close').show();
		$('.kiss_pic').parents().eq(1).addClass('kiss_layer');
	}
	if (anzahl < 20) {
		anzahl++;
		$('.kiss_pic').attr('class','kiss_'+anzahl+' kiss_pic');		
	}
	var name = $('.kiss_layer').next().children().find('.tooltip_content_new').html();
	name = name.split(" ");	
	$('.kiss_layer').next().children().find('.tooltip_content_new').html(name[0]+' wurde '+anzahl+' Mal geküsst.');
	
	if( $('.kiss_pic').parent().attr('class') == 'cockpit_suggestions_profile_img' ) {
		switch (aktReit) {
		  case "tipp":
			dataTipp.profiles[elem].count_kisses = anzahl;
		    break;
		  case "top":
			  dataTop.profiles[elem].count_kisses = anzahl;
		    break;
		  case "bday":
			dataBday.profiles[elem].count_kisses = anzahl;
		    break;
		}	
	}
}



/******************************
******* zu Favouriten *********
******************************/
function favoritenLayer(data){
	html  = data;
	html += '<div><div class="dialogCheck fav"><input type="checkbox" name="checkit" /> <span>Diesen Hinweis nicht mehr anzeigen. </span></div>';
	html += '<div class="diaBtn">'
	html += '<a href="javascript:void(0);" class="sBtn bRight closeFavLayer" title="Absenden">';
	html += '<div class="leftBtn">';
	html += '<div class="rightBtn">';
	html += '<div class="centerBtn" style="font-weight:normal;">Schließen</div>';
	html += '</div>';
	html += '</div>';
	html += '</a>';
	html += '</div></div>';
	
	dialogLoad(html, 'Favorit hinzugefügt')
	activeNoBtn();
}

$("a#favoritenLayer").live('click', function(){	
	$(this).blur();
	btnTarget = $(this);	
	HttpRequest('GET', '/Profil/addtofavorites/profile/'+$('#profile_id').val(), favoritenLayer, 'text', '');	
	is_active_fav()
});


$("a#favoritenNoLayer").live('click', function(){
	$(this).blur();
	btnTarget = $(this);
	HttpRequest('GET', '/Profil/addtofavorites/profile/'+$('#profile_id').val(), activeNoBtn, 'text', '');	
	is_active_fav()
});

$('.closeFavLayer').live('click', function(){
	if ($(this).parents().eq(1).children('.dialogCheck').children('input').is(":checked") == true) {	
		HttpRequest('POST', '/Ajax/Index/task/layerfavorites/','' , '', '');
		favUseLayer = 0;
	}
	dialogClose();
})

function is_active_fav() {
	if (typeof aktReit != "undefined") { 
		if (aktReit == 'tipp'){
			dataTipp.profiles[elem].is_favorite = true;	
		}
		else if (aktReit == 'top'){
			dataTop.profiles[elem].is_favorite = true;	
		}
		else if (aktReit == 'bday'){
			dataBday.profiles[elem].is_favorite = true;	
		}		
	}
}


/******************************
******* User blocken **********
* bis jetzt nur für fremdprofil - stupselliste und nachrichtenfeld anpassen *
******************************/
function blockenLayer(data){
	html  = data;
	html += '<div><div class="dialogCheck block"><input type="checkbox" name="checkit" /> <span>Diesen Hinweis nicht mehr anzeigen. </span></div>';
	html += '<div class="diaBtn">'
	html += '<a href="javascript:void(0);" class="sBtn bRight closeBlockLayer" title="Absenden">';
	html += '<div class="leftBtn">';
	html += '<div class="rightBtn">';
	html += '<div class="centerBtn" style="font-weight:normal;">Schließen</div>';
	html += '</div>';
	html += '</div>';
	html += '</a>';
	html += '</div></div>';
	
	dialogLoad(html, 'Erfolgreich geblockt')
	activeNoBtn();
}

function favTimerClose() {
	if ($('.dialogCheck.fav input').is(":checked") == false) {	
		dialogClose();
	}
}

$("a#blockLayer").live('click', function(){
	$(this).blur();	
	btnTarget = $(this);
	HttpRequest('GET', '/Profil/blocken/profile/'+$('#profile_id').val()+'/nickname/'+$('#profileName').val(), blockenLayer, 'text', '');		
});

function activeNoBtn () {
	$(btnTarget).removeAttr('id');
	$(btnTarget).css('cursor', 'default');
	$(btnTarget).parent().addClass('is_on');
	$(btnTarget).parent().children('.activeBtn').show();	
}

$("a#blockNoLayer").live('click', function(){
	$(this).blur();
	btnTarget = $(this);
	HttpRequest('GET', '/Profil/blocken/profile/'+$('#profile_id').val()+'/nickname/'+$('#profileName').val(), activeNoBtn, 'text', '');	
});

$('.closeBlockLayer').live('click', function(){
	if ($(this).parents().eq(1).children('.dialogCheck').children('input').is(":checked") == true) {	
		HttpRequest('POST', '/Ajax/Index/task/layerblock/','' , '', '');
	}	
	dialogClose();
})

/******************************
******** zu Kontakten *********
******************************/

function kontaktLayer(data){
	html  = data;
	html += '<div><div class="dialogCheck kont"><input type="checkbox" name="checkit" /> <span>Diesen Hinweis nicht mehr anzeigen. </span></div>';
	html += '<div class="diaBtn">'
	html += '<a href="javascript:void(0);" class="sBtn bRight closeKontLayer" title="Absenden">';
	html += '<div class="leftBtn">';
	html += '<div class="rightBtn">';
	html += '<div class="centerBtn" style="font-weight:normal;">Schließen</div>';
	html += '</div>';
	html += '</div>';
	html += '</a>';
	html += '</div></div>';
	
	dialogLoad(html, 'Kontaktanfrage versendet')
	activeNoBtn();
}

$("a#kontaktLayer").live('click', function(){
	$(this).blur();
	HttpRequest('POST', '/Profil/addtocontacts', kontaktLayer, 'text', '', {description:"Hi, ich würde Dich gern zu meinen Kontakten hinzufügen.", profile:$('#profile_id').val()});
	btnTarget = $(this);	
	is_active_kont();
});


$("a#kontaktNoLayer").live('click', function(){
	$(this).blur();
	btnTarget = $(this);
	HttpRequest('POST', '/Profil/addtocontacts', activeNoBtn, 'text', '', {description:"Hi, ich würde Dich gern zu meinen Kontakten hinzufügen.", profile:$('#profile_id').val()});
	is_active_kont();
});

$('.closeKontLayer').live('click', function(){
	if ($(this).parents().eq(1).children('.dialogCheck').children('input').is(":checked") == true) {	
		HttpRequest('POST', '/Ajax/Index/task/layercontact/','' , '', '');
		kontUseLayer = 0;
	}
	dialogClose();
})

function is_active_kont() {
	if (typeof aktReit != "undefined") { 
		if (aktReit == 'tipp'){
			dataTipp.profiles[elem].is_contact = true;	
		}
		else if (aktReit == 'top'){
			dataTop.profiles[elem].is_contact = true;	
		}
		else if (aktReit == 'bday'){
			dataBday.profiles[elem].is_contact = true;	
		}		
	}
}

/******************************
********* PLZ testen **********
******************************/
$(document).ready(function() {
	
	
	$('.search_form_txt.zip').keyup(function() {
	
		aktWert = $(this).val();
			
	    arg=[]
	    function mergeStr(Str){
	    	first = Str.substr(0,1);
	    	last = Str.substr((Str.length)-1,1);	    	
	    	if (first == ' ') { Str = Str.substr(1,(Str.length)); }
	    	if (last == ' ') { Str = Str.substr(0,(Str.length)-1); }
	    	aktWert = Str;
	    }
	    mergeStr(aktWert)		
		testWert = aktWert.match(/^\+?[0-9]*\.?[0-9]+$/);
	    if ((aktWert == '') || (aktWert == ' ') || (aktWert == '  ') || (aktWert == '   ')) {testWert = 1;}
		if ((testWert == null) || (aktWert == '00000') ) {
			$(this).parents().eq(1).children('.zipError').html('<strong>Ihre PLZ ist ungültig</strong>');
			$(this).parents().eq(2).find('.sBtn').css('cursor','default');
			$(this).parents().eq(2).find('.sBtn').addClass('inactive');
			$(this).parents().eq(2).find('.sBtn').removeClass('saveEW');
			$(this).css({'background-color' : '#CF1B48', 'color' : 'white'});			
		} else {
			$(this).parents().eq(1).children('.zipError').html('');
			$(this).parents().eq(2).find('.sBtn').addClass('saveEW');
			$(this).parents().eq(2).find('.sBtn').removeClass('inactive');
			$(this).parents().eq(2).find('.sBtn').css('cursor','pointer');	
			$(this).css({'background-color' : 'white', 'color' : '#333333'});		
		}
	});
	
	$('.sBtn.inactive').live('click',function(){
		return false;
	})
	

});

/*************************
**** Magazin Artikel  ****
*************************/
//pici = 1;
function initArtPicBackNext(){
	$('#frnArtPic').mouseover(function(){
	  if(pici != 0)$('#frnArtPicBack').removeClass('inactive');
	  $('#frnArtPicNext').removeClass('inactive');
	}).mouseout(function(){
	  $(this).bind('mouseleave',function(){
	    $('#frnArtPicBack').addClass('inactive');
	    $('#frnArtPicNext').addClass('inactive');
	  })
	}).click(function(){
	  if(pici == 1)$('#frnArtPicBack').removeClass('inactive');
	  if(klickzahl_soll != -1 && klickzahl == klickzahl_soll)picShow = function() {};
	})
}
	


function initSocialMedia() {}
function frnArtIconHover() {}
jQuery.fn.frnArtIconHover = function() {}
function frnmenu_open() {}
function frnmenu_timer() {}
function frnmenu_close() {}
function count_app() {}

$(document).ready(function(){
	$('#frnArtPicImgLink').click(function(){
		  if(pici < piciMax){
			    pici = pici+1;
			  }else{
			    pici = 0;  
			  }
			  klickzahl++;
			  picShow();		
		return false;
		
	});
})

/*************************
******* Shopseiten  ******
*************************/
function checkPrice(event) {
	$('.boxSmall, .boxBig').attr('id','');
	$(event).parent().attr('id','aktiv');
	price = $(event).val();
	$('#form1 input[name$="attributes[membership_length]"]').val(price);
}

function checkPayment(event) {
	payment = $(event).val();
	$('#form1 input[name$="attributes[paytype]"]').val(payment);
	$('.payFormBtn').attr('rel','1')
}
function checkGift(event) {
	$('.payFormBtn').attr('rel','2')
}
function sendOrder(event) {
	form = $(event).attr('rel');
	if (form == 1)
	{
		$('#form1').submit();
	} else {
		$('#form2').submit();
	}
}

/********************************/
/******* Kopf umschalten ********/
/********************************/
$(document).ready(function() {
	$('.back_black').live('click',function() {
		$('#nav').attr('class', 'header1');
		$.get('/index/setheadercookie/header/1'); 
		$('#nav').css('color', 'white'); 
		$('#nav a.red').css('color', 'white');
	})
	$('.back_white').live('click',function() {
		$('#nav').attr('class', 'header0');
		$.get('/index/setheadercookie/header/0'); 
		$('#nav').css('color', 'black'); 
		$('#nav a.red').css('color', '#CF1B48');
	})	
})

/********************************/
/***** Valentinstagsaktion ******/
/********************************/
$(document).ready(function() {
	$('.kiss_close').live('click', function() {
		$(this).hide();
		$('.kiss_pic').hide();
	})
	
	$("body").live("mouseover",function(){
		$('.main_box_v3_imgbox .kiss_layer').tooltip({
			position: 'top right',
			offset: [-202,-62]
		});
	});	
	
	$("body").live("mouseover",function(){
		$('.cockpit_wrap_suggestions .kiss_layer').tooltip({
			position: 'top right',
			offset: [-162,-46]
		});
	});	
	
	$("a[rel='link_zurueckkuessen']").click(function(){
		var username = $(this).parents().find('.mail_box').children().find('.red').attr('title');
		$(this).blur();
		var target = $(this).next('div').find('.tooltip_content_new');
	    $.ajax({
		      type: "POST",
		      timeout: 7000,
		      data: {guestprofile:$('#guest_profile_id').val()},
		      url: "/MeineKontakte/Stupselliste/zurueckstupseln",
		      success: function(result) {
		        var retStatus;
		        if (result)
		        	if (result == '"kiss"')
		        	{
		        		retStatus = 'Erfolgreich zurückgeküsst!';
		        	} else {
		        		retStatus = 'Leider nicht möglich. Sie können '+username+' nur einmal küssen.';
		        	}
		        else
		        	retStatus = 'Fehler! Bitte versuchen Sie es später noch einmal.';

		        $(target).html(retStatus);
		      }
		 })		
	});	
	
})
