/**
 * @file custom.js
 **/
//-----------------------------------------------------------------------------------------------------//
// Random Hero Message and Navigation
//-----------------------------------------------------------------------------------------------------//
$(document).ready(function heroMessages(){

// count available messages and gnerate random starting point
var heroMessages = $('#messages div.heromsg');
var messageTotal = heroMessages.length;
var messageStart = Math.ceil(messageTotal*Math.random());
//var messageStart = 1;

// Hide all divs
heroMessages.hide(); 

//When any link is clicked
$('#messages ul li a').click(function(){

// Set variable currentMsg href value, and get numeric id 
var currentMsg = $(this).attr('href'); 
var currentMsgId = currentMsg.match(/[\d]+/g);

// compute the id of the previous message and generate href for 'previous' button
var prevMsgId = (currentMsgId>1)?(parseInt(currentMsgId)-1):messageTotal; 
var prevMsgHref = '#messages-'+prevMsgId;

// compute the id of the next message and generate href for 'next' button
var nextMsgId = (currentMsgId<messageTotal)?(parseInt(currentMsgId)+1):1;
var nextMsgHref = '#messages-'+nextMsgId;

heroMessages.hide();
$(currentMsg).show();

// apply sIFR
sIFR.replace(fruitiger, {
     selector: '#messages div.heromsg h1',
     css: '.sIFR-root {color: #ffffff; font-size: 31px;letter-spacing:-.1; font-weight:bold;}',
     ratios: [6, 1.53, 8, 1.43, 11, 1.31, 15, 1.29, 25, 1.25, 33, 1.23, 43, 1.22, 61, 1.21, 91, 1.2, 92, 1.19, 107, 1.2, 108, 1.19, 110, 1.2, 113, 1.19, 115, 1.2, 119, 1.19, 120, 1.2, 121, 1.19, 122, 1.2, 124, 1.19, 1.2],
     offsetTop: '-3px',
     tuneHeight: '-7px'
   });
sIFR.replace(fruitiger, {
  selector: '#messages div.heromsg h4',
  css: '.sIFR-root {color: #ffffff; font-size: 20px;letter-spacing: -.25; offsetTop:-3; font-weight:bold;}',
  ratios: [8, 1.41, 11, 1.31, 15, 1.29, 25, 1.25, 33, 1.23, 43, 1.22, 61, 1.21, 91, 1.2, 92, 1.19, 107, 1.2, 108, 1.19, 110, 1.2, 113, 1.19, 115, 1.2, 119, 1.19, 120, 1.2, 121, 1.19, 122, 1.2, 124, 1.19, 1.2],  
  tuneHeight: '-2px'  
});

// update navigation
$('#messages ul li #currentMsg').text(currentMsgId.toString());
$('#messages ul li:first a').attr('href',prevMsgHref); // Set the class of the first link to the previous message id
$('#messages ul li:last a').attr('href',nextMsgHref); // Set the class of the first link to the previous message id

return false;

});

//show first message 
$('#messages div#messages-'+messageStart).show();
$('#messages ul li #currentMsg').text(messageStart);

// compute the id of the previous message and generate href for 'previous' button
var prevMsgId = (messageStart>1)?(parseInt(messageStart)-1):messageTotal; 
var prevMsgHref = '#messages-'+prevMsgId;

// compute the id of the next message and generate href for 'next' button
var nextMsgId = (messageStart<messageTotal)?(parseInt(messageStart)+1):1;
var nextMsgHref = '#messages-'+nextMsgId;

// update links
$('#messages ul li:first a').attr('href',prevMsgHref); // Set the class of the first link to the previous message id
$('#messages ul li:last a').attr('href',nextMsgHref); // Set the class of the first link to the previous message id

});

