/*
 * author: Konstantyn Smirnov
 */

function submitFormWithEnter(myfield,e)
{
   var keycode;
   if (window.event) {
	  keycode = window.event.keyCode;
   }
   else if (e) {
	  keycode = e.which;
   }
   else {
	  return true;
   }

   if (keycode == 13) {
	   validateLogin();
	  return false;
   }
   else {
	  return true;
   }
}

function validateLogin(){
  if( 0 < $( 'j_username' ).value.length && 0 < $( 'j_password' ).value.length ){
	new Ajax.Request( $( 'loginForm' ).action, {
	  parameters:$( 'loginForm' ).serialize() + '&ajax=true',
	  onSuccess:function(e){
		if( e.responseText ){
			document.location = e.responseText;
		}else{ 
			document.location.reload();
		}
	  },
	  onFailure:function(e){ $( 'exception' ).update( e.responseText ); }
	});   
    return false;
  }
  $( 'exception' ).update( 'Enter something ffs!' );
  return false;
}

// checks if terms and conditions are checked on payment bridges
function validatePaymentConditions(formId, radioGroupName) {
	var pt = Form.getInputs(formId, 'radio', radioGroupName).find( function(radio) { return radio.checked; } ).value;
	if (pt != 'pp' && pt != 'candb') {
		return true;
	}
	
	var tc = $('form_tc'); 
	if (tc != undefined && tc.checked) {
		$('tcContainer').removeClassName('error');		
		return true;
	}
	
	$('tcContainer').addClassName('error');
	return false;
}

// special function for validating and submitting the dialog "Berechtigtes Interesse"
function validateBerechtigtesInteresse() {
    if ($('followup_request_checkbox') != undefined && $('followup_request_checkbox').checked) {
        if ($('followup_email').value.empty() || $('followup_email').getValue().indexOf("@")==-1) {
            $('followup_email_container').addClassName('error');
            $('followup_email').focus();
            return false;
        }
    } 
    $('dynamicPopup').hide();
    $('popupOverlay').hide();
    return true;
}


//special function for validating and submitting the dialog "Recherche beauftragen"
function validateRechercheauftrag() {
    var ok = true;
    if ($('followup_email').value.empty() || $('followup_email').getValue().indexOf("@")==-1) {
        $('followup_email_container').addClassName('error');
        $('followup_email').focus();
        ok = false;
    } else {
        $('followup_email_container').removeClassName('error');
    }
    if ( ($('reason').value.empty())) {
        $('reason_container').addClassName('error');
        ok = false;
    } else {
        $('reason_container').removeClassName('error'); 
    }
    if (ok) {
        $('dynamicPopup').hide();
        $('popupOverlay').hide();
        return true;
    } else {
        return false;
    }
}


function newOption( container ){
	var div = new Element( 'div' );
	div.insert( new Element( 'span' ).update( 'Value: ' ) ); 
	div.insert( new Element( 'input', { type:'text', rel:'option_value' } ) ); 
	div.insert( new Element( 'span' ).update( '  Text: ' ) ); 
	div.insert( new Element( 'input', { type:'text', rel:'option_text' } ) ); 
	div.insert( new Element( 'input', { type:'button', value:'X' } ).observe( 'click', function( e ){ e.findElement( 'DIV' ).remove(); } ) ); 
	$( container ).insert( div );
}

function insertGroup(){
	$( 'groupBuilderContainer' ).show();
	$( 'groupBuilder' ).update();
	newOption( 'groupBuilder' );
}

var groupTemplates = {
		'select':'<option value="[val]">[txt]</option>\n',
		'radio':'<input type="radio" id="field_[id]" name="[name]" value="[val]"/>[txt]<br/>\n',
		'checkbox':'<input type="checkbox" id="field_[id]" name="[name]" value="[val]"/>[txt]<br/>\n'
};

function assembleGroup( container, name, target, add ){
	var t = $( container ).next( 'select[rel=groupType]' ).value;
	var buff = '<div>';
	if( 'select' == t ) buff = '<select name="' + name + '" id="field_' + name + '" selected="selected"><option value=""></option>';
	buff += '\n';
	$( container ).childElements().each( function( div ){
		var val = div.down( 'input[rel=option_value]' ).value;
		var txt = div.down( 'input[rel=option_text]' ).value;
		if( 0 < val.length || 0 << txt.length ) 
			buff += groupTemplates[ t ].replace( /\[val\]/, val ).replace( /\[txt\]/, txt ).replace( /\[name\]/, name ).replace( /\[id\]/, name.replace( /\W/, '_' ) );
	} );
	buff += 'select' == t ? '</select>\n' : '</div>';
	if( add ){
		$( target ).value += buff;
	}else{
		$( target ).value = buff;
	}
}

