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

  // initiate the Calendar
  calendar();

  // initiate the resizeText
  resizeText();

  // initiate the Simple Edit Interface
  simpleEdit();

  hideElements();

  formValidation();

  });
})(jQuery);


/*------- Mini calendar ---------*/
function calendar() {

  // Set up calendar if it is present on page.
  if ($("#calendarWrapper").length > 0) {

    /* Ensure the correct date is being highlighted as today */

    // Find out which date is currently highlighted as today
    var calTodayHref = $("#calendarTable td.today a").attr("href");
    if (calTodayHref != undefined) {
      var calTodayDate = calTodayHref.substring(calTodayHref.length - 10, calTodayHref.length);

      // Format today's date into yyyy-mm-dd format
      var today = new Date();

      var todayDate = today.getDate() + "";
      if (todayDate.length == 1) {
        todayDate = "0" + todayDate;
      }

      var todayMonth = today.getMonth() + 1;
      todayMonth += "";
      if (todayMonth.length == 1) {
        todayMonth = "0" + todayMonth;
      }

      var todayFormatted = today.getFullYear() + "-" + todayMonth + "-" + todayDate;

      // If the calendar's "today's" date is not the same as the real today's date then change the date of "today" in the calendar. This is to overcome squid caching issues.
      if (calTodayDate != todayFormatted) {

        // Determine if today is the first of the month. If it isn't then simply remove the class from the old date and add the class to the new date
        if (todayDate != "01") {

          // remove class from today's date
          $("#calendarTable td.today").removeClass("today");

          // add the class "today" to the correct date
          $("#calendarTable td a[href$=" + todayFormatted + "]").parent().addClass("today");

        } else {

          // If today is the fist of the month, reload the calendar from Matrix

          // remove class from today's date
          $("#calendarTable td.today").removeClass("today");

        }

      }
    }

    /* Change links in calendar */

    var correctHref = $("#calendarWrapper a.calendarNavLink").attr("href");
    correctHref = correctHref.substr(0, correctHref.indexOf("?"));

    changeCalendarLinks(correctHref);

  };

}; 
// end of calendar()

var changeCalendarLinks = function(correctHref) {

  // change links in calendar table and calendar month navigation so that their url is correct
  $("#eventsCalendarMonth a, #calendarTable a").each( function() {
    var hrefSuffix = $(this).attr("href");
    hrefSuffix = hrefSuffix.substr(hrefSuffix.indexOf("?"));

    $(this).attr({href: correctHref + hrefSuffix});
  });

  // when clicking on previous/next links, load calendar into page via ajax call
  $("#calendarWrapper a.calendarNavLink").click(function() {

var abc = $(this).attr("href") + "&SQ_PAINT_LAYOUT_NAME=noredirect";

    $.ajax({
      url: $(this).attr("href") + "&SQ_PAINT_LAYOUT_NAME=noredirect",
      async: false,
      success: function(html){
          $("#calendarWrapper").html(html);
          changeCalendarLinks(correctHref);
      }
    });
    return false;
  });

}; 
// end of changeCalendarLinks


/*------- Simple edit tabs ---------*/

function simpleEdit() {
   // Add tabs to simple edit interfaces
   $("#simple-edit-content ul#tabs").tabs();
   
   $('#image_0_use_editor_button').hide();

};

/*---- End Simple edit tabs ------*/


/*------- Hide elements ---------*/
function hideElements() {
   
  // Remove event time when the time hasn't been selected or equal to 12:00am 
   $("ul.events li span.event-time:contains(', 12:00 am - ')").remove();


  // Remove (-) from the event start-date when there is no event end-date
  $('.upcoming-event-date').each(function(){
    var t = $(this).text();    
    if(t.charAt(t.length-2) == "-"){
      $(this).text(t.substring(0, t.length-2))
    };
  })

  // Remove "Where" text when event's location isn't fillout
  $('.upcoming-event-location').each(function(){
   if($(this).text() == "Where: "){
      $(this).remove();
   };    
   
  })

};
/*---- End Hide elements ------*/


/*------- Resize text controls ---------*/
function resizeText() {

  /* requires the jquery.cookie plugin to work */

    var originalFontSize = $("body").css("font-size");

    // if cookie exists, load saved value
    var $cookie_name = "autCurrentFontSize";
    if($.cookie($cookie_name)) {
      var $getSize = $.cookie($cookie_name);
      $("body").css({fontSize : $getSize + ($getSize.indexOf("px")!=-1 ? "" : "px")}); // IE fix for double "pxpx" error
    }

    // Reset Font Size
    $("a.current").click(function(){
      $("section#content").css("font-size", "13px");
      $.cookie($cookie_name, null, { path: '/' });  // delete cookie
    });

     // Decrease Font Size
    $("a.smaller").click(function(){
      var currentFontSize = $("section#content").css("font-size");
      var currentFontSizeNum = parseFloat(currentFontSize, 10);
      var newFontSize = currentFontSizeNum*0.8;
      if (newFontSize, 11) {
        $("section#content").css("font-size", newFontSize);
        $.cookie($cookie_name, newFontSize, { path: '/' });
      }
      return false;
    });

    // Increase Font Size
    $("a.bigger").click(function(){
      var currentFontSize = $("section#content").css("font-size");
      var currentFontSizeNum = parseFloat(currentFontSize, 10);
      var newFontSize = currentFontSizeNum*1.2;
      if (newFontSize, 11) {
        $("section#content").css("font-size", newFontSize);
        $.cookie($cookie_name, newFontSize, { path: '/' });
      }
      return false;
    });

}; 
// end of resizeText

