(function($) {
  $(document).ready(function() { 

    // Set the Javascript API key
    setApiKey(3031679862);

    // Main navigation dropdowns
    $('#nav-pri-list').superfish({
      delay:100,
      autoArrows:true
    });

    // Set default value for main search box
    $("#site_searchbox_query").defaultValue("Search ECCC");

    // Set default value for Keep Informed Form
    if($('#sign-up-right').length) {
       $('#cs-name-right').defaultValue("Name");
       $('#cs-organisation-right').defaultValue("Organisation");
       $('#cs-email-right').defaultValue("Email");
    }

    // Set default value for Keep Informed Footer
    $('#cs-name-footer').defaultValue("Name");
    $('#cs-email-footer').defaultValue("Email");

    // Replace 'Leave Empty' text with 'All Regions' in dropdown box - News & Info - Site search Results
    $("#id3883 #root_node_selection option:first-child").text("All"); 

    // Add accordion functionality
    $("#accordion").accordion();
    $("#accordion2").accordion();

    // Remove empty uls from main nav so superfish can show arrows only when needed
     $('#nav-pri-list ul').each(function(){
       if($(this).find('li').length == 0){
         $(this).remove();
       }
     });

    // Content sharing toolbar
    if($('#content-share').length){
       contentShare();
    }

    //Inserts results per page select box and removes matrix results per page hidden input
    $("input:hidden[name='results_per_page']").remove();
    $("input[name='results_per_page_text_box']").after('<select class="results-per-page" name="results_per_page" ><option value="5" >5</option><option value="10">10</option><option value="25">25</option></select>').remove();

    // Accessible Sort by dropdownlist
    if($('#sort-bar').length){
       sortByDropDown();

}

    // Font replacments
    //Cufon.replace('h1,h2,#hp-whats-new h3, .sort-block h3, .sort-block-numbered h3, .resources-logo h3', {hover: true, fontFamily: 'Agenda-Light' }); 
    Cufon.replace('h1,h2,#hp-whats-new h3, .sort-block h3, .sort-block-numbered h3, .resources-logo h3', {hover: true, fontFamily: 'Myriad-Pro' });  
    Cufon.replace('ul.hp-feature-list li a, .morelink, .findlink, h4, #hp-voice a, .hp-feature-controls, .learn-more-button, #form_email_4767_submit', { hover: true, fontFamily: 'Aller' }); 
    Cufon.now();

// Campaign Suite Submission
    $.each($('.cs-sign-up'), function(i, form) {
		$(form).find("input:submit").click(function() {
			// First, disable the form from submitting
			$(form).submit(function() { return false; });

			// Grab form action
			var formAction = $(form).attr("action");

			// Hacking together id for email field
			// Replace the xxxxx below:
			var id = "athili";
			var emailId = id + "-" + id;
			var email = $(form).find('[name=cm-'+emailId+']');

			// Validate email address with regex
			if (!checkEmail(email)) {
				alert("Please enter a valid email address");
				return;
			}


			if(!$(form).find('input.cs-policy').attr('checked')) {
				alert("Please accept the Privacy Policy");
				return;
			}


			$(form).find('.loading').css('display', 'block');
			$(form).find('input:submit').css('display', 'none');
	
			// Serialize form values to be submitted with POST
			var str = $(form).serialize();

			// Add form action to end of serialized data
			// CDATA is used to avoid validation errors
			//<![CDATA[
			var serialized = str + "&action=" + formAction;
			// ]]>
			
			// Submit the form via ajax
			$.ajax({
				url: $(form).find('.cs-proxy').val(),
				type: "POST",
				data: serialized,
				success: function(data){
					// Server-side validation
					if (data.search(/invalid/i) != -1) {
						email.poshytip({
							className: 'tip-darkgray',
							showOn: 'none',
							alignTo: 'target',
							alignX: 'left',
							alignY: 'center',
							offsetX: 5,
							content: 'Email address is not valid'
						});
						email.poshytip('show');
					}
					else
					{
						$(form).find('.form').hide(); // If successfully submitted hides the form
						$(form).find(".result").slideDown("slow");  // Shows "Thanks for subscribing" div
						$(form).find(".result").tabIndex = -1;
						$(form).find(".result").focus(); // For screen reader accessibility
					}
				}
			});
		});
	});
  });



})(jQuery);

function sortByDropDown()
{
$('#sortby select option:first-child').text("Newest to Oldest").after('<option value="0">Oldest to Newest</option>');
$('#sortby select option:last-child').text("A to Z").after('<option value="1">Z to A</option>');

       $('#sortby select').click(function() {
        switch ($('#sortby select option:selected').attr("text"))
        {
           case "Newest to Oldest":
           $("#sortorder select option[value='1']").attr("selected","selected");
           break;
  
           case "Z to A":
           $("#sortorder select option[value='1']").attr("selected","selected");
           break;
  
           default:
           $("#sortorder select option[value='0']").attr("selected","selected");
        }
       });

       var url = window.location.href
       var str1 = /sort_by=0/g;
       var str2 = /sort_direction=0/g;
       var str3 = /sort_by/g;
       var sortdir = str1.test(url);
       var sortby = str2.test(url);
       var initial = str3.test(url)+1;
       var defaultsortoption = sortdir+sortby+initial;

       switch (defaultsortoption)
       {
          case 2:
             $("#sortby select option:last-child").attr("selected","selected");
          break;

          case 4:
             $("#sortby select option:nth-child(2)").attr("selected","selected");
       }
} // end sortByDropDown

function contentShare() {
  if($('#content-share option').length==1)
    {
       $('#content-share').remove();
    }

  $('#content-share select option').each(function() {
    var rootNodes = $(this).attr("value");

          var optionGroupClass = $(this).parent().attr('class');
          $(this).addClass(optionGroupClass);
          var groupClass = $(this).attr('class');

     getChildren(rootNodes, 2, function(data) {
       for (var id in data) {
          var currentAsset = $('body').attr('id').substr(2);

          if (id == currentAsset)
          {
            $('#content-share .'+groupClass).remove();
            if($('#content-share option').length==1)
            {
               $('#content-share').remove();
            }
          }
     
       }
     })
  })

  $('#sharebutton').click(function() {
     var createLinkNode = $('#content-share select option:selected').attr('value');
     var currentAsset = $('body').attr('id').substr(2);
   
     switch($('#sharebutton').attr('value'))
     {
        case "Share":
        createLink(createLinkNode, currentAsset, 1,"", 0, 0, 0, function() {}
        ),
        $('#sharebutton').attr('value','Undo')
        break;
      
        case "Undo":
        removeLink(createLinkNode, currentAsset, function() {}
        ),
        $('#sharebutton').attr('value', 'Share')      
     }
  })
} // end contentShare

function checkEmail(email) {	
  var pattern = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  var emailVal = email.val();
  return pattern.test(emailVal);
} // end checkEmail
