// init settings
var poll	= 10;	// poll max every 10 seconds
// ajax function call for "process" method
function getViewAjax(viewObject) {
var RemoteCall = function(){	
//set async
var async = true;
if (typeof viewObject.syncMode === 'string')	async = false;	
//set type
var type = 'POST';
if (typeof viewObject.sendMode !== 'undefined')	type = viewObject.sendMode;
//set dataType
var dataType = 'HTML';
if (typeof viewObject.returnFormat === 'string'){
if(viewObject.returnFormat === 'plain')	dataType = 'HTML';
else	dataType = viewObject.returnFormat;
}
//set url
var url = viewObject.execHandler;
url = '/cb/'+url.replace(/\./g,"/");
//add unique key to request because IE caches the request!!!!
/*
* navigator.appCodeName
* navigator.appName
* navigator.appVersion
* navigator.cookieEnabled
* navigator.platform
* navigator.userAgent
*/
if(navigator.appName == 'Microsoft Internet Explorer')	url+='?doNotCacheThisUrl='+Math.round(+new Date()/1000);
//ajax call
jQuery.ajax({
async:	async,
type:	type,
dataType:	dataType,
url:	url,
data:	viewObject.param,
success:	function(data){
callBackStandard(data);
},
error:	function(data){
callErrorStandard(data);
}
});
}
//default success action
var callBack = function(callvar) {
var validate = callBackValidation(viewObject, callvar);
if (!validate && typeof viewObject.writeDiv != 'undefined') document.getElementById(viewObject.writeDiv).innerHTML = callvar;
}
//default success action
var callBackStandard = function(callvar) { 
if (callvar == 'no session') callLogoutBack();	// if session is gone logout to main screen from script
else {
var executeFunction = eval(viewObject.callBack);
var validate = callBackValidation(viewObject, callvar);
if (!validate) executeFunction(callvar);
evaluateUserFeedback(viewObject, callvar);
}
//resize(); 
}
//default error action
var callError = function() {
// alert('test');
}
//default success action
var callErrorStandard = function(callvar) {
if (callvar == 'no session') callLogoutBack();
else {
var executeFunction = eval(viewObject.callError);
executeFunction(callvar);
if (typeof viewObject.messageError == 'string') messageNoSuccess(viewObject.messageError);
}
}
//run it	
RemoteCall();
}
//eval user feedback
function evaluateUserFeedback(viewObject, callvar) {	
if (typeof viewObject.messageSuccess == 'string') {
if (typeof callvar.status == 'number') var thisJson = callvar;
else var thisJson = jQuery.parseJSON(callvar);
if (typeof thisJson.status == 'number' && thisJson.status != 0) showUserFeedback(viewObject.messageSuccess);	// success message will be delivered
else if (typeof viewObject.messageNoSuccess == 'string' && thisJson.status == 0) showUserFeedback(viewObject.messageNoSuccess);	// else noSuccess message will be returned
}	
}	
//do user feedback
function showUserFeedback(msg) {
messageBox(msg);	
}
function callBackValidation(viewObject, callvar) {
var validate = false;
try {
if (typeof callvar == 'string') var r = jQuery.parseJSON(callvar);	// if it is a string then parse in to object
else var r = callvar;	// if it is a json object then not	
} catch (e) {
var r = '';
}	
if (typeof r == 'object') {
if (typeof r.errors !== 'undefined' ) {
if (r.errors.validation.length > 0) {
if (typeof viewObject.validateWriteDiv == 'string' && r.errors.validation[0].length > 0) { // since changed in object of validationservice there must be records
validate = true;
var errorMessage = '<div class="formError"><strong>Bitte folgende Meldungen beachten</strong>';
for (var i=0; i < r.errors.validation[0].length; i++) {
errorMessage += '<div>';
errorMessage += r.errors.validation[0][i].memento.message;
errorMessage += '</div>';
}
errorMessage += '</div>';
document.getElementById(viewObject.validateWriteDiv).innerHTML = errorMessage;	// move it to jProxy?
}
if (typeof viewObject.validateCallBack == 'string'){
var executeValidateCallBack = eval(viewObject.validateCallBack);
executeValidateCallBack(callvar);
}
}
}
}	// executed real callback here
return validate;
}
// evaluate correct parameter string for input provided
function showView(viewObject) {
switch (viewObject.paramType) {	// evaluate type of param and do the formatting for
case "string": 
if(typeof viewObject.param !== 'undefined' )
viewObject.param = viewObject.param.replace(/,/g,"&"); // string
break;
case "query": 
viewObject.param = '' + viewObject.param;
break;
case "array" : viewObject.param = viewObject.param;	// array
break;
case "form" : viewObject.param = $(viewObject.param).serialize();	// form
break;	
}
getViewAjax(viewObject);	// call the proxy for execution
// poll function call
if(typeof viewObject.bypassPoll == 'undefined') {	// put functions you want to call after each request
}
}
function searchForm() {
var sw = new Object();
sw.execHandler = 'Search.form'; 
sw.callBack = 'searchFormCallBack'; 
sw.callError = 'callError';
sw.param = 'siteID=' + siteID; 
sw.paramType = 'string'; 
showView(sw); 
}
function searchFormCallBack(callvar) {
// write content to result panel
$('.topRightSearch,.topRightSearchMobile').html(callvar);
// modify mobile search
$('.topRightSearchMobile form[name="cb_search_form"]').attr('name', 'cb_mobile_search_form');
$('.topRightSearchMobile form[name="cb_advanced_search_form"]').attr('name', 'cb_advanced_mobile_search_form');
$('.topRightSearchMobile .better-autocomplete').removeClass('better-autocomplete');
$('.topRightSearchMobile #searchFilter, .topRightSearchMobile .icon-arrow-up, .topRightSearchMobile .icon-remove').remove(); 
// bind autocomplete
$('#keywords').betterAutocomplete('init',
'/cb/search/completion/siteID/' + siteID + '/', 
{ cacheLimit: 128, selectKeys: [], crossOrigin: true }, 
{
processRemoteData: function(data) {
if ($.type(data) == 'object' && $.isArray(data.hits.hits))
return data.hits.hits;
else
return [];
},
themeResult: function(result) {
output = '<div class="highlightresult">' + result.fields.TITLE + '</div>';
//output += '<p>' + result.countryName + ' <em>(' + result.fclName +
//')</em></p>';
return output;
},
select: function(result, $input) {
$input.blur();
window.location = '/' + result.fields.LINK ;
},
getGroup: function(result) {
if ($.type(result.fields.DOCUMENT) == 'string' && result.fields.DOCUMENT.length)
return result.fields.DOCUMENT;
},
afterShow: function(result) {
$('.highlightresult').highlight($('#keywords').val());
},
}); 
}
function searchQuery() {
if($('.topRightSearchMobile').is(':visible')){
$('.topRightSearchMobile #filterKeywords').val($('.topRightSearchMobile #filterKeyWordsStatic').val());
// search form
if($('.topRightSearchMobile #cb_search_resultDiv').is(':visible')) {
documentForm = document.cb_advanced_mobile_search_form;
} else {
documentForm = document.cb_mobile_search_form;
}
var sw = new Object();
sw.execHandler = 'Search.query'; 
sw.callBack = 'searchQueryCallback'; 
sw.callError = 'callError'; 
sw.paramType = 'form';
sw.param = documentForm;
showView(sw); 
} else if($('.topRightSearch').is(':visible')) {
$('.topRightSearch #filterKeywords').val($('.topRightSearch #filterKeyWordsStatic').val());
// search form
if($('.topRightSearch #cb_search_resultDiv').is(':visible')) {
documentForm = document.cb_advanced_search_form;
} else {
documentForm = document.cb_search_form;
}
var sw = new Object();
sw.execHandler = 'Search.query'; 
sw.callBack = 'searchQueryCallback'; 
sw.callError = 'callError'; 
sw.paramType = 'form';
sw.param = documentForm;
showView(sw); 
} 
}
function searchQueryCallback(callvar) {
// is mobile search
if($('.topRightSearchMobile').is(':visible')){
searchEntryPoint = $('.topRightSearchMobile');
} else {
searchEntryPoint = $('.topRightSearch');
} 
// write content to result panel
searchEntryPoint.find('#cb_search_result').html(callvar);
// write searchterm in input fields
if(searchEntryPoint.find('#cb_search_result').is(':visible') == false) {
searchEntryPoint.find('#filterKeyWordsStatic').val($('#keywords').val());
} else {
searchEntryPoint.find('#keywords').val($('#filterKeyWordsStatic').val());
}
//show the result div
searchEntryPoint.find('ul.better-autocomplete').empty(); 
searchEntryPoint.find('#cb_search_resultDiv').fadeIn();
searchEntryPoint.find('#cb_search_resultDivSearch').fadeIn(); 
// style search box
searchFilterStyle(); 
if(searchEntryPoint.attr('class') == 'topRightSearchMobile') {
window.scrollBy(0,-100000); 
window.scrollBy(0,$( '#headerContainerMobile ul.meganizr' ).height() + 40);
} else if($('#cb_search_result div').size() > 1) {
// scroll to result begin
if(!$('#advancedFilter').is(':visible')) {
$( '#cb_search_resultDiv' ).scrollTop( 220 );
} else {
$( '#cb_search_resultDiv' ).scrollTop( 330 );
} 
} 
// focus search input field
searchEntryPoint.find('#filterKeyWordsStatic').focus();
$initialVal = searchEntryPoint.find('#filterKeyWordsStatic').val();
searchEntryPoint.find('#filterKeyWordsStatic').val($initialVal + ' ');
searchEntryPoint.find('#filterKeyWordsStatic').val($initialVal);
}
function searchFilterStyle() {
// is mobile search
if($('.topRightSearchMobile').is(':visible')){
searchEntryPoint = $('.topRightSearchMobile');
} else {
searchEntryPoint = $('.topRightSearch');
}
// div height
$('#cb_search_resultDiv').css('max-height', ($( window ).height() - 100) + 'px');
if(searchEntryPoint.hasClass('topRightSearchMobile')) {
searchEntryPoint.find('#cb_search_resultDivSearch').width($('#headerContainerMobile').width() - 20)
.css('top','-5px')
.css('left','-10px')
.css('position','absolute')
.css('padding','0 10px');
searchEntryPoint.find('#cb_search_resultDiv').width($('#headerContainerMobile').width())
.css('top','-30px')
.css('left','-10px')
.css('position','absolute')
.css('padding','0')
.css('box-shadow', '0 3px 3px rgba(0, 0, 0, 0.2)'); 
searchEntryPoint.find('#cb_search_resultDivSearch #filterSubmit').css('float', 'right')
.css('margin-top', '10px');
searchEntryPoint.find('#cb_search_resultDivSearch #filterKeyWordsStatic').css('margin-top', '10px')
.css('width', '40%'); 
searchEntryPoint.find('#cb_search_resultDiv .metaData').hide();
} else {
searchEntryPoint.find('#filterKeyWordsStatic').width($('div.container').width() - 220 );
// if page has header
if(!$('#mainNavFix').is(':visible')) {
searchEntryPoint.find('#cb_search_resultDiv').width($('div.container').width()).css('top','0px').css('right', '-153px');
searchEntryPoint.find('#cb_search_resultDivSearch').width($('div.container').width() - 20 ).css('top','0px').css('right', '-133px');
// if page has minimized nav 
} else {
searchEntryPoint.find('#cb_search_resultDiv').width($('div.container').width()).css('top','31px').css('right', '-13px'); 
searchEntryPoint.find('#cb_search_resultDivSearch').width($('div.container').width() - 20 ).css('top','32px').css('right', '14px'); 
}
if($('#cb_search_resultDiv').width() < 900) {
searchEntryPoint.find('#cb_search_resultDiv .metaData').fadeOut();
} else {
searchEntryPoint.find('#cb_search_resultDiv .metaData').fadeIn();
}
if($('#cb_search_resultDiv').width() < 700) {
searchEntryPoint.find('#cb_search_resultDiv .metaDataSmall').fadeOut();
} else {
searchEntryPoint.find('#cb_search_resultDiv .metaDataSmall').fadeIn();
} 
}
// place toTop button
$('#searchToTop').css('top', $('#cb_search_resultDiv').height() - 18); 
}
$(window).resize(function () {
searchFilterStyle();
});
$(document)
// DOCUMENT READY
.ready(function() {
searchForm();
})
// BINDINGS
.on('click', '#filterSubmit', function(e){ // submit button click
if($('.topRightSearchMobile').is(':visible')){
$('form[name="cb_advanced_mobile_search_form"]').submit();
} else {
$('form[name="cb_advanced_search_form"]').submit();
}
})
.on('keyup', '#filterKeyWordsStatic,#keywords', function(e){ // submit via return
if (e.keyCode == 13) {
if($('.topRightSearchMobile').is(':visible')){
$('form[name="cb_advanced_mobile_search_form"]').submit();
} else {
$('form[name="cb_advanced_search_form"]').submit();
}
} 
}) 
.on('click', 'body', function(e){ // close search
if(!$(e.target).hasId('cb_search_resultDiv') &&
!$(e.target).hasId('searchIcon') &&
!$(e.target).hasId('filterKeyWordsStatic') &&
!$(e.target).hasId('filterSubmit') &&
!$(e.target).hasId('searchToTop') &&
!$(e.target).hasId('cb_search_resultDivSearch') &&
$(e.target).parents('#cb_search_resultDiv').length < 1) {
$('#cb_search_resultDiv,#cb_search_resultDivSearch').hide(); 
}
})
.on('click', '#advancedFilterToggle', function(e){ // advanced filter panel toggle
if($('#advancedFilter').hasClass('hidden')) {
$('#advancedFilter').removeClass('hidden').fadeIn();
if(siteID == 'de') {
$('#advancedFilterToggle span').html('Erweiterte Filter ausblenden');	
} else if (siteID == 'fr') {
$('#advancedFilterToggle span').html('Masquer les filtres élargis');	
}
} else {
$('#advancedFilter').addClass('hidden').fadeOut();
if(siteID == 'de') {
$('#advancedFilterToggle').html('Erweiterte Filter');	
} else if (siteID == 'fr') {
$('#advancedFilterToggle').html('Filtres élargis');	
}
}
})
.on('mouseenter', '.searchResult', function(e){ // mouseenter styles
$(this).css('background-color','#F2F2F2');
})
.on('mouseleave', '.searchResult', function(e){ // mouseout styles
$(this).css('background-color','white');
});
function sendTerminAnmeldeForm(ele) {
var $form = $('.terminRegister');
var hasError = false;
var $element;
var errorString = '';
// name 
$element = $form.find('.name');
if($element.attr('value').length < 2) {
if(siteID == 'de') {
errorString = 'Bitte geben Sie Ihren Namen an\n';	
} else if (siteID == 'fr') {
errorString = "Entrer votre nom s'il vous plaît\n";	
}
hasError = true;	
}
// vorname 
$element = $form.find('.vorname');
if($element.attr('value').length < 2) {
if(siteID == 'de') {
errorString = errorString + 'Bitte geben Sie Ihren Vornamen an\n';	
} else if (siteID == 'fr') {
errorString = errorString + "Entrer votre prénom s'il vous plaît\n";	
}
hasError = true;	
} 
// vorname 
$element= $form.find('.email');
if(!validateEmail($element.attr('value'))) {
if(siteID == 'de') {
errorString = errorString + 'Bitte geben Sie eine gültige E-Mail an\n';	
} else if (siteID == 'fr') {
errorString = errorString + "Entrer une adresse d'e-mail valid s'il vous plaît\n";	
}
hasError = true;	
}
// adresse 
$element = $form.find('.adresse');
if($element.attr('value').length < 2) {
if(siteID == 'de') {
errorString = errorString + 'Bitte geben Sie Ihren Adresse an\n';	
} else if (siteID == 'fr') {
errorString = errorString + "Entrer une adresse s'il vous plaît\n";	
}
hasError = true;	
}	
// adresse 
$element = $form.find('.adresse');
if($element.attr('value').length < 2) {
if(siteID == 'de') {
errorString = errorString + 'Bitte geben Sie Ihren Wohnort an\n';	
} else if (siteID == 'fr') {
errorString = errorString + "Entrer une location s'il vous plaît\n";	
}
hasError = true;	
}	
// check and send
if(hasError === false) {
//validate mura form (in this case captcha only)
if(validate(ele) == true){
return true;
}
else{
return false;
}
return true;
} else {
alert(errorString);
return false;
}
}
function validateEmail(email) { 
var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
} 
function sendMenschenAnmeldeForm(ele) {
var $form = $('.menschenRegister');
var hasError = false;
var $element;
var errorString = '';
// name 
$element = $form.find('input[name="name"]');
if($element.attr('value').length < 2) {
if(siteID == 'de') {
errorString = 'Bitte geben Sie Ihren Namen an\n';	
} else if (siteID == 'fr') {
errorString = "Entrer votre nom s'il vous plaît\n";	
}
hasError = true;	
}
// vorname 
$element = $form.find('input[name="vorname"]');
if($element.attr('value').length < 2) {
if(siteID == 'de') {
errorString = errorString + 'Bitte geben Sie Ihren Vornamen an\n';	
} else if (siteID == 'fr') {
errorString = errorString + "Entrer votre prénom s'il vous plaît\n";	
}
hasError = true;	
} 
// ort 
$element = $form.find('input[name="ort"]');
if($element.attr('value').length < 2) {
if(siteID == 'de') {
errorString = errorString + 'Bitte geben Sie Ihre Ortschaft ein\n';	
} else if (siteID == 'fr') {
errorString = errorString + "Entrer votre lieu s'il vous plaît\n";	
}
hasError = true;	
} 
// email 
var regex = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
$element = $form.find('input[name="email"]');
if(!regex.test($element.attr('value'))) {
if(siteID == 'de') {
errorString = errorString + 'Bitte geben Sie Ihre E-Mail an\n';	
} else if (siteID == 'fr') {
errorString = errorString + "Entrer votre e-mail s'il vous plaît\n";	
}
hasError = true;	
} 
// kanton 
$element = $form.find('select[name="kanton"]');
if($element.attr('value').length < 1) {
if(siteID == 'de') {
errorString = errorString + 'Bitte geben Sie einen Kanton an\n';	
} else if (siteID == 'fr') {
errorString = errorString + "Entrer un canton s'il vous plaît\n";	
}
hasError = true;	
}
// branche 
$element = $form.find('select[name="branche"]');
if($element.attr('value').length < 2) {
if(siteID == 'de') {
errorString = errorString + 'Bitte geben Sie eine Branche an\n';	
} else if (siteID == 'fr') {
errorString = errorString + "Entrer une branche s'il vous plaît\n";	
}
hasError = true;	
}
// statement 
$element = $form.find('textarea[name="statement"]');
if($element.attr('value').length < 2) {
if(siteID == 'de') {
errorString = errorString + 'Bitte geben Sie Ihre Statement ein\n';	
} else if (siteID == 'fr') {
errorString = errorString + "Entrer votre déclaration s'il vous plaît\n";	
}
hasError = true;	
} 
// beruf 
$element = $form.find('input[name="beruf"]');
if($element.attr('value').length < 2) {
if(siteID == 'de') {
errorString = errorString + 'Bitte geben Sie Ihren Beruf an\n';	
} else if (siteID == 'fr') {
errorString = errorString + "Entrer votre profession s'il vous plaît\n";	
}
hasError = true;	
} 
// check and send
if(hasError === false) {
//validate mura form (in this case captcha only)
if(validate(ele) == true){
return true;
}
else{
return false;
}
} else {
alert(errorString);
return false;
}
}
function checkStatement() {
$('.statemenCounter').html(140 - $('#formStatement').val().length);
$('#formStatement').val($('#formStatement').val().substring(0, 140));
}