//-----------------------------------------------------------------------------------------------------//
// Email Support Toggle
// Implemtation 
// 1. <input id="YOURID" class="addemailsupport" /> <div id="YOURID_toggle"></div>
// 2. <a href="#YOURID"></a> <div id="YOURID"></div>
//-----------------------------------------------------------------------------------------------------//
$(document).ready(function addEmailSupport() {
 /* Initialize
 -------------------------------------------*/
 /**
  * @method init
  **/
 this.init = function init() {
  this.checkbox = $('input.addemailsupport');
  //-------------------------------//
  // 1. Validate
  if(this.checkbox.length == 0)
  {
   return;
  }
  
  //-------------------------------//
  // 2. Listen to checkbox triggers
  this.checkbox.toggle('click', true, '_toggle');
 };
 
 /* Call the initializer
 -------------------------------------------*/
 var _this = this;
 this.init(); 
});
//-----------------------------------------------------------------------------------------------------//
// Check User Implementation
// Implemtation <a href="#YOURID" class="checkuser"></a><input id="YOURID" />
//-----------------------------------------------------------------------------------------------------//
$(document).ready(function checkUser() {
 /* Properties
 -------------------------------------------*/
 this.url = '/ajax/check-username/?check=';
 
 /* Initialize
 -------------------------------------------*/
 /**
  * @method init
  **/
 this.init = function init() {
  this.checkuser = $('a.checkuser');
  //-------------------------------//
  // 1. Validate
  if(this.checkuser.length == 0)
  {
   return;
  }
  
  //-------------------------------//
  // 2. Listen to checkuser triggers
  this.checkuser.click(this.checkUserRequest);
 };
 
 /* Methods
 -------------------------------------------*/
 /**
  * @method checkUserRequest
  **/
 this.checkUserRequest = function checkUserRequest(e) {
  e.preventDefault();
  var target = $(e.target);
  var value = $(target.attr('href')).attr('value');
  $.getJSON(_this.url+value, function(data) {return _this.checkUserResponse(data, target);});
 };
 
 /**
  * @method checkUserResponse
  **/
 this.checkUserResponse = function checkUserResponse(data, target) {
  var clss = !data.exists ? 'success' : 'error';
  var html = $('<span class="'+clss+'">'+data.message+'</span>');
  if(target.parent().find('span').length > 0)
  {
    target.parent().find('span').replaceWith(html);
  }
  else
  {
   target.parent().append(html);
  }
 };
 
 /* Call the initializer
 -------------------------------------------*/
 var _this = this;
 this.init(); 
});
//-----------------------------------------------------------------------------------------------------//
// Tooltip Implementation
// Implemtation <a href="#YOURID" class="tooltip"></a><div id="YOURID" class="tooltip_box" />
//-----------------------------------------------------------------------------------------------------//
$(document).ready(function tooltip() {
 /* Initialize
 -------------------------------------------*/
 /**
  * @method init
  **/
 this.init = function init() {
  var tooltip = $('a.tooltip');
  //-------------------------------//
  // 1. Validate
  if(tooltip.length == 0)
  {
   return;
  }
  
  //-------------------------------//
  // 2. Listen to tooltip triggers
  tooltip.hover(this.show, this.hide);
 };
 
 /* Methods
 -------------------------------------------*/
 /**
  * @method show
  **/
 this.show = function show(e) {
  //notes: e.target tested in -
  //IE6, IE7, FF2, FF3, Safari, Opera, Chrome
  var trigger = $(e.target);
  var target = $(trigger.attr('href'));
  
  //create an iframe
  if(!_this.iFrame)
  {
   _this.iFrame = $('<iframe id="ieFormFix" frameborder="0"></iframe>');
   $(document.body).append(_this.iFrame);
  }
  
  //calculate the top and left
  var position = trigger.getPosition();
  var top = trigger.height() + position[1];
  var left = position[0];
  
  if(target.parent().get(0).tagName != 'BODY')
  {
   //get the tooltip box and show it
   target.css({
    position: 'absolute',
    top: top,
    left: left,
    background: 'transparent'
   });
   
   //append to body
   $(document.body).append(target);
   
   target.removeClass('hide');

   //apply sifr
   sIFR.replace(fruitiger, {
     selector: '.tooltip_box h3',
     css: '.sIFR-root {color: #e47911; font-size: 18px; font-weight:bold;}'
   });
  }
  else
  {
   //either way we should remove this class
   target.removeClass('hide');
  }
  
  //get the tooltip box and show it
  _this.iFrame.css({
   position: 'absolute',
   top: top,
   left: left,
   width: target.width(),
   height: target.height(),
   border: 0
  });
  _this.iFrame.removeClass('hide');
 };
 
 /**
  * @method hide
  **/
 this.hide = function hide(e) {
  var id = $(e.target).attr('href');
  $(id).addClass('hide');
  _this.iFrame.addClass('hide');
 };
 
 /* Call the initializer
 -------------------------------------------*/
 var _this = this;
 this.init(); 
});
//-----------------------------------------------------------------------------------------------------//
// Light Box Implementation
// Implemtation <a href="#YOURID"></a><div id="YOURID" class="lighBox" />
//-----------------------------------------------------------------------------------------------------//
$(document).ready(function lightBox() { 
 /* Initialize
 -------------------------------------------*/
 /**
  * @method init
  **/
 this.init = function init() {
  var boxes = $('div.lightBox');
  var modal = $('div.lightBack');
  
  //-------------------------------//
  // 1. Validate
  if(boxes.length == 0 || modal.length == 0)
  {
   return;
  }
  
  //-------------------------------//
  // 2. Set the boxes
  this.boxes = this.setBox(boxes).each(this.setTrigger);
  this.boxes.find('.close').bind('click', this.hide);
  
  //-------------------------------//
  // 3. Set the modal
  this.modal = this.setModal(modal).bind('click', this.hide);
  
  //-------------------------------//
  // 4. Listen to Window Resize
  $(window).bind('resize', this.adjust);
  //flash woes
  //$(window).bind('scroll', this.adjust);
  
  //-------------------------------//
  // 5. Hide Everything
  this.hide();
 };
 
 /* Private Methods
 -------------------------------------------*/
 /**
  * @method hide
  **/
 this.hide = function hide() {
  //add hide class
  _this.modal.addClass('hide');
  _this.boxes.addClass('hide');
 };
 
 /**
  * @method show
  **/
 this.show = function show(e) {
  e.preventDefault()
  //notes: e.target tested in -
  //IE6, IE7, FF2, FF3, Safari, Opera, Chrome
  var trigger = $(e.target);
  var box = $(trigger.attr('href'));
  
  box.removeClass('hide');
  
  var center = jQuery.getWindowCenter();
  var offset = jQuery.getOffset();
  
  var height = box.height();
  var width = box.width();
  
  
  //set the lightbox
  box.css({
   top  : offset[1] + center[1] - (height / 2),
   left : offset[0] + center[0] - (width / 2)
  });//.find('div.flash-demo object').get(0).StopPlay();
  //set the modal
  _this.modal.removeClass('hide').css({height: jQuery.getPageSize()[1]});
      
  if(trigger.attr('href').indexOf('sys2')!=-1)
  {
    window.document.fChk.Rewind();
    window.document.fChk.Play();
  }
  
  //run sIFR
  if(!box.data('sIFR'))
  {
   //apply sifr
   sIFR.replace(fruitiger, {
     selector: 'h3',
     css: '.sIFR-root {color: #e47911; font-size: 18px; font-weight:bold;}'
   });
   
   box.data('sIFR', true);
  }
 };
 
 /**
  * @method adjust
  **/
 this.adjust = function adjust() {
  var center = jQuery.getWindowCenter();
  var offset = jQuery.getOffset();
  
  _this.boxes.each(function adjust_each_box() {
   var box = $(this);
   var height = box.height();
   var width = box.width();
   
   //set the lightbox
   box.css({
    top   : offset[1] + center[1] - (height / 2),
    left  : offset[0] + center[0] - (width / 2)
   });
  });
  
  //set the modal
  _this.modal.css({height: jQuery.getPageSize()[1]});
 };
 
 /**
  * @method setBox
  **/
 this.setBox = function setBox(box) {
  box = $(box);
  
  box.css({
   zIndex  : 5,
   position : 'absolute',
   opacity: 100
  }).data('sIFR', false);
  
  return box;
 };
 
 /**
  * @method setModal
  **/
 this.setModal = function setModal(modal) {
  modal = $(modal);
  
  modal.bind('click', this.hide).css({
   width  : '100%',
   zIndex  : 4,
   position : 'absolute',
   top   : 0,
   left  : 0,
   background : '#000',
   opacity  : '.4',
   filter  : 'alpha(opacity=40)'});
  
  return modal;
 };
 
 /**
  * @method setTrigger
  **/
 this.setTrigger = function setTrigger() {
  return $("a." + $(this).attr('id') + "-open").bind('click', _this.show);
 };
 
 /* Call the initializer
 -------------------------------------------*/
 var _this = this;
 this.init(); 
});
//-----------------------------------------------------------------------------------------------------//
// Assign Learners Implementation
//-----------------------------------------------------------------------------------------------------//
$(document).ready(function assignLearners() { 
 /* Initialize
 -------------------------------------------*/
 /**
  * @method init
  **/
 this.init = function init() {
  var fielNode = $('select.learner_select');
  var formNode = $('div.learner_form');
  var linkNode = $('a.learner_form_btn');
  //-------------------------------//
  // 1. Validate
  if(fielNode.length == 0 || formNode.length == 0 || linkNode.length == 0)
  {
   return;
  }
  
  
  //-------------------------------//
  // 2. Setup Learner Select
  this.learners = fielNode.change(this.adjustChoices);
  
  //-------------------------------//
  // 3. Hide all the forms
  formNode.hide();
  
  //-------------------------------//
  // 4. Setup New Learner Button
  linkNode.click(this.showForm);
 };
 
 /* Private Methods
 -------------------------------------------*/
 /**
  * @method hide
  **/
 this.adjustChoices = function adjustChoices(e) {
  var options = {};
  _this.learners.find('option').each(function setOptions() {
   if(this.value != 0 && this.selected)
   {
    options[this.value] = true;
   }
   else if(this.value != 0 && options[this.value] != true)
   {
    options[this.value] = false;
   }
  }).removeClass('hide').each(function makeAdjustments() {
   if(!this.selected && options[this.value])
   {
    $(this).addClass('hide')
   }
  });
 };
 
 /**
  * @method showForm
  **/
 this.showForm = function showForm(e) {
  e.preventDefault();
  $(this).parent().hide();
  var selector = $(this).attr('href');
  $(selector).show();
 };
 
 /* Call the initializer
 -------------------------------------------*/
 var _this = this;
 this.init(); 
});