function assembleCalendar( container, name, target, add ){
	var format = $( container ).down( '#calendarFormat' ).value;
	var limit = $( container ).down( '#calendarLowerLimit' ).value;
	if( limit ) limit = Date.parse( limit ).toString( format );
	
	var buff = '<div class="boxFirst2"><input type="text" rel="calendar" id="field_' + name + '_from" name="' + name + '_from" class="formInput2"';
	if( format ) buff += ' format="' + format + '"';
	if( limit ) buff += ' limit="'+ limit + '"';
	buff += '/></div>';
	
	buff += 'bis <input type="text" rel="calendar" id="' + name + '_to" name="' + name + '_to" class="formInput2b"';
	if( format ) buff += ' format="' + format + '"';
	if( limit )	buff += ' limit="' + limit + '"';
	buff += '/>';
	
	if( add ) $( target ).value += buff;
	else $( target ).value = buff;
}

function text2Tip( target, text, e ){
    e.stop();
    if( text.blank() ) return false;

    var preview = $( 'hitPreview' );
    preview.update( text );
    preview.appear({ duration: 0.3 });
    // ie bug fix, tags in it are uppercase
    if( (-1 < text.indexOf( '<img' ) || -1 < text.indexOf( '<IMG' )) && 0 == text.stripTags().length ){
    	preview.down( 'div' ).style.width = '90px'; 
    	preview.style.padding = '0px 0px';
    }else{
    	if( null != preview.down( 'div' ) ) preview.down( 'div' ).style.width = '350px'; 
	    preview.style.padding = target ? '3px' : '3px 5px';
    }
    var elemDim = preview.getDimensions();
    var windowDim = document.viewport.getDimensions();

    preview.style.top = ( e.pointerY() - elemDim.height > 10 ? e.pointerY() - elemDim.height - 10 : 5) + 'px';
    
    if( windowDim.width < e.pointerX() + elemDim.width ) preview.style.left = ( windowDim.width - elemDim.width )  + 'px';
    else preview.style.left = ( e.pointerX() + 12 ) + 'px';
}

function expandTip( selector, e ){
	var target = ( 'string' == typeof selector ) ? e.findElement( selector ).down( 'span.hint' ) : selector;
	if( null == target ) return;
	var text = target.innerHTML.strip();
	if( 0 < text.length ) text = '<div class="innerModuleTippList">' + text + '</div>';
	text2Tip( target, text, e );
}

function collapseTip( e ){
	try{ 
		$( 'hitPreview' ).hide();
	}catch( e ){}
}

function addToolTips(){
	$$( 'a.boxList' ).each( function( a ){
		a.observe( 'mouseover', expandTip.curry( 'tr' ) );
		a.observe( 'mouseout', collapseTip );
	} );
}

function extendTitleTips(){
	$$( 'a[title^=tip_]', 'span[title^=tip_]', 'input[title^=tip_]' ).each( function( a ){
		var id = a.title.substring( 4 );
		a.title = ''; 
		var timeout = id.match( /^(\d+)_/ );
		if( timeout ){
			timeout = parseInt( timeout[ 1 ] );
			id = id.substring( id.indexOf( '_' ) + 1 );
			
			a.observe( 'mouseover', function( e ){ 
				a.stopObserving( 'mouseout' );
				expandTip( $( id ), e );
				setTimeout( collapseTip, timeout );
			} ); 
		}else{
			a.observe( 'mouseout', collapseTip );
			a.observe( 'mouseover', expandTip.curry( $( id ) ) ); 
		}
		
	} );
	$$( 'a[title]', 'span[title]', 'input[title]' ).each( function( a ){
		if( null != a.readAttribute( 'rel' ) && -1 < a.readAttribute( 'rel' ).indexOf( 'lightbox' ) ) return;
		a.observe( 'mouseover', text2Tip.curry( a, a.title ) );
		a.title = ''; 
		a.observe( 'mouseout', collapseTip ); 
	} );
}

