function strrPos (haystack, needle, offset) {
    // Finds position of last occurrence of a string within another string
    // *     example 1: strrpos('Kevin van Zonneveld', 'e');
    // *     returns 1: 16
    // *     example 2: strrpos('somepage.com', '.', false);
    // *     returns 2: 8
    // *     example 3: strrpos('baa', 'a', 3);
    // *     returns 3: false
    // *     example 4: strrpos('baa', 'a', 2);
    // *     returns 4: 2
    var i = -1;
    if (offset) {
        i = (haystack+'').slice(offset).lastIndexOf(needle); // strrpos' offset indicates starting point of range till end,
        // while lastIndexOf's optional 2nd argument indicates ending point of range from the beginning
        if (i !== -1) {
            i += offset;
        }
    }
    else {
        i = (haystack+'').lastIndexOf(needle);
    }
    return i >= 0 ? i : false;
}

/* ------##### CUT LONG TITLE-STRINGS #####----- */
function cutStr(string, pos) {
    var text;
	if (pos < string.length) {
        text = string.substr(0, pos);
        strrpos = strrPos(text,' ');
        if(strrpos !== false){
            text = text.substr(0, strrpos);
        }
        string = text + '...';
    }

    return string;
}
/* ------##### DEFAULT TYPO3 JS #####----- */

var browserName=navigator.appName;var browserVer=parseInt(navigator.appVersion);var version="";var msie4=(browserName=="Microsoft Internet Explorer"&&browserVer>=4);if((browserName=="Netscape"&&browserVer>=3)||msie4||browserName=="Konqueror"||browserName=="Opera"){version="n3";}else{version="n2";}
function blurLink(theObject){if(msie4){theObject.blur();}}
function decryptCharcode(n,start,end,offset){n=n+offset;if(offset>0&&n>end){n=start+(n-end-1);}else if(offset<0&&n<start){n=end-(start-n-1);}
return String.fromCharCode(n);}
function decryptString(enc,offset){var dec="";var len=enc.length;for(var i=0;i<len;i++){var n=enc.charCodeAt(i);if(n>=0x2B&&n<=0x3A){dec+=decryptCharcode(n,0x2B,0x3A,offset);}else if(n>=0x40&&n<=0x5A){dec+=decryptCharcode(n,0x40,0x5A,offset);}else if(n>=0x61&&n<=0x7A){dec+=decryptCharcode(n,0x61,0x7A,offset);}else{dec+=enc.charAt(i);}}
return dec;}
function linkTo_UnCryptMailto(s){location.href=decryptString(s,-1);}

/* ------##### TELL A FRIEND #####----- */

