jQuery(function ($) {
    var current_page = $(location).attr('href');
    $("#facebook-share").attr('href', $("#facebook-share").attr('href') + encodeURIComponent(current_page));
    $("#googleplus-share").attr('href', $("#googleplus-share").attr('href') + encodeURIComponent(current_page));
    $("#search-options").hide();
    $(".toggle-debug-data").on('click', function () {
        $(".debug-data").toggle();
    });
    $("#licensee-search").focusin(function () {
        $("#search-options").slideDown();
    });
      $('#ww').val(window.innerHeight);
    var activeMenuItem = $("#active-menu-item").html();
    if (activeMenuItem != null) $('.'+activeMenuItem).parent().parent().addClass('active');
    if ($('#table-of-contents').length > 0) {
        /*
         <div class="list-group triangle-bullets">
         <a id="toc-sample-chapter" href="#" class="list-group-item">javascript-required-chapter</a>
         <div class="list-group triangle-bullets">
         <a id="toc-sample-section" href="#" class="list-group-item">javascript-required-section</a>
         </div>
         </div>
         /**/
        var i = 0;
        var TofC = [];
        var appendHtml = '<div id="remove-this">';
        $('.toc-bookmark').each(function () {
            TofC[i] = {};
            TofC[i]['bookmarkId'] = $(this).attr('id');
            if (TofC[i]['bookmarkId'].substring(0, 4) == 'sect') {
                TofC[i]['bookmarkType'] = 'section';
            } else {
                TofC[i]['bookmarkType'] = 'chapter';
            }
            var parentText = $(this).parent().text();

            if (TofC[i]['bookmarkType'] == 'chapter') {
                appendHtml += '</div><a class="list-group-item toc-chapter" href="#' + TofC[i]['bookmarkId'] + '">' + parentText + '</a><div id="toc-chapter-' + TofC[i]['bookmarkId'] + '" class="toc-chapter-block">';

            } else if (TofC[i]['bookmarkType'] == 'section') {
                appendHtml += '<a class="list-group-item toc-section" href="#' + TofC[i]['bookmarkId'] + '">' + parentText + '</a>';
            }
            i++;
        });
        appendHtml += '</div>';
        //alert(appendHtml);
        //$('#table-of-contents').append(appendHtml);
        $('#table-of-contents').html(appendHtml);
        $('#remove-this').remove();
        $('.toc-chapter-block').hide();
        $('.toc-chapter').on("click", function (event) {
            var href = $(this).attr('href').replace('#', '');
            var showChapter = 'toc-chapter-' + href;
            if ($('#' + showChapter).is(":hidden")) {
                event.preventDefault();
                $('.toc-chapter-block').hide();
                $('#' + showChapter).show();
                //scroll the #toc-top bookmark into view.
                if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
                    var target = $('#toc-top');
                    target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
                    if (target.length) {
                        $('html,body').animate({
                            scrollTop: target.offset().top
                        }, 1000);
                        return false;
                    }
                }
            }
        });
    }

    $(".hp-form-field").closest("form").on("submit",function( event ){
    // $('input[name=license_search]').hide();
    //  $('input[name=license_reset]').before('<input name="license_search_wait" class="btn btn-default btn-sm btn-beveled" value="Please Wait..." type="button" disabled="">');
      $('#ww').attr('name','ws');
      if ($(this).find("#lic_hp").val()!=''){
          event.preventDefault();
          window.location ="https://www.trec.texas.gov/";
          return false;
        }
    });

    $('.rev-field').each(function ( index ){
      revField = $(this).attr("aria-data");
        //$(this).append("<span></span>");
      $(this).html($('#' + revField).html());
      //jQuery('head').append('<style id="style_'+ revFieldIndex +'" type="text/css">.rev-field[aria-data="'+ revFieldIndex + '"]\
      //  { unicode-bidi:bidi-override;direction:rtl; text-align:left;}</style>');
    });

    var queryVariables = getUrlVars();
    if (queryVariables['edit-keys']) {
        var url = [location.protocol, '//', location.host, location.pathname, queryVariables['edit-keys']].join('');
        window.location.href = url;
    }

    $(".navbar-collapse").collapse({toggle: false});
    $(".panel-collapse").collapse({toggle: false});

    $(".faq-widget-question").on('click', function (event) {
        event.preventDefault();
        if ($(this).nextAll(".faq-widget-answer").first().hasClass("hidden")) {
            $(".faq-widget-answer").addClass("hidden");
            $(this).nextAll(".faq-widget-answer").first().removeClass("hidden");
        } else {
            $(".faq-widget-answer").addClass("hidden");
        }
    });
    $("#btn-more-related-information").on('click', function (event) {
        event.preventDefault();
        if ($(this).text().trim() == 'More Pages') {
            $(".more-related-information-items").css("display", "inherit");
            $(this).html('<span>Less Pages</span>');
        } else {
            $(".more-related-information-items").hide();
            $(this).html('<span>More Pages</span>');
        }
        //$("#search-options").slideDown();
    });
    $("#login-block-form").on("submit", function (event) {
        event.preventDefault();
        showLoading("top");

        if ($("#userID").val() != "" && $("#userPassword").val() != "") {
            $.ajax({
                    type: "POST",
                    //http://drupal.talcb.state.tx.us
                    url: "/apps/widgets/auth-rpc.php",
                    data: {action: "login", userID: $("#userID").val(), userPassword: $("#userPassword").val()},
                    xhrFields: {withCredentials: true},

                    dataType: "json"
                })
                .done(function (data) {
                    $.each(data, function (key, value) {
			if (typeof(value)==='object'){
				//alert ('My Online Services will be unavailable from ' +value.maint_start + ' to ' +value.maint_stop + ' for maintenance.');
                                alert ('My Online Services is currently down for maintenance.');
                                
                                removeLoading("top");
				return;
			}

                        if (key == 'result' && value == true) {
                            //TODO: Maybe should be doing dynamic ajaxy things instead of a page reload
                            //location.reload(true);
                            window.location = "/apps/widgets/auth-vo-login.php";
                        } else { 
                            var errorText = '';  
                            var hold = false;                     
                            switch (value) {
                              case 'meetingsAppUser':
                                window.location = "/apps/meetings";
                                return;
                              break;
                              case 'max_attempts':
                                errorText = "You have reached the maximum number of invalid login attempts (3). Please close and reopen your web browser before trying again.";
                                hold = true;
                                break;
                              case 'locked':
                                errorText = "This account is locked.";
                                break;
                              case false:
                                errorText = "Invalid UserID or Password";
                                break;
                              default:
                                var loginCount = value.replace("login_attempts=","");
                                errorText = "Invalid UserID or Password";
                                if (loginCount > 6){
                                    errorText = "Invalid UserID or Password. "+(9-loginCount)+" login attempts remain before this account is locked.";
                                }
                                break;

                            }
                          showLoginInfoBox(errorText, hold);
                          
                        }
                    });
                })
                .fail(function (data) {
                    //Need to do some better error handling, ditch the alerts and incorporate it with our message system.
                    alert('Invalid User ID or Password.');
                });
        }
        /**/
    });

    function showLoginInfoBox(text,holdOpen){
       $('#login-info-block').width($('#login-block-form').width()-20);
       $('#login-info-block .login-info-block-text').text(text);
       $('#login-block-form').fadeOut('fast',function(){
           removeLoading("top");
           if (holdOpen){
             $('#login-info-block').fadeIn('fast');
           } else {
              $('#login-info-block').fadeIn('fast').delay(3000).fadeOut('fast',function(){
                $('#login-block-form').fadeIn('fast');
             });
           }
       });       
     }

    function showHomePageLoginInfoBox(text, holdOpen){
       $('#login-info-block-home-page .login-info-block-text').text(text);
       $('.login-block-form-home-page-button-container').fadeOut('fast',function(){
           removeLoading("middle");
           if (holdOpen){
             $('#login-info-block-home-page').fadeIn('fast');
           } else {
              $('#login-info-block-home-page').fadeIn('fast').delay(2700).fadeOut('fast',function(){
                $('.login-block-form-home-page-button-container').fadeIn('fast');
             });
           }
       });       
    }
     
    function showLoading(location){
      if (location=="top") {
        $('#login-block-form .login .form-group').css('visibility','hidden');
        $('#login-block-form .login').addClass("loading-gif");
      } else {
        $('.login-block-form-home-page-button-container .btn').css('visibility','hidden');
        $('.login-block-form-home-page-button-container').addClass("loading-gif");
      }
    }

    function removeLoading(location){
      if (location=="top") {
        $('#login-block-form .login .form-group').css('visibility','visible');
        $('#login-block-form .login').removeClass("loading-gif");
      } else {
        $('.login-block-form-home-page-button-container .btn').css('visibility','visible');
        $('.login-block-form-home-page-button-container').removeClass("loading-gif");
      }
    }




    $("#login-block-form-home-page").on("submit", function (event) {
        event.preventDefault();
        showLoading("middle");
        if ($("#homeUserID").val() != "" && $("#homeUserPassword").val() != "") {
            $.ajax({
                    type: "POST",
                    url: "/apps/widgets/auth-rpc.php",
                    data: {action: "login", userID: $("#homeUserID").val(), userPassword: $("#homeUserPassword").val()},
		    xhrFields: {withCredentials: true}
                })
                .done(function (data) {
                    $.each(data, function (key, value) {
			if (typeof(value)==='object'){
//				alert ('My Online Services will be unavailable from ' + value.maint_start + ' to ' +value.maint_stop+ ' for maintenance.');
                                alert ('My Online Services is currently down for maintenance.');
                                removeLoading("middle");
				return;
			}

                        if (key == 'result' && value == true) {
                            //TODO: Maybe should be doing dynamic ajaxy things instead of a page reload
                            //location.reload(true);
                            window.location = "/apps/widgets/auth-vo-login.php";
                        } else {
                            var errorText = '';  
                            var hold = false;                     
                            switch (value) {
                            case 'max_attempts':
                                errorText = "You have reached the maximum number of invalid login attempts (3). Please close and reopen your web browser before trying again.";
                                hold = true;
                                break;
                              case 'locked':
                                errorText = "This account is locked.";
                                break;
                              case false:
                                errorText = "Invalid UserID or Password";
                                break;
                              default:
                                var loginCount = value.replace("login_attempts=","");
                                errorText = "Invalid UserID or Password";
                                if (loginCount > 6){
                                    errorText = "Invalid UserID or Password. "+(9-loginCount)+" login attempts remain before this account is locked.";
                                }
                                break;

                            }
                          showHomePageLoginInfoBox(errorText, hold);
                        }
                    });
                })
                .fail(function (data) {
                    //Need to do some better error handling, ditch the alrts and incorporate it with our message system.
                    alert('Invalid User ID or Password.');
                });
        }
    });
    $("#user-logout").on('click', function (event) {
        event.preventDefault();
        $.ajax({
                type: "POST",
                url: "/apps/widgets/auth-rpc.php",
                data: {action: "logout"}
            })
            .done(function (data) {
                $.each(data, function (key, value) {
                    if (key == 'result' && value == true) {
                        //TODO: Should be doing dynamic ajaxy things instead of a page reload
                        var url = [location.protocol, '//', location.host, location.pathname].join('');
                        window.location.href = url;
                    }
                });
            })
            .fail(function (data) {
                //Need to do some better error handling, ditch the alrts and incorporate it with our message system.
                alert('Something went wrong');
            });
    });
    $("#release-alias").on('click', function (event) {
        event.preventDefault();
        $.ajax({
                type: "POST",
                url: "/apps/widgets/auth-rpc.php",
                data: {action: "releaseUser"}
            })
            .done(function (data) {
                $.each(data, function (key, value) {
                    if (key == 'result' && value == true) {
                        //TODO: Should be doing dynamic ajaxy things instead of a page reload
                        location.reload(true);
                    }
                });
            })
            .fail(function (data) {
                //Need to do some better error handling, ditch the alrts and incorporate it with our message system.
                alert('Something went wrong');
            });
    });

    function getUrlVars() {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    }

    // Add anchor class to a tags with id and name but no href
    jQuery("a:not([href])[id][name]").addClass('anchor');

    //replacing quicktabs default styling with bootstrap tab styling
    $('ul.quicktabs-tabs').each(function(){
      $(this).removeClass('quicktabs-style-nostyle');
        $(this).addClass('nav nav-tabs');
    });

  //making menu subnav menu categories work
   //just remove the parent "a" tag
	var spanHtml='';
	$('.menu-category-title').each(function(){
	  var aTag = $(this).closest("a");
          spanHtml = aTag.html();
          $(this).closest("li").append(spanHtml);
          aTag.remove();
	});

	spanHtml='';
	$('.menu-category-sub-title').each(function(){
          var aTag = $(this).closest("a");
	  spanHtml = aTag.html();
	  $(this).closest("li").html(spanHtml);
          aTag.remove();
	});
        
        $('.menu-category-title').each(function(){
          $(this).parent().siblings().each(function(i, element){   
            if ($(element).html().indexOf("<span") < 0 || $(element).html().indexOf("menu-category-sub-title")>0){
              $(element).hide();
            }
          });
        });

        $('ul.dropdown-menu li').on("click","span.menu-category-title, span.caret",function(e){
          e.stopPropagation();
          var keepToggling = true;
          $(this).parent().nextAll().each(function( i , element){
            if (($(element).html().indexOf("<span") > -1 && $(element).html().indexOf("menu-category-sub-title")<0) && i  ){
              keepToggling = false;
            } else if (keepToggling) {
                $(element).toggle("fade");
            }
            
          });
        });

//begin app tracker js	 
	  $("#becomeLicensedToggle").on("click",function(){
		  $("#photoButtonContainer").fadeOut('fast',function(){
			  $('#becomeLicensedContainer').fadeIn('fast')});
	  });
	  $('#applicationSearchToggle').on("click",function(){
		  $('#photoButtonContainer').fadeOut('fast',function(){
			  $('#applicationSearchFormHomePage').fadeIn('fast')});
	  });
	  $(".closeButton").on("click",function(){
		  $("#becomeLicensedContainer").fadeOut('fast',function(){
			  $("#photoButtonContainer").fadeIn('fast');
		  });
	  });
	  $("#cancelSearch").on("click",function(){
		  $('#applicationSearchFormHomePage').fadeOut('fast',function(){
			  $("#photoButtonContainer").fadeIn('fast');
		  });
	  });


       $("#homeApplicationSearchBox").keyup(function(event){
           if ($("#homeApplicationSearchBox").val()==''){
               $('.application-search-help','#applicationSearchFormHomePage').fadeOut("fast");
           } else {
            $('.application-search-help','#applicationSearchFormHomePage').fadeIn("fast");
           }
          });


	$('#becomeLicensedLicenseList').html($('#becomeLicensedMenuTitle').parent('a.dropdown-toggle').next('ul').html());
  //end app tracker js
  //begin homepage forms icons effects
  
    function openPopularForms(){
      var formIcons = $("#home-page-form-center").html();
      $("#home-page-form-center").fadeOut(function(){
        $("#home-page-form-center").html( $("#Popular-Forms").html() );
        $("#Popular-Forms").html(formIcons);
        $("#home-page-form-center").fadeIn(function(){
          $("#btnClosePopularForms").on('click',function(event){
            event.preventDefault();
            var popularForms = $('#home-page-form-center').html();
            $('#home-page-form-center').fadeOut(function(){
              $('#home-page-form-center').html( $('#Popular-Forms').html() );
              $('#Popular-Forms').html(popularForms);
              $('#home-page-form-center').fadeIn();
              $("#btnOpenPopularForms").on('click',openPopularForms);   
            });
          });
        }); 
      });
    }

    $("#btnOpenPopularForms").on('click',openPopularForms);
  //end homepage forms icons effects

  //begin forms center sidebar icon scripting
  if (window.location.href.indexOf("licensing-forms")>-1){
    $('#forms-center-sidebar #contracts-icon').show();
    $('#forms-center-sidebar #consumer-icon').show();
  }
  if (window.location.href.indexOf("consumer-forms")>-1){
    $('#forms-center-sidebar #licensing-forms-icon').show();
    $('#forms-center-sidebar #contracts-icon').show();
  }
  if (window.location.href.indexOf('agency-information/contracts')>-1){
    $('#forms-center-sidebar #licensing-forms-icon').show();
    $('#forms-center-sidebar #consumer-icon').show();
  }
  //end forms center sidebar icon scripting


//logo site survey toggle
//        setInterval(function() {
//    	  $('.navbar-custom .navbar-header .flip-card .flip-card-inner').toggleClass("hovered");
 //       },3000);

//Search box on required-agency-reports page
  $(".on-page-search").on("keyup", function () {
    var v = $(this).val();
    $(".on-page-search-results").html("");
    if (v != "") {
         $('.views-field-title .field-content a').each(function(i){
           if ($(this).text().search(new RegExp(v,'gi')) != -1){
             $(".on-page-search-results").append("<li>"+$(this).parent().html()+"</li>");
             $(".on-page-search-results").show();
           }
         });        
    }else {
             $(".on-page-search-results").hide();
    }
  });

  //begin SD-16787 & 27185 work arounds 
	if ($('.view-board-and-commission-members').length > 0){
          if ($('.view-display-id-block_2').length > 0){ 
            var moveRow = $('.view-display-id-block_2 table tbody .node-1319');
            moveRow.insertAfter($('.view-display-id-block_2 table tbody tr').last());	
            moveRow = $('.view-display-id-block_2 table tbody .node-23');
            moveRow.insertAfter($('.view-display-id-block_2 table tbody tr').last());	
	  }  
          if ($('.view-display-id-block_1').length > 0){ 
            $('.view-display-id-block_1 table tbody .node-1014 .views-field-field-title').html('');
            var moveRow = $('.view-display-id-block_1 table tbody .node-1014 ');
            moveRow.insertAfter($('.view-display-id-block_1 table tbody tr').last());	
            moveRow = $('.view-display-id-block_1 table tbody .node-1839');
            moveRow.insertAfter($('.view-display-id-block_1 table tbody tr').last());
	   } 
          if ($('.view-display-id-block_3').length > 0){ 
            $('.view-display-id-block_3 table tbody .node-1014 .views-field-field-title').html('');
            var moveRow = $('.view-display-id-block_3 table tbody .node-1320 ');
            moveRow.insertAfter($('.view-display-id-block_3 table tbody tr').last());	
            moveRow = $('.view-display-id-block_3 table tbody .node-1014');
            moveRow.insertAfter($('.view-display-id-block_3 table tbody tr').last());
            moveRow = $('.view-display-id-block_3 table tbody .node-2418');
            moveRow.insertAfter($('.view-display-id-block_3 table tbody tr').last());
	   }   
          if ($('.view-display-id-block_4').length > 0){ 
            $('.view-display-id-block_4 table tbody .node-2419 .views-field-field-title').html('');
            var moveRow = $('.view-display-id-block_4 table tbody .node-2419 ');
            moveRow.insertAfter($('.view-display-id-block_4 table tbody tr').last());	
            moveRow = $('.view-display-id-block_4 table tbody .node-1839');
            moveRow.insertAfter($('.view-display-id-block_4 table tbody tr').last());
	   }       
    
        }
   //end SD-16787

  //Agency required reports page workarounds
  $("#ui-accordion-quickset-financial_and_budget_reports-panel-0 .view-content ul li").each(function(i){
    if ($('.views-field-title span a',this).html().indexOf("Non-Financial") > -1){
      $(this).remove();
    }
  });
  $("#ui-accordion-quickset-financial_and_budget_reports-panel-1 .view-content ul li").each(function(i){
    if ($('.views-field-title span a',this).html().indexOf("Non-Financial") < 0){
      $(this).remove();
    }
  });
  $("#ui-accordion-quickset-browse_agency_reports_new-panel-2 .view-header").each(function(i){
    if (i > 0 ){
      $(this).remove();
    } else {
      //$("#ui-accordion-quickset-browse_agency_reports_new-panel-2").prepend($(this).html());
      $(this).remove();

    }
  });


});
