/**
 * Site Javascript
 */
(function($){
	

$(document).ready(function (){
	initRenewalForm();
	autoUserImport();
	removeAppIconsFromImageLinks();
	closeYearsMinutes();
});

function initRenewalForm(){
	var frm = $('#Form_RenewalForm');
	if(frm && frm.length > 0){
		//hide joint member area initially
		var joint = $('.CompositeField');
		var jointSelect = $('#Form_RenewalForm_renewalType');
		if(jointSelect.val() != 'joint'){
			joint.hide();
		}
		
		//hide period warning, if required
		var warning = $('#periodWarning');
		if($('#Form_RenewalForm_renewalPeriod').val() != 'next'){
			warning.hide();
		}
		
		//add trigger to select 
		jointSelect.change(function (){
			if(this.value == 'joint'){
				joint.fadeIn();
				$('#Form_RenewalForm_action_Renew').attr('disabled', true);
			} else {
				joint.fadeOut();
				//clear values
				joint.find('input[type="text"]').each(function (){this.value = '';});
				//clear any label classes
				clearIndicators();
				$('#Form_RenewalForm_action_Renew').attr('disabled', false);
			}
		});
		
		//add check button to composite area
		joint.append('<div class="field inlineformaction nolabel" id="btnCheckDiv"><div class="middleColumn"><input type="submit" class="action" id="btnCheck" name="btnCheck" value="Check details"></div></div>');
		
		//add handler
		$('#btnCheck').click(function (){
			
			//only allow submit as long as there are no validation messages within
			//the joint area
			if(joint.find('.validation:visible').length > 0){
				//show error
				addJointError('Please correct any errors below');
			} else {
				//hide error
				removeJointError();
				checking($(this), true);
				checkJointDetails();
			}
			
			return false;
		});
		
		//add handler for period select
		$('#Form_RenewalForm_renewalPeriod').change(function (){
			if(this.value == 'current'){
				warning.fadeOut();
			} else {
				warning.fadeIn();
			}
		});
	}

}

function removeAppIconsFromImageLinks() {
	var aTags = [];
	var layout = document.getElementById('Layout');
	$('.typography a[href$=".pdf"] img,.typography a[href$=".PDF"] img, .typography a.pdf img, .typography a[href$=".doc"] img, .typography a[href$=".DOC"] img, .typography a.doc img, .typography a[href$=".xls"] img, .typography a[href$=".XLS"] img, .typography a.xls img').each(function (){
		$(this.parentNode).addClass("noIcon");
	});
}

function closeYearsMinutes() {
	$('dl.closed').each(function(){
		$(this).hide();
	});
	$('p.revealer').each(function(){
		$(this.style.display = 'block');
	});
	$('.revealYear').click(function(){
		$(this).parent().next('dl').slideToggle('fast');
		$(this).text($(this).text() == 'Reveal this years minutes' ? 'Hide this years minutes' : 'Reveal this years minutes');
		return false;
	});
}

function checkJointDetails(){
	var inputs = [];
	var proceed = true;
	clearIndicators();
	
	$('.CompositeField :input[type="text"]').each(function (){
		if(this.name != '' && this.name !='undefined' && this.value.replace(/(^\s)|(\s$)/, '') != ''){
			inputs.push(this.name + '=' + escape(this.value));
		} else {
			var id = this.id.match(/(.*)-.*/);
			id = id ? 'Form_RenewalForm_' + id[1] : this.id; //multi field - date
			$('label[for="' + id + '"]').addClass('memberNotActive');
			proceed = false;
		}
	});
	
	if(proceed){
		//remove any error indicators
		clearIndicators();
		removeJointError();
		$.ajax({
			url: '/renewal/memberCheck',
			data: inputs.join('&'),
			dataType: 'json',
			type: 'post',
			async: false,
			error: function (xhr, ajaxOptions, thrownError){memberCheckError()},
			success: function (data){
				checking($('#btnCheck'), false);
				//check what happend
				if(data.status){
					//add tick
					$('.CompositeField label').addClass('memberActive').removeClass('memberNotActive');
					$('#Form_RenewalForm_action_Renew').attr('disabled', false); //allow submit
				} else {
					$('.CompositeField label').addClass('memberNotActive').removeClass('memberActive');
					alert(data.reason);
				}
			}
		});
	} else {
		checking($('#btnCheck'), false); 
		addJointError('Please make sure all joint member fields are completed.')
	}
}

function memberCheckError(){
	alert('Unable to check member details. Please try again.');
	checking($('#btnCheck'), false);
}

function checking(btn, checking){
	if(checking){
		btn.attr('disabled', true).val('Checking...');
	} else {
		btn.attr('disabled', false).val('Check details');
	}
}

function clearIndicators(){
	$('.CompositeField label').removeClass('memberActive').removeClass('memberNotActive');
}

function addJointError(str){
	var jError = $('#jointError');
	if(jError.length > 0){
		jError.text(str);
	} else {
		$('.CompositeField > h2').after('<p class="message required" id="jointError">' + str + '</p>');
	}
}

function removeJointError(){
	$('#jointError').remove();
}

function autoUserImport() {
	var cDiv = document.getElementById('Layout').innerHTML;
	var importForm = document.getElementById('Form_import');
	if (cDiv.match(/Stage 4 PARTIALLY RUN/gi)) { // Stage 4 PARTIALLY RUN
		setTimeout(function(){importForm.action_4.click();},500);
	}
	if (cDiv.match(/Stage 5 PARTIALLY RUN/gi)) {
		setTimeout(function(){importForm.action_5.click();},500);
	}
}

$(function(){
	$("ul#ticker01").liScroll();
});

$(function(){
    $('#slideshow img:gt(0)').hide();
    setInterval(function(){
      $('#slideshow :first-child').fadeOut('slow')
         .next('img').fadeIn('slow')
         .end().appendTo('#slideshow');}, 
      7000);
});


})(jQuery); //end of jQuery closure so we can use $

