/**
 *  Most of the scripts below were found at
 *  www.alistapart.com and related sites.  They are used
 *  here because they are web standards compliant.  These
 *  scripts are all free to reuse and are not licensed as
 *  part of the software core.
 *
 *  All onload() events go at the bottom of this file.
 */

/**
 *  Function DisableSubmit() used to disable submit buttons
 *  after then have been depressed.  This is implemented to
 *  stop multiple click submissions of forms.
 */

var submitted = false;
var emailFormValidated = false;
var isEmailFormLoading = false;

var validateEmailForm = function() {
	$('#email_fname, #email_lname, #email_email').bind({
		change: function() {
			validateEmailField(this, $(this).val());
		}
	});
	
	$('#email_submit').click(function() {
		if(!isEmailFormLoading) {
			setLoading(true);
			emailFormValidated = validateEmailField('#email_fname', $('#email_fname').val());
			
			if(emailFormValidated) {
				emailFormValidated = validateEmailField('#email_lname', $('#email_lname').val());
			}
			
			if(emailFormValidated) {
				emailFormValidated = validateEmailField('#email_email', $('#email_email').val());
			}
			
			if(emailFormValidated) {
				
				var emailFormData = new Array();
				emailFormData['fname'] = $('#email_fname').val();
				emailFormData['lname'] = $('#email_lname').val();
				emailFormData['email'] = $('#email_email').val();
				emailFormData['title'] = $('#email_title').val();
				
				$.ajax({
					type: "POST",
					url: "http://www.aht.org.uk/emailmarketer/form.php?form=1",
					data: "CustomFields[1]=" + encodeURIComponent(emailFormData['title']) + '&CustomFields[2]=' + encodeURIComponent(emailFormData['fname']) + '&CustomFields[3]=' + encodeURIComponent(emailFormData['lname']) + '&email=' + encodeURIComponent(emailFormData['email'])+ '&format=h',
					async: false,
					success: function(result) {
						
							$('#emailSignupForm').fadeOut(1000, function() {
								$('#emailSignupForm').html('<p>Your details have been saved. Thank you.</p>');
								$('#emailSignupForm').fadeIn(1000);
							});
						
						setLoading(false);
					},
					error: function (xhr, ajaxOptions, thrownError){
						setLoading(false);
					}
				});	
			} else {
				setLoading(false);	
			}
		}
	});
}

var setLoading = function(loading) {
	if(loading) {
		$('#emailFormLoading').css('display', 'inline');
		isEmailFormLoading = true;
	} else {
		$('#emailFormLoading').css('display', 'none');
		isEmailFormLoading = false;
	}
}

var validateEmailField = function(field, val) {
	
	var fieldName = $(field).attr('id');
	
	switch(fieldName) {
		case 'email_fname':
		case 'email_lname':
			if(val.length >= 2 && isAlphanumeric(val)) {
				setBackgroundImage(field, true);
				return true;	
			} else {
				setBackgroundImage(field, false);
				return false;	
			}
			break;
		case 'email_email':
			if(isEmail(val)) {
				setBackgroundImage(field, true);
				return true;	
			} else {
				setBackgroundImage(field, false);
				return false;
			}
			break;
	}
}

var isEmail = function(email) {
 
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   if(reg.test(email) == false) {
      return false;
   } else {
		return true;   
   }
}

var setBackgroundImage = function(field, valid) {
	/* This is messed up */
	if(!valid) {
		$(field).css('background', 'transparent url(\'skins/Default/media/valid.png\') no-repeat right');
	} else {
		$(field).css('background', 'transparent url(\'skins/Default/media/invalid.png\') no-repeat right');
	}
}

var isAlphanumeric = function(val) {
	var alphaExp = /^[0-9a-zA-Z]+$/;
	if(val.match(alphaExp)) {
		return true;
	} else {
		return false;
	}
}

var textfieldFocus = function() {
	$.each($('#emailSignupForm input[type="text"]'), function(index) {
		$(this).attr('custom:initialValue', $(this).val());	
		$(this).bind({
			focus: function() {
				if($(this).val() == $(this).attr('custom:initialValue')) {
					$(this).val('');
				}
			},
			blur: function() {
				if($(this).val() == '') {
					$(this).val($(this).attr('custom:initialValue'));
				}	
			}
		});
	});
}

var ajaxSearchIntervalId = null;

