/*
 * File 'javascript/js_default.js'.
 *
 * Handles all the default actions that are done on all pages or don't require
 * their own file
 *
 * @copyright  Copyright (c) 2011, Hocking College
 * @version    February 22th, 2011
 * @category   javascript
 */

var strBaseUrl = "/";
var strFullUrl = location.href;

strErrorMessage = "";

$(document).ready( function() { _initDefault() } );

/*
 * Function '_initDefault()' is the class constructor.
 *
 * @access  public
 * @since   February 22th, 2011
 */
function _initDefault()
{
   /*********************
    * IE HACK FOR STYLING
    *********************/
   styleHack();
 
   initVertNav();
   initAccordion();
   //initSendToFriend();   
   
   $(".parentText").click(function() {
      parentTextClick(this);
   });

   $(".collapseImg").click(function(){ 
      collapseImgClick(this);
   });
   
   $(".expandImg").click(function(){
      expandImgClick(this);
   }); 
   
   $('.accordion').on("click", ".accordionLink", function()
   {
      accordionToggle(this);
   });
      
   $(".programs").click(function()
   {
      return programsToggle();
   });
   
   $('#sendToFriendButton').click(function()
   {
      sendToFriendShow();
   });
   
   $('#sendToFriendContent').on("click", '#btnSendToFriendSubmit', function() 
   {
      sendToFriendSubmit();
   });
   
   $('#sendToFriendContent').on("click", "#btnSendToFriendReset", function() 
   {
      sendToFriendReset();
   });
      
   $('.creditSecurityQuestion').click(function()
   {
      creditSecurityQuestion();
   });
   
   $("input").keyup(function()
   {   
      if($(this).val().length == $(this).attr("maxlength"))
      {
         $(this).next("input").focus();
      }
   });
}

/**********************************************************
 * Hack to make IE display alternating background on tables
 * Also reinitalize tables on ajax updates
 **********************************************************/
function styleHack()
{   
   $(".styledTable tr:nth-child(odd)").css({'background': '#CCC'});
   $(".styledTable tr:nth-child(even)").css({'background': '#FFF'});
   $(".searchResults tr:nth-child(odd)").css({'background': '#CCC'});
   $(".searchResults tr:nth-child(even)").css({'background': '#FFF'});
   $(".styledWithHeaders tr:nth-child(odd)").css("background", "#BAC795"); 
   $(".styledWithHeaders tr:nth-child(even)").css("background", "#FFF"); 
}

/*
 * Function 'accordionToggle()' Toggles an accordion link to show or hide the 
 * content of that link
 *
 * @access  public
 * @since   February 22th, 2011
 * @param   object   The link that was clicked
 */
function accordionToggle(obj)
{   
   $(obj).next('.accordionText').toggle();
   $(obj).find(".expand").toggle();
   $(obj).find(".collapse").toggle();
}

/*
 * Function 'changeTerm()' Functionality to change the terms for comparing on 
 * the Enrollment page
 *
 * @access  public
 * @since   February 22th, 2011
 */
function changeTerm()
{
   var strTermOne = $("select[name='ddlFirstTerm']").val();
   var strTermTwo = $("select[name='ddlSecondTerm']").val();
   var strFormKey = $("input[name='txtFormKey']").val();
   $.ajax(
   {
      url: strBaseUrl + 'institutionalresearch/enrollment/getMasterEnrollment',
      type: "POST",
      dataType: "json",
      async: false,
      data: 
      {
         termone : strTermOne,
         termtwo : strTermTwo,
         formkey : strFormKey
      },
      success: function(json) 
      {
         if(json != null && json != "")
         {
            if(json.error == "")
            {
               $('#first').html(json.table_record_one);
               $('#second').html(json.table_record_two);
               $('#difference').html(json.difference);
               $('#percentChange').html(json.percent);
            }
            else
            {
               alert(json.error);
            }
         }
         else
         {
            alert("An error occured please contact the IT department");
         }
      },
      error: function(a, b, c) 
      {
         alert("An error occured please contact the IT department");
      }
   });
}