//-----------------------------------------------------------------------------------------------------//
// Show Faq Implementation
//-----------------------------------------------------------------------------------------------------//
$(document).ready(function showFaq(){
 /* Initialize
  -------------------------------------------*/
 /**
  * @method init
  **/
this.init = function init() {
var detailNode = $('div.accordionize a ~ p, dl.accordionize dd');
var linkNode  = $('div.accordionize a.faq');
var spanNode = $('dl.accordionize dt span');
if(detailNode.length == 0)
{
return;
}
detailNode.hide();
linkNode.click(this.linkToggle);
spanNode.click(this.spanToggle);
};
/* Methods
-------------------------------------------*/
/**
* @method linkToggle
**/
this.linkToggle = function linkToggle() {
  if($(this).next().hasClass('selected')){
    $(this).removeClass('selected').next().hide().removeClass('selected');
  }
  else {
    $(this).addClass('selected').next().show().addClass('selected');
  }
};
/**
 * @method spanToggle
 **/
this.spanToggle = function spanToggle() {
if($(this).parent('dt').next('dd').hasClass('selected')){
    $(this).parent('dt').removeClass('selected').next('dd').hide().removeClass('selected');
}
else {
   $(this).parent('dt').addClass('selected').next('dd').show().addClass('selected');
}
}
/* Call the initializer
-------------------------------------------*/
var _this = this;
this.init();
});