var ajaxSearchEvent = function() {
	$('#ecom--minisearch--ecom--prodsearch--string').keyup(function() {
		
		if(ajaxSearchIntervalId != null) {
			clearInterval(ajaxSearchIntervalId);
		}
		
		ajaxSearchIntervalId = setTimeout('ajaxSearch()', 500);
	});
	
}

var ajaxSearch = function() {
	if($('#ecom--minisearch--ecom--prodsearch--stringDD').length == 0) {
		$('#ecom--minisearch').append('<div id="ecom--minisearch--ecom--prodsearch--stringDD"></div>');
		$('#ecom--minisearch').append('<div id="ecom--minisearch--ecom--prodsearch--stringLoading" style="position: absolute;"><img src="skins/Default/media/loading.gif" alt="" /></div>');
	}
	
		var val = $('#ecom--minisearch--ecom--prodsearch--string').val();
		$('#ecom--minisearch--ecom--prodsearch--stringLoading').html('<img src="skins/Default/media/loading.gif" alt="" />');
		if(val != '') {
		
			$.ajax({
				type: "POST",
				url: "scripts/ajax/search.php",
				data: "q=" + encodeURIComponent(val),
				async:false,
				success: function(response) {
					
					$('#ecom--minisearch--ecom--prodsearch--stringDD').html(response);
					$('#ecom--minisearch--ecom--prodsearch--stringLoading').html('');
					$('#ecom--minisearch--ecom--prodsearch--stringDD').slideDown(500);
					
				}
			});
		
		} else {
			$('#ecom--minisearch--ecom--prodsearch--stringDD').slideUp(500, function() {
				$('#ecom--minisearch--ecom--prodsearch--stringDD').html('');
			});
		}

}


var ajaxSearchPage = function() {
	
		var val = ajaxSearchVal;
		if(val != '') {
		
			$.ajax({
				type: "POST",
				url: "scripts/ajax/search.php",
				data: "q=" + encodeURIComponent(val),
				async:false,
				success: function(response) {
					
					$('ul.cpul_search').html(response);
					$('ul.cpul_search').slideDown(500);
					
				}
			});
		
		}

}

$(document).ready(function() {
	textfieldFocus();
	validateEmailForm();
	ajaxSearchEvent();
});

function DisableSubmit(formname) {

     if(submitted == true) { return; }
     document.forms[formname].submit();
     document.forms[formname].SUBMIT.value = 'Please Wait...';
     document.forms[formname].SUBMIT.disabled = true;
     submitted = true;

}

/**
 *  Function externalLinks() used to provide a standards
 *  compliant way of producing a pop-up link to another
 *  page.
 */

function externalLinks() {

     if (!document.getElementsByTagName) return;
     var anchors = document.getElementsByTagName("a");
     for (var i=0; i<anchors.length; i++) {
     var anchor = anchors[i];
     if (anchor.getAttribute("href") &&
     anchor.getAttribute("rel") == "external")
     anchor.target = "_blank";
     }

}

/**
 *  Function to add multiple onload() events to a page. 
 *  Authored by Scott Andrew.  Visit www.scottandrew.com
 *  for info.
 */

function addWindowEvent(elm, evType, fn, useCapture) {

     if (elm.addEventListener) {
     elm.addEventListener(evType, fn, useCapture);
     return true;
     } else if (elm.attachEvent) {
     var r = elm.attachEvent('on' + evType, fn);
     return r;
     } else {
     elm['on' + evType] = fn;
     }

}

/**
 *	Whatever:hover - V1.42.060206 - hover & active
 *	------------------------------------------------------------
 *	(c) 2005 - Peter Nederlof
 *	Peterned - http://www.xs4all.nl/~peterned/
 *	License  - http://creativecommons.org/licenses/LGPL/2.1/
 *
 *	Whatever:hover is free software; you can redistribute it and/or
 *	modify it under the terms of the GNU Lesser General Public
 *	License as published by the Free Software Foundation; either
 *	version 2.1 of the License, or (at your option) any later version.
 *
 *	Whatever:hover is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 *	Lesser General Public License for more details.
 *
 *	Credits and thanks to:
 *	Arnoud Berendsen, Martin Reurings, Robert Hanson
 *
 *	howto: body { behavior:url("csshover.htc"); }
 *	------------------------------------------------------------
 */

