
jQuery.fn.outerHTML = function() {
return $( $('<div></div>').html(this.clone()) ).html();
}

jQuery(function() {
	   jQuery.support.placeholder = false;
	   webkit_type = document.createElement('input');
	   if('placeholder' in webkit_type) jQuery.support.placeholder = true;});
/*
 -- expand or collapse all items:
 -- add a button or a link with class="expandcollapseall collapsed" and data attribute "data-parent"=<<id of the outer container>>
 */
$('.expandcollapseall').click(function() {

	var collapsed = $(this).hasClass( "collapsed" ),
		icon = collapsed ? "minus" : "plus",
		dataParent = $(this).attr('data-parent');		

	if ( collapsed ) {
		$(dataParent).find('div.toggled_element:not(.in)').collapse('show');
		$(dataParent).find("[data-toggle='collapse']").removeClass( "collapsed" );
		$(this).removeClass( "collapsed" );
		
	}
	else {
		$(dataParent).find('div.toggled_element.in').collapse('hide');
		$(dataParent).find("[data-toggle='collapse']").addClass( "collapsed" );
		$(this).addClass( "collapsed" );
	}
});



$(function() {
	
	
	//HTML5 Placeholders for troublesome browsers (ie. IE9) 
	if(!$.support.placeholder) {
        var active = document.activeElement;
        $('textarea[placeholder]').each(function(index, element) {
         if($(this).val().length == 0) {
             $(this).html($(this).attr('id')).addClass('hasPlaceholder');
             }
      });
        $('input[placeholder], textarea[placeholder], search[placeholder]').focus(function () {
             if ($(this).attr('placeholder') != '' && $(this).val() == $(this).attr('placeholder')) {
                  $(this).val('').removeClass('hasPlaceholder');
             }
        }).blur(function () {
             if (($(this).attr('placeholder') != '' && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder')))) {
                  $(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
                  //$(this).css('background', 'red');
             }
        });
        //$(':text').blur();
        $('input[placeholder], textarea[placeholder], search[placeholder]').trigger("blur");
        
        $(active).focus();
        $('form').submit(function () {
             $(this).find('.hasPlaceholder').each(function() { $(this).val(''); });
        });
   }

	/* blur the fields with readonly property*/
	$("input[readonly]").on("focus", function(){
		if($(this).attr("readonly")) {
			$(this).blur();
		} else {
			$(this).focus();
		}
	});
	
	/* listen for readonly property abd blur the field if the attribute is present*/
	if ($("input[type=text],input[type=password],textarea").watch) { 
		
		$("input[type=text],input[type=password],textarea").watch('readonly', function(){
			$(this).on("focus", function(){
				if($(this).attr("readonly")) {
					$(this).blur();
				} else {
					$(this).focus();
				}
			});
		});
	}

	
	/*
	--used for the forms with captcha to submit the form on pressing enter button
	*/
	
	$('.submitDefault').click(function(event) {
		var form = getDefaultForm();
		initErrorsDiv(form);
		var isvalid = false;
		
		var targetValidationFormDynamic = 'validate'+form.attr('name').substring(0, 1).toUpperCase() + form.attr('name').substring(1)+"Dynamic";
		var targetValidationForm = 'validate'+form.attr('name').substring(0, 1).toUpperCase() + form.attr('name').substring(1);			
		
		var formObject= form;
		if(form instanceof jQuery){
			formObject = form.get(0);
		}
		if (typeof window[targetValidationFormDynamic] === 'function'){
			isvalid = window[targetValidationFormDynamic](formObject);
		} else if (typeof window[targetValidationForm] === 'function'){
			isvalid = window[targetValidationForm](formObject);
		} else {
			return true;
		}
		
		if(isvalid == false){
			initFocus(form);
			initFieldsClass(form);
		}
	
		
		
		if(isvalid && checkSubmit()) {
			$(this).closest("form").submit(function(){
			   $('#changecaptchatype').attr('disabled',true); 
			});
			return true;
		} else {
			event.preventDefault();
		    event.stopPropagation();
			return false;
		}

	});

    $("form input").keypress(function (e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
        	$(this).closest("form").find('.submitDefault').click();
	       	e.preventDefault();
		    e.stopPropagation();
		    return false;
            
        } else {
            return true;
        }
    });
	

	
	$('.checkSubmit').click(function() {
		return checkSubmit();
	});
	
	
	
	//css class = numericKeyOnly
	$('.numericKeyOnly').on('keypress', function(event) {
		return isNumberKey(event, event.target, 0);
	}).bind('copy paste', function (e) {
              e.preventDefault();
              return false;
    });
	
	//css class = numericAndDecimalsKeyOnly
	$('.numericAndDecimalsKeyOnly').on('keypress', function(event) {
		return isNumberKey(event, event.target, 2);
	}).bind('copy paste', function (e) {
            e.preventDefault();
            return false;
    });
	
	$("textarea").each(function(){
        //this.value = this.value.replace("AFFURL",producturl);
		var maxSize = 4000;
		var cssClass = $(this).attr('class');
		var textareaId = $(this).attr('id');
		var counter = $("#"+textareaId.replace('.','\\.')+'_rest');
		if(cssClass!=null && cssClass.search("max-size\-.*")>0){
			try{
				maxSize = parseInt(cssClass.substring(cssClass.lastIndexOf('-')).match(/[0-9]+/));
			} catch(e) {}
		}
		textDecrement($(this),maxSize,counter);
				
		$(this).keydown(function(event ) {
				textDecrement(event.target,maxSize,counter);
			});
		$(this).keyup(function(event ) {
				textDecrement(event.target,maxSize,counter);
			});
    });
	
	$(".showHideNextRow").each(function(){
		var nextRow = $(this).next().children(":first");
		$(this).find('input[type=radio]').change(function () {
			if($(this).val() == 'YES'){
				nextRow.removeClass( "js-hidden" );
			} else {
				nextRow.addClass( "js-hidden" );
			}
		});
	});
	
	
	//add collapsible behaviour to pannels:
	$("div.panel.collapsible").each(function(){
		var pannelHeading = $(this).children(".panel-heading");
		pannelHeading.addClass( "clearfix" );
		pannelHeading.find('h4').addClass( "pull-left" );
		var rightContainer = pannelHeading.find('.pull-right');
		var panelClass = $(this).attr('class').split(' ');
		var btnStyle = "info";
		
		for(var i=0;i<panelClass.length;i++){
			if(/^panel-/.test(panelClass[i])){
				btnStyle=panelClass[i].split('-')[1];
			}
		}
		
		
		if(rightContainer!=null && rightContainer.length>0){
			rightContainer.append( "<span class='hidden-print clickable btn btn-hover btn-"+btnStyle+"'><i class='fa fa-minus-square-o'></i></span>" );
		} else {
			$(this).children(".panel-heading").append( "<span class='hidden-print pull-right clickable btn btn-hover btn-"+btnStyle+"'><i class='fa fa-minus-square-o'></i></span>" );
		}
		
		if($(this).hasClass('panel-collapsed')){
			$(this).find('.panel-body').slideUp();
			var collapseBtn = $(this).find('.panel-heading span.clickable');
			collapseBtn.addClass('panel-collapsed');
			collapseBtn.find('i').removeClass('fa-minus-square-o').addClass('fa-plus-square-o');
			
		}
		
	});
	$('.panel-heading span.clickable').on("click", function (e) {
		if ($(this).hasClass('panel-collapsed')) {
			// expand the panel
			$(this).parents('.panel').find('.panel-body').slideDown();
			$(this).removeClass('panel-collapsed');
			$(this).find('i').removeClass('fa-plus-square-o').addClass('fa-minus-square-o');
		}
		else {
			// collapse the panel
			$(this).parents('.panel').find('.panel-body').slideUp();
			$(this).addClass('panel-collapsed');
			$(this).find('i').removeClass('fa-minus-square-o').addClass('fa-plus-square-o');
		}
	});
	
	var pageNav = $("#pageNav");
	if (pageNav.length) {
		
		pageNav.addClass('hidden-print');
		
		$('.container').scrollNav({
			sections: 'h4.panel-title',
			subSections: false,
			sectionElem: 'section',
			showHeadline: false,
			showTopLink: false,
			insertTarget: "#pageNav",
			insertLocation: 'appendTo',
			fixedMargin: 33,
			scrollOffset: 90,
			onRender: function() {
				var $item = $('.scroll-nav__item');
					var pageNavWidth = 0;
					$.each($item, function(){
						var link = $(this).find('a');						
						var text = $(link.attr('href')).find('h4 strong').html();
						link.attr('data-toggle','tooltip');
						link.attr('title',text);
						link.html($(link.attr('href')).find('h4 i').clone());
						pageNavWidth +=40;
					});
					var $subnav = $("#pageNav nav");
					var $placeholder = $subnav.clone().addClass("scroll-nav-placeholder");		
					$subnav.after($placeholder);
					
					$(window).resize(function () {
						var pagenav = $("#pageNav");
						var pagenav_wrapper = $("#pageNav .scroll-nav__wrapper");
						var windowWidth = $(".container").outerWidth();
						var windowHeight = $(window).outerHeight();
						
						if(windowWidth<768 && windowHeight < pagenav.outerHeight()){
							var percentage = windowHeight/pagenav.outerHeight();
							$("#pageNav a .fa").css( {"font-size":(20*percentage)+"px", "line-height":(15*percentage)+"px"} );
						} else {
							$("#pageNav a .fa").css( {"font-size":"", "line-height":""} );
						}
						
						var largeScreen = { "margin-left" : ""+((windowWidth - pageNavWidth)/2-40)+"px", "top" : ""+$('#menu .container-fluid').height()+"px"};
						var smallScreen = { "margin-left" : "", "top" : ""+(windowHeight - pagenav.outerHeight())/2+"px"};
						
						if(windowWidth>720){				
							pagenav.css( largeScreen );
							pagenav_wrapper.css( {"top":""+$('#menu .container-fluid').height()+"px"} );
							$('#pageNav a[data-toggle="tooltip"]').tooltip({
								animated: 'fade',
								placement: 'bottom',
							});
						} else {
							pagenav.css( smallScreen );
							pagenav_wrapper.css( smallScreen );
							$('#pageNav a[data-toggle="tooltip"]').tooltip('destroy');
						}
					}); 
					$(window).resize();
			
			 }
		});
		
		
		
		

	}


	$(function () {

	    $('td').each(function(i, el) {
	    	if ($(el).hasClass && $(el).hasClass( "overflow" )) {
	    		var element = $(this)
                .clone()
                .css({display: 'inline', width: 'auto', visibility: 'hidden'})
                .appendTo('body');

				if( element.width() > $(this).width() ) {
				    $(this).tooltip({
		                title: $(el).html(),
		                container: 'body'
		            });
				}
				
				element.remove();
	    	}
	        
	    });

	});


       addLoadEvent(checkFormState);

		$("#printToPDF").click(function(ev){
            			var postData = {
        					"template":"faq",
            			   "payload": $('#printable').parent().html()
            			}
            			$("#template").val("faq");
            			$("#payload").val($('#printable').parent().html());
            			$("#sendToPDF").submit();


                    });

                    function activateOtherField() {
                                 let element = document.getElementById("Objectifs_6");
                                 if(element && element.checked){
                                     if($('#financialData_otherSourcesMoreInfo')){
                                        $("#financialData_otherSourcesMoreInfo").removeAttr("readonly");
                                     }
                                 } else {
                                     if($('#financialData_otherSourcesMoreInfo')){
                                          $("#financialData_otherSourcesMoreInfo").attr('readonly', true);
                                          $("#financialData_otherSourcesMoreInfo").val("");
                                     }
                                 }
                    }

                    function checkFormState(){
                           if ($('input[name="recentClosedFY"]:checked').val() == "YES") {
                                $('#financialData_customerName').removeAttr("disabled");
                                $('#financialData_customerGroup').removeAttr("disabled");
                                 if($('#addClosedIntermediaries')){
                                    $("#addClosedIntermediaries").removeAttr("disabled");
                                 }
                                 if($('#addCustomer')){
                                    $("#addCustomer").removeAttr("disabled");
                                 }
                            }else if($('input[name="recentClosedFY"]:checked').val() == "NO"){
                                $("#financialData_customerName").attr('disabled', true);
                                $("#financialData_customerGroup").attr('disabled', true);
                                if($('#addClosedIntermediaries')){
                                   $("#addClosedIntermediaries").attr('disabled', true);
                                }
                                if($('#addCustomer')){
                                   $("#addCustomer").attr('disabled', true);
                                }
                            }

                            if ($('input[name="currentFY"]:checked').val() == "YES") {
                                     $("#financialData_customerCurrentFYName").attr('disabled', false);
                                     if($('#addCustomerCurrentFY')){
                                          $("#addCustomerCurrentFY").removeAttr('disabled');
                                      }
                                      if($('#addCurrentIntermediary')){
                                         $("#addCurrentIntermediary").removeAttr('disabled');
                                      }
                                }else if($('input[name="currentFY"]:checked').val() == "NO")
                                {
                                    $("#financialData_customerCurrentFYName").attr('disabled', true);
                                    $("#addCustomerCurrentFY").attr('disabled', true);
                                    if($('#addCustomerCurrentFY')){
                                        $("#addCustomerCurrentFY").attr('disabled', true);
                                    }
                                    if($('#addCurrentIntermediary')){
                                       $("#addCurrentIntermediary").attr('disabled', true);
                                    }
                                }
                                if ($('input[name="recentClosedFYGrant"]:checked').val() == "YES") {
                                            $('#financialData_euClosedName').removeAttr("disabled");
                                            $('#financialData_euClosedAmount').removeAttr("disabled");
                                            $('#addEUClosedGrant').removeAttr("disabled");
                                }else if($('input[name="recentClosedFYGrant"]:checked').val() == "NO")
                                {
                                    $("#financialData_euClosedName").attr('disabled', true);
                                    $("#financialData_euClosedAmount").attr('disabled', true);
                                    $("#addEUClosedGrant").attr('disabled', true);
                                }
                                if ($('input[name="currentFYGrant"]:checked').val() == "YES") {
                                                $("#financialData_euCurrentName").attr('disabled', false);
                                                $("#financialData_euCurrentAmount").attr('disabled', false);
                                                $("#addEUCurrentGrant").attr('disabled', false);
                                }else if ($('input[name="currentFYGrant"]:checked').val() == "NO")
                                {
                                    $("#financialData_euCurrentName").attr('disabled', true);
                                    $("#financialData_euCurrentAmount").attr('disabled', true);
                                    $("#addEUCurrentGrant").attr('disabled', true);
                                }

                    }


/* INTERMEDIARIES: CLOSED and CURRENT*/
    $('input[type=radio][name=recentClosedFY]').change(function() {
        checkFormState();
	});
	$('input[type=radio][name=currentFY]').change(function() {
        checkFormState();
    });

    /* NEW ORGANISATION */
    $('input[type=checkbox][name=newOrganisation]').change(function() {
            let financialData_costRange = document.getElementsByClassName('financialData_costRange');
            let closedFyRadio = document.getElementsByClassName('recentClosedFYRadio');
            let recentClosedFYGrant = document.getElementsByClassName('recentClosedFYGrant');
            let financialData_closedGrants = document.getElementsByClassName('input_closedGrants');
            var financialData_sources = document.getElementsByClassName('input_fundingSources');
            if($(this).is(":checked")){
               $("#financialData_startMonth").attr('disabled', true);
               $("#financialData_startMonth").val('');
               $("#financialData_startYear").attr('disabled', true);
               $("#financialData_startYear").val('');
               $("#financialData_startDate").attr('disabled', true);
               $("#financialData_startDate").val('');
               $("#financialData_endMonth").attr('disabled', true);
               $("#financialData_endMonth").val('');
               $("#financialData_endYear").attr('disabled', true);
               $("#financialData_endYear").val('');
               $("#financialData_endDate").attr('disabled', true);
               $("#financialData_endDate").val('');
              if($("#financialData_costRange")){
                     $("#financialData_costRange").attr('disabled', true);
               }
               if(closedFyRadio){
                   for(let i = 0; i < closedFyRadio.length; i++){
                           closedFyRadio[i].checked=false;
                           closedFyRadio[i].disabled = true;
                   }
               }
               if(recentClosedFYGrant){
                      for(let i = 0; i < recentClosedFYGrant.length; i++){
                              recentClosedFYGrant[i].checked=false;
                              recentClosedFYGrant[i].disabled = true;
                      }
               }
               if(financialData_closedGrants){
                   			  for(let i = 0; i < financialData_closedGrants.length; i++){
                                       financialData_closedGrants[i].checked=false;
                                       financialData_closedGrants[i].disabled = true;
                                 }
               }
               if($("#financialData_customerName")){
                 $("#financialData_customerName").attr('readonly', true);
                 $("#financialData_customerName").attr('disabled', true);
                 $("#financialData_customerName").val("");
               }
               if($("#financialData_customerGroup")){
                 $("#financialData_customerGroup").attr('readonly', true);
                 $("#financialData_customerGroup").attr('disabled', true);
                 $("#financialData_customerGroup").val("");
               }
               if($("#addClosedIntermediaries")){
                  $("#addClosedIntermediaries").attr('disabled', true);
               }
               if($("#financialData_legislativeProposals")){
                  $("#financialData_legislativeProposals").attr('readonly', true);
                  $("#financialData_legislativeProposals").val("");
               }
               if($("#addCustomer")){
                  $("#addCustomer").attr('disabled', true);
               }
               $('#financialData_euClosedName').attr('readonly', true);
               $('#financialData_euClosedName').attr('disabled', true);
               $("#financialData_euClosedName").val("");
               $('#financialData_euClosedAmount').attr('readonly', true);
               $('#financialData_euClosedAmount').attr('disabled', true);
               $("#financialData_euClosedAmount").val("");
               $("#EUClosedGrant").attr('disabled', true);
               $("#addEUClosedGrant").attr('disabled', true);
               $("#addCustomer").attr('disabled', true);

               if(financialData_sources){
                   	for(var i = 0; i < financialData_sources.length; i++){
                        		financialData_sources[i].checked=false;
                        		financialData_sources[i].disabled = true;
                        }
               }
               if($("#financialData_otherSourcesMoreInfo")){
                    $('#financialData_otherSourcesMoreInfo').attr('readonly', true);
               }
               if($("#financialData_otherSourcesMoreInfo")){
                      $("#financialData_otherSourcesMoreInfo").val("");
               }
               if($("#financialData_genericName")){
                      $('#financialData_genericName').attr('readonly', true);
                      $("#financialData_genericName").val("");
               }
               if($("#financialData_genericAmount")){
                     $('#financialData_genericAmount').attr('readonly', true);
                     $("#financialData_genericAmount").val("");
               }
               if($("#addContribution")){
                    $("#addContribution").attr('disabled', true);
               }
               if($("#financialData_operatingBudget")){
                   $("#financialData_operatingBudget").attr('readonly', true);
                   $("#financialData_operatingBudget").val("");
               }
               if($("#financialData_0budgetMoreInfo")){
                   $("#financialData_0budgetMoreInfo").attr('readonly', true);
                   $("#financialData_0budgetMoreInfo").val("");
               }
                if($("#financialData_totalAmountClientsRevenue")){
                        $("#financialData_totalAmountClientsRevenue").attr('disabled', true);
                        $("#financialData_totalAmountClientsRevenue").val("");
                }
                if($("#tableClosedInt")){
                        $("#tableClosedInt").hide();
                }
                if($("#tableClosedCusts")){
                        $("#tableClosedCusts").hide();
                }
                if($("#tableClosedGrants")){
                        $("#tableClosedGrants").hide();
                }
                if($("#financialData_grantsClosedAmountTotal")){
                        $("#financialData_grantsClosedAmountTotal").val("");
                }
            } else {
              $("#financialData_startDateLimit").removeAttr("disabled");
              $("#financialData_startMonth").removeAttr("disabled");
              $("#financialData_startYear").removeAttr("disabled");
              $("#financialData_startDate").removeAttr("disabled");
              $("#financialData_endMonth").removeAttr("disabled");
              $("#financialData_endYear").removeAttr("disabled");
              $("#financialData_endDate").removeAttr("disabled");
              if($("#financialData_costRange")){
                    $("#financialData_costRange").removeAttr('disabled');
              }
              if($("#financialData_customerName")){
                $("#financialData_customerName").removeAttr('readonly');
              }
              if($("#financialData_customerGroup")){
                $("#financialData_customerGroup").removeAttr('readonly');
              }
              if($("#financialData_operatingBudget")){
                   $("#financialData_operatingBudget").removeAttr('readonly');
              }
              if($("#addClosedIntermediaries")){
                 $("#addClosedIntermediaries").removeAttr('disabled');
              }
              if($("#financialData_legislativeProposals")){
                 $("#financialData_legislativeProposals").removeAttr('readonly');
              }
              if($("#addCustomer")){
                 $("#addCustomer").removeAttr('disabled');
              }
              if($("#financialData_totalAmountClientsRevenue")){
                  $("#financialData_totalAmountClientsRevenue").removeAttr("disabled");
              }
              $('#financialData_euClosedName').removeAttr("readonly");
              $('#financialData_euClosedName').removeAttr("disabled");
              $('#financialData_euClosedAmount').removeAttr("readonly");
              $('#financialData_euClosedAmount').removeAttr("disabled");
              $('#financialData_euCurrentName').removeAttr("readonly");
              $('#financialData_euCurrentAmount').removeAttr("readonly");
              $("#EUClosedGrant").removeAttr("disabled");
              $("#addEUClosedGrant").removeAttr("disabled");
              $("#addCustomer").removeAttr("disabled");

              if(financialData_closedGrants){
                      for(let i = 0; i < financialData_closedGrants.length; i++){
                             financialData_closedGrants[i].disabled = false;
                       }
              }
              if(recentClosedFYGrant){
                      for(let i = 0; i < recentClosedFYGrant.length; i++){
                              recentClosedFYGrant[i].disabled = false;
                      }
              }
              if(closedFyRadio){
                      for(let i = 0; i < closedFyRadio.length; i++){
                              closedFyRadio[i].disabled = false;
                      }
              }
              if(financialData_sources){
                                  for(var i = 0; i < financialData_sources.length; i++){
                                    		financialData_sources[i].disabled = false;
                                  }
              }
              if($("#financialData_otherSourcesMoreInfo")){
                    $('#financialData_otherSourcesMoreInfo').removeAttr("readonly");
               }
               if($("#financialData_genericName")){
                      $('#financialData_genericName').removeAttr("readonly");
               }
               if($("#financialData_genericAmount")){
                     $('#financialData_genericAmount').removeAttr("readonly");
               }
               if($("#addContribution")){
                   $("#addContribution").removeAttr("disabled");
               }
               if($("#tableClosedInt")){
                   $("#tableClosedInt").show();
               }
               if($("#tableClosedCusts")){
                  $("#tableClosedCusts").show();
               }
               if($("#tableClosedGrants")){
                   $("#tableClosedGrants").show();
               }

            }
            activateOtherField();
    	});
    /* GRANTS: CLOSED and CURRENT*/
    $('input[type=radio][name=recentClosedFYGrant]').change(function() {
        checkFormState();
	});
	$('input[type=radio][name=currentFYGrant]').change(function() {
       checkFormState();
    });


    /*SEARCH BY CRYTERIA: INTERESTS REPRESENTED*/
     $( "#allRegistrants" ).change(function() {
    			$( "#interestsRepresented" ).find("input[id^='interestRepresented']").prop('checked', $(this).is(':checked'));
     });
});



	

