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

    // All pages (apart from thickbox pages)
    if ($(".thickbox-content").length == 0) {

      loadGraphs();  // Load the various graphs

      $("ul.nav-pri-list").supersubs({ 
            minWidth:    6,   // minimum width of sub-menus in em units 
            maxWidth:    17,   // maximum width of sub-menus in em units 
            extraWidth:  1     // extra width can ensure lines don't sometimes turn over 
                               // due to slight rounding differences and font-family 
        }).superfish(); // Initialises pretty dropdowns
      $('.sIFR').sifr({font: 'GothamRounded', path: 'http://squiz-nzlta1.actrix.co.nz/feetfirst/__data/assets/file/0014/455', width: '100%;', height: "100px", zoom: 1, offsetLeft: 0 }); // Adds SIFR font replacement to page

      iePngFix();                       // IE png fix
      $("#queries_searchbox_query").DefaultValue("Search the Site");  // Add text to search box

    };

    // Curriculum pages
    if ($("#curriculum-menu").length > 0) {
      $("#curriculum-menu").treeview();  // add expandable/collapsable sub menu to curriculum pages
    }

    // Stories page
    if ($("div#region-map").length > 0) {
      hoverMap();                     // Makes regions appear highlighted when mouse hovers over them
    }

    // Region page
    if ($("div#external-map").length > 0) {
      initialiseMap();                // Initialise Google Maps
    }

    // School Registration page
    if ($("#school-registration").length > 0) {
      hideAndAutoPopulateSchoolRegistrationInputFields();
      getAndValidateSchoolNameFromSchoolNumberForSchoolRegistration();
      stopMatrixSchoolRegistrationFormSubmission();
      validateSchoolRegistrationForm();
    }

    // Non school Registration page (for TAs and Walking groups)
    if ($("#ta-registration").length > 0) {
      hideAndAutoPopulateNonSchoolRegistrationInputFields();
      stopMatrixNonSchoolRegistrationFormSubmission();
      validateNonSchoolRegistrationForm();
    }

    // Schools Walking Data input page
    if ($("body#id67").length > 0) {
      $('#input ul').tabs();
      walkingDataInputFormControls();
      showCorrectTermDatesForSelectedTab();
      dateHelper();

    }

    // Reports pages
    if ($("#results").length > 0) {
      $('#results ul').tabs();  // set content area to show tabs for each term
    }

    // Regional reports page
    if ($("#id933").length > 0) {
      showSchoolsLink();
    }

    // Regional reports school graphs page
    if ($("#id1585").length > 0) {
      fixBreadcrumbs();
    }

    // National reports page
    if ($("#id2710").length > 0) {
      showSchoolsLink();
    }

    // Submit a Story page
    if ($("#id285").length > 0) {
      validateSubmitStoryForm();
    }

    // Login page
    if ($("#id527").length > 0) {
      loginPageFns();
    }
    
    // School Edit profile page
    if ($("#school-edit-profile").length > 0) {
      tidyUpSchoolEditProfile();
      addSaveAndExitFns();
      stopMatrixEditProfileFormSubmission();
      validateEditProfileForm();
    }

    // Site Map page
    if ($("#id565").length > 0) {
      sitemapFns();
    }

    // Book entry form
    if($('body#id4225').length > 0){
	populateEntryForm();
    }

  });  
})(jQuery);


function loadGraphs() {

  //$('#branding-information').hide().removeClass('access').show('slow')find;
/*  $('.my-school-table table').not(':last').gChartTable( {
      chart: "bvg",
      additional: "&chdl=Children&nbsp;walking",
      color: "4D89F9,C6D9FD",
      ySize: "200",
      xSize: "800",
      xLabel: "Week",
      yLabel: "Children Walking"
  });
  $('.my-school-table table:last').gChartTable( {
      chart: "bvg",
      additional: "&chdl=Children&nbsp;walking",
      color: "4D89F9,C6D9FD",
      ySize: "200",
      xSize: "800",
      xLabel: "Week",
      yLabel: "Children Walking"
  }); */

$('.my-school-table table').each(function(){
   $(this).gChartTable( {
      chart: "bvg",
      additional: "&chdl=Children&nbsp;walking",
      color: "4D89F9,C6D9FD",
      ySize: "200",
      xSize: "800",
      xLabel: "Week"
    });
});
 /* $('.comparison-table table').not(':last').gChartTable( {  
      ySize: "200",
      xSize: "800" ,
      additional: "&chdl=My&nbsp;school|Region",
      xLabel: "Week",
      yLabel: "% of school"
  });
 $('.comparison-table table:last').gChartTable( {  
  ySize: "200",
      xSize: "800" ,
      additional: "&chdl=My&nbsp;school|Region",
      xLabel: "Week",
      yLabel: "% of school"
  }); */

$('.comparison-table table').each(function(){
   $(this).gChartTable( {  
      ySize: "200",
      xSize: "800" ,
      additional: "&chdl=My&nbsp;school|Region",
      xLabel: "Week",
      yLabel: "% of school"
  })
})

$('.graph-national').gChartTable( {  
      chart: "bvg",
      background: "f6f6f6",
      xMax: "12"
  });

}