function newFreeCap(id, noImageMessage) {
	if (document.getElementById) {
			// extract image name from image source (i.e. cut off ?randomness)
		var theImage = document.getElementById("tx_srfreecap_pi2_captcha_image_"+id);
		var parts = theImage.src.split("&");
			// add ?(random) to prevent browser/isp caching
			// parts[0] should be base url up to eID parameter
			// parts[1] should be id=page_id
			// parts[2] should be L=sys_language_uid
		var LParameterInUse = (typeof(parts[2]) != "undefined") && (parts[2].indexOf("L=") != -1);
		theImage.src = parts[0] + "&" + parts[1] + (LParameterInUse ? "&" + parts[2] : "") + "&set=" + Math.round(Math.random()*100000);
	} else {
		alert(noImageMessage ? noImageMessage : "Sorry, we cannot autoreload a new image. Submit the form and a new image will be loaded.");
	}
}
$.fn.getData = function(eid,action,selector,checkedCounter){
	var portalID = $('input[disabled]').val();
	var pageID   = $('#page_id').text();
	if(pageID.length>0){
		if(action == "getAllowedPortals"){
			var selectedCat = $(selector).val();
			var params = {eID:eid,action:action,catID:selectedCat,pageID:pageID,portalID:portalID};
		}else{
			if(action == "getPriceInfo"){
				var selectedCat = $('.tx-exinitjobexchange-pi1-category').val();
				/*if(($('#adPrice').length > 0 || $('#rabattSteps').length > 0) && selectedCat!=53){
					var response = Object();
					response['rabatt_steps'] = $('#rabattSteps').text().split(",");
					response['adPrice'] = $('#adPrice').text();
					$(document).setPrice(selector,response);
					return false;
				}else{*/
					var params = {eID:eid,action:action,catID:selectedCat,pageID:pageID,portalID:portalID};
				//}
			}
		}
		//Ajaxabfrage stellen
		var req = $.ajax({
			url: "index.php",		// Achtung mit RealURL!
			cache: true,
			type: "GET",			// Daten per GET verschicken
			data: params,
			dataType: "json",		// das gibts zurück
			// Es hat funktioniert?
			success: function(response) {
				if(action == "getAllowedPortals"){
					$(document).showAllowedPortals(response);
				}else{
					if(action == "getPriceInfo"){
						if(response['adPrice'] && response['rabatt_steps'] && selector){
							$(document).setPrice(selector,response);
						}
					}
				}
			},
			// Schade, es war ein Fehler
			error: function(error) {
				alert("Sorry, hat nicht funktioniert");
			}
		});
		//console.log(res.responseText);
		return req;
	}
};
$.fn.showAllowedPortals = function(response){
	$('.tx-exinitjobexchange-pi1-positionen').hide();
	var allowedPortals 	= response['allowedPortals'];

	for(i=0;i<allowedPortals.length;i++){
		$('#tx_exinitjobexchange_pi1_positionen__'+allowedPortals[i]+'_').parent().show();
		$('#tx_exinitjobexchange_pi1_positionen__'+allowedPortals[i]+'_').show();
	}
	var portalRow = $('.tx-exinitjobexchange-pi1-positionen').parents("tr");
	if(i==1){
		//$('.tx-exinitjobexchange-pi1-positionen').parents("tr").find(".title").text('Folgendes Portal wird gebucht');
		portalRow.find(".title").text('Folgendes Portal wird gebucht');
	}else if(i>1){
		portalRow.find(".title").text('Wählen Sie die gewünschten Portale');
	}
	$('.tx-exinitjobexchange-pi1-positionen:input').each(function(i){
		if(this.style.display == "none"){
			$(this).attr('checked', false);
		}
	});
	// Home-Portal has to be displayed
	var portalID = $('input[disabled]').val();
	$('input[disabled]').attr('checked', true);
	$('#tx_exinitjobexchange_pi1_positionen__'+portalID+'_').parent().show();
	$('#tx_exinitjobexchange_pi1_positionen__'+portalID+'_').show();
};
$.fn.setPrice = function(selector,response){
	var selPos 		= selector.position();
	var selWidth 	= selector.width();
	var adPrice		= response['adPrice'];
	var rabattSteps = response['rabatt_steps'];
	var checkedPortals = $("input.tx-exinitjobexchange-pi1-positionen:checked").length;
	var rabatt		= rabattSteps[checkedPortals - 1];
	var price		= checkedPortals *  adPrice * (1 - rabatt/100 );
	var price	    = Math.floor(price);
	var save		= checkedPortals *  adPrice - price;

	if($('#price_preview').length > 0){
		$('#price_preview').remove();
	}
	if($('#rabatt_info').length > 0){
		$('#rabatt_info').remove();
	}
	var price_preview 	= "Preisvorschau";
	var price_hint	  	= "(nur Online-Anzeige)";
	var rabatt_text_1   = "Sie sparen ";
	var rabatt_text_2   = "im Vergleich zur Einzelbuchung!";
	selector.find("td:last").append('<div id="price_preview" >'+price_preview+'<br /><span style="font-weight:normal;">'+price_hint+'</span><p id="price">'+price+'&euro;</p><p id="adPrice" style="display:none;">'+ adPrice +'</p><p id="rabattSteps" style="display:none;">'+rabattSteps+'</p></div><div id="rabatt_info" style="font-style:italic; clear:both; font-size: 11px">'+ rabatt_text_1 + save +' &euro; '+rabatt_text_2 +'</div>')

};
/* ------##### INLINE VALIDATION #####----- */
$.fn.inlineValid = function(selector){
	var errorClass = '.'+ selector.substr(25)+'_formError';
	$(errorClass).remove();
	// Inline Validation VAT Number
	console.log(selector,'selector');
	if(selector.substr(25)=='vat_number'){
		var vat_number, ccode, number;
		var errorNoVat 				= "Sie haben keine USt-IdNr eingegeben, obwohl Sie \"Ja\" ausgewählt haben! ";
		var errorVatStructurInvalid = "Der Aufbau der USt-IdNr ist ungültig! <br /> Die eingegebene USt-IdNr wird daher nicht gespeichert!";
		var errorVatInvalid 		= "Ihre USt-IdNr ist ungültig! <br /> Die eingegebene USt-IdNr wird daher nicht gespeichert.";
		vat_number = $.trim($(selector).val());
		checked_vat_number = checkVATNumber(vat_number);
		if(checked_vat_number != '' && checked_vat_number){
			$(selector).val(checked_vat_number);
			ccode = checked_vat_number.substr(0,2);
			number = checked_vat_number.substr(2);
			//console.log(ccode + number);
			$.getJSON('http://isvat.appspot.com/'+ccode+'/'+number+'/?callback=?', function(data){
				//console.log(data);
				if(data == true){
					$(selector).parent().find('.formError').remove();
					$(errorClass).remove();
					if($('.tx-srfeuserregister-pi1-vat_valid_token').length>0){
						$('.tx-srfeuserregister-pi1-vat_valid_token').attr('value','valid');
					}else{
						$('.reg_table').after('<input class="tx-srfeuserregister-pi1-vat_valid_token" type="hidden" value="valid" name="tx_srfeuserregister_pi1[vat_valid]">');
					}
				}else if(data == false){
					$(document).placeErrorHint(selector,errorVatInvalid);
					if($('.tx-srfeuserregister-pi1-vat_valid_token').length>0){
						$('.tx-srfeuserregister-pi1-vat_valid_token').attr('value','invalid');
					}else{
						$('.reg_table').after('<input class="tx-srfeuserregister-pi1-vat_valid_token" type="hidden" value="invalid" name="tx_srfeuserregister_pi1[vat_valid]">');
					}
				}
			});
		}else{
			if(vat_number == ''){
				$(document).placeErrorHint(selector,errorNoVat);
				if($('.tx-srfeuserregister-pi1-vat_valid_token').length>0){
					$('.tx-srfeuserregister-pi1-vat_valid_token').attr('value','no_vat');
				}else{
					$('.reg_table').after('<input class="tx-srfeuserregister-pi1-vat_valid_token" type="hidden" value="no_vat" name="tx_srfeuserregister_pi1[vat_valid]">');
				}
			}else{
				$(document).placeErrorHint(selector,errorVatStructurInvalid);
				if($('.tx-srfeuserregister-pi1-vat_valid_token').length>0){
					$('.tx-srfeuserregister-pi1-vat_valid_token').attr('value','invalid');
				}else{
					$('.reg_table').after('<input class="tx-srfeuserregister-pi1-vat_valid_token" type="hidden" value="invalid" name="tx_srfeuserregister_pi1[vat_valid]">');
				}
			}

		}
	}
};
/* ------##### PLACE ERROR-TOOLTIP #####----- */
$.fn.placeErrorHint = function(selector,errorText){
	var sel = $(selector);
	var selpos = sel.position();
	var selwidth = sel.width();
	var errorclass = selector.substr(25)+'_formError';
	if(sel.parent().find('.formError').length){
		sel.parent().find('.formError').addClass(errorclass);
	}else{
		sel.before('<div class="formError '+errorclass+'"><div class="formErrorContent">'+errorText+'</div></div>');
	}
	$('.formError').click(function(){
		$(this).hide();
		if($(this).parent().find('input').length){
			$(this).parent().find('input').focus();
		}else if($(this).parent().find('textarea').length){
			$(this).parent().find('textarea').focus();
		}
	});
	var errorwidth = $('.'+errorclass).width();
	var xerror	= selpos.left + selwidth - errorwidth + 30;
	var errorheight = $('.'+errorclass).height();
	var yerror = selpos.top - errorheight + 3;
	$('.'+errorclass).css({'margin-top':'0px','opacity':'0.87','top':yerror,'left':xerror});
	$('.'+errorclass).append('<div class="formErrorArrow"></div>');
	var x=10;
	while (x >=1) {
		$('.'+errorclass).find('.formErrorArrow').append('<div class="line'+x+'"><!-- --></div>');
		x--;
	}
};


/* ------##### FAQ #####----- */
$('.box-faq').hide();

/* ------##### EXTENSIONS / FUNCTIONS #####----- */

$.extend({
	decodeString: function(psEncodeString){
	  return unescape(psEncodeString);
	}
});
/*
$.fn.fadeToggle = function(speed, easing, callback) {
	return this.animate({opacity: 'toggle'}, speed, easing, callback);
};*/

/* ------##### AFTER DOM LOADING #####----- */
var asInitVals = new Array();