function extendMiniHitTips(){
	$$( 'dd[class^=minihit]', 'span.minihit' ).each( function( a ){ 
		a.observe( 'mouseover', expandTip.curry( '.minihit' ) ); 
		a.observe( 'mouseout', collapseTip ); 
	} );
	extendTitleTips();
}

//document.observe( 'click', collapseTip ); 
	
document.observe( 'dom:loaded', function(){
	var preview = new Element( 'div', { id:'hitPreview', style:'display:none' } );
	preview.addClassName( 'hitPreview' );
	preview.observe( 'focus', collapseTip );
	document.observe( 'click', function( e ){
		if( !e.element().up( '#hitPreview' ) ) collapseTip(); 
	} );
	$$( 'body' )[ 0 ].insert( preview );
	if( 'undefined' == typeof stopExtendTooltips ){
		addToolTips();
		extendTitleTips();
	}
});

function showSmds( e ){
	var list = eval( "("+e.responseText+")" );
	var text = list.inject( '<div style="line-height:20px; background-color:white; border: 1px solid orange; width:400px;padding: 10px 10px">', function( t, smd ){
		return t + '<a href="javascript://" onclick="$( \'dbShortcut\' ).value=\'' + smd.name + '\';myDynamicPopup.end();return false" title="' + smd.description + '">' + 
		smd.name + '</a>&nbsp;<a href="javascript://" onclick="$( \'dbShortcut\' ).value+=\' ' + smd.name + '\';return false">+</a>&nbsp; ' ;
	} ) + '</div>';
	myDynamicPopup.showContent( text );
}

function updatePrice( form ){
	var sum = ( 'undefined' == typeof form ? $$( 'input.single' ) : $( form ).select( 'input.single' ) ).inject( 0, function( res, curr ){
		var priceText = curr.up( 'tr' ).down( 'span.price' ).innerHTML.replace( /,/, '.' );
		var price = parseFloat( priceText.substring( 0, priceText.lastIndexOf( ' ' ) ) );
	    return !isNaN( price ) && isFinite( price ) && curr.checked ? ( res + price ) : res;
	} );
	$$( '.priceAccumulator' ).invoke( 'update', '(' + sum.toFixed( 2 ).replace( /\./, ',' ) + ' €) ' );
}

function referenceOps( a, refId ){
	a = $( a );
	a.stopObserving( 'click' );
	a.writeAttribute( 'onclick', '' );
	new Ajax.Request( 'undefined' == typeof( refId ) ? ( add2refLink + a.id.substring( 1 ) ) : ( removeRefLink + refId ),
		{ onComplete:function( e ){
	  		var res = eval( "("+e.responseText+")" );
	  		if( null != res.refId ){
	  			a.title = 'Von Merkliste löschen';
	  			a.removeClassName( 'boxSetNotice' ).addClassName( 'boxNotice' );
	  			a.observe( 'click', function(e){
	  				e.stop(); 
	  				referenceOps( e.element().id, res.refId );
	  			} );
	  		}else{
	  			a.title = 'Dokument merken';
	  			a.removeClassName( 'boxNotice' ).addClassName( 'boxSetNotice' );
	  			a.observe( 'click', function(e){
	  				e.stop(); 
	  				referenceOps( e.element().id );
	  			} );
	  		}
	  		if( !$( 'layer_mygenios' ).empty() ) new Ajax.Updater( 'layer_mygenios', geniosConsoleLink );
	  		extendTitleTips();
	  		$$( '#activeReferenceGroupSize' ).invoke( 'update', res.count );
		} 
		}
	);
}

function switchTab( ix, exceptFor ){
	$( 'subDocContent' + Math.floor( ix / 10 ) ).update( $( 'contentContainer_' + ix ).innerHTML );
	$$( 'a.boxNav' ).invoke( 'removeClassName', 'boxActive' );
	$( 'tab_' + ix ).addClassName( 'boxActive' );
	hideHitlistPopups( exceptFor );
}

function hideHitlistPopups( exceptFor ){
	if( 'undefined' == typeof exceptFor ) exceptFor = null;
	$$( 'li.popupContainer' ).each( function( popup ){
		var ix = popup.id.substring( 15 );
		if( ix == exceptFor ) return;
		if( null != $( 'popupTrigger_' + ix ) ) $( 'popupTrigger_' + ix ).removeClassName( 'boxOpened' ).addClassName( 'boxClosed' ); 
		popup.hide();
	} ); 
}

