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

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

    // Make the main nav menu using Superfish
    $("#nav-pri-list").superfish({autoArrows: true});

    // Font replacement
    Cufon.replace('h1,h2,#hp-whats-new h3, .sort-block h3, .sort-block-numbered h3, .resources-logo h3', {hover: true, fontFamily: 'Agenda-Light' });  
    Cufon.now();

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

    // 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");

    }

    // Sponsor box on homepage js
    if($('#id3131').length) {
      setupHomepageSponsorBox();
    }

    // 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();
    }
  
    // Add lightbox for CCV2 link to Pay an Invoice - step 3
    if($('body#id5289').length){
       $('a#security-code-help').fancybox();
    }

    // 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 = "atlfy";
			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 setupHomepageSponsorBox() {

  var rand_no = Math.random();
  var currentImg = $("#sponsors li a img").attr("id").substr(3);
  $.ajax({
     url : "http://" + top.location.host + "/_media/wecc/sponsor-listing-js",
     data: "nocache=" + rand_no,
     success: function(data){
        $.each(data.imgs, function(i, img){
           if(img.id != currentImg) {
              $("#sponsors").append('<li><a href="' + img.url + '"><img src="' + img.src + '" alt="' + img.alt + '" width="' + img.w + '" height="' + img.h + '" /></a></li>');
           }
        })
        $("#sponsors")
        .css({"margin-left":"0"})
        .before('<a id="prevSponsor" href="#" title="Previous"><img src="/__data/assets/image/0007/5956/icon-arrow-left.gif" alt="Previous" /></a>')
        .after('<a id="nextSponsor" href="#" title="Next"><img src="/__data/assets/image/0008/5957/icon-arrow-right.gif" alt="Next" /></a>');
         $('#sponsors').cycle({ 
            prev:   '#prevSponsor', 
            next:   '#nextSponsor', 
            timeout: 2000 
        });
     }
  })
} // end setupHomepageSponsorBox


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