var csshoverReg = /(^|\s)(([^a]([^ ]+)?)|(a([^#.][^ ]+)+)):(hover|active)/i,

currentSheet, doc = window.document, hoverEvents = [], activators = {
onhover:{on:'onmouseover', off:'onmouseout'},
onactive:{on:'onmousedown', off:'onmouseup'}
}

function parseStylesheets() {

     if(!/MSIE (5|6)/.test(navigator.userAgent)) return;
     window.attachEvent('onunload', unhookHoverEvents);
     var sheets = doc.styleSheets, l = sheets.length;
     for(var i=0; i<l; i++) 
     parseStylesheet(sheets[i]);

}

function parseStylesheet(sheet) {

     if(sheet.imports) {
     try {
     var imports = sheet.imports, l = imports.length;
     for(var i=0; i<l; i++) parseStylesheet(sheet.imports[i]);
     } catch(securityException){}
     }
     try {
     var rules = (currentSheet = sheet).rules, l = rules.length;
     for(var j=0; j<l; j++) parseCSSRule(rules[j]);
     } catch(securityException){}

}

function parseCSSRule(rule) {

     var select = rule.selectorText, style = rule.style.cssText;
     if(!csshoverReg.test(select) || !style) return;
     var pseudo = select.replace(/[^:]+:([a-z-]+).*/i, 'on$1');
     var newSelect = select.replace(/(\.([a-z0-9_-]+):[a-z]+)|(:[a-z]+)/gi, '.$2' + pseudo);
     var className = (/\.([a-z0-9_-]*on(hover|active))/i).exec(newSelect)[1];
     var affected = select.replace(/:(hover|active).*$/, '');
     var elements = getElementsBySelect(affected);
     if(elements.length == 0) return;
     currentSheet.addRule(newSelect, style);
     for(var i=0; i<elements.length; i++)
     new HoverElement(elements[i], className, activators[pseudo]);

}

function HoverElement(node, className, events) {

     if(!node.hovers) node.hovers = {};
     if(node.hovers[className]) return;
     node.hovers[className] = true;
     hookHoverEvent(node, events.on, function() { node.className += ' ' + className; });
     hookHoverEvent(node, events.off, function() { node.className = node.className.replace(new RegExp('\\s+'+className, 'g'),''); });

}

function hookHoverEvent(node, type, handler) {

     node.attachEvent(type, handler);
     hoverEvents[hoverEvents.length] = { 
     node:node, type:type, handler:handler 
     };

}

function unhookHoverEvents() {

     for(var e,i=0; i<hoverEvents.length; i++) {
     e = hoverEvents[i]; 
     e.node.detachEvent(e.type, e.handler);
     }
}

function getElementsBySelect(rule) {

     var parts, nodes = [doc];
     parts = rule.split(' ');
     for(var i=0; i<parts.length; i++) {
     nodes = getSelectedNodes(parts[i], nodes);
     }
     return nodes;

}

function getSelectedNodes(select, elements) {

     var result, node, nodes = [];
     var identify = (/\#([a-z0-9_-]+)/i).exec(select);
     if(identify) {
     var element = doc.getElementById(identify[1]);
     return element? [element]:nodes;
     }
     var classname = (/\.([a-z0-9_-]+)/i).exec(select);
     var tagName = select.replace(/(\.|\#|\:)[a-z0-9_-]+/i, '');
     var classReg = classname? new RegExp('\\b' + classname[1] + '\\b'):false;
     for(var i=0; i<elements.length; i++) {
     result = tagName? elements[i].all.tags(tagName):elements[i].all; 
     for(var j=0; j<result.length; j++) {
     node = result[j];
     if(classReg && !classReg.test(node.className)) continue;
     nodes[nodes.length] = node;
     }
     }	
     return nodes;

}

/**
 *  Function to show or hide an id within an XHTML page.
 */

function idShowHide(obj) {

     var el = document.getElementById(obj);
     if ( el.style.display != "none" ) {
     el.style.display = 'none';
     } else {
     el.style.display = 'block';
     }

}

/**
 *  WYSIWYG Editors.
 */

function wysiwygLoad(id) {

     var pid = id + '--wysiwyglink';
     var el  = document.getElementById(pid);

     if ( el.style.display != "none" ) {
     el.style.display = 'none';
     $(id).mooEditable({buttons: 'bold,italic,underline,strikethrough,|,insertunorderedlist,insertorderedlist,indent,outdent,|,undo,redo,|,toggleview'});
     }

}

/**
 *  LOAD EVENT
 */

addWindowEvent(window,'load',externalLinks,false);

/**
 *  LOAD EVENT
 */

var IE6   = false /*@cc_on || @_jscript_version < 5.7 @*/;

if ((IE6) && (window.MochaUI === undefined)) {addWindowEvent(window,'load',parseStylesheets,false);}

/**
 *  End.
 */