function formValidation() {

  // Remove (--) from the Matrix date select box
  $("select[id^=q2588], select[id^=q2594], select[id^=q2951]").each(function(){
    $(this).find('option:first').attr('value','');
  })

  //$("#q3009_q1_0").attr('validate', 'required:true');

  $.metadata.setType("attr", "validate");

  // Hide label errors when page is loaded
  jQuery(".hidden, .error").hide();

  // If users say No to NZ citizen, they have to answer the permanent resident status question.
  jQuery( jQuery("input[name='q2951:q1']") ).change( function()
  {
     if ( jQuery("input[name='q2951:q1']:checked" ).val() == "0" )
     {
       jQuery("#q2951_q2_0").rules("remove", "required");
     }
     else
     {
       jQuery("#q2951_q2_0").rules("add", "required");
     }
  });

  // If users say No to permanent resident status, they have to anser a current work permist question.
  jQuery( jQuery("input[name='q2951:q2']") ).change( function()
  {
    if ( jQuery("input[name='q2951:q2']:checked" ).val() == "0" )
    {
      jQuery("#q2951_q3_0").rules("remove", "required");
    }
    else
    {
      jQuery("#q2951_q3_0").rules("add", "required");
    }
  });

  // If users say Yes to a current working permit, they have to choose the expiry date of their work permit.
  jQuery( jQuery("input[name='q2951:q3']") ).change( function()
  {
    if ( jQuery("input[name='q2951:q3']:checked" ).val() == "1" )
    {
      jQuery("#q2951\\:q4value\\[d\\]").rules("remove", "required");
      jQuery("#q2951\\:q4value\\[m\\]").rules("remove", "required");
      jQuery("#q2951\\:q4value\\[y\\]").rules("remove", "required");
    }
    else 
    {
      jQuery("#q2951\\:q4value\\[d\\]").rules("add", "required");
      jQuery("#q2951\\:q4value\\[m\\]").rules("add", "required");
      jQuery("#q2951\\:q4value\\[y\\]").rules("add", "required");
    }
  });

  // If users say Yes to Medical condition, they have to provide more details.
  jQuery( jQuery("input[name='q2952:q1']") ).change( function()
  {
    if ( jQuery("input[name='q2952:q1']:checked" ).val() == "0" )
    {
      jQuery("#q2952_q2").rules("add", "required");
    }
    else
    {
      jQuery("#q2952_q2").rules("remove", "required");
    }
  });

   // If users say Yes to Criminal convictions, they have to provide more details.
  jQuery( jQuery("input[name='q2953:q1']") ).change( function()
  {
    if ( jQuery("input[name='q2953:q1']:checked" ).val() == "0" )
    {
      jQuery("#q2953_q2").rules("add", "required");
    }
    else
    {
      jQuery("#q2953_q2").rules("remove", "required");
    }
  });

  // If users say Yes to Criminal convictions, they have to provide more details.
  jQuery( jQuery("input[name='q2980:q2[]']") ).change( function()
  {
    if ( jQuery("input[name='q2980:q2[]']:checked" ).val() == "5" )
    {
      jQuery("#q2980_q3").rules("add", "required");
    }
    else
    {
      jQuery("#q2980_q3").rules("remove", "required");
    }
  });


  // Hide the default form error and place the custom error after each question.
  $("#form_email_2832").validate({
     errorPlacement: function(error, element) 
      {
	error.prependTo(".standardForm");
      },
      rules: {
         q2871_q1: {
                      required: true
                     }
         },
      messages: {
         q2871_q1: "This field is required" 
      }
  });

};
 

/*
addPrintLink function by Roger Johansson, www.456bereastreet.com
*/
var addPrintLink = {
  init:function(sTargetEl,sLinkText) {
    if (!document.getElementById || !document.createTextNode) {return;} // Check for DOM support
    if (!document.getElementById(sTargetEl)) {return;} // Check that the target element actually exists
    if (!window.print) {return;} // Check that the browser supports window.print
    var oTarget = document.getElementById(sTargetEl);
    var oLink = document.createElement('a');
    oLink.id = 'print-link'; // Give the link an id to allow styling
    oLink.href = '#'; // Make the link focusable for keyboard users
    oLink.appendChild(document.createTextNode(sLinkText));
    oLink.onclick = function() {window.print(); return false;} // Return false prevents the browser from following the link and jumping to the top of the page after printing
    oTarget.appendChild(oLink);
  },
/*
addEvent function included here for portability. Replace with your own addEvent function if you use one.
*/
/* addEvent function from http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html */
  addEvent:function(obj, type, fn) {
    if (obj.addEventListener)
      obj.addEventListener(type, fn, false);
    else if (obj.attachEvent) {
      obj["e"+type+fn] = fn;
      obj[type+fn] = function() {obj["e"+type+fn](window.event);}
      obj.attachEvent("on"+type, obj[type+fn]);
    }
  }
};
addPrintLink.addEvent(window, 'load', function(){addPrintLink.init('print','');});
/* End addPrintLink Function */