//-----------------------------------------------------------------------------------------------------//
// Show Faq Flag Implementation
// Implementation http://brainspark.com/faq/?f=YOURFLAG <div class="YOURFLAG" />
//-----------------------------------------------------------------------------------------------------//
$(document).ready(function faqShowFlag() {
 /* Initialize
 -------------------------------------------*/
 /**
  * @method init
  **/
 this.init = function init(flag) {
  var span = $('dl.accordionize dt span');
  var dd = $('dl.accordionize dd');
  //-------------------------------//
  // 1. Validate
  if(span.length == 0 || dd.length == 0)
  {
   return;
  }
  
  //-------------------------------//
  // 2. Get the flag value
  this.name = this.getUrlParam(flag);
  this.anchor = this.getUrlAnchor();
  
  //-------------------------------//
  // 3. Look in the faq for nodes 
  //  with this class and trigger 
  //  the click
  span.each(this.triggerFlag);
  dd.each(this.triggerDetail);
 };
 
 /* Private Methods
 -------------------------------------------*/
 /**
  * @method triggerFlag
  **/
 this.triggerFlag = function triggerFlag() {
 el = $(this);
 if(el.hasClass(_this.name) || this.parentNode.id == _this.anchor)
 {
 $(this).parent('dt').addClass('selected').next('dd').show().addClass('selected').focus();
 }
 };

 /**
  * @method triggerDetail
  **/
this.triggerDetail = function triggerDetail() {
el = $(this);
if(this.id == _this.anchor)
{
$(this).addClass('selected').show().previous('dt').addClass('selected').focus();
}
};
 
 /**
  * @method getUrlParam
  **/
this.getUrlParam = function getUrlParam( name ) {
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
{
return null;
}
else
{
return results[1];
}
};
this.getUrlAnchor = function getUrlAnchor() {
return window.location.href.split('#')[1];
};

 
 /* Call the initializer
 -------------------------------------------*/
 var _this = this;
 this.init('f');
});