//don't put any code out here if you want to use $ syntax

/**
* Returns an XMLHttp instance to use for asynchronous
* downloading. This method will never throw an exception, but will
* return NULL if the browser does not support XmlHttp for any reason.
* @return {XMLHttpRequest|Null}
*/
function createXmlHttpRequest() {
 try {
   if (typeof ActiveXObject != 'undefined') {
     return new ActiveXObject('Microsoft.XMLHTTP');
   } else if (window["XMLHttpRequest"]) {
     return new XMLHttpRequest();
   }
 } catch (e) {
   changeStatus(e);
 }
 return null;
};

/**
* This functions wraps XMLHttpRequest open/send function.
* It lets you specify a URL and will call the callback if
* it gets a status code of 200.
* @param {String} url The URL to retrieve
* @param {Function} callback The function to call once retrieved.
*/
function downloadUrl(url, callback) {
 var status = -1;
 var request = createXmlHttpRequest();
 if (!request) {
   return false;
 }

 request.onreadystatechange = function() {
   if (request.readyState == 4) {
     try {
       status = request.status;
     } catch (e) {
       // Usually indicates request timed out in FF.
     }
     if (status == 200) {
       callback(request.responseXML, request.status);
       request.onreadystatechange = function() {};
     }
   }
 }
 request.open('GET', url, true);
 try {
   request.send(null);
 } catch (e) {
   changeStatus(e);
 }
};

/**
 * Parses the given XML string and returns the parsed document in a
 * DOM data structure. This function will return an empty DOM node if
 * XML parsing is not supported in this browser.
 * @param {string} str XML string.
 * @return {Element|Document} DOM.
 */
function xmlParse(str) {
  if (typeof ActiveXObject != 'undefined' && typeof GetObject != 'undefined') {
    var doc = new ActiveXObject('Microsoft.XMLDOM');
    doc.loadXML(str);
    return doc;
  }

  if (typeof DOMParser != 'undefined') {
    return (new DOMParser()).parseFromString(str, 'text/xml');
  }

  return createElement('div', null);
}

/**
 * Appends a JavaScript file to the page.
 * @param {string} url
 */
function downloadScript(url) {
  var script = document.createElement('script');
  script.src = url;
  document.body.appendChild(script);
}