/*
 * Function 'collapseImgClick()' Handles the expanding and closing of the child 
 * navigation depending on the collapse image that was clicked
 *
 * @access  public
 * @since   February 22th, 2011
 * @param   object   the collapse image that was clicked
 */
function collapseImgClick(obj)
{
   var x = ($(obj).parent());           
   x.parent().find(".child:first").slideDown();
   x.find(".expandImg:first").show(); 
   $(obj).hide();
}

/*
 * Function 'countLetters()' Given a max length and the name of the textarea
 * to check will see how many characters there are and make sure it doesn't
 * pass the max length allowed.
 * 
 * @access  public
 * @since   March 10th, 2011
 * @param   integer  max length allowed
 * @param   string   name of the textarea to check
 * @param   string   id of div to update after checking length
 */
function countLetters(intMaxLength, strTextArea, strId)
{         
   strVal = $("textarea[name='"+strTextArea+"']").val();
   intLetters = strVal.length;
   
   if ( intMaxLength < intLetters )
   {
      $("textarea[name='"+strTextArea+"']").val( strVal.substring(0, intMaxLength) );
      intLetters = intMaxLength;
   }
   strHtml = ""
      + "   <strong>" + (intMaxLength - intLetters) + "</strong> characters left\n"
      + "\n";
   
   $("#"+strId).html(strHtml)
}

/*
 * Function 'creditSecurityQuestion()' Shows the credit card security code
 * example in a lightbox
 *
 * @access  public
 * @since   February 22th, 2011
 */
function creditSecurityQuestion()
{
   $('#question').html('<img src="/application/images/Apply/creditCardSecurityCode.jpg" />');
   lightboxSetup("#question");      
   centerLightbox('#question');   
}

/*
 * Function 'displayError()' Displays an message cause by an error on the server side
 * that needs to be fixed.
 *
 * @access  public
 * @since   February 24th, 2011
 * @param   object   the object of where to display the message
 */
function displayError(obj)
{
   $(obj).html("<ul><li><h3>An error occured please contact the IT department</h3></li></ul>");
   $(obj).show();
}

/*
 * Function 'expandImgClick()' Handles the expanding and closing of the child 
 * navigation depending on the expand image that was clicked
 *
 * @access  public
 * @since   February 22th, 2011
 * @param   object   the expand image that was clicked
 */
function expandImgClick(obj)
{
   var x = ($(obj).parent());   
   x.parent().find(".child").slideUp(); 
   x.parent().find(".expandImg").hide(); 
   x.parent().find(".collapseImg").show(); 
}

/*
 * Function 'initAccordion()' Initialize the accordion to show the links but
 * not the content for it
 *
 * @access  public
 * @since   February 22th, 2011
 * @param   object   The link that was clicked 
 */
function initAccordion()
{   
   $(".accordion").find('.accordionText').hide();
//   $(".accordion").find('div.accordion').show();
}

/*
 * Function 'initSendToFriend()' Initializes the send to friend form so that it
 * displays correctly the first time.
 *
 * @access  public
 * @since   February 22th, 2011
 */
function initSendToFriend()
{
   $.ajax( 
   {
      url : strBaseUrl + "sendtofriend/loadData",
      type : 'POST',
      data : 
      {
         strUrl : strFullUrl
      },
      success : function(data) 
      {
         $('#sendToFriendContent').html(data)
      }
   });
}

/*
 * Function 'initVertNav()' Initialize the vertical navigation
 *
 * @access  public
 * @since   February 22th, 2011
 */
function initVertNav()
{
   $(".parent").find(".child").hide();  
   $(".expandImg").hide();
   $(".collapseImg").show(); 

   $('#currentPortalLink a:first').css('color','#769321');
   $('#currentPortalLink a:first').css('font-weight','bold');

   $('#currentPortalLink').find('div:first').show();
   $('#currentPortalLink').parents('.child').show();
   $('#currentPortalLink').parents('tr').find('.expandImg:first').show();
   $('#currentPortalLink').parents('tr').find('.collapseImg:first').hide();
   $('#currentPortalLink').find('.expandImg:first').show();
   $('#currentPortalLink').find('.collapseImg:first').hide(); 
}
   