function toggleHitlistPopup( ix, url ){
	switchTab( ix, ix );
	$( 'popupContainer_' + ix ).toggle();
	$( 'popupTrigger_' + ix ).toggleClassName( 'boxOpened' ).toggleClassName( 'boxClosed' );
	if( $( 'popupTrigger_' + ix ).hasClassName( 'boxOpened' ) && !$( 'popupContainer_' + ix ).innerHTML ) loadHitlist( ix, url );
}

function loadHitlist( ix, url ){
	if( 'undefined' == typeof url ) return;
	var pc = $( 'popupContainer_' + ix );
//	var top = $( 'tab_' + ix ).cumulativeOffset().top;
//	pc.style.top = ( 24 + top ) + 'px';
	if( pc.empty() ) pc.update( '<div class="boxContent"><div class="spinner">&nbsp;</div>&nbsp;&nbsp;&nbsp;Dokumente werden geladen...</div><div class="boxShadow"></div>' );
	new Ajax.Request( url, { 
		parameters:{ ix:ix },
		onComplete:function(e){
			pc.update( e.responseText );
			addToolTips();
			pc.select( 'div.innerModulePager a' ).invoke( 'observe', 'click', function( ee ){ 
				ee.stop();
				loadHitlist( ix, ee.element().href );
			} );
		}
	} );
}

function handleInputDefault (elementId, value) {
	var e = $(elementId);
	if (e == 'undefined') { return; }
	
	var newValue = e.value;
	if (e.value == value) {
		newValue = "";
	}
	else if (e.value == '') {
		newValue = value;
	}
	e.value = newValue;
}


/*
 * If targetFieldName is empty, the value of orgFieldName is copied into it
 */
function copyValue (orgFieldName, targetFieldName ) {
    if ($(targetFieldName).value=="" && $(orgFieldName).value!=null) {
        $(targetFieldName).value = $(orgFieldName).value;
    }
}

if (Prototype.Browser.IE) {
    Event.observe( window, 'load', function (){
        $$( 'label img' ).invoke( 'observe', 'click', function (e) {
            $( e.element().up('label').readAttribute('for') ).click();
        });
    });
}

// <<<<<<< search

var blockFilter = false;

function extendPaginationLinks(){
  $( 'content' ).select( 'div.innerModulePager a', 'th.sortable a' ).invoke( 'observe', 'click', loadContent );
}

function loadContentInternal( url, params ){
  new Ajax.Updater( 'content', url, {
    parameters:'undefined' != typeof( params ) ? params : '',
    onComplete:function(){
      if( $( 'filterSpinner' ) ) $( 'filterSpinner' ).hide();
      blockFilter = false;
      addToolTips();
      extendTitleTips();
      extendFilterLinks();
      extendPaginationLinks();
    },
    onFailure:function(e){alert('Die Funktion steht aktuell nicht zur Verfügung.');}
  } );
}

function extendFilterLinks(){
  $( 'content' ).select( 'div.moduleSetResultLimits a' ).invoke( 'observe', 'click', function( e ){
    if( $( 'filterSpinner' ) ) $( 'filterSpinner' ).show();
    loadContent( e );
    blockFilter = true;
  } );
}

function loadContent(e){
	e.stop();
	if( !blockFilter ) loadContentInternal(e.findElement( 'A' ).href);
	try{ dsHistory.addFunction(loadContentInternal, window, e.findElement( 'A' ).href); }catch(e){}
}

function initHistory() {
  var url = window.location.href;
  var urlParts = url.split('/');
  url = urlParts[urlParts.length-1];
  try{ dsHistory.addFunction(loadContentInternal, window, url); }catch(e){}
};

function searchObserve(){
    if (Prototype.Browser.IE) {
        $( 'search' ).select( 'input[type=text]' ).invoke( 'observe', 'keydown', function(e){
            if(e.keyCode==13){
                e.stop();
                var submit = $$(".moduleSimpleSearch .innerModuleButtonSubmit input")[0];
                submit.click();
            }
        });
    }
}

document.observe( 'dom:loaded', function(){
  extendFilterLinks();
  extendPaginationLinks();
  initHistory();
  searchObserve();
} );

// >>>>>>> search

function showMinihitList( query, text, a ){
	  if( 'undefined' != a ) myDynamicPopup.link = a;
	  new Ajax.Request( query2popupLink, {
	                    parameters:{ query:query, text:text, popup:true },
	                    onComplete:function( e ){
	                      myDynamicPopup.showContent( e.responseText );
	                    }
	  } );
	}