function hoverMap() {

  $("#region-map area, #region-links ul li a").mouseover(function () {
    var location = $(this).attr("class");
    $("#region-map img").attr("src","./?a=" + location);
  });

  $("#region-map area, #region-links ul li a").mouseout(function () {
    var location = $(this).attr("class");
    $("#region-map img").attr("src","./?a=746");
  });

}; // end of hoverMap()


function resizeMap(map, points) {
  
  var minLong = 999;
  var minLat = 999;
  var maxLong = -999;
  var maxLat = -999;

  // Find the max/min points
  
  for ( var i = 0; i < points.length; i++ ) {
    if ( points[i].x < minLong ) minLong = points[i].x;
    if ( points[i].x > maxLong ) maxLong = points[i].x;
    if ( points[i].y < minLat ) minLat = points[i].y;
    if ( points[i].y > maxLat ) maxLat = points[i].y;
  }
  

  //Define Centre and zoom
  var botLeft = new GLatLng(minLat, minLong);
  var topRight = new GLatLng(maxLat, maxLong);
  var bounds = new GLatLngBounds(botLeft, topRight);
  
  var medLat = ((parseFloat(maxLat) + parseFloat(minLat)) / 2);
  var medLong = ((parseFloat(maxLong) + parseFloat(minLong)) / 2);
  if (i>1){
    map.setCenter(new GLatLng(medLat,medLong),map.getBoundsZoomLevel(bounds));
  }else if(i=1){ 
    map.setCenter(new GLatLng(medLat,medLong),13);
  }
}; // end of resizeMap(map, points)


function initialiseMap() {
  
  //show map div and hide table div
  if ($("div#external-map-data").length > 0) {

    $('div#external-map').show();
    $('div#external-map-data').addClass('access');
    var points = [];
    if (GBrowserIsCompatible()) {

      // Initialise Google map
      var map = new GMap2(document.getElementById("external-map"));

      // Set the map center and add controls
      map.setCenter(new GLatLng(-42.000000, 172.646078), 5, G_NORMAL_MAP);
      map.addControl(new GSmallMapControl());
      map.addControl(new GMapTypeControl());

      // Define the look of the marker
      var baseIcon = new GIcon(G_DEFAULT_ICON);
      baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
      baseIcon.iconSize = new GSize(20, 34);
      baseIcon.shadowSize = new GSize(37, 34);
      baseIcon.iconAnchor = new GPoint(9, 34);
      baseIcon.infoWindowAnchor = new GPoint(9, 2);

      // Get table data and convert to Google Map Points
      $('div#external-map-data tr').next().each(function(){

        var schoolInfo = [];
        $(this).children('td').each(function(i){
            schoolInfo[i] = $(this).text();          
        });

        var latlng = new GLatLng(schoolInfo[1], schoolInfo[2]);
        map.addOverlay(createMarker(latlng, schoolInfo[0], schoolInfo[3]));

      });

      if ($('div#external-map-data tr').length > 1){ 
        resizeMap( map, points );
      }
    }
  } else {
  
    // hide the text about adding stories for schools in this region
    $("div[class*='stories-from-this-region']").addClass("no-schools");
    
  }

  // Create Marker function
  function createMarker(point, schoolName, schoolURL) {

    var schoolName = schoolName;
    var schoolURL = schoolURL;
    var markerHTML;
    var marker = new GMarker(point);
    points.push (point);

    GEvent.addListener(marker, "click", function() {
      if (schoolURL.length > 0) {
        markerHTML = '<strong>' + schoolName + '</strong><br /><a href="' + schoolURL + '"><strong>Visit our site</strong></a>';
      } else {
        markerHTML = '<strong>' + schoolName + '</strong><br />';
      }
      marker.openInfoWindowHtml(markerHTML);
    });

    return marker;
  } // end of createMarker()


}; // end of initialiseMap()