/*
 * Function 'lightboxSetup()' Performs all the actions involved with displaying
 * a lightbox to the user
 *
 * @access  public
 * @since   February 22th, 2011
 * @param   object   The object that needs shown within the lightbox
 */
function lightboxSetup(obj)
{
   $('#sendToFriend').hide();
   $('#contentMessage').hide();
   $('#question').hide(); 
   $('#application').hide();
   $('html').css( {
      "overflow-x" : 'hidden'
   });
   $('.overlay').css("height", $(document).height() + "px");
   $('.overlay').css("width", $(document).width() + "px");
   $(obj).show(); 
   $('#popup, .overlay').fadeIn();
}

/*
 * Function 'parentTextClick()' Handles the expanding and closing of the child 
 * navigation depending on the parent text that was clicked
 *
 * @access  public
 * @since   February 22th, 2011
 * @param   object   the text that was clicked
 */
function parentTextClick(obj)
{
   var x = ($(obj).parent()); 
     
   if (x.find(".child:first").is(':hidden'))
   {
      x.find(".child:first").slideDown();   
      x.parent().find(".expandImg:first").show(); 
      x.parent().find(".collapseImg:first").hide();
   }
   else
   {
      x.find(".child").slideUp(); 
      x.parent().find(".collapseImg").show();
      x.parent().find(".expandImg").hide();
   }
}

/*
 * Function 'programsToggle()' Toggles an programs list to show or hide at the 
 * top of every page
 *
 * @access  public
 * @since   February 22th, 2011
 * @param   object   The link that was clicked
 * @return  boolean  return false so the link doesn't work else it will go to 
 *                   programs page instead of dropping down the programs list.
 */
function programsToggle()
{   
   $("#programsContainer").slideToggle();
   return false;
}

/*
 * Function 'sendToFriendReset()' Resets the send to friend form
 *
 * @access  public
 * @since   February 22th, 2011
 */
function sendToFriendReset()
{
   $('#sendToFriendError').hide();
   strErrorMessage = '';
   
   $.ajax( 
   {
      url : strBaseUrl + "sendtofriend/loadData",
      type : 'POST',
      async : false,
      data : 
      {
         "strUrl" : strFullUrl
      },
      success : function(data) 
      {
         $('#sendToFriendContent').html(data);
      }
   });
   centerLightbox('#popup');
}

/*
 * Function 'sendToFriendShow()' When the send to friend button is clicked on
 * the page the form is shown in a lightbox
 *
 * @access  public
 * @since   February 22th, 2011
 */
function sendToFriendShow()
{
   strErrorMessage = '';
   $('#sendToFriendError').hide();
   
   $.ajax( 
   {
      url : strBaseUrl + "sendtofriend/loadData",
      type : 'POST',
      async : false,
      data : 
      {
         strUrl : strFullUrl
      },
      success : function(data) 
      {
         $('#sendToFriendContent').html(data);
      }
   });
   
   lightboxSetup("#sendToFriend");
   centerLightbox('#popup');
}

/*
 * Function 'sendToFriendSubmit()' Validates and does the required actions of
 * sending the form through AJAX.  Updates the form depending on the success
 * of the input and sending of the message.
 *
 * @access  public
 * @since   February 22th, 2011
 */
function sendToFriendSubmit()
{
   $('.formSuccess').hide();
   $('.formError').hide();
   strErrorMessage = validateSendToFriendForm();
   if (strErrorMessage == "") 
   {
      $('#sendToFriendError').hide();
      $.ajax( 
      {
         url : strBaseUrl + "sendtofriend/postData",
         type : 'POST',
         data : 
         {
            "strUrl" : strFullUrl,
            "txtSendToFriendFrom" : $("input[name='txtSendToFriendFrom']").val(),
            "txtSendToFriendName" : $("input[name='txtSendToFriendName']").val(),
            "txtSendToFriendTo" : $("input[name='txtSendToFriendTo']").val(),
            "txtSendToFriendSubject" : $("input[name='txtSendToFriendSubject']").val(),
            "txaSendToFriendMessage" : $("textarea[name='txaSendToFriendMessage']").val(),
            "txtSendFormKey" : $("input[name='txtSendFormKey']").val()
         },
         success : function(data) 
         {
            $('#sendToFriendContent').html(data);
            centerLightbox('#popup');
         }
      });
   } 
   else 
   {
      $('#sendToFriendError').html("<ul>" + strErrorMessage + "</ul>");
      $('#sendToFriendError').show();
   }
   centerLightbox('#popup');
}