//-----------------------------------------------------------------------------------------------------//
// Home Page Hero Image Change Implementation
//-----------------------------------------------------------------------------------------------------//
$(document).ready(function heroImage(){
 /* Properties
 -------------------------------------------*/
 this.heroImage = ['grass', 'head-touch'];
 
 /* Initialize
 -------------------------------------------*/
 /**
  * @method init
  **/
 this.init = function init() {
  var img = $('.home div#hero div.img');
  if(img.length == 0)
  {
   return;
  }
  img.each(this.change);
 };
  
 /* Methods
 -------------------------------------------*/
 /**
  * @method change
  **/
 this.change = function change() {
  var heroClass = _this.heroImage[Math.floor(Math.random() * _this.heroImage.length)];
  $(this).addClass(heroClass);
 };
 
 /* Call the initializer
 -------------------------------------------*/
 var _this = this;
 this.init();
});

//-----------------------------------------------------------------------------------------------------//
// Extend jQuery Core
//-----------------------------------------------------------------------------------------------------//
/**
 * @note Extend the jQuery methods
 **/
jQuery.extend({
 /**
  * Get the page size
  **/
 getPageSize: function getPageSize() {
  var windowSize = this.getWindowSize();
  var scrollHeight = (document.compatMode != 'CSS1Compat') ? document.body.scrollHeight : document.documentElement.scrollHeight;
  var scrollWidth = (document.compatMode != 'CSS1Compat') ? document.body.scrollWidth : document.documentElement.scrollWidth;
  return [Math.max(scrollWidth, windowSize[0]), Math.max(scrollHeight,windowSize[1])];
 },
 
 /*
  * Get the browser's view port
  * by: Andy Langton 
  * http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/
  */
 getWindowSize: function getWindowSize() {
  // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
  if (typeof window.innerWidth != 'undefined')
  {
   return [window.innerWidth, window.innerHeight];
  }
   
  // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
  if (typeof document.documentElement != 'undefined' && 
   typeof document.documentElement.clientWidth != 'undefined' && 
   document.documentElement.clientWidth !== 0)
  {
   return [document.documentElement.clientWidth, document.documentElement.clientHeight];
  }
   
   // older versions of IE
  return [document.getElementsByTagName('body')[0].clientWidth, document.getElementsByTagName('body')[0].clientHeight];
 },
 
 /*
  * Get center view of port
  */
 getWindowCenter: function getWindowCenter() {
  var viewport = this.getWindowSize();
  return [Math.round(viewport[0] / 2), Math.round(viewport[1] / 2)];
 },
 
 /**
  * @method getOffset
  **/
 getOffset: function getOffset() {
  if(typeof(window.pageYOffset)=='number') 
  {
   return [window.pageXOffset, window.pageYOffset];
  }
  return [document.documentElement.scrollLeft, document.documentElement.scrollTop];
 }
});
//-----------------------------------------------------------------------------------------------------//
// Extend jQuery Element Core
//-----------------------------------------------------------------------------------------------------//
/**
 * @note Extend the jQuery node methods
 **/