function iePngFix() {
  
  if($.browser.msie && (jQuery.browser.version <= 6.0)) {
    $('img[@src$=.png], #content-wrap, .content-secondary-area div, .nav-pri-list li a, .nav-pri-list li').ifixpng('http://feetfirst.squiz.co.nz/__data/assets/image/0017/746/pixel.gif');
  }
}; // end of iePngFix()




function getAndValidateSchoolNameFromSchoolNumberForSchoolRegistration() {

  $("#school-registration #metadata_field_text_78_value").change(function() {

    // reset imput field values
    $("#backend_user_0_287").attr({value:""});  // name
    $("#metadata_field_text_823_value").attr({value:""}); // region
    $("#metadata_field_text_844_value").attr({value:""});  // latitude
    $("#metadata_field_text_845_value").attr({value:""});  // longitude
    $("#isASchoolNumber").attr({value: ""});
    $("#schoolRegistered").attr({value: "No school yet"});

    // check if field contains any data
    if ($(this).attr("value") != "") {

      var schoolID = $(this).val();

      $("#school-details").load("/js-content/get-school-details?number=" + schoolID, {} ,function() {

        // if school exists, check to see if it is already regisitered
        if ($("#school-details span.school-name").text() != "") {

          $("#isASchoolNumber").attr({value: "School exists"});
          $("#schoolRegistered").attr({value: "No school yet"});
          $("#valid-school").load("/js-content/school-registered?SchoolID=" + schoolID, {}, function() {
            if ($("#valid-school").text() == "0") {
              $("#schoolRegistered").attr({value: "School not registered"});
            } else {
              $("#schoolRegistered").attr({value:""});          
            }

          // trigger validation on field
            $("#page_account_manager_54").validate().element( "#schoolRegistered" );

          });

          // populate school details fields
          $("#backend_user_0_287").attr({value: $("#school-details span.school-name").text()});  // name
          $("#metadata_field_text_823_value").attr({value: $("#school-details span.school-region").text()});  // region
          $("#metadata_field_text_844_value").attr({value: $("#school-details span.school-latitude").text()});  // latitude
          $("#metadata_field_text_845_value").attr({value: $("#school-details span.school-longitude").text()});  // longitude

        }      

        // trigger validation on fields
        $("#page_account_manager_54").validate().element( "#schoolRegistered" );
        $("#page_account_manager_54").validate().element( "#isASchoolNumber" );

      });
      
    } else {

      // trigger validation on fields
      $("#page_account_manager_54").validate().element( "#schoolRegistered" );
      $("#page_account_manager_54").validate().element( "#isASchoolNumber" );
    
    }
  
  });

}; // end of getAndValidateSchoolNameFromSchoolNumberForSchoolRegistration()


function hideAndAutoPopulateSchoolRegistrationInputFields() {

  // Hide username field and populate it automatically from the email address field.
  $("#school-registration #username").hide();

  $("#school-registration #email-address input").change(function() {
    var schoolName = $(this).val();
    $("#school-registration #username input").val(schoolName);
  });

}; // end of hideAndAutoPopulateSchoolRegistrationInputFields()


function hideAndAutoPopulateNonSchoolRegistrationInputFields() {

  // Hide username field and populate it automatically from the email address field.
  $("#ta-registration #username").hide();

  $("#ta-registration #email-address input").change(function() {
    var schoolName = $(this).val();
    $("#ta-registration #username input").val(schoolName);
  });

}; // end of hideAndAutoPopulateNonSchoolRegistrationInputFields()