/*
 * Function 'setBaseUrl()' Sets the base url to use mainly with ajax calls to
 * know the baseurl of the site its on
 *
 * @access  public
 * @since   February 22th, 2011
 * @param   string   the base url of the current site
 */
function setBaseUrl(baseUrl)
{
   strBaseUrl = baseUrl;
}

/*
 * Function 'validateEmail()' Validates an email meets our standards for being a
 * real email address
 *
 * @access  public
 * @since   February 22th, 2011
 * @param   string   The email to check
 * @return  boolean  true if passed false if not
 */
function validateEmail(strEmail)
{
   var regexp = /^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,6}))$/;
   
   if (strEmail.match(regexp) == null)
   {
      return false;
   }
   else 
   {
      return true;
   }     
}

function validatePhone( strPhoneNumber )
{
   var regexp = /^(1)?(-|\.|\s)?(\()?(\d{3})(\))?(-|\.|\s)?(\d{3})(-|\.|\s)?(\d{4})(\s)?((x|X)(\.)?(\s)?)?((e|E)(x|X)(t|T)(\.)?(\s)?)?(\d*)?$/;
   
   var result = strPhoneNumber.match( regexp );
   
   if ( result == null )
   {
      return false;
   }
   else 
   {
      return true;
   }
}

function formatPhoneNumber( strPhoneNumber )
{
   var regexp = /^(1)?(-|\.|\s)?(\()?(\d{3})(\))?(-|\.|\s)?(\d{3})(-|\.|\s)?(\d{4})(\s)?((x|X)(\.)?(\s)?)?((e|E)(x|X)(t|T)(\.)?(\s)?)?(\d*)?$/;
   
   var result = strPhoneNumber.match( regexp );
   
   if ( result == null )
   {
      return false;
   }
   else 
   {
      return result[1] + " (" + result[4] + ") " + result[7] + "-" + result[9] + " x." + result[21];
   }
}

/*
 * Function 'validateSendToFriendForm()' Validates the inputs received from the
 * send to friend popup form
 *
 * @access  public
 * @since   February 22th, 2011
 * @return  string   string containing the error message if any
 */
function validateSendToFriendForm()
{
   strErrorMessage = "";
   with(document.sendToFriendForm)
   {
      strFrom = txtSendToFriendFrom.value;
      strName = txtSendToFriendName.value;
      strTo = txtSendToFriendTo.value;
      strSubject = txtSendToFriendSubject.value;
      //strMessage = txaSendToFriendMessage.value;

      if(strFrom == "")
      {
         txtSendToFriendFrom.style.background="pink";
         strErrorMessage += "<li>From email is Required.</li>";         
      }
      else if (!validateEmail(strFrom))
      {
         txtSendToFriendFrom.style.background="pink";
         strErrorMessage += "<li>From email is in Incorrect Format.</li>";
      }
      else
      {
         txtSendToFriendFrom.style.background="white";
      }
      if (strName == "")
      {
         txtSendToFriendName.style.background="pink";
         strErrorMessage += "<li>Name is Required.</li>";
      }
      else
      {
         txtSendToFriendName.style.background="white";
      }
      if(strTo == "")
      {
         txtSendToFriendTo.style.background="pink";
         strErrorMessage += "<li>To email is Required.</li>";
      }
      else if (!validateEmail(strTo))
      {
         txtSendToFriendTo.style.background="pink";
         strErrorMessage += "<li>To email is in Incorrect Format.</li>";
      }
      else
      {
         txtSendToFriendTo.style.background="white";
      }
      if (strSubject == "")
      {
         txtSendToFriendSubject.style.background="pink";
         strErrorMessage += "<li>Subject is Required.</li>";
      }
      else
      {
         txtSendToFriendSubject.style.background="white";
      }
   }
   return strErrorMessage; 
}