jQuery.fn.extend({
 /*
  * Toggle Effect
  */
 toggle: function toggle(on, hide, suffix) {
  //note: this equals jQuery element object
  this.each(function() {
   //note: this equals element object
   var trigger = $(this);
   
   var toggle = null;
   
   //find the toggle
   if(suffix)
   {
    toggle = $('#'+trigger.attr('id')+suffix);
   }
   else 
   {
    var href = trigger.get(0).href || null;
    if(href)
    {
     toggle = $(href);
    }
   }
   // unset hide for checked boxes
   if(on=='click' && trigger.attr('checked')==true)
   {
   hide=false;
   }
   //add initial state for toggle
   if(hide)
   {
    toggle.addClass('hide');
   }
   
   trigger.bind(on, function _toggle(e) {
    //toggle
    if(toggle.hasClass('hide'))
    {
     toggle.removeClass('hide');
    }
    else
    {
     toggle.addClass('hide');
    }
   });
  });
  
 },
 
 /*
  * Gets the position of the element
  */
 getPosition: function getPosition() {
  //note: this equals jQuery element object
  var curleft = 0, curtop = 0, el = this.get(0);
  if (el.offsetParent) {
   do {
    curleft += el.offsetLeft;
    curtop += el.offsetTop;
   } while (el = el.offsetParent);
   return [curleft,curtop];
  }
 }
});

// Login-Passport Pop-up 
function popUp(URL) {
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=1,resizable=0,width=680,height=620,left = 380,top = 152.5');");
};

var submitted=false;

//-----------------------------------------------------------------------------------------------------//
// Unobtrusive opening of new windows
//-----------------------------------------------------------------------------------------------------//

var JSTarget = { 
  init: function(att,val,warning) { 
  if (document.getElementById && document.createElement && document.appendChild) { 
    var strAtt = ((typeof att == 'undefined') || (att == null)) ? 'class' : att; 
    var strVal = ((typeof val == 'undefined') || (val == null)) ? 'non-html' : val; 
    var strWarning = ((typeof warning == 'undefined') || (warning == null)) ? ' (opens in a new window)' : warning; 
    var oWarning; 
    var arrLinks = document.getElementsByTagName('a'); 
    var oLink; 
    var oRegExp = new RegExp("(^|\\s)" + strVal + "(\\s|$)"); 
    for (var i = 0; i < arrLinks.length; i++) { 
      oLink = arrLinks[i]; 
      if ((strAtt == 'class') && (oRegExp.test(oLink.className)) || (oRegExp.test(oLink.getAttribute(strAtt)))) { 
        oWarning = document.createElement("em"); 
        oWarning.appendChild( document.createTextNode(strWarning) ); 
        oLink.appendChild(oWarning); 
        oLink.onclick = JSTarget.openWin; 
      } 
      oWarning = null; 
    } 
  } 
}, 
openWin: function(e) { 
  var event = (!e) ? window.event : e; 
  if (event.shiftKey || event.altKey || event.ctrlKey || event.metaKey) return true; 
  else { 
    var oWin = window.open(this.getAttribute('href'), '', 'resizable=1'); 
    if (oWin) { 
      if (oWin.focus) oWin.focus(); 
        return false; 
    } 
    oWin = null; 
    return true; 
  } 
}
};
 
$(document).ready(function(){JSTarget.init("rel","external","");});