function validateSchoolRegistrationForm() {

  $("#page_account_manager_54").validate({
    rules: {

      // School Number
      metadata_field_text_78_value: {
        required: true,
        digits: true
      },

      // Is a school number
      isASchoolNumber: {
        required: true
      },

      // Registered School
      schoolRegistered: {
        required: true
      },

      // School Representative
      metadata_field_text_91_value: {
        required: true
      },

      // Blog URL
      metadata_field_text_366_value: {
        url: true
      },

      // Email address
      backend_user_0_286: {
        required: true,
        email: true
      },

      // Username
      backend_user_0_292: {
        required: true
      },
      
      // Password
      backend_user_0_290_one: {
        required: true,
        minlength: 6
      },

      // Re-enter password
      backend_user_0_290_two: {
        equalTo: "#backend_user_0_290_one",
        required: true,
        minlength: 6
      }
    },

   messages: {

      isASchoolNumber: "School number is not a valid school",
      schoolRegistered: "This school has already been registered"

   }

  });

}; // end of validateSchoolRegistrationForm()



function validateNonSchoolRegistrationForm() {

  $("#page_account_manager_311").validate({
    rules: {

      // TA Name
      backend_user_0_287: {
        required: true
      },

      // TA Representative
      metadata_field_text_330_value: {
        required: true
      },

      // Email address
      backend_user_0_292: {
        required: true,
        email: true
      },

      // Username
      backend_user_0_286: {
        required: true
      },
      
      // Password
      backend_user_0_290_one: {
        required: true,
        minlength: 6
      },

      // Re-enter password
      backend_user_0_290_two: {
        equalTo: "#backend_user_0_290_one",
        required: true,
        minlength: 6
      }
    },

   messages: {

      isASchoolNumber: "School number is not a valid school",
      schoolRegistered: "This school has already been registered"

   }

  });

}; // end of validateNonSchoolRegistrationForm()



function stopMatrixSchoolRegistrationFormSubmission() {

  $("#page_account_manager_54").removeAttr("onsubmit");

}; // end of stopMatrixSchoolRegistrationFormSubmission()



function stopMatrixNonSchoolRegistrationFormSubmission() {

  $("#page_account_manager_311").removeAttr("onsubmit");

}; // end of stopMatrixNonSchoolRegistrationFormSubmission()



function walkingDataInputFormControls() {

  // disable input fields which are in the future
  $("#input .term input").each(function() {
    var labelDate = $(this).prev('label').find('span.week-commencing').text();
    var labelDay = labelDate.substr(0,2);
    var labelMonth = labelDate.substr(3,2) - 1;
    var labelYear = labelDate.substr(6,4);

    var weekCommencing = new Date();
    weekCommencing.setFullYear(labelYear,labelMonth,labelDay);
    
    var currentDate = new Date();
    if (weekCommencing > currentDate) {
      $(this).addClass("read-only");
    }
  });

  $('.read-only').attr("disabled", true);

}; // end of walkingDataInputFormControls()



function showCorrectTermDatesForSelectedTab() {

  // initially hide all term dates apart from term 1
  $("#term2-dates, #term3-dates, #term4-dates").hide();

  // show corresponding term dates for whichever tab is being displayed
  $("#term1-tab").click(function() {
    $("#term2-dates, #term3-dates, #term4-dates").hide();
    $("#term1-dates").show();
  });
  $("#term2-tab").click(function() {
    $("#term1-dates, #term3-dates, #term4-dates").hide();
    $("#term2-dates").show();
  });
  $("#term3-tab").click(function() {
    $("#term1-dates, #term2-dates, #term4-dates").hide();
    $("#term3-dates").show();
  });
  $("#term4-tab").click(function() {
    $("#term1-dates, #term2-dates, #term3-dates").hide();
    $("#term4-dates").show();
  });

}; // end of showCorrectTermDatesForSelectedTab()

