/*
  ryd appform jquery/js code
*/

var formSubmitLock      = false;
var fileSizeLimit       = 3145728;
var totalFileSizeLimit  = fileSizeLimit * 3;
var exts                = '*.doc;*.zip;*.pdf;*.jpg;*.png';

$(document).ready(function(){
    
  initUploadify();
  reloadFileList(); // ajax load the file list
  initWebLinks(); // must go before accordion bind
  //bindTableAccordion('qf_header_tr');  
  $('#appform_container').corner("round 8px").parent().css('padding', '4px').corner("round 10px");
  
  // Prevent user from submitting while a file is uploading.
  $('form').submit(function(){
    if(formSubmitLock) {
      alert('Please wait until your files have finished uploading before submitting this application form.');
      return false;
    }
    return true;
  });
  
});

function initUploadify() {
  $('#uploadify').fileUpload({ 
    'uploader'        : 'lib/uploadify/uploader.swf', 
    'script'          : 'lib/uploadify/upload.php', 
    'folder'          : 'uploads', 
    'auto'            : true,
    'multi'           : false,
    'cancelImg'       : 'lib/uploadify/cancel.png',
    'fileDesc'        : 'Documents ('+exts+')',
    'fileExt'         : exts,
    'sizeLimit'       : fileSizeLimit,
    'simUploadLimit'  : 1,
    'scriptData'      : { 'session_id' : session_id },
    onSelectOnce      : function(event, data) { formSubmitLock = true; },
    onAllComplete     : function(event, data) { handleAllComplete(event, data); }
  }); 
}

/**
 * Since I separated fileList from uplodify in the table structure, anything in the uploadify TD can be removed.
 */
function reinitUploadify() {
  $('#uploadify').nextAll().remove();
  initUploadify();
}

/**
 * Accordion like behaviour, but customised for web links
 */
var webLinkIdx = 1;
function initWebLinks() {
  
  // first, find starting web link number (that which has an empty 'text' field)
  for(var i = 0; i < 5; i++) {
    var elem = $("input[name='web_link["+i+"][url]']");
    if('' == $.trim(elem.val())) {
      webLinkIdx = i;
      break;
    }
  }
  if(0 == webLinkIdx) { webLinkIdx = 1; } // dont' start from 0

  // eq(1) = jQuery selector for 2nd element
  var startHeader = $('.qf_header_web_link:eq('+webLinkIdx+')');
  startHeader.hide();
  startHeader.nextAll().each(function() {
    if($(this).hasClass('qf_spacer_row')) { return false; } // stop at Submit header, spacer is just before
    $(this).hide();
  });
  
}

/**
 * UI Triggered function
 */
function showAnotherWebLink(e) {
  if(5 == webLinkIdx < 5) { return false; } // max number of links reached, stop showing more
  var startHeader = $('.qf_header_web_link:eq('+webLinkIdx+')');
  startHeader.show();
  startHeader.nextAll().each(function() {
    if($(this).hasClass('qf_header_web_link')) { return false; } // stop at next web link header
    if($(this).hasClass('qf_spacer_row')) { return false; } // stop at Submit header, spacer is just before
    $(this).show();
  });
  if(webLinkIdx < 5) { webLinkIdx++; } // incremement counter
}

/**
 * Hide/show test
 * todo: add/remove the hide/show desc to the "content" of the hidden section
 */
function bindTableAccordion(trClass) {
  var hideShowDescElem = '<div class="hide_show_desc">Click the header to hide/show this section\'s content...</div>'
  
  $('.'+trClass).css('cursor', 'pointer'); // Should do here, or via standard css? What's responsible?
  $('.'+trClass).toggle(
    function(){  
    	// Hide sibling rows until we find the next header 'section'.
      $(this).nextAll().each(function(){
      	if($(this).hasClass(trClass)) { return false; } 
      	if($(this).hasClass('qf_header_tr_nojs')) { return false; } 
      	$(this).hide();
      });
      //$('this > td').append(hideShowDescElem);
      $(this).addClass('trHidden');
      $(this).removeClass('trShown');
      $.scrollTo('#top_anchor');
    },
    function() {
      // Show sibling rows until we find the next header 'section'.
      $(this).nextAll().each(function(){
      	if($(this).hasClass(trClass)) { return false; } 
      	if($(this).hasClass('qf_header_tr_nojs')) { return false; } 
      	$(this).show();
      });
      $(this).removeClass('trHidden'); // No longer hidden
      $('.trShown').click(); // Also hide any other "shown" sections
      $(this).addClass('trShown'); // Now flag as "shown"
      $.scrollTo('#top_anchor');
      initWebLinks();
    }
  );
  
  // Hack?
  
  // Simulate a click to hide on all headers to start with
  $('.'+trClass).click();
  // Then click the first one again to show it, to start off
  $('.'+trClass+':first').click();
}

/**
 * All queued files have finished uploading.
 */
function handleAllComplete(event, data) {
  formSubmitLock = false; // release the form submission lock
  reloadFileList();
}

/**
 * ajax load the file list
 */
function reloadFileList() {
  $('#fileList').hide();
  $.get('lib/uploadify/file_list.php', function(data){
    $('#fileList').html(data).fadeIn();
    countFileSizes(); // check to see if the user has gone over their limit?
  });
}

/**
 * Disable the uploader once they've uploaded too much data.
 */
function countFileSizes() {
  var fileSize = 0;
  var limit = totalFileSizeLimit / 1024; // k
  
  $('#userFileList').children().each(function() {
    fileSize += parseInt($(this).attr('fileSize')); // attribute inserted by php
  });
  
  if(fileSize > limit) {
    // too many uploads, disable browse button
    $('#uploadifyUploader').fadeOut().remove();
    $('#uploadify').html('Maximum allowed file size limit reached for this application.').fadeIn();
  }
}

/**
 * SM 27Mar09: For more control over wordcounting.
 * Called from lib/RuleWordCount.php's js
 */
function doWordCount(str, max) {
  return (getWordCount(str) <= max);
}

/**
 * Used by form validation and UI counters.
 */
function getWordCount(str) {
  var arr = str.split(' ');
  // exclude "short" words like: a, in , as
  arr = jQuery.grep(arr, function(n, i){ return (n.length > 2); });
  return arr.length;
}

/**
 * SM: send ajax command to delete file from server, and refresh.
 */
function deleteUpload(fileName) {
  $.post("ajax.php", { 
    action: "deleteUpload",
    fileName: fileName
  },function(data){
    //alert(data.msg);
    // Only need to reload file list on successful deletion.
    if(data.result) { 
      reloadFileList(); 
    } else {
      alert('FAILURE: ' + data.msg);
    }
  }, "json");
}

/*
  SM 06Apr09: For stardard UI usage.
*/
function popup(url,name,features){
	
	name = typeof(name) != 'undefined' ? name : 'PopupWindow';
	features = typeof(features) != 'undefined' ? features : 'width=700,height=500,resizable=yes,scrollbars=yes';
	
	newwindow=window.open(url, name, features);
	if (window.focus) {newwindow.focus()}
	//return false;
}