$(document).ready(function(){
	//Show portal_free_hint
	var portalname = $('head').find('base').attr('href');
	$("input.tx-exinitjobexchange-pi1-positionen").parents("tr").hover(
		    function(){
		    	      if(portalname == 'http://www.stellenwerk-hamburg.de/'){
		    		var portal_hint_text = "Das Stellenwerk PLUS! Mehr buchen. Weniger bezahlen.<br /> Mit einem Klick Stellenwerk Lübeck dazu buchen und sparen.<br /> Beachten Sie bitte die Preisvorschau.";
		    	}else if(portalname == 'http://www.stellenwerk-luebeck.de/'){
		    		var portal_hint_text = "Das Stellenwerk PLUS! Mehr buchen. Weniger bezahlen.<br />Mit einem Klick Stellenwerk Hamburg dazu buchen und sparen.<br /> Beachten Sie bitte die Preisvorschau.";
		    	}else if(portalname == 'http://www.stellenwerk-darmstadt.de/'){
		    		var portal_hint_text = "Das stellenwerkPLUS! <br /> Ab Juni 2011 nicht mehr kostenlos, aber weiterhin kostengünstig! <br /> Die Nachbarportale Mainz und Koblenz-Landau einfach dazu buchen. <br /> Mehr Reichweite, weniger Kosten. Beachten Sie bitte die Preisvorschau.";
		    	}else if(portalname == 'http://www.stellenwerk-dortmund.de/'){
		    		var portal_hint_text = "Das stellenwerkPLUS!<br />Ab Juni 2011 nicht mehr kostenlos, aber weiterhin kostengünstig!<br />Die Nachbarportale Düsseldorf und Köln einfach dazu buchen.<br />Mehr Reichweite, weniger Kosten. Beachten Sie bitte die Preisvorschau.";
		    	}else if(portalname == 'http://www.stellenwerk-duesseldorf.de/'){
		    		var portal_hint_text = "Das stellenwerkPLUS!<br />Ab Juni 2011 nicht mehr kostenlos, aber weiterhin kostengünstig!<br />Die Nachbarportale Dortmund und Köln einfach dazu buchen.<br />Mehr Reichweite, weniger Kosten. Beachten Sie bitte die Preisvorschau.";
		    	}else if(portalname == 'http://www.stellenwerk-koeln.de/'){
		    		var portal_hint_text = "Das stellenwerkPLUS!<br />Ab Juni 2011 nicht mehr kostenlos, aber weiterhin kostengünstig!<br />Die Nachbarportale Düsseldorf und Dortmund einfach dazu buchen.<br />Mehr Reichweite, weniger Kosten. Beachten Sie bitte die Preisvorschau.";
		    	}else if(portalname == 'http://www.stellenwerk-mainz.de/'){
		    		var portal_hint_text = "Das stellenwerkPLUS!<br />Ab Juni 2011 nicht mehr kostenlos, aber weiterhin kostengünstig!<br />Die Nachbarportale Darmstadt und Koblenz-Landau einfach dazu buchen.<br />Mehr Reichweite, weniger Kosten. Beachten Sie bitte die Preisvorschau.";
		    	}else if(portalname == 'http://www.stellenwerk-koblenz-landau.de/'){
		    		var portal_hint_text = "Das stellenwerkPLUS!<br />Ab Juni 2011 nicht mehr kostenlos, aber weiterhin kostengünstig!<br />Die Nachbarportale Darmstadt und Mainz einfach dazu buchen.<br />Mehr Reichweite, weniger Kosten. Beachten Sie bitte die Preisvorschau.";
		    	}

		    	$('#portal_hint td div').html(portal_hint_text);
		    	$('#portal_hint').fadeIn('slow');
		},
		    function(){
		        $('#portal_hint').fadeOut('fast');

	});
	/* ##### Check which Checkboxes are checked ##### */
	var selector = $("input.tx-exinitjobexchange-pi1-positionen").parents("tr");
	$(document).getData('getData','getPriceInfo',selector);
	$("input.tx-exinitjobexchange-pi1-positionen").click(function(){
		selector = $(this).parents("tr");
		$(document).getData('getData','getPriceInfo',selector);
	});
	/* ----- ##### set PORTALs for selected CATEGORIES ##### ----- */
	var catSelector = $('.tx-exinitjobexchange-pi1-category');
	if(catSelector.length > 0){
		$(document).getData('getData','getAllowedPortals',catSelector);
		$(catSelector).change(function (){
			$(document).getData('getData','getAllowedPortals',this);
			setTimeout(function(){
				selector = $("input.tx-exinitjobexchange-pi1-positionen").parents("tr");
				$(document).getData('getData','getPriceInfo',selector);
			},500);
		});
	}
	//}
	if($('.left .title').length>0){
		var string = $('.left .title').text();
		var croppedString = cutStr(string,80);
		$('.left .title').text(croppedString);
	}
	/* ##### REMOVE INFOTEXT in PREVIEW ##### */
	if($("h2:contains('Vorschau')").length > 0){
  		$("h1:contains('Anzeige schalten')").parent().parent().children('p').hide();
	}


	/* ##### SET REG ERROR Tooltips ##### */
	$('.tx-srfeuserregister-pi1-error').hide().addClass('formError').removeClass('tx-srfeuserregister-pi1-error').show();
	/* ##### REG ERROR ServerErrorText into Tooltips ##### */
	$('.formError').each(function(index){
		var ServerErrorText = $(this).text();
		$(this).text('');
		$(this).append('<div class="formErrorContent">'+ServerErrorText+'</div>');

		var formElemId 		= $(this).parent().children("input:last").attr('id');
		var nextText = $(this).next('.formError').text();
		if(nextText){
			$(this).find('.formErrorContent').text(ServerErrorText);
			$(this).find('.formErrorContent').append('<br /> '+ nextText);
			$(this).next('.formError').remove();
		}
		var errorText = $(this).find('.formErrorContent').text();
		if(formElemId){
			var selector = '#'+formElemId;
			$(document).placeErrorHint(selector,errorText);
		}else{
			var formElemId 		= $(this).parent().children("textarea").attr('id');
			if(formElemId){
				var selector = '#'+formElemId;
				$(document).placeErrorHint(selector,errorText);
			}
		}
	});
	/* ##### VAT Radio Button Events ##### */
	if($('#tx-srfeuserregister-pi1-vat_number').val()){
		$('#vat_number_yes').attr('checked', true);
	}else{
		$('#vat_number_no').attr('checked', true);
		$('#tx-srfeuserregister-pi1-vat_number').hide();
	}
	$('#vat_number_yes').click(function(){
		$('#tx-srfeuserregister-pi1-vat_number').css({'backgroundColor':''});
		$('#tx-srfeuserregister-pi1-vat_number').show();
		if($('.tx-srfeuserregister-pi1-vat_valid_token').length>0){
			$('.tx-srfeuserregister-pi1-vat_valid_token').remove();
		}
		$('#tx-srfeuserregister-pi1-vat_number').focus();
	});
	$('#vat_number_no').click(function(){
		$('#tx-srfeuserregister-pi1-vat_number').val('').hide();
		$('.vat_number_formError').next('.formError').remove();
		$('.vat_number_formError').remove();
		if($('.tx-srfeuserregister-pi1-vat_valid_token').length>0){
			$('.tx-srfeuserregister-pi1-vat_valid_token').attr('value','no_vat');
		}
	});
	/* ##### REG FORM SUBMIT ##### */
	$('#tx-srfeuserregister-pi1-fe_users_form').submit(function() {
		if($('#vat_number_yes').is(':checked')) {
			$(document).inlineValid('#tx-srfeuserregister-pi1-vat_number');
			if ($("input[name='tx_srfeuserregister_pi1[vat_valid]']").val() == "valid") {
				return true;
			}else {
				var invalid_vat_number = $("input[name='FE[fe_users][vat_number]']").val();
				//$("input[name='FE[fe_users][vat_number]']").attr('value',invalid_vat_number + ' NICHT VALIDE. BITTE PRUEFEN!');

				if($('#tx-srfeuserregister-pi1-vat_number').val()){
					if($('#tx-srfeuserregister-pi1-vat_number').val()== ''){
						$('.tx-srfeuserregister-pi1-vat_valid_token').attr('value','no_vat');
					}else{
						$('.tx-srfeuserregister-pi1-vat_valid_token').attr('value','invalid');
					}
				}

				return true; /* neu wieder entfernen*/
			}
		}else{
			if($('#tx-srfeuserregister-pi1-vat_number').length>0){
				$('.vat_number_formError').remove();
				if($('.tx-srfeuserregister-pi1-vat_valid_token').length>0){
					$('.tx-srfeuserregister-pi1-vat_valid_token').attr('value','no_vat');
				}else{
					$('.reg_table').after('<input class="tx-srfeuserregister-pi1-vat_valid_token" type="hidden" value="no_vat" name="tx_srfeuserregister_pi1[vat_valid]">');
				}
				return true;
			}else{
				//XXX
				var validatethis = "<?php echo $_POST['tx_srfeuserregister_pi1']['vat_valid']; ?>";
				console.log(validatethis,'validatethis');
				if(validatethis=='invalid'){
					$('.reg_table').after('<input class="tx-srfeuserregister-pi1-vat_valid_token" type="hidden" value="invalid" name="tx_srfeuserregister_pi1[vat_valid]">');
				}
			}
		}
	});
	/* ##### INLINE VALID VAT ##### */
	if($('#tx-srfeuserregister-pi1-vat_number').length > 0){
		$('#tx-srfeuserregister-pi1-vat_number').focusout(function() {
			setTimeout(function(){
				if($('#vat_number_yes').is(':checked')) {
					$(document).inlineValid('#tx-srfeuserregister-pi1-vat_number');
				}
			},500);
		});
	}


	/* ##### FIRMENNAMEN Validierung ##### */
	var pressed = 0;
	$('#tx-srfeuserregister-pi1-company').keydown(function() {
		var infoText = "Geben Sie bitte den ganzen Praxisnamen ein: <br /> z.B. Praxis Dr. Klaus Mustermann";
		pressed= pressed + 1;
		if(pressed >= 5){
			eingabe = $('#tx-srfeuserregister-pi1-company').val();
			if(eingabe.match(/Praxi/) && !$('.company_formError').length){
				$(document).placeErrorHint('#tx-srfeuserregister-pi1-company',infoText);
			}else if($('#tx-srfeuserregister-pi1-company').val()==''){
				$('.company_formError').fadeOut().remove();
				pressed=1;
			}else if(!eingabe.match(/Praxi/) && $('.company_formError').length>0){
				$('.company_formError').fadeOut().remove();
			}
		}
	});
	/* ##### INLINE VALID COMPANY ##### */
	if($('#tx-srfeuserregister-pi1-company').length > 0){
		$('#tx-srfeuserregister-pi1-company').focusout(function() {
			var infoText = "Geben Sie bitte den ganzen Praxisnamen ein: <br /> z.B. Praxis Dr. Klaus Mustermann";
			eingabe = $('#tx-srfeuserregister-pi1-company').val();
			if(eingabe.match(/Praxis$/) && !$('.company_formError').length){
				$(document).placeErrorHint('#tx-srfeuserregister-pi1-company',infoText);
			}else if(eingabe.match(/Praxis$/) && $('.company_formError').length){
				$('.company_formError').show();
			}else if(eingabe.match(/Praxis\s\w+/) && $('.company_formError').length){
				$('.company_formError').hide();
			}
		});
	}

	/* ------##### HIDE List-HEADLINE in Detail View #####----- */
	/* ------##### CROP AD_HEAD LEFT #####----- */
	if($('#ad_head').length){
	    var contentArea = $('#ad_head').parent().parent();
	    $(contentArea).find('.csc-header h1:first').fadeOut('slow');
	    $('#ad_head').css({'margin-top':'0px'});
	    var topWidth = $('#ad_head .top').width();
	    var rightWidth = 122; //$('#ad_head .top .right').width();
	    var leftWidth = topWidth - rightWidth - 5 ;
	    $('#ad_head .top>.left').css({'width':leftWidth});
	}


	/* ------##### Nur fuer Hamburg #####----- */

	if($('h1').parents().andSelf().find('base').attr('href') == 'http://www.stellenwerk-hamburg.de/'){

	}

	/* ----- ##### TWITTER RETWEET BUTTON ##### ----- */

	var title = escape(document.title);
	var _url=window.location.href;
	var _url=_url.replace(/((?:\?|&)?fbc_receiver=.+)?(?:#.*)?$/,"");
	var url=escape((typeof tweetmeme_url=="string")?tweetmeme_url:((typeof TWEETMEME_URL=="string")?TWEETMEME_URL:_url)).replace(/\+/g,"%2b");
	var source=(typeof tweetmeme_source=="string")?escape(tweetmeme_source):((typeof TWEETMEME_SOURCE=="string")?escape(TWEETMEME_SOURCE):false);
	var style=(typeof tweetmeme_style=="string")?escape(tweetmeme_style):((typeof TWEETMEME_STYLE=="string")?escape(TWEETMEME_STYLE):"normal");
	var service=(typeof tweetmeme_service=="string")?escape(tweetmeme_service):((typeof TWEETMEME_SERVICE=="string")?escape(TWEETMEME_SERVICE):false);
	var service_api=(typeof tweetmeme_service_api=="string")?escape(tweetmeme_service_api):((typeof TWEETMEME_SERVICE_API=="string")?escape(TWEETMEME_SERVICE_API):false);
	var alias=(typeof tweetmeme_alias=="string")?escape(tweetmeme_alias):((typeof TWEETMEME_ALIAS=="string")?escape(TWEETMEME_ALIAS):false);
	var hashtags=(typeof tweetmeme_hashtags=="string")?escape(tweetmeme_hashtags):((typeof TWEETMEME_HASHTAGS=="string")?escape(TWEETMEME_HASHTAGS):false);
	var space=(typeof tweetmeme_space=="number")?escape(tweetmeme_space):((typeof TWEETMEME_SPACE=="number")?escape(TWEETMEME_SPACE):false);
	var width=(typeof tweetmeme_width=="number")?escape(tweetmeme_width):((typeof TWEETMEME_WIDTH=="number")?escape(TWEETMEME_WIDTH):false);
	var src="http://api.tweetmeme.com/button.js";

	switch(style){
		case"compact":
			var h=20;
			var w=90;
			break;
		default:
			var h=61;
			var w=50;
			break
	}
	if(width){
		w=width
	}
	src+="?url="+url;src+="&style="+style;
	if(source!=false){
		src+="&source="+source
	}
	if(service){
		src+="&service="+service
	}
	if(service_api){
		src+="&service_api="+service_api
	}
	if(alias){
		src+="&alias="+alias
	}
	if(hashtags){
		src+="&hashtags="+hashtags
	}
	if(space){
		src+="&space="+space
	}
	//document.write('<iframe src="'+src+'" height="'+h+'" width="'+w+'" frameborder="0" scrolling="no"></iframe>');
	//alert(url);
	$('.twitter').hide();
	$('.twitter').fadeIn(4000).html('<iframe allowTransparency="true" src="'+src+'" height="'+h+'" width="'+w+'" frameborder="0" scrolling="no"></iframe>');
	tweetmeme_url=null;
	TWEETMEME_URL=null;
	tweetmeme_source=null;
	TWEETMEME_SOURCE=null;
	tweetmeme_service=null;
	TWEETMEME_SERVICE=null;
	tweetmeme_service_api=null;
	TWEETMEME_SERVICE_API=null;
	tweetmeme_style=null;
	TWEETMEME_STYLE=null;
	tweetmeme_alias=null;
	TWEETMEME_ALIAS=null;
	tweetmeme_hashtags=null;
	TWEETMEME_HASHTAGS=null;
	tweetmeme_space=null;
	TWEETMEME_SPACE=null;

	/* ----- ##### FACEBOOK SHARE / LIKE ##### ----- */
if($('.fb_share').length > 0){
	$('.fb_share').hide();
	$('.fb_share').fadeIn(3000).html('<a class="fb_share_link" name="fb_share" type="box_count" href="http://www.facebook.com/sharer.php?u='+url+'&t='+title+'">Teilen</a>');
	$.getScript('http://static.ak.fbcdn.net/connect.php/js/FB.Share');
	setTimeout(function(){
		$('span').removeClass('fb_share_no_count');
		$('.fb_share a').css({'display':'inline','width':'auto'});
	},1000);

	$('.fb_like').hide();
	$('.fb_like').fadeIn(5000).html('<iframe src="http://www.facebook.com/plugins/like.php?href='+url+'&amp;layout=button_count&amp;show_faces=true&amp;width=110&amp;action=recommend&amp;colorscheme=light&amp;height=21" scrolling="no" frameborder="0" style=" display:none;" allowTransparency="true"></iframe>');
	$('.fb_like iframe').css({'border':'none','overflow':'hidden','width':'110px','height':'21px'});
}
	/* ----- ##### SERVICE TOOLTIPS ##### ----- */
	setTimeout(function(){
$('.services span>a[title]').tooltip(
			{
				offset: [1, 2],
				position: ['top', 'center'],
				effect: 'slide'
			}).dynamic(
			{
				bottom: { direction: 'down', bounce: true }
		});
		$(".pdf_link[title]").tooltip(
			{
				offset: [1, 2],
				position: ['top', 'center'],
				effect: 'slide'
			}).dynamic(
			{
				bottom: { direction: 'down', bounce: true }
		});
	},1000);
	$('.tx-timtabsociable-pi1 img').eq(8).css("border-left","1px solid #ccc").css("padding-left","8px").css("opacity","1");

	/* ----- ##### BOOMARKING ##### ----- */

	$('.bookmark_link,.tellafriend, .fb_like iframe').show();
	/*$('.tellafriend_link').show();*/

	$(".bookmark_link, .add_favorite, .close").hover(
			function () {
			    $(this).css({cursor:'pointer'});
			}
		);

	$('.bookmark_link,.close').click(function(){
		$('.bookmark_box').toggle();
	});
	$('.bookmark_box li a').hover(

	    function() {
	    	$(this).stop().animate({ paddingLeft: '20px' },300);
  },

  	function() {
	  	$(this).stop().animate({ paddingLeft: '0px' }, 300);
    });

	if($.browser.opera || $.browser.webkit) {
		$("ul.left li:first-child ").remove();
		$("ul.left").append($("ul.right li:first-child "));
		if($.browser.webkit){

		}else{
			$('.right').css({'width':'120px'});
		}
	}

	$("a.add_favorite").click(function(event){
		event.preventDefault(); // prevent the anchor tag from sending the user off to the link

		var url = window.location.href;
		var title = document.title;

		if (window.sidebar) { // Mozilla Firefox Bookmark
			window.sidebar.addPanel(title, url,"");
		} else if( window.external ) { // IE Favorite
			window.external.AddFavorite( url, title);
		} else { // for Safari, Konq etc - browsers who do not support bookmarking scripts (that i could find anyway)
			 alert('Unfortunately, this browser does not support the requested action,'
			 + ' please bookmark this page manually.');
		}

	});

	/* ----- ##### PRINT SERVICE ##### ----- */

	//alert($(this).parents().andSelf().find('base').attr('href'));
	$('.print_link').click(function(){
		if($.browser.msie || $.browser.opera){
			var print_rel_path = $(this).parents().andSelf().find('base').attr('href') + $('.print_link').attr('href');
			newWin = window.open(print_rel_path,"Druckvorschau");
			if($.browser.opera){
				setTimeout(function(){
					newWin.print();
					newWin.close();
				},1000);
			}else{
				newWin.print();
				setTimeout(function(){
					newWin.close();
				},1000);
			}

			//newWin.close();
		}else{
			var print_rel_path = document.baseURI + $('.print_link').attr('href');
			newWin = window.open(print_rel_path,"Druckvorschau");
			setTimeout(function(){
				newWin.print();
				newWin.close();
			},1000);

			/*$.get(print_rel_path, function(data){
				console.log(data);
				newWin = window.open("");
				newWin.document.write(data);
				newWin.print();
				//newWin.close();
			});*/
		}
		return false;
	});

	/* ----- ##### TELL A FRIEND ##### ----- */

	if($('.sendAFriendLinkPopup').length > 0){
		var url = $(".sendAFriendLink").attr("href");
		$(".sendAFriendLink").remove();
		$(".sendAFriendLinkPopup").removeAttr("href");
		$(".sendAFriendLinkPopup").removeAttr("onclick");
		$(".sendAFriendLinkPopup").removeAttr("onkeypress");
		$(".sendAFriendLinkPopup").removeClass("sendAFriendLinkPopup").addClass("sendAFriendLink");
		//$(".sendAFriendLink").prepend("<img src='fileadmin/img/sendAFriend.png' style='margin-right:3px;'></img>");

		url = url.split('?tipUrl=');
		var ajaxPath = url[0];
		var ajaxParam = $.decodeString(url[1]);

		$(".sendAFriendLink, input[type=button]").hover(
			function () {
			    $(this).css({cursor:'pointer'});
			}
		);

		$(".sendAFriendLink").click(function(){
			$.ajax({
				url:ajaxPath,
				type: "GET",
				data: {tipUrl:ajaxParam},
				dateType: 'html',
				beforeSend: function() {
					$('.services').after('<input type="hidden" name="ajaxUrl" value="'+ ajaxPath + '">');

					if($.browser.msie){

						$('.overlay').css( {opacity:0.7,backgroundColor:'black'});
						$('#center').css({position:'relative','z-index':1});
						$('.overlay').fadeIn(3000);



					}else{
						$('.overlay').toggle();
						$('.overlay').css( {backgroundColor:'black'});
						$('.overlay').animate( {opacity:0.7,backgroundColor:'black'}, 3000 ); /* that needs the color plugin*/
						$('.overlay').animate( {opacity:0.7}, 3000 );

					}
				},
				// Es hat funktioniert?
				success: function(data) {
						$("#taf_content").html(data);

						if($.browser.msie){
							$("#tellfriend").fadeToggle('slow');
							//$("#tellfriend").animate({opacity: 'toggle'}, 'slow');
						}else{
							//$("#tellfriend").fadeToggle('slow').corner("6px");
							$("#tellfriend").fadeToggle('slow');
							//$("#tellfriend").animate({opacity: 'toggle'}, 'slow');
						}
						$('input#close').click(function() {
							$("#tellfriend").animate({opacity: 'toggle'}, 'slow');
					    	$("input[name=ajaxUrl]").remove();
					    	$(".overlay").animate( {opacity:0.0}, 1000 );
					    	$('#center').css({position:'static'});
					    	setTimeout(function(){
								$('.overlay').toggle();
						        },1000);
					    });
						$(".sendAFriendLink, input[type=button]").hover(
								  function () {
								    $(this).css({cursor:'pointer'});
								  }
						);
				},
				// Schade, es war ein Fehler
				error: function(error) {
					alert("Sorry, hat nicht funktioniert");
				}
			});
		});
	}

});

/* ----- ##### ADVERTISING STUFF ##### ----- */
var portalname = $('head').find('base').attr('href');
setTimeout(function(){
	if(portalname.match(/hamburg/i)){
		var src = $('#banner_right').find('script').attr('src');
		if(src.match(/461658/i)){
			$('#banner_right').css('top','-4px');
			$('#banner_top').css('right','-164px');
			$('#banner_right').show('fast');
		}else{
			$('#banner_right').show('fast');
			/* no wallpaper */
			/*if($('#banner_right').find('.banner').find('div').find('style').length > 0){*/
				if($('#banner_top object, #banner_top iframe').length > 0){
					$('#banner_top').animate({
						right: '+=7'
					}, 1000, function() {
					});
				}
				$('#banner_right').animate({
					opacity: 1,
					top: '+=96'
				}, 1000, function() {
				})
			}
		/*}*/
		if($('.rectangle').length > 0){
		    setTimeout(function(){
		        if($('.rectangle .banner_hint').length > 0){

			}else{
		        	$('.rectangle object').parent().prepend("<div class='banner_hint' style='color:#999;font-size:10px;'>Anzeige</div>");
			}
		        if($('.rectangle .banner_hint').length > 0){

			}else{
		        	$('.rectangle embed').parent().prepend("<div class='banner_hint' style='color:#999;font-size:10px;'>Anzeige</div>");
			}
		        if($('.rectangle .banner_hint').length > 0){

			}else{
		        	$('.rectangle a img').each(function() {
						        if ( $(this).width() > 1 ) {
						            $(this).parents('.banner').prepend("<div class='banner_hint' style='color:#999;font-size:10px; '>Anzeige</div>");
						        }else{
								}
							});
			}
					},2000);
				}
	}else{
		setTimeout(function(){
			$('object').parent().prepend("<div class='banner_hint' style='color:#999;font-size:10px;'>Anzeige</div>");
			if($('#center .banner').height() > 0){
			    //$('#center .banner').height('70px');
			}
			//$('span span object').parent().parent().prepend("<div style='color:#999;font-size:10px;'>Anzeige</div>");
			$('.banner a img').each(function() {
		        if ( $(this).width() > 1 ) {
		            $(this).parents('.banner').prepend("<div style='color:#999;font-size:10px; '>Anzeige</div>");
		        }else{
					//$('.banner').hide();
				}
			});

		},2000);
	}
},100);

/* ----- ##### VIDEO EFFECTS ##### ----- */

$('#video').hide();
$("a.video").removeAttr('href');
$("a.video").hover(function() {$(this).css({cursor: 'pointer'});});
$('a.video').click(function() {
	if($('#video').is(':visible')){
		var linkText = 'Video ansehen';
	}
	if($('#video').is(':hidden')){
		var linkText = 'Video ausblenden';
	}
	$('#video').slideToggle('fast');
	$("#video>div").remove();
	$("a.video").text(linkText);
});

/* ----- ##### TWITTER MANIPULATION ##### ----- */
$('.twtr-hd h3').text("Best offers, Tipps und Infos") ;

/* ----- ##### FAQ MANIPULATION ##### ----- */

$(".link-faq").hover(
		  function () {
		    $(this).css({cursor:'pointer'});
		  }
);
$('.link-faq').click(function() {
	$(this).nextUntil('.link-faq, h1, h3').slideToggle('fast');

});

/* ------##### Nur fuer Düsseldorf #####----- */
var portalname = $('head').find('base').attr('href');
if(portalname == 'http://www.stellenwerk-duesseldorf.de/'){
	/* ------##### DUE PRIVATE/INTERN SWITCH #####----- */
	if($('.job_preview_table .ang_table_zeile_1:contains(INTERN)').text() == 'INTERN'){
		$('h1:contains(Private)').text('Uni-interne Anzeige aufgeben') ;
	}
	$('#type_uni').click(function(){
		if($('#type_uni').is(':checked')){
			$('h1:contains(Private)').text('Uni-interne Anzeige aufgeben') ;
		}
	});
	$('#type_privat').click(function(){
		if($('#type_privat').is(':checked')){
			$('h1:contains(interne)').text('Private Anzeige aufgeben') ;
		}
	});

	if($('p:contains(Team)').text() == 'Ihr Stellenwerk-Team'){
		$('h1:contains(Anzeige)').text('Ihre Anzeige ist bei uns eingegangen')
	}
	/* ------##### DUE Veranstaltungskalender Replace Text Anmeldung #####----- */
	$('.registration_box a').text('zur Anmeldung');

	setTimeout(function(){
		if($('.banner object').length || $('.banner embed').length || $('.banner').length){
			var rightHeight = $('#right').height();
			var centerHeight = $('#center').height();
			if(rightHeight>centerHeight ){
				$('#center').height(rightHeight + 15);
			}
		}
	},500);


	if($('.bc_active').length && $('.back a').length){
		var textBC = $('.bc_active').text();
		var copy   = $('.back a').clone();
		copy.text(textBC);
		$('.bc_active').html(copy);
	}
}

/* ------##### ANIMATE EFFECT > LISTE BEWERBER-PROFILE #####----- */
var website = window.location.pathname;
var match 	= website.search(/bewerber.+/);
if(match != -1){
	//console.log(window.location.pathname);
	$(".profile_list_item").hover( function(){
		$(this).parent().find('div').css({height: "100%"});
		if($(this).parent().find('div:eq(0)').height() < $(this).parent().find('div:eq(1)').height()){
			var maxheight = $(this).parent().find('div:eq(1)').height();
		}else{
			var maxheight = $(this).parent().find('div:eq(0)').height();
		}
		if(maxheight < $(this).parent().find('div:eq(2)').height()){
			var maxheight = $(this).parent().find('div:eq(2)').height();
		}
		$(this).parent().find('div').css({height: "25px"});

		$(this).parent().find('div').stop().animate({height: maxheight},{queue:true,duration:1000});
	}, 	function(){
		$(this).parent().find('div').stop().animate({height: "25px"},{queue:false,duration:500});
		});
}

/* ##### Twitter Plugin Tests ##### */
if(portalname.match(/hamburg/i)){
	var twitterAccount = 'stellenwerkHH';
	var twitterCount = 5;
}else if(portalname.match(/duesseldorf/i)){
	var twitterAccount = 'stellenwerkD';
	var twitterCount = 3;
}else if(portalname.match(/luebeck/i)){
	var twitterAccount = 'StellenwerkFHL';
	var twitterCount = 3;
}else if(portalname.match(/darmstadt/i)){
	var twitterAccount = 'KarriereTweets';
	var twitterCount = 3;
}

if($('#twitterFeeds').length > 0){
	jQuery('#twitterFeeds').jTweetsAnywhere({
		username: [twitterAccount],
	    count: twitterCount,
	    tweetProfileImagePresent: true,
	    showTweetFeed: {
	        expandHovercards: true,
	        showSource: true,
	        showInReplyTo: true,
	        showUserScreenNames: true,
	        includeRetweets: true,
	        showTimestamp: {
	            refreshInterval: 15
	        },
	        autorefresh: {
	            mode: 'auto-insert',
	            interval: 300
	        },
	        paging: { mode: 'none' }
	    },

	    loadingDecorator: function(options)
		{
			// the default loading decorator simply says: loading ...
			return '<li class="jta-loading">laden ...</li>';
		},
		noDataDecorator: function(options)
		{
			// the default no-data decorator simply says: No more data
			//return '<li class="jta-nodata">Keine weitere Meldungen</li>';
			//return '';
			setTimeout(
				    function(){
				        var elementCounter = $(".jta-tweet-list").children().length ;
				        if(elementCounter == 0){
				        	$(".jta-tweet-list").append('<li class="jta-nodata">Zur Zeit gibt es keine Meldungen!</li>')
				        }else{
				        	if(elementCounter > 3){
				        		$(".jta-tweet-list li:last").fadeOut('slow');
				        	}
				        }
				    	//$(".jta-nodata").fadeOut('slow')
				    },
				    500
			);
		},
		tweetFeedControlsMoreBtnDecorator: function(options)
		{
			return '<span class="jta-tweet-list-controls-button jta-tweet-list-controls-button-more">' + 'Mehr' + '</span>';
		},
		tweetFeedAutorefreshTriggerContentDecorator: function(count, options)
		{
			var content = '' + count + (count > 1 ? ' neue' : ' neuer') + (count > 1 ? ' Tweets' : ' Tweet');

			return '<span class="jta-tweet-list-autorefresh-trigger-content">' + content + '</span>';
		},
		tweetTimestampFormatter: function(timeStamp)
		{
			var now = new Date();

			var diff = parseInt((now.getTime() - Date.parse(timeStamp)) / 1000);

			var tweetTimestamp = '';
			if (diff < 60)
			{
				tweetTimestamp += diff + ' Sekunde' + (diff == 1 ? '' : 'n') + ' her';
			}
			else if (diff < 3600)
			{
				var t = parseInt((diff + 30) / 60);
				tweetTimestamp += t + ' Minute' + (t == 1 ? '' : 'n') + ' her';
			}
			else if (diff < 86400)
			{
				var t = parseInt((diff + 1800) / 3600);
				tweetTimestamp += t + ' Stunde' + (t == 1 ? '' : 'n') + ' her';
			}
			else
			{
				var d = new Date(timeStamp);
				var period = 'AM';

				var hours = d.getHours();
				if (hours > 12)
				{
					hours -= 12;
					period = 'PM';
				}

				var mins = d.getMinutes();
				var minutes = (mins < 10 ? '0' : '') + mins;

				var monthName = [ "Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez" ];

				//tweetTimestamp += monthName[d.getMonth()] + ' ' + d.getDate();
				tweetTimestamp += d.getDate() + '. ' + monthName[d.getMonth()] ;

				if (d.getFullYear() < now.getFullYear())
				{
					tweetTimestamp += ', ' + d.getFullYear();
				}

				var t = parseInt((diff + 43200) / 86400);
				tweetTimestamp += ' (' + t + ' Tag' + (t == 1 ? '' : 'e') + ' her)';
			}

			return tweetTimestamp;
		},

		tweetGeoLocationDecorator: function(tweet, options)
		{
			var html = '';

			// if tweet is a native retweet, use the retweet's source
			var tw = tweet.retweeted_status || tweet;

			var q;
			if (tw.geo && tw.geo.coordinates)
			{
				q = tw.geo.coordinates.join();
			}
			else if (tw.place && tw.place.full_name)
			{
				q = tw.place.full_name;
			}

			if (q)
			{
				var location = 'hier';
				if (tw.place && tw.place.full_name)
				{
					location = tw.place.full_name;
				}

				var link = 'http://maps.google.com/maps?q=' + q;

				html =
					'<span class="jta-tweet-location">' +
					' von ' +
					'<a class="jta-tweet-location-link" href="' + link + '" target="_blank">' +
					location +
					'</a>' +
					'</span>';
			}

			return html;
		},
	     onDataRequestHandler: function(stats, options) {
	        if (stats.dataRequestCount < 11) {
	            return true;
	        }
	        else {
	            stopAutorefresh(options);
	            //alert("Um Probleme mit Twitter's Begrenzungslimit zu vermeiden, laden wir keine weiteren Daten nach 10 erfolgten API-Aufrufen.");
	        }
	    }
	});
}

/* ------##### TEXT COUNTER #####----- */
// ------ Firmenportraits
if($("textarea#tx_exinitjobexchange_pi2_products_").length > 0) {

	$("textarea#tx_exinitjobexchange_pi2_products_")
			.dodosTextCounter(240, {counterDisplayClass: "textcounter-products",addLineBreak:true});
	$("textarea#tx_exinitjobexchange_pi2_locations_")
			.dodosTextCounter(240, {counterDisplayClass: "textcounter-locations",addLineBreak:true});
	$("textarea#tx_exinitjobexchange_pi2_description_")
			.dodosTextCounter(500, {counterDisplayClass: "textcounter-description",addLineBreak:true});
	$("textarea#tx_exinitjobexchange_pi2_lookingfor_")
			.dodosTextCounter(400, {counterDisplayClass: "textcounter-lookingfor",addLineBreak:true});
	// ------ Studentenprofile
	$("input#tx_uhhmgstudentsdb_pi1_field_of_study_")
			.dodosTextCounter(60, {counterDisplayClass: "textcounter-field_of_study",addLineBreak:true});
	$("textarea#tx_uhhmgstudentsdb_pi1_desired_initial_range_")
		.dodosTextCounter(60, {counterDisplayClass: "textcounter-desired_initial_range",addLineBreak:true});
	$("textarea#tx_uhhmgstudentsdb_pi1_practical_experience_")
		.dodosTextCounter(80, {counterDisplayClass: "textcounter-practical_experience",addLineBreak:true});

	$(".textcounter-products,.textcounter-locations,.textcounter-description,.textcounter-lookingfor,.textcounter-field_of_study,.textcounter-desired_initial_range,.textcounter-practical_experience")
		.after(" Zeichen verbleiben")
		.css({'font-weight' : 'bold', 'font-style' : 'italic', 'padding-left' : '5px', 'font-family' : 'Arial'});
}
/* ------##### LINK MANIPULATION #####----- */

$('.job_detail_table a[target=_blank]').each(function (i,Option) {

				if($(this).val()<30){
					//$(this).text("zur Website") ;
				}else{
					$(this).text("Link") ;
				}
});
if($('.date-pick').length > 0){
	// the german localization
	$.tools.dateinput.localize("ger",  {
	   months:        'Januar,Februar,M&auml;rz,April,Mai,Juni,Juli,August,Sebtember,Oktober,November,Dezember',
	   shortMonths:   'jan,feb,m&auml;rz,apr,mai,jun,jul,aug;,sep,okt,nov,dez',
	   days:          'sonntag,montag,dienstag,mittwoch,donnerstag,freitag,samstag',
	   shortDays:     'so,mo,di,mi,do,fr,sa'
	});
	$('.date-pick').dateinput({
		lang: 'ger',
		trigger: true,
		format: 'dd.mm.yyyy',
		min: -1
	});
	$('.date-pick').bind("onShow onHide", function()  {
		$(this).parent().toggleClass("active");
	});
	$('.date-pick:first').data("dateinput").today();
	$('.date-pick:last').data("dateinput").today();
	$('.date-pick:first').data("dateinput").change(function() {

		// we use it's value for the seconds input min option
		$(".date-pick:last").data("dateinput").setMin(this.getValue(), true);
	});
}
if($('#example').length > 0){
	var oCache = {
			iCacheLower: -1
		};

		function fnSetKey( aoData, sKey, mValue )
		{
			for ( var i=0, iLen=aoData.length ; i<iLen ; i++ )
			{
				if ( aoData[i].name == sKey )
				{
					aoData[i].value = mValue;
				}
			}
		}

		function fnGetKey( aoData, sKey )
		{
			for ( var i=0, iLen=aoData.length ; i<iLen ; i++ )
			{
				if ( aoData[i].name == sKey )
				{
					return aoData[i].value;
				}
			}
			return null;
		}
		function fnClientSort()
		{
			//console.log(oTable.fnSettings().aiDisplayMaster.length);
			//console.log(oTable.fnSettings()._iRecordsDisplay);

				if(oTable.fnSettings().aiDisplayMaster.length + 1 != oTable.fnSettings()._iRecordsDisplay){
					  var tempDisplayLength =  oTable.fnSettings()._iDisplayLength;
					  var tempDisplayEnd = oTable.fnSettings()._iDisplayEnd;
					   oTable.fnSettings()._iDisplayLength = parseInt(oTable.fnSettings()._iRecordsDisplay);
					   oTable.fnSettings()._iDisplayEnd = parseInt(oTable.fnSettings()._iRecordsDisplay);
					   oTable.fnDraw();
					   oTable.fnSettings()._iDisplayLength = tempDisplayLength;
					   oTable.fnSettings()._iDisplayEnd = tempDisplayEnd;

					   oTable.fnSettings().oFeatures.bServerSide=false;
					   oTable.fnDraw();

				}
				//oTable.fnSettings().oFeatures.bServerSide=true;

			return null;
		}

		function fnDataTablesPipeline ( sSource, aoData, fnCallback ) {
			var iPipe = 5; /* Ajust the pipe size */
			//console.log('pipeline');
			var bNeedServer = false;
			var sEcho = fnGetKey(aoData, "sEcho");
			var iRequestStart = fnGetKey(aoData, "iDisplayStart");
			var iRequestLength = fnGetKey(aoData, "iDisplayLength");
			var iRequestEnd = iRequestStart + iRequestLength;
			oCache.iDisplayStart = iRequestStart;
			//console.log(oCache);
			aoData.push( { "name": "iMin", "value": $('#min').val() } );
			aoData.push( { "name": "iMax", "value": $('#max').val() } );

			/* outside pipeline? */
			if ( oCache.iCacheLower < 0 || iRequestStart < oCache.iCacheLower || iRequestEnd > oCache.iCacheUpper )
			{
				bNeedServer = true;
			}

			/* sorting etc changed? */
			if ( oCache.lastRequest && !bNeedServer )
			{
				for( var i=0, iLen=aoData.length ; i<iLen ; i++ )
				{
					if ( aoData[i].name != "iDisplayStart" && aoData[i].name != "iDisplayLength" && aoData[i].name != "sEcho" )
					{
						if ( aoData[i].value != oCache.lastRequest[i].value )
						{
							bNeedServer = true;

							break;
						}
					}
				}
			}

			/* Store the request for checking next time around */
			oCache.lastRequest = aoData.slice();

			if ( bNeedServer )
			{
				if ( iRequestStart < oCache.iCacheLower )
				{
					iRequestStart = iRequestStart - (iRequestLength*(iPipe-1));
					if ( iRequestStart < 0 )
					{
						iRequestStart = 0;
					}
				}

				oCache.iCacheLower = iRequestStart;
				oCache.iCacheUpper = iRequestStart + (iRequestLength * iPipe);
				oCache.iDisplayLength = fnGetKey( aoData, "iDisplayLength" );
				fnSetKey( aoData, "iDisplayStart", iRequestStart );
				fnSetKey( aoData, "iDisplayLength", iRequestLength*iPipe );

				$.getJSON( sSource, aoData, function (json) {
					/* Callback processing */
					oCache.lastJson = $.extend(true, {}, json);

					if ( oCache.iCacheLower != oCache.iDisplayStart )
					{
						json.aaData.splice( 0, oCache.iDisplayStart-oCache.iCacheLower );
					}
					json.aaData.splice( oCache.iDisplayLength, json.aaData.length );

					fnCallback(json)
				} );
			}
			else
			{
				//fnClientSort();
				json = $.extend(true, {}, oCache.lastJson);
				json.sEcho = sEcho; /* Update the echo for each response */
				json.aaData.splice( 0, iRequestStart-oCache.iCacheLower );
				json.aaData.splice( iRequestLength, json.aaData.length );
				fnCallback(json);
				return;
			}
		}
		/* Custom filtering function which will filter data in column four between two values */
		$.fn.dataTableExt.afnFiltering.push(
			function( oSettings, aData, iDataIndex ) {
				var iMin = document.getElementById('min').value * 1;
				var iMax = document.getElementById('max').value * 1;
				var iDate = aData[0] == "-" ? 0 : aData[0]*1;
				//console.log('iMin: ' + iMin + ' iMax: ' + iMax + 'iDate: ' + iDate);
				if ( iMin == "" && iMax == "" )
				{
					return true;
				}
				else if ( iMin == "" && iDate < iMax )
				{
					return true;
				}
				else if ( iMin < iDate && "" == iMax )
				{
					return true;
				}
				else if ( iMin < iDate && iDate < iMax )
				{
					return true;
				}
				return false;
			}
		);
}