//selects right term and locks editing for previous term entry data
function dateHelper(){
	
	var months = { // array of month as they appear in table
		1: "Jan",
		2: "Feb",
		3: "Mar",
		4: "Apr",
		5: "May",
		6: "Jun",
		7: "Jul",
		8: "Aug",
		9: "Sep",
		10: "Oct",
		11: "Nov",
		12: "Dec"
	}
	
	var currentDate = new Date(); // get current Date
	var currentMonth = currentDate.getMonth() + 1;
	var currentDay = currentDate.getDate();
	
	//process each table to find current term
	$('div[id^="term"][id$="-dates"] table').each(function(o){
	    o++;
		var start = $(this).find('tr:eq(2) td[class!="week"]').text();
		var end = $(this).find('tr:last td:last').text();
		start = start.substr(0, start.indexOf(" -"));
		end = end.substr(end.lastIndexOf("- ") + 2, end.length);
		var startMonth = start.substr(start.indexOf(" ") + 1, start.length);
		var startDate = start.substr(0, start.indexOf(" "));
		var endMonth = end.substr(end.indexOf(" ") + 1, end.length);
		var endDate = end.substr(0, end.indexOf(" "));
		for(i=1;i<=12;i++){
			if(months[i] == startMonth){
				startMonth = i;
			}
			if(months[i] == endMonth){
				endMonth = i;
			}
			
		}
		
		var termStartDate = new Date();
		termStartDate.setDate(startDate);
		termStartDate.setMonth(startMonth);
		
		var termEndDate = new Date();
		termEndDate.setDate(endDate);
		termEndDate.setMonth(endMonth);
		
		//bind click functions on previous terms
		function bindEvent(){ //unbinding first to ensure its only bound once
			$('input.disabled').unbind("click").bind("click", function(){
				var confirmation = confirm('Are you sure you would like to change data from a previous term?')
				if(confirmation){
					$(this).siblings('input').andSelf().removeClass('disabled').unbind("click");
				}
			})
		};
		
		// figure out current term
		if(termStartDate < currentDate && termEndDate < currentDate){
			$('div#term' + o).find('input').addClass("disabled");
			bindEvent();
		} else if (termStartDate < currentDate && termEndDate > currentDate){
		    $('#input ul.ui-tabs-nav li:eq(' + (o - 1) + ') a').click();
		}
		
	})
	
} //dateHelper


function tidyUpSchoolEditProfile() {

  // When editing school profile page, hide cascade metadata checkboxes
  $("#school-edit-profile input[id*='cascade'], #school-edit-profile label[for*='cascade']").hide();
  
  // Remove initial password text from first password field and split password field up into two divs
  $("#school-edit-profile #password input:first").attr({value: ""});

  // Hide username field and populate it automatically from the email address field.
  $("#school-edit-profile #username").hide();
  $("#school-edit-profile #email-address input").change(function() {
    var schoolName = $(this).val();
    $("#school-edit-profile #username input").val(schoolName);
  });

  // Make email address field be 30 characters wide
  $("#school-edit-profile #email-address input, #school-edit-profile #password input").attr({size: "30"});

  // Make cancel and close buttons close the thickbox window
  $("input#cancel, #input#close").click(function() { window.top.tb_remove(); });

  // Make Blog URL field wider
  $("#blog-url input").attr("size", "50");

  // Show password field when change password link clicked
  $("#change-password a").click(function() {
    $("div#password").slideDown();
    $(this).hide();
  });

}; // end of tidyUpSchoolEditProfile()


function validateEditProfileForm(){

  $(".school-edit-profile form").validate({
    rules: {

      // School Representative
      metadata_field_text_91_value: {
        required: true
      },

      // Blog URL
      metadata_field_text_366_value: {
        url: true
      }
    }

  });

  // add rules to elements that we can't specify using their id (as it changes for each asset being edited)

  // Email address
  $("input[id*='_286']").rules("add", {
        required: true,
        email: true
  });

  // Password
  $("input[id*='_290_one']").rules("add", {
        required: function(element) {
           return $("input[id*='_290_one']").attr("value").length > 0
        },
        minlength: 6
  });

      // Re-enter password
  $("input[id*='_290_two']").rules("add", {
        equalTo: "input[id*='_290_one']",
        required: function(element) {
           return $("input[id*='_290_two']").attr("value").length > 0
        },
        minlength: 6
  });

} // end of validateEditProfileForm()


function stopMatrixEditProfileFormSubmission() {

  var abc = $(".school-edit-profile form");
  $(".school-edit-profile form").removeAttr("onsubmit");

}; // end of stopMatrixEditProfileFormSubmission()


function addSaveAndExitFns() {

  // If there is a URL parameter save_and_exit=yes then show message saying that profile has been saved
  var urlParam = $(document).getUrlParam("save_and_exit");
  if (urlParam == "yes") {
    $("input#save, div#password, div#change-password").hide();
    $("div#email-address input, div#school-representative input, div#blog-url input").attr({disabled: "disabled"});
    $("h1").after('<p style="color: red;">Your profile was successfully saved.</p>');
    $("input#cancel").attr("value", "Close");
  };

  // Make Save button add 'save_and_exit=yes' to url so that when Save button is pressed, it will then automatically release locks and go back to showing the non simple edit user profile screen
  $("input#save").click(function () {
    var formAction = $("#main_form").attr("action");
    var alreadySubmitted = formAction.indexOf("save_and_exit=yes");
    if (alreadySubmitted == -1) {
      formAction += "&save_and_exit=yes";
    }
    $("#main_form").attr({action: formAction});
  });

}; // end of addSaveAndExitFns()


function loginPageFns(){

  // Refresh (parent) page when user clicks Close button after logging in
  $("input#close").click(function() {
    parent.location.href="/nested-assets/redirect-after-login/";
  });

  // If the user has logged in, make the 'close' link at the top of the thickbox window trigger the same actions as the main close button on the page
  if ($("p#successful-login").length > 0) {
    parent.$("#TB_closeWindowButton").unbind('click');
    parent.$("#TB_closeWindowButton").click(function() {
      $("input#close").click();
      return false;
    });
  };
  
  $(".do-not-open-in-modal-window").click(function() {
    parent.location.href = $(this).attr("href");
  });

}; // end of loginPageFns()


function fixBreadcrumbs() {

  // rewrite links to /my-region/regional-reports-school so that they now go to /my-region/regional-reports
  $("#nav-breadcrumbs a[href*='regional-reports-school']").attr("href", "/my-region/regional-reports");

} // end of fixBreadcrumbs()


function showSchoolsLink() {

  // first, hide the schools
  $("ul#school-list").hide();

  // make the Show Schools link show or hide the schools
  $("a#show-schools").toggle(
    function () {
      $(this).text("Hide schools");
      $("ul#school-list").slideDown();
    },
    function () {
      $(this).text("Show schools");
      $("ul#school-list").slideUp();
    }
  );

}


function validateSubmitStoryForm() {

  // remove matrix submit event javascript
  $("#form_email_286").removeAttr("onsubmit");

  $("#form_email_286").validate();

  // add rules to elements that we can't specify using their id

  // Name
  $("input#q286_q1").rules("add", {
      required: true
  });

  // Email address
  $("input#q286_q4").rules("add", {
      required: true,
      email: true
  });

  // Story title
  $("input#q286_q2").rules("add", {
      required: true
  });

}


function sitemapFns() {

  // Convert the basic sitemap unordered list into a expandable collapsable list using treeview plugin
  $("#content-inner li").addClass("closed");
  $("#content-inner li a").wrap("<span></span>");
  $("#content-inner > ul").treeview();

} 

/* Book Comp Entry Form */
function populateEntryForm(){

	/* Lets start of with populating the inputs - nice and manual */
	$('#competition-form div#school-name input').attr('value', $('#additional-school-details span#name').text()); //school name
	$('#competition-form div#school-address input').attr('value', $('#additional-school-details span#address1').text() + ', ' + $('#additional-school-details span#address2').text() + ', ' + $('#additional-school-details span#address3').text() + ' ' + $('#additional-school-details span#postcode').text()); //address
	$('#competition-form div#school-phone input').attr('value', $('#additional-school-details span#phone').text()); //phone number
	$('#competition-form div#school-email input').attr('value', $('#additional-school-details span#email').text()); //phone number

	/* Show/Hide of Software used box */
	$('#competition-form div#software-used').hide();
	$('#competition-form div#entry-type input:first').click(function(){
		$('#competition-form div#software-used').slideUp();
		$('#competition-form div#software-used input').attr('value', 'Print entry - No software used');
	})
	$('#competition-form div#entry-type input:last').click(function(){
		$('#competition-form div#software-used input').attr('value', '');
		$('#competition-form div#software-used').slideDown();
	})
	
	/* Conditions of Entry - show only when link is clicked */
	$('#competition-form div#conditions-text').hide();
	$('#competition-form div#conditions label:first').html('I agree with the <a id="conditions-activate" href="#">conditions of entry</a>');
	$('#conditions-activate').click(function(){
		$('#competition-form div#conditions-text').slideDown();
		return false;
	})
}