jQuery("html").addClass("has-js");
		
		jQuery.fn.filterListings = function() {
			jQuery('.filter_checkbox').change(function() {
				
				var filename = jQuery('#filename').val();
			
				if(filename == 'merchants'){
				
					/*
					 * gets the paths parts, checks to see if there is a page number or a-z letter, removes it and attaches the correct get string
					 */
					
					var changed = jQuery(this).val();
					
					var path = jQuery('#path').val();
					var base_url = jQuery('#base_url').val();
					var filter = jQuery('#merchant_filter').val();
	
					var parts = path.split('/');
					
					var number = (parts.length) - 1;
					
					if((parts[number] == parseInt(parts[number])) || (parts[number].match(/^[a-z]$/))){
						
						var number = number - 1;
					}	
					var url = base_url;
					var i = 0;
					while (i<=number){
						
						url = url + parts[i] + "/"; 
						i++;
					}	
								
					if(filter == 'all'){
						if(changed == 'voucher'){
							var getstring = '?cb=cashback';
						}
						if(changed == 'cashback'){
							var getstring = '?vc=voucher';
						}
					} else {
						var getstring = '';
					}	
					
					url = url + getstring;				
					window.location = url;
				}
				else if(filename == 'search'){
					
					/*
					 * gets the full url and uses regex to search and remove the page number and filter type if necessary
					 */
					
					var full_url = jQuery('#full_url').val();
								
					full_url = full_url.replace(/\&page=[0-9]+/,'');				
					
					var filter = jQuery('#merchant_filter').val();
					
					var changed = jQuery(this).val();
					
					if(filter == 'all'){
						if(changed == 'voucher'){
							var getstring = '&cb=cashback';
						}
						if(changed == 'cashback'){
							var getstring = '&vc=voucher';
						}
					} else {
						
						var getstring = '';
						
						full_url = full_url.replace(/\&cb=cashback/,'');		
						full_url = full_url.replace(/\&vc=voucher/,'');
						
					}	
					var url = full_url + getstring;				
					window.location = url;
					
				}	
								
			});
		}

		jQuery.fn.referSearch = function(options) {
			
			var camp_id = '';
			
			 jQuery(".create-deep-link").click(function() {
				 camp_id = jQuery(this).parents(".refer-methods").attr("id");
				 createDeepLink(jQuery("#" + camp_id).find(".retailer-text-box").val(), true);
			});
			
			var settings = jQuery.extend({
				defaultText : 'Type retailer name here',
				autoSuggest : 'false'
			},options||{});	

			if (jQuery(".retailer-text-box").val() == '') {

				jQuery(".retailer-text-box").val(settings.defaultText);
			}
			jQuery(".retailer-text-box").click(function() {				
				if (jQuery(this).val() == settings.defaultText) {
					jQuery(this).val('');
				}
			});
			
			jQuery(".retailer-text-box").blur(function() {
				if (jQuery(this).val().length === 0 ){
					jQuery(this).val(settings.defaultText);
				}
			});

			if (settings.autoSuggest == "true"){
				jQuery(".retailer-text-box").one("click",function() {
					camp_id = jQuery(this).parents(".refer-methods").attr("id");
					$.getScript("/merchant_qsearch.php", function(){autosearch_refer()});
					searchID = jQuery(this).attr("id");
						
				function autosearch_refer(){
					jQuery("input#" + searchID).autocomplete(merchants, {
						minChars: 2,
						width: 252,
						selectFirst: false,
						scrollHeight : "auto",
						matchContains: "s",
						autoFill: false,
						max : "5",
						formatItem: function(row, i, max) {
							var returned_string;									
							returned_string = "<span class='store'>" + row.s + "</span>";							
								return returned_string;
						},
						formatMatch: function(row, i, max) {
								return row.s;
						},
						formatResult: function(row) {								
								return row.s;
						}	
												
						}).result(function(event, item) {
							var url_name = item.u;
							camp_id = jQuery(this).parents(".refer-methods").attr("id");
							createDeepLink(url_name, false);
						//location.href = "/" + item.u + "/?ac";
						});
						
					}
				});// end autosearch_refer
			}	//end if	
			
			function createDeepLink(url_name, is_button) {
				// do nothing if null, else write referral link and return to populate div
				if (typeof(url_name) == "undefined") {
					// replace with some kind of 'try again' message
					return false;
				}
				else {
					//
					// call script to generate URL and write to DB
					jQuery.ajax({ 
						type: "GET", 
						url: "/ajax/referrals", 
						dataType: "HTML", 
						data: "action=generate_referral_link&url_name="+url_name+"&is_button="+is_button+"&cid="+camp_id, 
						error: function() {
							jQuery("#" + camp_id).find('.deep-link-text-box').val("");
							jQuery("#" + camp_id).find('.response').html("<span></span>Retailer name not found. Please try again.");
							jQuery("#" + camp_id).find('.response span').addClass("show-error");
							jQuery("#" + camp_id).find('.response').show();
							jQuery("#" + camp_id).find('.retailer-link-wrapper').hide();
						},
						success: function(html) {
							var returned_url = html;
					
							if(returned_url.length > 1) {
								jQuery("#" + camp_id).find('.deep-link-text-box').val(returned_url);
								jQuery("#" + camp_id).find('.response').html("<span></span>Retailer link sucessfully created.");
								jQuery("#" + camp_id).find('.retailer-link-wrapper').show();
							} else {
								jQuery("#" + camp_id).find('.deep-link-text-box').val("");
								jQuery("#" + camp_id).find('.response').html("<span></span>Retailer name not found. Please try again.");
								jQuery("#" + camp_id).find('.response span').addClass("show-error");
								jQuery("#" + camp_id).find('.retailer-link-wrapper').hide();
								
							}
							jQuery("#" + camp_id).find('.response').show();
						}		
					});
					
					return false;
				}
			}
			
		}
		
		jQuery.fn.qsearch = function(options) {
			
				var settings = jQuery.extend({
				defaultText : 'Type in a store or product, e.g. Tesco, iPad, Amazon',
					autoSuggest : 'false'
				},options||{});						
								
				if (jQuery("#store-qsearch").val() == '') {
					jQuery("#store-qsearch").val(settings.defaultText);
				}
				jQuery("#store-qsearch").click(function() {				
					if (jQuery(this).val() == settings.defaultText) {
						jQuery(this).val('');
					}

					// hide the favourites drop down if search box is clicked
					if ( jQuery('#header .favourites-dropdown').is(':visible') ) {
						jQuery('#header .favourites-dropdown').slideUp(function() {
							jQuery('#header .text-nav ul').removeClass('faves-open');
							jQuery('#header .text-nav ul #faves a').removeClass('open');										
						});
					}
				
					
				});
				
				jQuery("#store-qsearch").blur(function() {
					if (jQuery(this).val().length === 0 ){
						jQuery(this).val(settings.defaultText);
					}
				});
				
				jQuery(this).find(".sq-submit").click(function() {
					jQuery(this).submit();
				});
				
				jQuery(this).submit(function(ev) {
					var curVal = jQuery(this).find("#store-qsearch").val();
					if (curVal == settings.defaultText || curVal == '') {
						jQuery("#store-qsearch").val('');
						jQuery("#store-qsearch").focus();
						return false;
					}
				});
				
				if (settings.autoSuggest == "true"){
					var searchID = "";
					
					jQuery("#store-qsearch").one("click",function() {
					
						searchID = jQuery(this).attr("id");
						
					jQuery("input#" + searchID).autocomplete("/ajax/search/merchants", {
								minChars: 2,
								width: 391,
								selectFirst: false,
								scrollHeight : "auto",
						matchSubset: false,
								autoFill: false,
								max : "7",
						dataType: 'json',
						parse: function(data) {
				            var array = new Array();
				            for (var i = 0; i < data.length; i++) {
				                array[array.length] = { data: data[i], value: data[i].ID, result: data[i].ID };
				            }
				            return array;
				        },
								formatItem: function(row, i, max) {
										
				        	jQuery("div.ac_results h2").remove();
							jQuery("div.ac_results").append("<h2>Store Results</h2>");
							
									var returned_string;									
									returned_string = "<span class='store'>" + row.s + "</span><span class='rate'>";
								
									var cashback = 'no';
									var voucher_codes = 'no';
									var printable_vouchers = 'no';
									
									//if has_cashback									
									if(row.r != 'no'){									
										returned_string = returned_string + row.r + " cashback";
										cashback = 'yes';
									}	
									
									//if has_voucher_code
									if((row.vc != 0) && (row.vc != undefined)){
										
										var word = "";										
										if(row.vc == 1){
											word = " voucher code";
										}	
										if(row.vc > 1){
											word = " voucher codes";
										}
										
										if(cashback == 'yes'){
											returned_string = returned_string + " / ";
										} 										
										returned_string = returned_string + row.vc + word;										
										voucher_codes = 'yes';
									}
									
									//if has_printable_vouchers
									if((row.pv != 0) && (row.pv != undefined)){
										
										var word = "";										
										if(row.pv == 1){
											word = " printable voucher";
										}	
										if(row.pv > 1){
											word = " printable vouchers";
										}
										
										if((cashback == 'yes') || (voucher_codes == 'yes')){
											returned_string = returned_string + " / ";
										}
										returned_string = returned_string + row.pv + word;										
										printable_vouchers = 'yes';
									}
									
									//if no_codes_or_printables, show offers
									if((row.vc == 0) && (row.pv == 0) && (row.o != 0) && (row.o != undefined)){
										
										var word = "";										
										if(row.o == 1){
											word = " offer";
										}	
										if(row.o > 1){
											word = " offers";
										}
										if(cashback == 'yes'){
											returned_string = returned_string + " / ";
										}										
										returned_string = returned_string + row.o + word;										
									}	
								
									returned_string = returned_string + "</span>";									
									return returned_string;
								},
								formatMatch: function(row, i, max) {
									return row.s;
								},
								formatResult: function(row) {								
									return row.s;
								}								
							}).result(function(event, item) {
							location.href = "/" + item.u + "/?ac";
							});  
					
						jQuery("input#" + searchID).keyup(function() {
							jQuery("div.ac_results h2").remove();
							jQuery("div.ac_results").append("<h2>Store Results</h2>");
						
							if (jQuery("div.ac_results").css("display") == "block"){
								jQuery(this).parent().parent().parent().addClass("open");
							}else{
								jQuery(this).parent().parent().parent().removeClass("open");
							} //if	
	
						});	//keyup
						jQuery("input#" + searchID).blur(function() {
							jQuery(this).parent().parent().parent().removeClass("open");
						});						
					}); // end click	
					
				}//if
		}; // end plugin
		
		jQuery.fn.nav = function(options) {
			jQuery(this).each(function() {				
				function showSubNav(){
					jQuery(jQuery(this).find("div")).addClass("hover");
					jQuery(jQuery(this).find("ul.sub-menu")).show();
					jQuery(this).addClass("hover");
				}
				function hideShowNav(){
					jQuery(jQuery(this).find("div")).removeClass("hover");
					jQuery(jQuery(this).find("ul.sub-menu")).hide();
					jQuery(this).removeClass("hover");
				}	
				var megaConfig = {interval: 30, sensitivity: 4, over: showSubNav, timeout: 100, out: hideShowNav};	
				jQuery("#nav td").hoverIntent(megaConfig);
				
				/*
				The following code is to dynamically set the width of the nav drop-down menus.
				This is necessary for IE6 and also to refactorize columns and avoid unnecessary white-space
				*/
				
				var nav_total = 10 //Number of nav tabs
				var cat_width = 178; //li.category width (inc padding)
				var new_col_width = 178; //li.new-column width (inc padding)
				var browse_width = 177; //li.browse width (inc padding)

				//Loop through nav tabs (ignoring first Browse tab)
				for (i=2;i<(nav_total+1);i++){
					var nav_li = "pos-" + i;
					var new_cols = jQuery("#nav td." + nav_li + " ul.sub-menu li.new-column").length; //number of .new-column elements
					var dd_cols = new_cols + 2; //total number of columns
					//If drop-down has more than standard two columns i.e. back-end wrapping
					if(dd_cols > 2){
						//Find position of final li.new-column 
						var final_new_col = dd_cols - 1;
						//Number of items in li.category
						var cat_length = jQuery("#nav td." + nav_li + " ul.sub-menu li.category ul li").length;
						//Number of items in final li.new-column
						var final_new_col_length = jQuery("#nav td." + nav_li + " ul.sub-menu").children("li:eq(" + final_new_col + ")").find("ul li").length;
						//Set the width of the drop-down menus
						//If length of final .new-column is less than half the length of li.category then move Browse column under final li.category via smaller set width
						if((cat_length/2) > final_new_col_length){
							var sub_menu_width = (((dd_cols - 2) * new_col_width) + cat_width + browse_width) - browse_width;
							jQuery("#nav td." + nav_li + " ul.sub-menu").width(sub_menu_width);
						}
						//Otherwise set the width of the drop-down menu as normal
						else{
							var sub_menu_width = ((dd_cols - 2) * new_col_width) + cat_width + browse_width;
							jQuery("#nav td." + nav_li + " ul.sub-menu").width(sub_menu_width);
						}
					}
					//No back-end wrapping necessary
					else{
						var sub_menu_width = cat_width + browse_width;
						jQuery("#nav td." + nav_li + " ul.sub-menu").width(sub_menu_width);
					}
				}
			}); // end each
		} // end plugin	
		
		jQuery.fn.share = function(options) {
			jQuery(this).each(function() {
				scriptURL = ('https:' == document.location.protocol ? 'https://' : 'http://') + 's7.addthis.com/js/250/addthis_widget.js?domready=1#pub=quidco';
				$.getScript(scriptURL);
			}); // end each
		} // end plugin	
		
		jQuery.fn.splashHeader = function(options) {
			jQuery(this).each(function() {
				var settings = jQuery.extend({
					splashHeaderDiv : 'div.module.js-splash-header div.module-content',
					actionLink:'ul li a',
					bannerClass1: 'browse',
					bannerClass2: 'buy',
					bannerClass3: 'cashback'					
				},options||{});	
				
				var splashItems;
				var curritem=0;
				var iPause=0;
				var currentHover = "browse"

				//Pause rotate if hovering any part of the banner	
				jQuery(settings.splashHeaderDiv).hover(
						function(){
							iPause=1;
						},
						function(){
							iPause=0;
						}
				);
					
				//Add logic to buttons to hover & pause	
				splashItems = jQuery(settings.splashHeaderDiv + " " + settings.actionLink).hover(
						function(){
							currentHover = jQuery(this).attr("class");
							jQuery(settings.splashHeaderDiv + " div div").hide();
							jQuery(settings.splashHeaderDiv + " div." + currentHover).show();
							jQuery(settings.splashHeaderDiv).removeClass().addClass("module-content " + currentHover);
							jQuery(settings.actionLink).parent().removeClass("hover");
							jQuery(this).parent().addClass("hover");
							
							if (currentHover == "browse"){
								curritem = 0;
							} else if (currentHover == "buy"){
								curritem = 1;
							} else if (currentHover == "cashback"){
								curritem =2;
							}
							
							iPause=1;
						},
						function(){
							iPause=0;
						}
				).filter(":eq(0)").add(settings.splashHeaderDiv + " div div").size();
				
				function ticknews(itemDiv) {
					  if (iPause===0){
						 
						
					    jQuery(settings.splashHeaderDiv + " div div:eq("+curritem+")").hide();
					    jQuery(settings.splashHeaderDiv + " li a:eq("+curritem+")").parent().removeClass("hover");
					    curritem = ++curritem%(splashItems -1);
					    currentHover = jQuery(settings.splashHeaderDiv + " li a:eq("+curritem+")").parent().attr("class");
					    jQuery(settings.splashHeaderDiv + " div div:eq("+curritem+")").show();
					    jQuery(settings.splashHeaderDiv + " li a:eq("+curritem+")").parent().addClass("hover");
					    jQuery(settings.splashHeaderDiv).removeClass().addClass("module-content " + currentHover);
					    } //end if
					} //end function
					setInterval(ticknews,6000); //time in milliseconds				

			}); // end each
		} // end plugin	
		
		jQuery.fn.inputFocus = function(options) {
			jQuery(this).each(function() {
				var settings = jQuery.extend({
					inputField : 'div.module.contact-form input#subject'
				},options||{});					
				jQuery(settings.inputField).focus();
			}); // end each
		} // end plugin			
	
		jQuery.fn.takeSurvey = function(options) {
			jQuery(this).each(function() {
				var settings = jQuery.extend({
					surveyDiv : 'div#limited-access',
					surveyLink :'div#limited-access a',
					closeLink : 'div#limited-access a.close',
					cookieName: 'quidcoSurveyClickTravel'
				},options||{});
				if (jQuery.cookie(settings.cookieName) == "true"){
					jQuery(settings.surveyDiv).hide();
				}else{
					jQuery(settings.surveyDiv).show();
				}
				jQuery(settings.surveyLink).click(function() {
					jQuery.cookie(settings.cookieName, 'true', {path: '/', expires: 30});
				});					
				jQuery(settings.closeLink).click(function() {
					jQuery(settings.surveyDiv).slideUp();
					jQuery.cookie(settings.cookieName, 'true', {path: '/', expires: 30});
					return false;
				});	
			}); // end each
		} // end plugin	
		
		jQuery.fn.itemHover = function(options) {
			jQuery(this).each(function() {							   
				var settings = jQuery.extend({
					hoverItem : 'div.content-item'
				},options||{});					  
				jQuery(settings.hoverItem).hover(
					  function () {
						jQuery(this).addClass("hover");
					  }, 
					  function () {
						jQuery(this).removeClass("hover");
					  }
				); //end hover
			}); // end each
		} // end plugin	
		
		jQuery.fn.expandList = function(options) {
			jQuery(this).each(function() {							   
				var settings = jQuery.extend({
					containerDiv : 'div.content-item',
					expandLink : 'blog-headlines'
				},options||{});					  
				jQuery(".module.blog-headlines .module-footer a").click(function() {
					jQuery(".module.blog-headlines ul li").attr("style", "display:none").show();
					jQuery(this).hide();
					return false;
				});		
				
			}); // end each
		} // end plugin	
		
		jQuery.fn.supportReply = function(options) {
			jQuery(this).each(function() {							   
				var settings = jQuery.extend({
					replyLink : 'cite a.reply',
					replyDiv : 'div.support-inbox-view div.content-item.reply'
				},options||{});					  
				jQuery(settings.replyLink).click(function() {
					jQuery(this).hide();
					jQuery(settings.replyDiv).slideDown();
					return false;
				});		
			}); // end each
		} // end plugin		
		
		jQuery.fn.createClan = function(options) {
			jQuery(this).each(function() {							   
				var settings = jQuery.extend({
					createLink : 'div.module.sub-nav ul li.create-clan a',
					formDiv : 'div.item.ipos-2 div.module.edit-clan',
					inputFocus :'input#name'
				},options||{});					  
				jQuery(settings.createLink).click(function() {
					jQuery(settings.formDiv).slideDown(500, function(){jQuery(settings.formDiv + " " + settings.inputFocus).focus();});
					
					return false;
				});		
			}); // end each
		} // end plugin		
	
		jQuery.fn.paymentDetails = function(options) {
			jQuery(this).each(function() {	
				var settings = jQuery.extend({
					clickDiv: 'table .date a.payment-expander',
					divExpanded : 'table td#trans',
					errorMsg: '<div class="content-item alert error">Error retreiving transactions details</div>'
				},options||{});				
				jQuery(this).find(settings.clickDiv).click(function() {
					var itemID = jQuery(this).attr("id");
					if (jQuery(this).parent().parent().hasClass("open")){
						//Collapse Payment Details
						jQuery(this).parent().parent().removeClass("open");
						jQuery(settings.divExpanded + itemID + " table").slideUp();				
					}else{
						//Load Payment Details
						statusItem = jQuery(this).parent().parent();
						statusItem.addClass("loading");
						jQuery.ajax({ 
								type: "GET", 
								url: "/ajax/payments", 
								dataType: "HTML", 
								data: "action=get_payments_out&payment_out_id="+itemID, 
								error: function() {
										statusItem.removeClass("loading");
								},
								success: function(html) {
									statusItem.removeClass("loading");
									statusItem.addClass("open");
									var response = html || settings.errorMsg;
									jQuery(settings.divExpanded +itemID).empty().append(response).slideDown();
								}
							});				
					}
					return false; //Disable Click			
			}); // end click	
			}); // end each
		} // end plugin	
		
		jQuery.fn.transactionDetails = function(options) {
			jQuery(this).each(function() {	
				var settings = jQuery.extend({
					clickDiv: 'table .date a.transaction-expander',
					divExpanded : 'table td#trans',
					errorMsg: '<div class="content-item alert error">Error retreiving transactions details</div>'
				},options||{});				
				jQuery(this).find(settings.clickDiv).click(function() {
					var date = jQuery(this).attr("href");
					var year = jQuery(this).attr("href").substring(0, 4);
					var month = jQuery(this).attr("href").substring(5, 7);
					if (jQuery(this).parent().parent().hasClass("open")){
						//Collapse Payment Details
						jQuery(this).parent().parent().removeClass("open");
						jQuery(settings.divExpanded + year + month + " table").slideUp();				
					}else{
						//Load Payment Details
						statusItem = jQuery(this).parent().parent();
						statusItem.addClass("loading");
						jQuery.ajax({ 
								type: "GET", 
								url: "/ajax/transactions", 
								dataType: "HTML", 
								data: "action=get_month_details&year=" + year + "&month=" + month, 
								error: function() {
										statusItem.removeClass("loading");
								},
								success: function(html) {
									statusItem.removeClass("loading");
									statusItem.addClass("open");
									var response = html || settings.errorMsg;
									jQuery(settings.divExpanded + year + month).empty().append(response).slideDown();
								}
							});				
					}
					return false; //Disable Click			
			}); // end click	
			}); // end each
		} // end plugin	
		
		jQuery.fn.showDetails = function(options) {
			jQuery(this).each(function() {
				
				var settings = jQuery.extend({
					actionLink : '.reveal-details',
					parentSlideOne : '.more-detail',
					parentFind : '.offer'
				},options||{});
				
				function merchantOver() {
					jQuery(this).addClass("hover-border");
				}
				function merchantOut() {
					jQuery(this).removeClass("hover-border");
				}
				var merchantHoverConfig = {interval: 100, sensitivity: 7, over: merchantOver, timeout: 25, out: merchantOut};
				jQuery(settings.parentFind).parent().hoverIntent(merchantHoverConfig);
				
				jQuery(settings.actionLink).live('click', function() {
					jQuery(this).parents(settings.parentFind).find(settings.parentSlideOne).slideToggle("slow");
					
					var htmlString = jQuery(this).html();
					
					if(htmlString == "Show details") {
						jQuery(this).html("Hide details");
						jQuery(this).toggleClass("reveal-active");
						jQuery(this).parents(settings.parentFind).parent().toggleClass("offer-border");
					} else if(htmlString == "Hide details") {
						jQuery(this).html("Show details");
						jQuery(this).toggleClass("reveal-active");
						jQuery(this).parents(settings.parentFind).parent().toggleClass("offer-border");
					} else if(htmlString == "Show banners") {
						jQuery(this).html("Hide banners");
						jQuery(this).toggleClass("reveal-active");
					} else if(htmlString == "Hide banners") {
						jQuery(this).html("Show banners");
						jQuery(this).toggleClass("reveal-active");
					}else{
						jQuery(this).toggleClass("reveal-active");
						jQuery(this).parents(settings.parentFind).parent().toggleClass("offer-border");
					}
					
					return false; //Disable Click			
				}); // end click
				
			});//each
		}//end plugin
		
		jQuery.fn.merchantListInfo = function(options) {
			jQuery(this).each(function() {
				
				var settings = jQuery.extend({
					//Used on Quidclans/Fundraiser listing pages
					actionLink : 'dd.more-info a',
					merchantInfo : 'dd.desc',
					showAll : 'input#full-desc',
					listDiv : 'div.module.merchant-list',
					//Used on merchant listing pages
					sortOptions: 'select#merchant-order',
					voucherOptions: 'checkbox#filter_cb_voucher',
					cashbackOptions: 'checkbox#filter_cb_cashback'
				},options||{});
				
				jQuery(settings.sortOptions).change(function() {
					jQuery(settings.sortOptions + " option:selected").each(function () {
						window.location=jQuery(this).val();	
	            	});	
				
				}); // end change
				
//				jQuery(settings.voucherOptions).click(function() {
//					window.location=jQuery(settings.voucherOptions).attr('name') + '/cashback';
//				}); // end change
//				
//				jQuery(settings.cashbackOptions).click(function() {
//					window.location=jQuery(settings.cashbackOptions).attr('name') + '/voucher';	
//				}); // end change
				
				//Toggle hide/show listing description. Used on Quidclans and Fundraisers pages
				jQuery(this).find(settings.actionLink).click(function() {
						jQuery(this).parent().parent().parent().toggleClass("open").find(settings.merchantInfo).slideToggle("slow");
						return false; //Disable Click			
					}); // end click
				
				//Reveal all listing descriptions via checkbox. Used on Quidclans and Fundraisers pages
				jQuery(settings.showAll).click(function() {
						var showDivs = settings.listDiv + " " + settings.merchantInfo;
					if (jQuery(settings.showAll).attr("checked")){
						jQuery(showDivs).slideDown("slow");
						jQuery(showDivs).parent().parent().addClass("open");
					}else{
						jQuery(showDivs).removeClass("open").slideUp("slow");
						jQuery(showDivs).parent().parent().removeClass("open");
					}
				}); // end click
				
			});//end each
		} // end plugin
		
		// Create a custom campaign modal
		jQuery.fn.customCampaignModal = function(options) {
			jQuery(this).each(function(event) {
				var settings = jQuery.extend({
					customCampaignLink : 'a.custom-campaign'
				}, options||{});//end settings
				
				jQuery(settings.customCampaignLink).colorbox({inline:true, href:".modal-custom-campaign", opacity:0.6});
				
				jQuery('#modal-custom-campaign .module-content .content-item form').formValidator({
					onError:function(e,message){
						e.parent().next('div.textbox-alert').unbind("click").remove();
						e.parent().after('<div class="textbox-alert">'+message+'</div>');
						jQuery.fn.colorbox.resize();
						jQuery.fn.colorbox.resize();
					},
					onSuccess:function(e){
						e.parent().next('div.textbox-alert').unbind("click").remove();
						//e.after('<div class="textbox-alert success"></div>');
					},
					rules:{
						'#campaign_name_modal':{
							validate:{
								required:{
									errorMessage:'Oops, that\'s required'
								},
								maxLength:{
									value:100,
									errorMessage:'Oops, that\'s too long'
								} 
							}
						},
						'#campaign_keep_modal':{
							validate:{
								required:{
									errorMessage:'Oops, that\'s required'
								},
								regex:{
									value:'^[0-2]\.[0-9][0-9]?$',
									errorMessage:'Oops, this needs to be a decimal amount (i.e. 2.50) not higher than &pound;2.50'
								}

							}
						}
					}
				});
				
				
				var modalCustomCampaignValidator = jQuery('#modal-custom-campaign .module-content form').data('formValidator');
				var totalBonus = 2.5;
				
				jQuery("#campaign_keep_modal").keyup(function(){
					var retainAmount = jQuery(this).val();
					
					if(retainAmount > 2.5) {
						retainAmount = 2.5;
						jQuery(this).parent().next('div.textbox-alert').unbind("click").remove();
						jQuery(this).parent().after('<div class="textbox-alert">Oops, needs to be smaller than &pound;2.50</div>');
					} else if(retainAmount < 0) {
						retainAmount = 0.01;
						jQuery(this).parent().next('div.textbox-alert').unbind("click").remove();
						jQuery(this).parent().after('<div class="textbox-alert">Oops, needs to be zero or positive money.</div>');
					} else if(isNaN(retainAmount)) {
						retainAmount = 1.25;
						jQuery(this).parent().next('div.textbox-alert').unbind("click").remove();
						jQuery(this).parent().after('<div class="textbox-alert">Oops, this needs to be a decimal amount (i.e. 2.50) not higher than &pound;2.50</div>');
					} else if(retainAmount == '' ) {
						retainAmount = 0.00;					
						if(jQuery('#campaign_share_modal').val() != '2.50'){ 					
							jQuery("#campaign_keep_modal").val(retainAmount);
						}		
					} else {
						jQuery(this).parent().next('div.textbox-alert').unbind("click").remove();
					}
					
					if(retainAmount.length > 3){
						retainAmount = parseFloat(retainAmount).toFixed(2);
						jQuery("#campaign_keep_modal").val(retainAmount);	
					}
					referAmount = totalBonus - retainAmount;						
					referAmount = parseFloat(referAmount).toFixed(2);
					
					jQuery("#campaign_share_modal").val(referAmount);
					jQuery("#campaign_keep_modal").focus();
				});//end keyUp
				
				jQuery("#custom-campaign-submit").click(function(event) {
					
					modalCustomCampaignValidator.reset('#campaign_name_modal');
					modalCustomCampaignValidator.reset('#campaign_keep_modal');
					var isfalse = modalCustomCampaignValidator.validate(jQuery('#modal-custom-campaign .module-content .content-item form'));
					
					if(isfalse == false){
						jQuery.fn.colorbox.resize();
						jQuery.fn.colorbox.resize();
						return false;
					}
					
				}); //end click
				
				jQuery(".cancel-link").click(function() {
					
					jQuery(this).colorbox.close();
				});	//end click
				
			});//end each
		}//end plugin
		// End of create a custom campaign modal
		
		jQuery.fn.loginSignUp = function(options) {
			jQuery(this).each(function(event) {	
				var settings = jQuery.extend({
					loginLink : 'a.sign-in',
					loginModal : 'div.module.modal.login', 
					signUpLink: 'a.join-quidco', 
					signUpDDLink: 'a.sign-in-dropdown',
					signUpModal : '.modal-sign-up',
					joinOptionalLink :'div.module.sign-up fieldset div.form-item.optional a'				
				},options||{});
				
				//Sign in dropdown
				jQuery(settings.signUpDDLink).click(function() {	
					jQuery(this).parent().parent().parent().parent().find("div.module.sign-in-dropdown").slideToggle(function(){
						if ($(this).is(':visible')) {
							jQuery('div.module.sign-in-dropdown input#dd-username').focus();
						}
					});
					
					jQuery(this).parent().parent().parent().toggleClass("open");
					//Fix tabindex issues
					if (jQuery("div.text-nav").hasClass("open")){
						jQuery("input").attr("tabindex", "-1");
						jQuery("div.module.sign-in-dropdown input#dd-username").attr("tabindex", "1");
						jQuery("div.module.sign-in-dropdown input#dd-password").attr("tabindex", "2");
						jQuery("div.module.sign-in-dropdown input#dd-remember_me").attr("tabindex", "3");
						jQuery("div.module.sign-in-dropdown input.sq-submit").attr("tabindex", "4");					
					}else{
						jQuery("input").attr("tabindex", "0");
						jQuery("input#store-qsearch").attr("tabindex", "1");
					}
					return false;
				}); // end click
				
				if(jQuery("body").hasClass("visit-prep")) {
					var cantClose = true;
				}else{
					var cantClose = false;
				}
				
				//Show Join/Login Modal
				jQuery("a.sign-in, a.join-quidco").quidcoModal({href : ".modal-sign-up", closeDisable : cantClose, 
					complete : function(){
						jQuery("#store-qsearch").attr("tabindex", "0");
						if(jQuery('#username_modal').val().length > 0){
							jQuery('#username_modal_label').attr("style", "display:none");
						}
						jQuery(function($){ $(".modal-sign-up .ipos-2 input.textbox").val('') });
						jQuery(".captcha .app").sexyCaptcha('/ajax/captcha');
						
						if ( jQuery("a.join-quidco").attr("sign_in_redirect_path") ) {
							$("input[name=sign_in_redirect_path]").val( jQuery("a.join-quidco").attr("sign_in_redirect_path") );
						}
						//Google analytics
						_gaq.push(
							['_trackPageview', 'OVERLAY>{modal-sign-up}'],
							['cross._trackPageview', 'OVERLAY>{modal-sign-up}']
						);
					},
					closed : function(){
						jQuery("#store-qsearch").attr("tabindex", "1");
					}
				});
				
				jQuery('#password_modal').focus(function(){
					jQuery('#password_modal').attr("style", "display:block");
				}).blur(function(){
					if($('#password_modal').val().length == 0){
						jQuery('#password_modal').attr("style", "display:none");
						jQuery('#password_modal_placeholder').attr("style", "display:block");
					}
				});
				jQuery('#password_modal_placeholder').focus(function(){
					jQuery('#password_modal_placeholder').attr("style", "display:none");
					jQuery('#password_modal').focus();
				});
									
				jQuery('#modal-join .ipos-2 form').formValidator({
					onError:function(e,message){
						e.next('div.textbox-alert').unbind("click").remove();
						e.after('<div class="textbox-alert error">'+message+'</div>');
					},
					onSuccess:function(e){
						e.next('div.textbox-alert').unbind("click").remove();
						e.after('<div class="textbox-alert success"></div>');
					},
					rules:{
						'#new_email':{
							validate:{
								required:{
									errorMessage:'Oops, that\'s required'
								},
								maxLength:{
									value:100,
									errorMessage:'Oops, that\'s too long'
								},
								email:{
									errorMessage:'Oops, that\'s not an email'
								},
								remote:{
									value:{
										type:'POST',
										url: '/email-check/',
										dataType: 'text',
										data:{
											'new_email':function(){
												return $('#new_email').val();
											},
											'check_email':'yes'
										}
									},
									onRun:function(){
										$('#new_email').next('div.textbox-alert').unbind("click").remove();
										$('#new_email').after('<div class="textbox-alert">Checking</div>');
									},
									onSuccess:function(data,status){
										if(data == 'no'){
											$('#new_email').next('div.textbox-alert').unbind("click").remove();
											$('#new_email').after('<div class="textbox-alert error">Oops, that email is in use. <a href="/sign-in/">Please sign in</a></div>');
											
											$('#new_email').next('div.error').click(function(){
												modalJoin.close();
												modalLogin.open();
											});
											return false;
										}else{
											$('#new_email').next('div.textbox-alert').unbind("click").remove();
											$('#new_email').after('<div class="textbox-alert success"></div>');
											return true;
										}
									}
								}
							}
						},
						'#confirm_email':{
							validate:{
								match:{
									value:$('#new_email'),
									errorMessage:'Oops, that doesn\'t match'
								}
							}
						},
						'#new_password':{
							validate:{
								minLength:{
									value:6,
									errorMessage:'Oops, that\'s not long enough'
								},
								regex:{
									value:'^[a-z|A-Z|0-9]{6,}$',
									errorMessage:'Oops, only numbers and/or letters'
								}
							}
						}
					}
				});
				
				var modalJoinValidator = jQuery('#modal-join .ipos-2 form#frmJoin').data('formValidator');
				
				jQuery('#username_modal').blur(function(){
					if($('#username_modal').val().length == 0){
						jQuery('#username_modal_label').attr("style", "display:block");
					}
				}).focus(function(){
					jQuery('#username_modal_label').attr("style", "display:none");
				});
				
				jQuery('#new_email').blur(function(){
					modalJoinValidator.validate($(this));
					if($('#confirm_email').val().length > 0){
						modalJoinValidator.validate(jQuery('#confirm_email'));
					}
					if($('#new_email').val().length == 0){
						jQuery('#new_email_label').attr("style", "display:block");
					}
				}).focus(function(){
					jQuery('#new_email_label').attr("style", "display:none");
					modalJoinValidator.reset('timeout');
					jQuery(this).next('div.textbox-alert').unbind("click").remove();
					jQuery(this).after('<div class="textbox-alert">To get your cashback</div>');
				});
					
				jQuery('#confirm_email').blur(function(){
					jQuery('#confirm_email').next('div.textbox-alert').unbind("click").remove();
					if($('#confirm_email').val().length > 0){
						modalJoinValidator.validate($('#confirm_email'));
					}
					else{
						jQuery('#confirm_email_label').attr("style", "display:block");
					}
				}).focus(function(){
					jQuery('#confirm_email_label').attr("style", "display:none");
					jQuery(this).next('div.textbox-alert').unbind("click").remove();
					jQuery(this).after('<div class="textbox-alert">To make sure it\'s right</div>');
				});
				
				jQuery('#new_password').blur(function(){
					modalJoinValidator.validate(jQuery(this));
					if($('#new_password').val().length == 0){
						jQuery('#new_password_label').attr("style", "display:block");
					}
				}).focus(function(){
					jQuery('#new_password_label').attr("style", "display:none");
					jQuery(this).next('div.textbox-alert').unbind("click").remove();
					jQuery(this).after('<div class="textbox-alert">At least 6 numbers and/or letters</div>');
				});
				
				jQuery('#validate_modal').blur(function(){
					if($('#validate_modal').val().length == 0){
						jQuery('#validate_modal_label').attr("style", "display:block");
					}
					jQuery(this).next('div.textbox-alert').unbind("click").remove();
					validateCaptchaModal('blur');					
				}).focus(function(){
					jQuery('#validate_modal_label').attr("style", "display:none");
					jQuery(this).next('div.textbox-alert').unbind("click").remove();
					jQuery(this).after('<div class="textbox-alert">Enter the text from the image below</div>');
				});
				
				function validateCaptcha(){
					if(jQuery("#captchaWrapper .targetWrapper").hasClass("captchaSuccess")){
						return true;
					}
					else{
						jQuery("#captchaWrapper .targetWrapper").addClass("captchaFail");
						return false;
					}
				}
				
				function validateTerms(){
					if(jQuery('#agree_to_terms_modal').attr('checked') == true){
						jQuery("#agree_to_terms_modal").parent().removeClass("terms-error");
						return true;
					}
					else{
						jQuery("#agree_to_terms_modal").parent().addClass("terms-error");
						return false;
					}
				}
							
				jQuery('#modal-join .ipos-2 form').submit(function(ev){
					modalJoinValidator.reset('timeout');
					modalJoinValidator.reset('#confirm_email');
					var captchaIsFalse = validateCaptcha();
					var termsIsFalse = validateTerms();
					var isfalse = modalJoinValidator.validate(jQuery(this));
					if (!isfalse || !captchaIsFalse || !termsIsFalse) { 
						ev.preventDefault();
					}
				});	
				
			}); // end each
		} // end plugin

		jQuery.fn.authentication = function(options) {
			jQuery(".authenticated .close").click(function() {
				jQuery(this).parent().hide();
			}); // end each
		} // end plugin

		jQuery.fn.referralMerchantBanner = function(options) {
			jQuery(".referral-merchant-banner .close").click(function() {
				jQuery(this).parent().hide();
				$.cookie("show_referral_header", "false", { expires: 30 });
			}); // end each
		} // end plugin
		
		
		jQuery.fn.joinQuidco = function(options) {
			jQuery(this).each(function() {							   
				var settings = jQuery.extend({
					joinOptionalLink :'div.module.sign-up fieldset div.form-item.optional a',
					joinPostcode: "div.module.sign-up fieldset div.form-item.optional input#postcode"
				},options||{});
				
				// check if uk postcode is valid
				if(jQuery(".optional").length){
					jQuery(".sq-submit, select").click(function() {
						if (jQuery(settings.joinPostcode).val().length > 0){
							jQuery(settings.joinPostcode).parent().find("div").remove();
							  if (checkPostCode (jQuery(settings.joinPostcode).val())) {
								  jQuery(settings.joinPostcode).val(checkPostCode (jQuery(settings.joinPostcode).val()));
							  } else {
								  jQuery(settings.joinPostcode).after("<div class='textbox-alert error'>Oops, we don't recognise that postcode</div>")
								  return false;
							  } //end if			
						}	
					}); // end click
				}				
				
				jQuery('#join-quidco').formValidator({
					onError:function(e,message){
						e.next('div.textbox-alert').unbind("click").remove();
						e.after('<div class="textbox-alert error">'+message+'</div>');
					},
					onSuccess:function(e){
						e.next('div.textbox-alert').unbind("click").remove();
						e.after('<div class="textbox-alert success"></div>');
					},
					rules:{
						'#new_email_join':{
							validate:{
								required:{
									errorMessage:'Oops, that\'s required'
								},
								maxLength:{
									value:100,
									errorMessage:'Oops, that\'s too long'
								},
								email:{
									errorMessage:'Oops, that\'s not an email'
								},
								remote:{
									value:{
										type:'POST',
										url: '/join-quidco/',
										dataType: 'text',
										data:{
											'new_email':function(){
												return $('#new_email_join').val();
											},
											'check_email':'yes'
										}
									},
									onRun:function(){
										$('#new_email_join').next('div.textbox-alert').unbind("click").remove();
										$('#new_email_join').after('<div class="textbox-alert">Checking</div>');
									},
									onSuccess:function(data,status){
										if(data == 'no'){
											$('#new_email_join').next('div.textbox-alert').unbind("click").remove();
											$('#new_email_join').after('<div class="textbox-alert error">Oops, that email is in use. <a href="/sign-in/">Please sign in</a></div>');
											// reattach jQuery event handler to the new sign in link
											jQuery("a.sign-in").colorbox({inline:true, href:"div.module.modal.login", opacity:0.6, initialWidth:"350px", initialHeight:"257px"});
											$('#new_email_join').next('div.error').click(function(){
												modalJoin.close();
												modalLogin.open();
											});
											return false;
										}else{
											$('#new_email_join').next('div.textbox-alert').unbind("click").remove();
											$('#new_email_join').after('<div class="textbox-alert success"></div>');
											return true;
										}
									}
								}
							}
						},
						'#confirm_email_join':{
							validate:{
								match:{
									value:$('#new_email_join'),
									errorMessage:'Oops, that doesn\'t match'
								}
							}
						},
						'#new_password_join':{
							validate:{
								minLength:{
									value:6,
									errorMessage:'Oops, that\'s not long enough'
								},
								regex:{
									value:'^[a-z|A-Z|0-9]{6,}$',
									errorMessage:'Oops, only numbers and/or letters'
								}
							}
						}
					}
				});
				
				var modalJoinValidator = jQuery('#join-quidco').data('formValidator');
	
				jQuery('#new_email_join').blur(function(){
					modalJoinValidator.validate($(this));
					if($('#confirm_email_join').val().length > 0){
						modalJoinValidator.validate(jQuery('#confirm_email_join'));
					}
				}).focus(function(){
					modalJoinValidator.reset('timeout');
					jQuery(this).next('div.textbox-alert').unbind("click").remove();
					jQuery(this).after('<div class="textbox-alert">To get your cashback</div>');
				});

				
				jQuery('#confirm_email_join').blur(function(){
					jQuery('#confirm_email_join').next('div.textbox-alert').unbind("click").remove();
					if($('#confirm_email_join').val().length > 0){
						modalJoinValidator.validate($('#confirm_email_join'));
					}
				}).focus(function(){
					jQuery(this).next('div.textbox-alert').unbind("click").remove();
					jQuery(this).after('<div class="textbox-alert">To make sure it\'s right</div>');
				});
				
				jQuery('#new_password_join').blur(function(){
					modalJoinValidator.validate(jQuery(this));
				}).focus(function(){
					jQuery(this).next('div.textbox-alert').unbind("click").remove();
					jQuery(this).after('<div class="textbox-alert">At least 6 numbers and/or letters</div>');
				});
				
				jQuery('#agree_to_terms_join').click(function(){
					if(jQuery('#agree_to_terms_join').attr('checked') == true){
						jQuery(this).next('div.textbox-alert').unbind("click").remove();
					}
					else{
						jQuery(this).next('div.textbox-alert').unbind("click").remove();
				jQuery(this).after(termsError);
					}
				});
				
				function validateCaptcha(){
					if(jQuery("#captchaWrapper .targetWrapper").hasClass("captchaSuccess")){
						return true;
					}
					else{
						jQuery("#captchaWrapper .targetWrapper").addClass("captchaFail");
						return false;
					}
				}
				
				function validateTerms(){
					if(jQuery('#agree_to_terms_join').attr('checked') == true){
						jQuery("#agree_to_terms_join").parent().removeClass("terms-error");
						return true;
					}
					else{
						jQuery("#agree_to_terms_join").parent().addClass("terms-error");
						return false;
					}
				}
				
				jQuery('#join-quidco').submit(function(ev){
					
					var cobrand = jQuery('#cobrand_type').val();
					
					modalJoinValidator.reset('timeout');
					modalJoinValidator.reset('#confirm_email_join');
					var termsIsFalse = validateTerms();
					var isfalse = modalJoinValidator.validate(jQuery(this));
					
					if(cobrand == 'www'){
						var captchaIsFalse = validateCaptcha();
						if (!isfalse || !captchaIsFalse || !termsIsFalse) { 
							ev.preventDefault();
						}
					} else {
						if(!isfalse || !termsIsFalse){
							ev.preventDefault();
						}	
					}	
				});			
				
				jQuery(function($){ $(".sign-up input.textbox").val('') });
				
			}); // end each
		} // end plugin	

		jQuery.fn.itemBoxMore = function(options) { 
			jQuery(this).each(function() {							   
				var settings = jQuery.extend({
					rhsVisitedDiv : 'div.my-quidclans',
					containerDiv : '.content-item',
					showAll: 'div.my-quidclans p.all a', 
					defaultMsg : 'div.default-msg',
					cookieName : 'quidclans'
				},options||{});
				if (jQuery.cookie(settings.cookieName) == "true"){
					jQuery(settings.rhsVisitedDiv  + " " + settings.containerDiv).attr("style", "display:none").show();
					jQuery(settings.showAll).text("Show Less").removeClass("more");
				}
				jQuery(settings.showAll).click(function() {
					
					if (jQuery(settings.showAll).hasClass("more")){
						jQuery(settings.rhsVisitedDiv  + " " + settings.containerDiv).attr("style", "display:none").show();
						jQuery(this).text("Show Less").removeClass("more");
						jQuery.cookie(settings.cookieName, 'true');
					}else{
						var itemCount = jQuery(settings.rhsVisitedDiv  + " " + settings.containerDiv).size();
						if(settings.rhsVisitedDiv == "div.earnings-tracking"){
							itemNumber = 3;
						}
						else{
							itemNumber = 5;
						}
						for (i=itemNumber;i<=itemCount;i++){
							jQuery(settings.rhsVisitedDiv  + " " + settings.containerDiv + ":eq(" + i + ")").slideUp();
						} // for
						jQuery(settings.rhsVisitedDiv  + " " + settings.containerDiv).attr("style", "display:none").show();
						jQuery(this).text("Show All").addClass("more");	
						jQuery.cookie(settings.cookieName, 'false');
					}
					return false; //Disable Click	
				});
			});	
		}		
		
		
		/**
		 * Recently visited
		 */
		jQuery.fn.recentlyVisited = function(options) { 
			jQuery(this).each(function() {							   
				var settings = jQuery.extend({
					rhsVisitedDiv : 'div.visited',
					containerDiv : '.content-item',
					showAll: 'div.visited p.all a', 
					removeVisitLink : 'span.remove a',
					defaultMsg : 'div.default-msg'
				},options||{});
				if (jQuery.cookie("recentlyVisited") == "true"){
					jQuery(settings.rhsVisitedDiv  + " " + settings.containerDiv).attr("style", "display:none").show();
					jQuery(settings.showAll).text("Show Less").removeClass("more");
				}				
				jQuery(settings.showAll).click(function() {
					if (jQuery(settings.showAll).hasClass("more")){
						jQuery(settings.rhsVisitedDiv  + " " + settings.containerDiv).attr("style", "display:none").show();
						jQuery(this).text("Show Less").removeClass("more");
						jQuery.cookie('recentlyVisited', 'true');
					}else{
						var itemCount = jQuery(settings.rhsVisitedDiv  + " " + settings.containerDiv).size();
						for (i=5;i<=itemCount;i++){
							jQuery(settings.rhsVisitedDiv  + " " + settings.containerDiv + ":eq(" + i + ")").slideUp();
						} // for
						jQuery(settings.rhsVisitedDiv  + " " + settings.containerDiv).attr("style", "display:none").show();
						jQuery(this).text("Show All").addClass("more");
						jQuery.cookie('recentlyVisited', 'false');
					}
					return false; //Disable Click	
				});
				jQuery(this).find(settings.removeVisitLink).click(function() {
					var merchant_id = jQuery(this).attr("rel");
					$.ajax({
						  type: 'GET',
						  cache: false,
						  url: '/ajax/home',
						  data: 'action=remove_merchant_visit&merchant_id=' + encodeURI(merchant_id),
						  success: function(html) {
						    	//successMsg;
						  }
					});
				});
			});	
		}
		
		
		/**
		 * Add favourite
		 */
		jQuery.fn.favourites = function(options) {
			jQuery(this).each(function() {
				var settings = jQuery.extend({
					favLink : '.addFavourite a',
					containerDiv : 'div.content-item',
					showAll: 'div.user-favourites p.all a', 
					removeBtn : 'span.remove a',
					favCounterDiv : 'div.user-favourites span.fav-count',
					rhsFavDiv : 'div.user-favourites',
					defaultMsg : 'div.default-msg',
					addedFavDiv : '.favorites span'
				},options||{});
				jQuery(settings.favLink).live('click', function() {
					var itemID = jQuery(this).attr("id");
					var submit_string = jQuery(this).attr("rel");
					var submit_array = submit_string.split("_");					                                
					var itemName = submit_array[0];					                                
					var itemLink = submit_array[1];
					var successMsg = jQuery(this).parent().replaceWith("<p class=\"added\" id=\""+ itemID + "\">Added to favourites</span>");
					
					jQuery.ajax({
						type: 'GET',
						cache: false,
						url: '/ajax/index',
						data: 'action=add_favourite&merchant_id=' + escape(itemID),
						success: function(html) {
						
							// replace favourites with Added To Favourites text
							successMsg;
							
							// if this is the first favourite added, show the favourites link in the header
							if ( !jQuery('#header li#faves').is(':visible') ) {
								jQuery('#header li#faves').show();
								jQuery('#header .text-nav ul').addClass('faves-closed');
							}
						
							// for the merchant category page, increment counter
							if(jQuery("body").hasClass("merchant-category")){
								if(jQuery(settings.rhsFavDiv).length>0){
									var favCount = jQuery(settings.favCounterDiv).text().replace("(","").replace(")","");
									jQuery(settings.rhsFavDiv + " div.module-content div.content-item:eq(0)").before("<div class='content-item'><p><a href='" + itemLink + "'>" + itemName +"</a></p><span class='remove'><a href='#' rel='" + itemID + "'>Remove</a></span></div>");	
									favCount++;
									jQuery(settings.favCounterDiv).text("(" + favCount + ")");
								}
							}
							
							// get user favourites
							jQuery.ajax({
								type: 'GET',
								cache: false,
								url: '/ajax/user/get_favourites',
								success: function(html) {
									jQuery('#header .favourites-dropdown .module-content').html(html);
									jQuery('#header .favourites-dropdown .module-content .content-item').mouseHover();
									faves = jQuery('#header .text-nav li#faves a');
									faves.fadeOut(200, function() {
										faves.fadeIn(200, function() {
											faves.fadeOut(200, function() {
												faves.fadeIn(200, function() {
												})
											})
										})
									});
								}
							});
					
						}
					}); //ajax
				}); // add favourite

				
				/**
				 * Remove favourite
				 */
				jQuery(settings.removeBtn).live('click', function() {
					
					var merchantID = escape(jQuery(this).attr("rel"));
					var successMsg = jQuery(this).parent().parent().slideUp(function(){jQuery(this).remove();});

					// if the user clicked the recently visited remove link, do not try remove from favourite merchants
					if ( jQuery(this).parent().parent().parent().parent().parent().hasClass('visited') ) {
						return;
					}
					
					jQuery.ajax({
						type: 'GET',
						cache: false,
						url: '/ajax/index',
						data: 'action=remove_favourite&merchant_id=' + merchantID,
						success: function(html) {
							successMsg;
							var favCount = jQuery(settings.favCounterDiv).text().replace("(","").replace(")","");
							favCount = favCount - 1;
							jQuery(settings.favCounterDiv).text("(" + favCount + ")");
							if (favCount <= 5){
								jQuery(settings.showAll).hide();
								if (favCount == 5){
									jQuery(settings.rhsFavDiv  + " " + settings.containerDiv + ":eq(5)").slideDown();
								}else if(favCount === 0){
									jQuery(settings.favCounterDiv).text("");
									jQuery(settings.defaultMsg).slideDown();
								}// else if
							}//if
							else{
								for (i=0;i<=5;i++){
									jQuery(settings.rhsFavDiv  + " " + settings.containerDiv + ":eq(" + i + ")").slideDown();
								} // for						
							} //else
						} //success
					
					});
					if(jQuery("body").hasClass("merchant-category")){
						var RemoveID = "#" + merchantID;
						var RemoveName = jQuery(this).parent().parent().find("p a").text();
						var RemoveURLName = jQuery(this).parent().parent().find("p a").attr("href");
						var RemoveURLName = RemoveURLName.substr(1);
						var RemoveURLNameArray = RemoveURLName.split("?");
						var RemoveURLName = RemoveURLNameArray[0];
						jQuery(RemoveID).replaceWith("<p><a id=\""+ merchantID + "\" rel=\"" + RemoveName + "_" + RemoveURLName + "\">Add to your favourites</a></p>");
					}
					
					
					if ( jQuery('.user-favourites .module-content') ) {
						jQuery('.user-favourites .module-content').find('.content-item').each(function() {
							if ( merchantID == jQuery(this).find('span.remove a').attr('rel') ) {
								jQuery(this).slideUp(function(){jQuery(this).remove();});
							}
						});
					}
					
					// remove favourites from drop down
					if ( jQuery('#header .favourites-dropdown .module-content') ) {
						jQuery('#header .favourites-dropdown .module-content').find('.content-item').each(function() {
							if ( merchantID == jQuery(this).find('span.remove a').attr('rel') ) {
								jQuery(this).slideUp(function() {
									jQuery(this).remove();
									if ( jQuery('#header .favourites-dropdown .module-content .content-item').length == 0) {
										jQuery('#header .favourites-dropdown').slideUp(function() {
											jQuery('#header .text-nav ul').removeClass('faves-open');
											jQuery('#header .text-nav ul #faves a').removeClass('open');										
											jQuery('#header li#faves').hide();
											jQuery('#header .text-nav ul').removeClass('faves-closed');
										});
									}
								});
							}
						});
					}
				});// remove favourite
				
			//	if(jQuery("body").hasClass("merchant-category") ||jQuery("body").hasClass("home") ){
					jQuery(settings.showAll).click(function() {
						if (jQuery(settings.showAll).hasClass("more")){
							jQuery(settings.rhsFavDiv  + " " + settings.containerDiv).attr("style", "display:none").show();
							jQuery(this).text("Show Less").removeClass("more");
							jQuery.cookie('favourites', 'true');
						}else{
							var favCount = jQuery(settings.favCounterDiv).text().replace("(","").replace(")","");
							for (i=5;i<=favCount;i++){
								jQuery(settings.rhsFavDiv  + " " + settings.containerDiv + ":eq(" + i + ")").slideUp();
							} // for
							jQuery(settings.rhsFavDiv  + " " + settings.containerDiv).attr("style", "display:none").show();
							jQuery(this).text("Show All").addClass("more");
							jQuery.cookie('favourites', 'false');
						}
						return false; //Disable Click	
					});
			//	}// if body.merchant-category or home
			}); // end each
		} // end plugin	
		
		jQuery.fn.signupLoad = function() {
			jQuery.fn.colorbox({inline:true, open:true, opacity:0.6, href: ".modal-sign-up", width:"654px"});
			//Google analytics
			_gaq.push(
				['_trackPageview', 'OVERLAY>{modal-sign-up-auto}'],
				['cross._trackPageview', 'OVERLAY>{modal-sign-up-auto}']
			);
		} // end plugin	
		
		/**
		 * refer a friend part 1
		 * 
		 * Hopefully only I will ever have to look at this madness,
		 * but incase you are not me, let the imaginary me
		 * take you by the hand and guide you through it.
		 * 
		 */
		jQuery.fn.referModal = function(options) {
			jQuery(this).each(function() {			
				
				var settings = jQuery.extend({
					referDiv : '.modal-refer-this',
					referLink : '.referLink'
				},options||{});	
				
					jQuery(settings.referLink).colorbox({inline:true, href: settings.referDiv, opacity:0.6, width:"654px"});
					
					jQuery(settings.referLink).click(function(){
						//Google analytics
						_gaq.push(
							['_trackPageview', 'OVERLAY>{modal-refer-this}'],
							['cross._trackPageview', 'OVERLAY>{modal-refer-this}']
						);
					});
					
					jQuery('#friend_one_modal').click(function(){ 
						jQuery('#friend_one_modal_label').hide();
					});
					
					
					/**
					 *  when a user click a logo to import contacts it will be in a new window
					 *  we need to let the user know if they look back that we are doing this...
					 *  the 'rel' is because we need to personalise the alert message depending
					 *  on provider.
					 *  
					 *  this is where part 2 comes in. validation explainations are provided below
					 *  but part 2 is the function 'fillContacts'
					 */
				
					jQuery(".provider-link").live('click', function() {
						var rel_explode = new String(jQuery(this).attr("rel"));
						var rel_array = rel_explode.split(','); 
						var provider = rel_array[0];
						var continue_var  = rel_array[1];
						var protocol = jQuery(this).attr("rev"); 	
							
						if (continue_var==undefined && jQuery("#imported-email-list").val().length > 2) {
							jQuery(this).parents(".content-item").find(".alert").show();
							jQuery(this).parents(".content-item").find(".alert p").html("You have already added your contacts. If you try again the contacts you've already imported will be overwritten. <a class='provider-link "+provider.toLowerCase()+"' rev='"+protocol+"' rel='"+provider+",continue' href='/user-referrals?provider="+provider.toLowerCase()+"&protocol='"+protocol+"' target='_blank'>Continue</a>");	
							jQuery.fn.colorbox.resize();
							jQuery.fn.colorbox.resize();
							return false;
						}
						else {
							jQuery(this).parents(".content-item").find(".alert").show();
							jQuery(this).parents(".content-item").find(".alert p").html("We have opened a new window to fetch your contacts info from " + provider + ", please login to " + provider + " there.");
							if(provider == 'Yahoo') {
								jQuery("#modal-refer-this .pos-2 .module-header p").addClass("yahoo");
							} else {
								jQuery("#modal-refer-this .pos-2 .module-header p").removeClass("yahoo");
							}
							jQuery.fn.colorbox.resize();
						}
					});//click
					
					jQuery(".close-modal").click(function() {
						jQuery(this).colorbox.close();
						return false;
					});
					
					jQuery('#modal-refer-this form').formValidator({
						onError:function(e,message){
							e.parent().prev('div.textbox-alert').unbind("click").remove();
							e.parent().before('<div class="form-item textbox-alert error">'+message+'</div>');
							jQuery.fn.colorbox.resize();
						},
						onSuccess:function(e){
							e.parent().prev('div.textbox-alert').unbind("click").remove();
							jQuery.fn.colorbox.resize();
						},
						rules:{
							'#yourname_modal':{
								validate:{
									required:{
										errorMessage:'<strong><font>Oops</font></strong>, please enter a name'
									}
								}
							}
						}
					});
					
					var modalJoinValidator = jQuery('#modal-refer-this form').data('formValidator');
					
					jQuery('#yourname_modal').blur(function(){
						modalJoinValidator.validate($(this));
					});
				
			}); // end each
			
			/**
			 * future reference: clicks included in an .each() get executed a bazillion times, give or take.
			 * try to keep them outside.
			 * 
			 * normally we would use the formValidator plugin for everything, however becasue we have multiple
			 * values (i.e. lots of emails seperated by commas) we can't validate the emails the usual way.
			 * Also the emails field is not necessarily required if they have imported contacts, so we cant use
			 * the normal 'required' validation either.
			 */
			jQuery('#modal-refer-this form').submit(function(ev){
				
				jQuery('#modal-form-error').remove();
				
				//if user has not imported and not entered any addresses, tell them
				if((jQuery(".imported-addresses p").html().length < 2) && (jQuery("#friend_one_modal").val().length < 2)){
					if(jQuery("#friend_one_modal").parent().before('<div id="modal-form-error" class="form-item textbox-alert error"><b>Oops,</b> that is required</div>')) {
						jQuery.fn.colorbox.resize();
						jQuery.fn.colorbox.resize();
					}
					return false;
				} else if(jQuery("#friend_one_modal").val().length > 2){
					/**
					 * if they did type in their own addresses we need to check them.
					 * so we split the value into an array seperated by commas.
					 */ 
					var addresses = jQuery("#friend_one_modal").val().split(',');
					var toCheck = "";
					
					for (addr in addresses){
						//do a trim in case user put spaces after commas and such
						toCheck = jQuery.trim(addresses[addr]);
						if(!isValidEmailAddress(toCheck)) {
							
							if(jQuery("#friend_one_modal").parent().before('<div id="modal-form-error" class="form-item textbox-alert error"><b>Oops,</b> there is an invalid address</div>')) {
								//colorbox resize rarely works correctly becasue it calculates during new DOM data being inserted
								//calling twice is the quickest and easiest way to overcome this
								jQuery.fn.colorbox.resize();
								jQuery.fn.colorbox.resize();
							}
							return false;
						}
					}
				}
				
				modalJoinValidator.reset('timeout');
				var isfalse = modalJoinValidator.validate(jQuery(this));
				if (!isfalse) { 
					ev.preventDefault();
				}
			});
			
			/**
			 * user submits contacts, logically this would go in part 2,
			 * however because the part 2 function (fillContacts) is called with each import,
			 * so would this event binder be. This means each import would click this
			 * button more and more times at once, so it has to go here.
			 * 
			 * The two vers below are delcared here so that they are available to the following
			 * click function for showing and hiding the email list. 
			 */
			
			var short ="";
			var selected = "";
			
	    	jQuery("#add-selected-emails").click(function() {
	    		
	    		selected = "";
	    		short= "";
	    		
	    		//find all checked boxes, and pull email out of value.
	    		//NOTE: a space is put in deliberately to make the string wrap inside the <p> tag
	    		jQuery(this).parent().parent().find("input:checked").each(function() {
	    			selected += ", " + jQuery(this).parent().find("input:hidden").attr("value");
	    		});
	    		
	    		//if they actually selected any
	    		if(selected.length > 0) {
	    			//show the imported section on the form
	    			jQuery(".imported-addresses").show();
	    			//there will be a comma at the start, take it out
	    			selected = selected.substring(2);
	    			
	    			jQuery("#imported-email-list").val(selected);
	    			
	    			//if there is more than a line of email data
	    			if(selected.length > 60){
	    				//create short version and put that in imported list
	    				short = selected.substring(0, 57) + "...";
	    				jQuery(".imported-addresses p").html(short);
	    				jQuery("#modal-refer-this .show-all-imported").show();
	    				
	    			} else {
	    				jQuery("#modal-refer-this .show-all-imported").hide();
	    				jQuery(".imported-addresses p").html(selected);
	    			}
	    		}
	    		
	    		//hide the import form as we are done with it and show the referral form again
	    		jQuery("#modal-refer-this .pos-1").toggleClass("content-hidden");
	    		jQuery("#modal-refer-this .pos-2").toggleClass("content-hidden");
	    		jQuery("#modal-refer-this .alert").hide();
	    		
	    		//and again >:(
	    		jQuery.fn.colorbox.resize();
		    	jQuery.fn.colorbox.resize();
	    		
	    		return false;
	    	});//end click
	    	
	    	//if they want to show the whole list, put the whole list in and change link to hide and vis versa
			jQuery("#modal-refer-this .show-all-imported").click(function() {
				//check if the import list matches the short or full version
				if(jQuery(".imported-addresses p").html() == short) {
					jQuery(".imported-addresses p").html(selected);
					jQuery("#modal-refer-this .show-all-imported").html("hide some");
				} else {
					jQuery(".imported-addresses p").html(short);
					jQuery("#modal-refer-this .show-all-imported").html("show all");
				}
				
				jQuery.fn.colorbox.resize();
		    	jQuery.fn.colorbox.resize();
				
				return false;
				
			});//end click
			// following to be commented later
			jQuery("#content").find('.referLink').each(function() {
				jQuery(this).click(function() {
					jQuery('#message_modal').empty();
					
					var username = jQuery("#username_reference_modal").val();
					var userID = jQuery("#refer_user_id").val();
					var cobrandName = jQuery("#refer_cobrand_name").val();
					var cobrandURL =  'http://' + window.location.hostname + '/';
					
					if(jQuery("#refer_campaign_id").length > 0) {
						var campaign_id = jQuery("#refer_campaign_id").val();
					} else {
						var campaign_id = '';
					}
					
					var merchantName;
					//All info-box components
					if(jQuery(this).parent().parent().parent().parent().hasClass('info-box')) {
						var referType = "info-box";
						merchantName = jQuery(this).parent().parent().parent().parent().find(".module-content p").html();
						var merchantLink = jQuery(this).parent().parent().parent().parent().find(".module-content a").attr('rel');
						
						var contents = jQuery("#refer_message_banner").attr("value");
						var contents_subject = jQuery("#refer_subject_banner").attr("value");

					}
					else{
						// Referrals page specific
						if (jQuery("body").hasClass('referral-earnings') || jQuery("body").hasClass('referrals')) {
							var referType = "quidco-referral";
							var contents = jQuery("#refer_message_quidco").attr("value");
							var contents_subject = jQuery("#refer_subject_quidco").attr("value");
							var campaign_id = jQuery(this).find("a").attr("rel");
						}
						// Amazon-deal-finder page specific
						if (jQuery("body").hasClass('amazon-deal-finder')) {
							var contents = jQuery("#refer_message_merchant").attr("value");
							var contents_subject = jQuery("#refer_subject_merchant").attr("value");
							var campaign_id = '';
							var merchantLink = 'amazon-deal-finder';
							var merchantName = 'Amazon Offers and Amazon Discounts - Up to 75% off Hidden Amazon Deals';
						}
						//Merchant page specific
						if(jQuery("body").hasClass('merchant')){
							var merchantName = jQuery("#content-2 .ipos-1").find(".logo img").attr('alt');
							var merchantLink = jQuery("#content-2 .ipos-1").find(".logo img").attr('class');
							//Refer merchant
							if(jQuery(this).parent().parent().parent().parent().hasClass('links')){
								var referType = "merchant-merchant";
								var contents = jQuery("#refer_message_merchant").attr("value");
								var contents_subject = jQuery("#refer_subject_merchant").attr("value");
							}
							//Refer offer
							if(jQuery(this).parent().parent().parent().parent().parent().parent().hasClass('merchant-list-item')){
								var referType = "merchant-offer";
								var offerDesc = jQuery(this).parent().parent().parent().parent().parent().find(".module-header h3").html();
								if(jQuery(this).parent().parent().parent().parent().parent().hasClass('cashback-item')){
									var offerType = "cashback";
								}
								if(jQuery(this).parent().parent().parent().parent().parent().hasClass('voucher-item')){
									var offerType = "voucher";
								}
								if(jQuery(this).parent().parent().parent().parent().parent().hasClass('voucher-cashback-item')){
									var offerType = "voucher";
								}
								if(jQuery(this).parent().parent().parent().parent().parent().hasClass('voucher-print-item')){
									var offerType = "voucher";
								}
								if(jQuery(this).parent().parent().parent().parent().parent().hasClass('deal-item')){
									var offerType = "deal";
								}
								
							}
						}
						//Refer offer (Hot Offers and User homepage)
						
						if(jQuery("body").hasClass('hot-offers') || jQuery("body").hasClass('home')){
							
							var referType = "merchant-offer";
							var merchantName = jQuery(this).parent().parent().parent().parent().parent().parent().find(".module-header a img").attr('alt');
							var merchantLink = jQuery(this).parent().parent().parent().parent().parent().parent().find(".module-header a img").attr('class');
							var offerDesc =  jQuery.trim(jQuery(this).parents(".offer").find(".module-header h2 a").html().replace(/[\t\s]+/g,' '));
							
							if(jQuery(this).parent().parent().parent().parent().parent().parent().hasClass('cashback-item')){
								var offerType = "cashback";
							}
							if(jQuery(this).parent().parent().parent().parent().parent().parent().hasClass('voucher-item')){
								var offerType = "voucher";
							}
							if(jQuery(this).parent().parent().parent().parent().parent().parent().hasClass('deal-item')){
								var offerType = "deal";
							}
						}
						
						
						if(referType == "merchant-offer"){ 
						
							if((offerType == "cashback") || (offerType == "deal")){
								var contents = jQuery("#refer_message_cashback").attr("value");
								var contents_subject = jQuery("#refer_subject_cashback").attr("value");
							}
							if(offerType == "voucher"){
								var contents = jQuery("#refer_message_voucher").attr("value");
								var contents_subject = jQuery("#refer_subject_voucher").attr("value");
							}
							if(offerType == "deal"){
								var contents = jQuery("#refer_message_offer").attr("value");
								var contents_subject = jQuery("#refer_subject_offer").attr("value");
							}
						}
					}// else
					
					contents = contents.replace('%merchant%',merchantName);
					contents = contents.replace('%url_name%',merchantLink);
					contents = contents.replace('%voucher%',offerDesc);
					contents = contents.replace('%cashback_rate%',offerDesc);
					contents = contents.replace('%user_name%',username);
					contents = contents.replace('%user_id%', userID);
					if(campaign_id != ''){
						campaign_id = campaign_id + "/";
					}
					contents = contents.replace('%campaign_id%', campaign_id);
					
					jQuery('#message_modal').prepend(contents);
					jQuery('#subject_deal_modal').val(contents_subject);
				});
			});
		} // end plugin	
		
		jQuery.fn.revealReferrals = function(options) {
			var settings = jQuery.extend({
				personalLink : '.pos-2 .method-outro a',
				bannersLink : '.pos-3 .method-outro a',
				bannersContainer : '.pos-4',
				personalContainer : '.refer-methods'
			},options||{});
			//Open-close personal onclick
			jQuery(settings.personalLink).click(function(e) {
				e.preventDefault();
				if(jQuery(this).hasClass("open")){
					jQuery(this).removeClass("open");
					jQuery(this).addClass("closed");
					jQuery(this).parent().parent().find(settings.personalContainer).hide();
					jQuery(this).parent().parent().parent().parent().removeClass("refer-open");
					//closePersonal();
				}
				else{
					if(jQuery(this).parent().parent().parent().parent().find(settings.bannersLink).hasClass("open")){
						jQuery(this).parent().parent().parent().parent().find(settings.bannersLink).trigger("click");
						//closeBanners();
					}
					jQuery(this).removeClass("closed");
					jQuery(this).addClass("open");
					jQuery(this).parent().parent().find(settings.personalContainer).show();
					jQuery(this).parent().parent().parent().parent().addClass("refer-open");
					//openPersonal();
				}
			});
			//Open-close banners onclick
			jQuery(settings.bannersLink).click(function(e) {
				e.preventDefault();
				if(jQuery(this).hasClass("open")){
					jQuery(this).html("Show banners");
					jQuery(this).removeClass("open");
					jQuery(this).addClass("closed");
					jQuery(this).parent().parent().parent().parent().find(settings.bannersContainer).hide();
					//closeBanners();
				}
				else{
					if(jQuery(this).parent().parent().parent().parent().find(settings.personalLink).hasClass("open")){
						jQuery(this).parent().parent().parent().parent().find(settings.personalLink).trigger("click");
						//closePersonal();
					}
					jQuery(this).html("Hide banners");
					jQuery(this).removeClass("closed");
					jQuery(this).addClass("open");
					jQuery(this).parent().parent().parent().parent().find(settings.bannersContainer).show();
					//openBanners();
				}
			}); // end each
		} // end plugin
		
		function postcodeAnywhereCheck(sort_code, account_number, modal_container) {

			sort_code_re = /^\*{6}$/;
			account_re = /^\*{4}\d{4}$/;
			if ( sort_code.val().match(sort_code_re) && account_number.val().match(account_re) ) {
				return;
			}
			
			if(sort_code.val().length == 6 && account_number.val().length == 8) {
				$.ajax({
					type:'POST',
					url:'/ajax/bacs/validate',
					dataType:'json',
					data:{
						'account_number':function(){
							return encodeURI(account_number.val());
						},
						'sort_code':function(){
							return encodeURI(sort_code.val());
						}
					},
				  	success: function(data) {
						
						$('#bacs_status').empty();
						
						if(!data){
							return false;
						} 
						else{
							success_icon = '<div id="bacs_msg" class="bacs-success"><div class="icon"></div><div class="message">';
							error_icon = '<div id="bacs_msg" class="bacs-error"><div class="icon"></div><div class="message"><b>Error</b> ';
							if(data.status == 'OK') {
								$('#bacs_status').html(success_icon + 'This sort-code belongs to ' + data.bank + '. Not your bank? Please check your entered sort-code.</div>');
							} else if(data.status == 'CautiousOK') {
								$('#bacs_status').html(success_icon + 'This sort-code has been successfully recognised.</div>');
							} else if(data.status == 'UnknownSortCode') {
								$('#bacs_status').html(error_icon + 'Sorry, we couldn\'t recognise this sort-code.</div>');
								addInvalidBacsAttempt();
							} else if(data.status == 'InvalidAccountNumber') {
								$('#bacs_status').html(error_icon + 'Sorry, you have entered an invalid bank account number.</div>');
								addInvalidBacsAttempt();							
							} else if(data.status == 'DetailsChanged') {
								$('#bacs_status').html(error_icon + 'Sorry, an error has occurred. Please check your entered account number and sort-code.</div>');
							} else {
								$('#bacs_status').html(error_icon + 'Sorry, an error has occurred. Please try again later.</div>');
							}
							$('#bacs_status').css('display', 'block');
							
							if(typeof modal_container != "undefined") {
								modal_container.quidcoModal("resize");
							}
						}
				    }
				});
			}
      	}
				
		function addInvalidBacsAttempt() {
			
			$.ajax({
				type:'POST',
				url:'/ajax/bacs/add_attempt',
				dataType:'json',
				success: function(data) {
															
					if(data.status == 'banned') {
						$('#banned_bacs_container').remove();
						$('#banned_bacs_message').show();
					}
					
					if(typeof $('#content') != "undefined") {
						$('#content').quidcoModal("resize");
					}
			    }
			});
		}

		jQuery.fn.paymentMethod = function(options) {
			jQuery(this).each(function() {							   
				var settings = jQuery.extend({
					noneDiv : 'div.content.none',
					payPalDiv : 'Store search...',
					payPalVal : 'PayPal',
					bacsDiv : 'Store search...',
					bacsVal : 'BACS'
				},options||{});	
				
				var paymentSettingsValidator;
				
				function bacs(){
					jQuery("#settings-bacs-form:hidden, #settings-minpay-form:hidden, div#action-btns, div#current-password, div.content-item.alert.error").show();
					jQuery("#settings-pp-form:visible, div.content-item.none").hide();
					jQuery("body").addClass("bacs").removeClass("paypal");
					jQuery("#paypal-fraud-message .alert").hide();
					jQuery("#no-payment-method-message .alert").hide();
					jQuery("#banned_bacs_message").hide();
					
					jQuery("#payment-settings").formValidator({
						onError:function(e,message){
							e.next('p.text-guide').unbind("click").remove();
							e.after('<p class="text-guide error">'+message+'</p>');
							$('#bacs_status').hide();
						},
						onSuccess:function(e) {
							
						},
						rules:{
							'#bacs_sort_code':{
								validate:{
									required:{
										errorMessage:'Oops, that\'s required'
									},
									maxLength:{
										value:6,
										errorMessage:'Oops, that\'s too long'
									},
									minLength:{
										value:6,
										errorMessage:'Oops, that\'s too short'
									},
									regex:{
										value:'^\\d{6}|\\*{6}$',
										errorMessage:'Oops, only numbers'
									}
								}									
							},
							'#bacs_account_number':{
								validate:{
									required:{
										errorMessage:'Oops, that\'s required'
									},
									maxLength:{
										value:8,
										errorMessage:'Oops, that\'s too long'
									},
									minLength:{
										value:8,
										errorMessage:'Oops, that\'s too short'
									},
									regex:{
										value:'^(\\d{8})|(\\*{4}\\d{4})$',
										errorMessage:'Oops, only numbers'
									}
								}
							},
							'#bacs_account_name':{
								validate:{
									required:{
										errorMessage:'Oops, that\'s required'
									},
									maxLength:{
										value:18,
										errorMessage:'Oops, that\'s too long'
									}
								}
							},
							'#minimum_payout':{
								validate:{
									required:{
										errorMessage:'Oops, that\'s required'
									},
									regex:{
										value:'^[0-9]*(\.[0-9]{2,2})?$',
										errorMessage:'Oops, only valid currency amounts'
									}
								}
							}
						}
					}); // end formValidator
					paymentSettingsValidator = jQuery("#payment-settings").data("formValidator");
				} // end bacs
	
				function paypal(){
		        	jQuery("#settings-bacs-form:visible, div.content-item.none").hide();
					jQuery("#settings-pp-form:hidden, #settings-minpay-form:hidden, div#action-btns, div#current-password, div.content-item.alert.error").show();
					jQuery("body").addClass("paypal").removeClass("bacs");
					jQuery("#paypal-fraud-message .alert").show();
					jQuery("#no-payment-method-message .alert").hide();
					
					jQuery("#payment-settings").formValidator({
						onError:function(e,message){
							e.next('p.text-guide').unbind("click").remove();
							e.after('<p class="text-guide error">'+message+'</p>');
						},
						onSuccess:function(e){
							e.next('p.text-guide').unbind("click").remove();
							e.after('<p class="text-guide success"></p>');
						},
						rules:{
							'#paypal_email':{
								validate:{
									required:{
										errorMessage:'Oops, that\'s required'
									},
									email:{
										errorMessage:'Oops, that\'s not an email'
									}
								}
							},
							'#paypal_email_confirm':{
								validate:{
									match:{
										value:$('#paypal_email'),
										errorMessage:'Oops, that doesn\'t match'
									}
								}
							},
							'#minimum_payout':{
								validate:{
									required:{
										errorMessage:'Oops, that\'s required'
									},
									regex:{
										value:'^[0-9]*(\.[0-9]{2,2})?$',
										errorMessage:'Oops, only valid currency amounts'
									}
								}
							}
						}
					}); // end formValidator
					paymentSettingsValidator = jQuery("#payment-settings").data("formValidator");
				} // end paypal
				
				var selected = jQuery("input[name='payment_method']:checked").val();
				
				if (selected == "BACS") {
					bacs();
				} else if (selected == "PayPal") {
					paypal();
				} else {
					jQuery("div.module.payment-type div.content-item").hide();					
					jQuery("div.module.payment-type div.intro").show();
					jQuery("div.content-item.select-payment-type, div.content-item.none").show();
					jQuery("#no-payment-method-message .alert").show();
					jQuery("div.module.payment-type div.content-item.alert.error").show();
				} // end if				
				
				jQuery("#payment_method_paypal").click(function() {
					paypal();
				}); // end click			
					      	
				jQuery("#payment_method_bacs").click(function() {
					bacs();
				}); // end click				      	
				
				jQuery("#payment-settings").submit(function(e) {
					var isFormValid = paymentSettingsValidator.validate($(this));
					var isBacsError = jQuery('#bacs_msg').attr('class') == 'bacs-error';
					if(!isFormValid || isBacsError) {
						e.preventDefault();
					}
				});			
				
				jQuery("#bacs_sort_code").blur(function() {
					postcodeAnywhereCheck($('#bacs_sort_code'), $('#bacs_account_number'));
		      		paymentSettingsValidator.validate($(this));		      		
				}).focus(function(){
					jQuery(this).next('p.text-guide').unbind("click").remove();
					jQuery(this).after('<p class="text-guide">6 digits no spaces, no dashes</p>');
				});
		      	
		      	jQuery("#bacs_account_number").blur(function() {
		      		postcodeAnywhereCheck($('#bacs_sort_code'), $('#bacs_account_number'));
		      		paymentSettingsValidator.validate($(this));   		
		      	}).focus(function(){
					jQuery(this).next('p.text-guide').unbind("click").remove();
					jQuery(this).after('<p class="text-guide">8 digits no spaces, no dashes</p>');
				});
		      	
		      	jQuery("#bacs_account_name").blur(function(){
					paymentSettingsValidator.validate($(this));
				}).focus(function(){
					jQuery(this).next('p.text-guide').unbind("click").remove();
					jQuery(this).after('<p class="text-guide">Name associated with the account. Max 18 characters</p>');
				});
	
				jQuery("#paypal_email").blur(function(){
					paymentSettingsValidator.validate($(this));								
				}).focus(function(){
					jQuery(this).next('p.text-guide').unbind("click").remove();
					jQuery(this).after('<p class="text-guide">Email associated with PayPal account</p>');
				});
				
				jQuery("#paypal_email_confirm").blur(function(){
					paymentSettingsValidator.validate($(this));								
				}).focus(function(){
					jQuery(this).next('p.text-guide').unbind("click").remove();
					jQuery(this).after('<p class="text-guide">Re-enter email address</p>');
				});
				
				jQuery("#minimum_payout").blur(function(){
					paymentSettingsValidator.validate($(this));								
				}).focus(function(){
					jQuery(this).next('p.text-guide').unbind("click").remove();
					jQuery(this).after('<p class="text-guide">Threshold for payment of earnings</p>');
				});
				
			}); // end each
		} // end plugin
		
		jQuery.fn.browseTree = function(options) {
			jQuery(this).each(function() {							   
				var settings = jQuery.extend({
					moduleDiv : 'div.module.help-browser',
					firstLevelClick : 'ul li a',
					firstLevelExpand : 'ul'
				},options||{});	
				if(jQuery("body").hasClass("new-enquiry")){
					jQuery(settings.moduleDiv + " " + settings.firstLevelClick).click(function() {
						jQuery(this).parent().parent().find(settings.firstLevelExpand).slideToggle("slow");
						jQuery(this).parent().parent().toggleClass("open");
						return false; //Disable Click
					}); // end click
				}
				else{
					jQuery(settings.moduleDiv + " " + settings.firstLevelClick).click(function() {
						// return true to enable click for help node type link
						if ( jQuery(this).parent().hasClass('link') ) {
							return true;
						}
						if (jQuery(this).attr("href").length > 4){
							if (jQuery(this).parent().hasClass("open")){
								jQuery(this).parent().removeClass("open")
								jQuery(this).next().slideUp().parent().find("p").remove();
								return false; //Disable Click
							}else{
								itemID = jQuery(this).attr("href").replace('/help/','');
								jQuery(settings.moduleDiv + " " + settings.firstLevelClick + "[href=/help/" + itemID + "]").after("<div class='answer'><span class='loading'>Loading</span><div style='height:2px;'></div></div>");
								jQuery.ajax({ 
									type: "GET", 
									url: "/ajax/help/get_help_content", 
									dataType: "HTML", 
									data: "help_topic_id="+itemID, 
									error: function() {
									},
									success: function(html) {
										var response = html || settings.errorMsg;
										jQuery(settings.moduleDiv + " " + settings.firstLevelClick + "[href=/help/" + itemID + "]").next().empty().append(response).slideDown().parent().addClass("open");
									}
								});	
								return false; //Disable Click
							}//if
						}else{
							jQuery(this).next().slideToggle();
							jQuery(this).parent().toggleClass("open");
							return false; //Disable Click					
						}
					}); // end click
					
					//Expand Help Topic if passing help parent ID
					var helpUrl = document.location.toString();
					if (helpUrl.match('#')) {
					  var helpId = "help-" + helpUrl.split('#')[1];
							jQuery(settings.moduleDiv + " ul li#" + helpId + " ul").slideToggle();
							jQuery(settings.moduleDiv + " ul li#" + helpId).toggleClass("open");					  
					}
				}//else
			}); // end each
		} // end plugin		
		
		jQuery.fn.pressReleaseInfo = function(options) {
			jQuery(this).each(function() {	
				
				var settings = jQuery.extend({
					iconLink : '.release-button a',
					textLink : '.release-desc p a',
					releaseInfo : '.release-detail', 
					containerDiv : 'div.release-container'
				},options||{});					  
				
				jQuery(this).find(settings.iconLink).click(function() {
						jQuery(this).parent().parent().toggleClass("open").find(settings.releaseInfo).slideToggle("slow");
						return false; //Disable Click			
				}); // end click
				
				jQuery(this).find(settings.textLink).click(function() {
					jQuery(this).parent().parent().parent().toggleClass("open").find(settings.releaseInfo).slideToggle("slow");
					return false; //Disable Click			
				}); // end click
				
			}); // end each
		} // end plugin	
		
		
		jQuery.fn.cashbackNews = function(options) {
			jQuery(this).each(function() {
				var settings = jQuery.extend({
					removeLink : '.cashback-news .remove a'
				},options||{});		
				jQuery(settings.removeLink).click(function(ev) {
					jQuery(this).unbind();
					ev.preventDefault();
					
					var news_id = jQuery(this).attr("href").substring("#remove-news-".length);
					var user_id = jQuery('#user_id_hidden').val();
					
					jQuery.ajax({
					  type: 'GET',
					  cache: false,
					  url: '/ajax-simple/home.php',
					  data: 'action=remove_cashback_news&news_id=' + escape(news_id) + '&user_id=' + user_id,
					  success: function(text) {
						jQuery("#news-div"+news_id).slideUp();
							if ((jQuery("div.module.cashback-news div div:visible").size() - 1) == 0){
							jQuery("div.module.cashback-news div.content-item.default").slideDown();
						}
					  }
					});
				});
			});
		}
		
		jQuery.fn.smartHelp = function(options) {
			jQuery(this).find('.smart-help-question').each(function() {
				jQuery(this).click(function() {
					
					// style smart links if new link is clicked and ignore if clicked same link again
					if ( !jQuery(this).smartHelpLinks() ) {
						return false;
					}
					
					// loading
					jQuery('#about-purchase').showLoading();
					
					// get help topic id
					help_topic_id = jQuery(this).attr('help_topic_id');

					// ajax call
					jQuery.ajax({ 
						type: "GET", 
						url: "/ajax/smarthelp", 
						dataType: "HTML", 
						data: "action=get_children_for_help_topic&help_topic_id=" + help_topic_id, 
						error: function() { jQuery('#answer').empty(); },
						success: function(html) {
							
							// get questions for help_topic_id
							jQuery('.smart-help-ipos-2').html(html);
							
							// loop over all links on about-purchase section and associate links
							jQuery('#about-purchase').find('.smart-help-question').each(function() {
								jQuery(this).click(function() {
									
									// style smart links if new link is clicked and ignore if clicked same link again
									if ( !jQuery(this).smartHelpLinks() ) {
										return false;
									}
									
									// loading
									jQuery('#answer').showLoading();
									
									// get help topic id
									help_topic_id = jQuery(this).attr('help_topic_id');
									
									// ajax call
									jQuery.ajax({ 
										type: "GET", 
										url: "/ajax/smarthelp", 
										dataType: "HTML", 
										data: "action=get_help_topic&help_topic_id=" + help_topic_id, 
										error: function() {
											// on fail
											jQuery('#answer').html('');
										},
										success: function(html) {
											// set html answer
											jQuery('#answer').html(html);
										}
									});
									
									// done
									return false;
								});
							});
						}
					});				

					// make the answer hidden if smart-help-ipos-1 is changed
					jQuery('#answer').html('');
					jQuery('.smart-help-ipos-3').css('visibility', 'hidden');

					// done
					return false;
				});
			});
		}
		
		
		$.fn.smartHelpLinks = function() {
			
			// ignore if already clicked link is clicked again
			if ( jQuery(this).hasClass('smart-help-active') ) {
				return false;
			}
		
			// find all questions down from parent and reset the css
			jQuery(this).parent().find('.smart-help-question').css('font-weight', 'normal');
			jQuery(this).parent().find('.smart-help-question').css('background-color', '#FFFFFF');
			jQuery(this).parent().find('.smart-help-question').find('.smart-tick').css('visibility', 'hidden');
			jQuery(this).parent().find('.smart-help-question').removeClass('smart-help-active');
			
			// highlight the currently clicked link
			jQuery(this).css('font-weight', 'bold');
			jQuery(this).css('background-color', '#F0F0F0');
			jQuery(this).find('.smart-tick').css('visibility', 'visible');		
			jQuery(this).addClass('smart-help-active');
			
			
			if ( jQuery(this).hasClass('link') ) {
				self.location = jQuery(this).find('.smart-text a').attr('href');
				return false;
			}			
			
			// make the next smart-help-ipos visible
			jQuery(this).parent().parent().next().css('visibility', 'visible');

			// get scroll position
			var scrollPosition = document.body.scrollTop;
			if ( scrollPosition == 0 ) {
			    if ( window.pageYOffset ) {
			    	scrollPosition = window.pageYOffset;
			    } else {
			    	scrollPosition = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
			    }
			}
			
			// get the offset of next help block
			offset = jQuery(this).parent().parent().next().offset();
			
			// if user has moved past the top, scroll back up to the top 
			if ( scrollPosition > parseInt(offset.top) ) {
				window.scrollTo(0, parseInt(offset.top)-5);
			}			
			
			// success
			return true;
		}
		
		jQuery.fn.showLoading = function() {
				jQuery(this).html("<div class='smart-loading'><img src='/static/img/loading-small.gif'> Loading</div>");
		}
		
		/* selected merchant on smart help */
		jQuery.fn.smartHelpAboutPurchaseMerchant = function() {
			
			jQuery('.smart-help-ipos-3').css('visibility','hidden').find('#answer').empty();
			
			selected_merchant_id = jQuery(this).find('option:selected').attr('id');
			if ( !selected_merchant_id ) {
				jQuery(this).parent().prev().removeClass('merchant-selected-tick');
				jQuery(this).parent().parent().parent().css('border-bottom', 'none').next().hide();
				return false;
			}

			jQuery(this).parent().prev().addClass('merchant-selected-tick');
			jQuery(this).parent().parent().parent().css('border-bottom', '1px solid #CCCCCC').css('padding-bottom', '20px').next().show();
			div = jQuery(this).parent().parent().parent().css('border-bottom', '1px solid #CCCCCC').css('padding-bottom', '20px').next();
			div.showLoading();
			
			// ajax call
			jQuery.ajax({ 
				type: "GET", 
				url: "/ajax/smarthelp", 
				dataType: "HTML", 
				data: "action=get_activity_for_merchant&merchant_id=" + selected_merchant_id, 
				error: function() { },
				success: function(html) {
					jQuery(div).html(html);
				}
			});			
		}
		
		/* selected activity on smart help */
		jQuery.fn.smartHelpAboutPurchaseActivity = function() {
			selected_transaction_id = jQuery(this).find('option:selected').attr('id');
			if ( !selected_transaction_id ) {
				jQuery(this).parent().prev().removeClass('merchant-selected-tick');
				jQuery('.smart-help-ipos-3').css('visibility','hidden').find('#answer').empty();
				return false;
			}

			jQuery(this).parent().prev().addClass('merchant-selected-tick');
			jQuery('.smart-help-ipos-3').css('visibility', 'visible').find('#answer').showLoading();
			
			// ajax call
			jQuery.ajax({ 
				type: "GET", 
				url: "/ajax/smarthelp", 
				dataType: "HTML", 
				data: "action=get_transaction_query&transaction_id=" + selected_transaction_id, 
				error: function() { },
				success: function(html) {
					
					jQuery('.smart-help-ipos-3').find('#answer').html(html);
					
				}
			});			
		}		
			
		/* form validation */
		jQuery.fn.formValidator = function(options) {
			this.each(function() {
				if (jQuery(this).data("formValidator") && !options) {
					return;
				}
				jQuery(this).data("formValidator", new FormValidator(this, options));
			});
		}
		
		jQuery.fn.joinConfirm = function(options) { 
			this.each(function() {
				if (jQuery('div.modal.earn-cashback').length) { 
					jQuery.fn.colorbox({inline:true, open:true, opacity:0.6, href:"div.modal.earn-cashback", initialWidth:"350px", initialHeight:"257px"});
				}
			});
		}

		jQuery.fn.cookiesTest = function(options) { 
			jQuery(this).each(function() {	
				if (document.cookie.indexOf("cookies_enabled") == -1) {
					jQuery("div#cookies-enabled").hide();
					jQuery("div.module.cookies div.cookies-disabled").show();
					var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
					
					var show = null;
					if (jQuery.browser.msie && $.browser.version.substring(0, 1) < 7) {
						show = "ie6"; 
					} 
					else if (jQuery.browser.msie && $.browser.version.substring(0, 1) >= 7) {
						show = "ie7";
					}
					else if (jQuery.browser.mozilla) {
						show = "firefox";
					}
					else if (is_chrome) { //needs to come before safari
						show = "chrome";
					}
					else if (jQuery.browser.safari) {
						show = "safari";
					}
					else if (jQuery.browser.opera) {
						show = "opera";
					}
					
					if (show != null) {
						jQuery("#how-to li:not(#how-" + show + ")").hide();
					}
				}
				else {
					jQuery("div#cookies-enabled").show();
					jQuery("div.module.cookies div.cookies-disabled").hide();
				}	
			});
		}
		
		jQuery.fn.landingPage = function(options) {
			jQuery(this).each(function() {				
				function showPop(){
					jQuery(jQuery(this)).removeClass("content-item");
					jQuery(jQuery(this)).addClass("content-item-hover");
				}
				function hidePop(){
					jQuery(jQuery(this)).removeClass("content-item-hover");
					jQuery(jQuery(this)).addClass("content-item");
				}	
				var megaConfig = {interval: 30, sensitivity: 4, over: showPop, timeout: 100, out: hidePop};	
				jQuery("#content-1 .ipos-4 .select-merchants .content-item").hoverIntent(megaConfig);
			}); // end each
		} // end plugin	
		
		jQuery.fn.infoHover = function(options) {
			jQuery(this).each(function(options) {
				var settings = jQuery.extend({
					hoverItem : ".stats-info"
				}, options|| {});//end settings
				
				function offerOver(){
					jQuery(this).addClass("hover");
				}
				
				function offerOut(){
					jQuery(this).removeClass("hover");
				}
				
				var hoverConfig = {interval: 30, sensitivity: 4, over: offerOver, timeout: 100, out: offerOut};
				jQuery(settings.hoverItem).hoverIntent(hoverConfig);
				
			}); //end each
		} //end plugin
		
		jQuery.fn.merchantOfferHover = function(options) {
			jQuery(this).each(function() {
				var settings = jQuery.extend({
					hoverItem : "#content-2 .ipos-3 .module .offerContent"
				},options||{});
				function offerOver(){
					if(jQuery("body").hasClass("merchant-category")) {
						jQuery(this).addClass("hover");
					}else{
						jQuery(this).find(".popUp").removeClass("displayNone");
						jQuery(this).find(".popUp").addClass("displayBlock");
					}
				}
				function offerOut(){
					if(jQuery("body").hasClass("merchant-category")) {
						jQuery(this).removeClass("hover");
					}else{
						jQuery(this).find(".popUp").removeClass("displayBlock");
						jQuery(this).find(".popUp").addClass("displayNone");
					}
				}
				var offerConfig = {interval: 30, sensitivity: 4, over: offerOver, timeout: 100, out: offerOut};
				jQuery(settings.hoverItem).hoverIntent(offerConfig);
			}); // end each
		} // end plugin	
		
		jQuery.fn.attachTransitMerchant = function(options) { 
			jQuery(this.each(function() {
				
				jQuery('.join-quidco').live('click', function() {
					if (jQuery(this).attr('href').length != 0){
						var link_submit = jQuery(this).attr('rev');
						
						if( typeof link_submit !== "undefined" ){
							
							var link_submit_array = link_submit.split(",");							
							var link_merchant_id;
							var link_network_name;
							var cashback;
							var link_type;
							var link_id;
							var link;
							
							if (link_submit_array.length == 1){
								link_cashback = link_no_cashback = link_submit;
							}							
							
							if (link_submit_array.length == 3){									
								var link_merchant_id = link_submit_array[0];
								var link_network_name = link_submit_array[1];
								var cashback = link_submit_array[2];								
								var link_cashback = "/visit-prep/" + link_merchant_id + "/" + link_network_name + "/" + cashback;
								var link_no_cashback = "/visit/" + link_merchant_id + "/" + link_network_name + "/no-cashback/";
							}	
							
							if (link_submit_array.length == 5){								
								
								var link_merchant_id = link_submit_array[0];
								var link_network_name = link_submit_array[1];
								var cashback = link_submit_array[2]
								var link_type = link_submit_array[3];								
								var link_id = link_submit_array[4];
								
								var is_printable = false;
								if ( link_type == 'printable-voucher' ) {
									is_printable = true;
									link_type = 'voucher';
								}
								
								var link_cashback = "/visit-prep/" + link_merchant_id + "/" + link_network_name + "/" + cashback + "/" + link_type + "/" + link_id;
								var link_no_cashback = "/visit-prep/" + link_merchant_id + "/" + link_network_name + "/no-cashback/" + link_type + "/" + link_id;
								if (link_type != 'voucher') { 
									link_no_cashback = "/visit/" + link_merchant_id + "/" + link_network_name + "/no-cashback/" + link_type + "/" + link_id;
								}
							}

						}
						
						if (link_type == "voucher") { 
							if ( is_printable ) {
								jQuery('#join-header').attr('innerHTML', '<h1><strong>Sign in</strong> or <strong>join</strong> to get your printable voucher</h1>');
								jQuery('#dont_have_time').attr('innerHTML','');
								jQuery('#transit_merchant_no_cashback_link').attr('innerHTML', '');
							} else if (cashback == "cashback") {
								jQuery('#join-header').attr('innerHTML', '<h1><strong>Sign in</strong> or <strong>join</strong> to reveal your voucher code and get cashback</h1>');
								jQuery('#dont_have_time').attr('innerHTML','Dont have time?');
								jQuery('#transit_merchant_no_cashback_link').attr('innerHTML', 'Just show the voucher code');
							} else {
								jQuery('#join-header').attr('innerHTML', '<h1><strong>Sign in</strong> or <strong>join</strong> to reveal your voucher code</h1>');
								jQuery('#dont_have_time').attr('innerHTML','Dont have time?');
								jQuery('#transit_merchant_no_cashback_link').attr('innerHTML', 'Just show the voucher code');
							}
							
							if(jQuery(this).attr("rel").length != 0){
								jQuery("#code_link_to_reveal").attr("value", jQuery(this).attr("rel"));
							}
							
						} else if ((link_type == "offer") && (cashback == "no-cashback")) {
							jQuery('#join-header').attr('innerHTML', '<h1><strong>Sign in</strong> or <strong>join</strong> to get access to 1000s of great deals</h1>');
							jQuery('#dont_have_time').attr('innerHTML','Dont have time?');
							jQuery('#transit_merchant_no_cashback_link').attr('innerHTML', 'Just go to the merchant');
							var href = jQuery('#transit_merchant_no_cashback_link').attr('href');
							jQuery('#transit_merchant_no_cashback_link').attr('href', href + link_type + '/' + link_id + '/');
						} else if (link_submit_array.length < 2) {
							jQuery('#join-header').attr('innerHTML', '<h1><strong>Sign in</strong> or <strong>join</strong></h1>');
							jQuery('#transit_merchant_no_cashback_link').attr('innerHTML', '');
							jQuery('#dont_have_time').attr('innerHTML', '');
						} else {
							jQuery('#join-header').attr('innerHTML', '<h1><strong>Sign in</strong> or <strong>join</strong> to get your cashback</h1>');
							jQuery('#dont_have_time').attr('innerHTML','Dont have time?');
							jQuery('#transit_merchant_no_cashback_link').attr('innerHTML', 'Just go to the merchant');
						}

						jQuery('#transit_merchant_no_cashback_link').attr('href', link_no_cashback + "?bp");					
						jQuery('#transit_link_join').attr('value', link_cashback);
						jQuery('#transit_link_sign_in').attr('value', link_cashback);
						
						jQuery('#transit_merchant_no_cashback_link').click(function() {
							$(this).quidcoModal("close", {href : '', disable : false});
							$(this).trigger("quidcodal_closed");
							
							// if the voucher code is shown for this merchant, do not hide button and re-show voucher
							if ( jQuery("#" + link_id + " .code-container").html() != null ) {
								jQuery("#" + link_id + " p.submit").hide();
								jQuery("#" + link_id + " .code-container").show();
							}
						});
						
					}
				});
			}));
		}
		
		/*
		 * Sexy Captcha v.0.2
		 * Designed and developed by: BWM Media (bwmmedia.com)
		 */
		
		jQuery.fn.sexyCaptcha = function(url) {
			this.each(function() {
				jQuery(this).load(url + "/refresh", {  }, function() {
					
					//On double-click of object
					jQuery('.draggable').bind('click', function(event, ui) {
						jQuery('#captchaWrapper').find('.captchaAnswer').val(jQuery(this).attr('id'));
						jQuery('#captchaWrapper').find('.draggable').unbind('click');
						jQuery('#captchaWrapper').find('.targetWrapper').children('.target').hide();
						jQuery(this).removeClass('draggable');
						jQuery(this).addClass('target');
						jQuery('#captchaWrapper').find('.targetWrapper').prepend(jQuery(this));
						//jQuery(this).hide();
		
						//Check captcha answer
						jQuery.post(url + '/verify', { captcha: jQuery(this).attr('id'), vnumber: jQuery('#vnumber').val() }, function(data) {
							if (data.status == "success") {
								jQuery('#captchaWrapper').find('.targetWrapper').removeClass('captchaFail');
								jQuery('#captchaWrapper').find('.targetWrapper').addClass('captchaSuccess').hide().fadeIn('slow');
							} else {
								jQuery('#captchaWrapper').find('.targetWrapper').addClass('captchaFail').hide().fadeIn('slow');
							}
						}, 'json');
					});
					
					//Redraw captcha
					jQuery('.captchaRefresh a').click(function() {
						jQuery('.captcha .app').sexyCaptcha(url);
						return false;
					});
				});
			});

			return this;
		};	
		
       jQuery.fn.showInsuranceQuotes = function() {
			jQuery.ajax({ 
				type: 'GET', 
				cache: false,
				url: '/ajax/seopa_price_comparison',
				data: 'action=count_quotes', 
				timeout: 8000,
				error: function() { },
				success: function(returned_html) {
					returned_html = jQuery.trim(returned_html);
					if ( !isNaN(returned_html) && returned_html >= 1 ) {
						var quotesHtml;
						quotesHtml = '(' + returned_html + ')';
						if ( jQuery("li .insurance-quotes-count").length ) {
							jQuery("li .insurance-quotes-count").html(quotesHtml);
						}
					}
				}		
			});
		} // end plugin
        
        jQuery.fn.displayInsuranceQuoteButton = function() {
			jQuery.ajax({ 
				type: 'GET', 
				cache: false,
				url: '/ajax/seopa_price_comparison',
				data: 'action=count_quotes', 
				timeout: 8000,
				error: function() { },
				success: function(returned_html) {
					returned_html = jQuery.trim(returned_html);
					if ( !isNaN(returned_html) && returned_html >= 1 ) {
						if ( jQuery("body.car-insurance-comparison #retrieve-quote").length ) {
							jQuery("body.car-insurance-comparison #retrieve-quote").css('visibility', 'visible');
						} else if ( jQuery('#car-insurance-comparison-banner a.retrieve-quote').length ) {
							jQuery('#car-insurance-comparison-banner a.retrieve-quote').css('visibility', 'visible');
						}
					}
				}		
			});
		} // end plugin
        
        jQuery.fn.checkSeopaQuotesPage = function(options) {
        	
        	loading = jQuery('.seopa-' + options.page + '-loading');
        	iframe = jQuery('.seopa-' + options.page + '-iframe');
        	error = jQuery('.seopa-' + options.page + '-error');
        	
        	jQuery.ajax({ 
				type: 'GET', 
				cache: false,
				url: '/ajax/seopa_price_comparison', 
				data: 'action=get_page_status&url=' + escape(options.url),
				timeout: 8000,
				error: function() {
        			iframe.html('');
					iframe.css('display', 'none');
					loading.css('display', 'none');
					error.css('display', 'block');
					error.css('height', '80px');
				},
                success: function(returned_html) {
                    returned_html = jQuery.trim(returned_html);
                    if ( returned_html == 'active' ) {
                            loading.css('visibility', 'hidden');
                            loading.animate({
                                    height: '0px'
                            }, 1000);
                            loading.css('padding', '0px');
                            jQuery('.seopa-' + options.page + '-iframe iframe').css('display', 'block');
                            jQuery('.seopa-' + options.page + '-iframe iframe').animate({
                                    height: options.height
                            }, 1000);
                    } else {
                    		iframe.html('');
                            iframe.css('display', 'none');
                            loading.css('display', 'none');
                            error.css('display', 'block');
                            error.css('height', '80px');
                    }
				}		
			});
        	
		} // end plugin
		
		jQuery.fn.visitPrep = function(options) {
			jQuery(this).each(function() {
				if (jQuery("div#modal-visit-prep").length) { 
					jQuery("#content").quidcoModal({href : "div#modal-visit-prep", closeDisable : true});
				}
				jQuery("#content").trigger("click");
				//Google analytics
				_gaq.push(
					['_trackPageview', 'OVERLAY>{modal-visit-prep}'],
					['cross._trackPageview', 'OVERLAY>{modal-visit-prep}']
				);
			}); // end each
		} // end plugin	
		
		jQuery.fn.clickLike = function(options) {
			jQuery(this).each(function() {		
				jQuery(".like a").live('click',function() {
									 
					var submit_string = jQuery(this).attr("id");
					var submit_array = submit_string.split("_");
					var parent_id = submit_array[0];
					var parent_type = submit_array[1];					                                

					jQuery.ajax({ 
						type: "GET", 
						url: "/ajax/merchant/insert_like_link", 
						dataType: "text", 
						data: "parent_id="+parent_id+"&parent_type="+parent_type, 
						error: function() {
							// oops ( alert here for debugging )
						},
						success: function(text) {
							if (text != 'false') {
								var clickID = "#" + submit_string;
								text = jQuery.trim(text.replace(/<\/?[^>]+>/gi, ''));
								var likeText = "<p class=\"like\"><span class=\"noLink\">(" + text + " like this)</span></p>";
								jQuery(clickID).parent().replaceWith(likeText);
							}
						}
					});		
					
				});
			}); // end each
		} // end plugin
		
		jQuery.fn.revealVoucherCode = function(options) {
			jQuery(this).each(function() {		
				jQuery("a.hot-offers-voucher-code").live('click', function() {
					var voucherID = jQuery(this).attr("rel");
					/* if the voucher code is shown for this merchant, do not hide button and re-show voucher */
					if ( jQuery("#" + voucherID + " .code-container").html() != null ) {
						jQuery("#" + voucherID + " p.submit").hide();
						jQuery("#" + voucherID + " .code-container").show();
					}
					
				});
				//Created for Google Analytics (Harvest Digital)
				jQuery("a.printable-hosted").live('click', function() {
					var merchantName = jQuery(this).attr("rev");
					var voucherID = jQuery(this).attr("rel");
					var randomNum = Math.ceil(Math.random()*10000);
					var uniqueID = "http://" + location.hostname + "/&voucher-printable-hosted-" + voucherID + "_" + randomNum;
					_gaq.push(
						['_addTrans', uniqueID, '', '0.00', '', '', '', '', ''],
						['_addItem', uniqueID, '2', 'Get Voucher Printable Hosted', merchantName, '0.00', '1'],
						['_trackTrans'],
						['_trackPageview', 'VIRTUAL>Get-Voucher-Printable-Hosted-Goal.html'],
						
						['cross._addTrans', uniqueID, '', '0.00', '', '', '', '', ''],
						['cross._addItem', uniqueID, '2', 'Get Voucher Printable Hosted', merchantName, '0.00', '1'],
						['cross._trackTrans'],
						['cross._trackPageview', 'VIRTUAL>Get-Voucher-Printable-Hosted-Goal.html']
					);
				});
			}); // end each
		} // end plugin
		
		jQuery.fn.revealedVoucherCode = function(options) {
			jQuery(this).each(function() {
				jQuery("p.revealed-code").hover(
					function() {
						var thisCode = jQuery(this).parent().parent().find("p.code-container").html();
						jQuery(this).find("a").html(thisCode);
					},
					function() {
						jQuery(this).find("a").html("Get voucher code");
					}
				);
			}); // end each
		} // end plugin
		
		jQuery.fn.mouseHover = function() {
			jQuery(this).mouseover(function() {
				jQuery(this).css('background-color', '#F1F8FC');
			});
			jQuery(this).mouseout(function() {
				jQuery(this).css('background-color', '#FFFFFF');
			});
		} // end plugin
		
		jQuery.fn.popUpCodeReveal = function(options) {
			var settings = jQuery.extend({
				url : "0"
			},options||{});
			jQuery(this).each(function() {
				var vCode = settings.url.split("/");
				var end = vCode.length - 1;
				if (jQuery("#" + vCode[end] + " .code-container").html() != null) {
					jQuery("#" + vCode[end] + " p.submit").hide();
					jQuery("#" + vCode[end] + " .code-container").show();
				}
			}); // end each
		} // end plugin
		
		jQuery.fn.showMoreNews = function(options) {
			jQuery(this).each(function() {
				jQuery(".show-more-news").click(function() {
					jQuery(".news-hidden").slideToggle("slow");
					
					var htmlString = jQuery(this).html();
					
					if(htmlString == "Show more") {
						jQuery(this).html("Show less");
					} else{
						jQuery(this).html("Show more");
					}
					
					return false;
				});
			});
		}
		
		jQuery.fn.carousel = function(options) {
			var slideNumber = 1;
			var hoverState = "false";
			var easingSpeed = 800;
			var delayTime = 5000;
			var rollOutDelay = 2000;
			var playCarousel = "";
			var pauseStart = "false";
			var timeout1 = "";
			var timeout2 = "";
			var timeout3 = "";
			jQuery(".controls .play").addClass("pause");
			function setFadeOut1(){
				jQuery("#slide1").fadeOut(easingSpeed, function () {
					jQuery(".controls #control1").removeClass("on");
					jQuery(".controls #control1").addClass("off");		
					cycle(2);
				});//.fadeOut
			}
			function setFadeOut2(){
				jQuery("#slide2").fadeOut(easingSpeed, function () {
					jQuery(".controls #control2").removeClass("on");
					jQuery(".controls #control2").addClass("off");		
					cycle(3);
				});//.fadeOut
			}
			function setFadeOut3(){
				jQuery("#slide3").fadeOut(easingSpeed, function () {
					jQuery(".controls #control3").removeClass("on");
					jQuery(".controls #control3").addClass("off");
					cycle(1);
				});//.fadeOut
			}
			function cycle(slide){
				jQuery(".controls .control").addClass("off");
				if(slide == 1){
					slideNumber = 1;
					jQuery("#slide1").fadeIn(easingSpeed, function () {
						jQuery(".controls #control1").removeClass("off");
						jQuery(".controls #control1").addClass("on");
						if(pauseStart == "true"){
							if(playCarousel == "started"){
								timeout1 = setTimeout(setFadeOut1,delayTime);
							}
						}
						else{
							if(hoverState == "false"){
								timeout1 = setTimeout(setFadeOut1,delayTime);
							}
						}
					});//.fadeIn
				}
				if(slide == 2){
					slideNumber = 2;
					jQuery("#slide2").fadeIn(easingSpeed, function () {
						jQuery(".controls #control2").removeClass("off");
						jQuery(".controls #control2").addClass("on");
						if(pauseStart == "true"){
							if(playCarousel == "started"){
								timeout2 = setTimeout(setFadeOut2,delayTime);
							}
						}
						else{
							if(hoverState == "false"){
								timeout2 = setTimeout(setFadeOut2,delayTime);
							}
						}
					});//.fadeIn
				}
				if(slide == 3){
					slideNumber = 3;
					jQuery("#slide3").fadeIn(easingSpeed, function () {
						jQuery(".controls #control3").removeClass("off");
						jQuery(".controls #control3").addClass("on");
						if(pauseStart == "true"){
							if(playCarousel == "started"){
								timeout3 = setTimeout(setFadeOut3,delayTime);
							}
						}
						else{
							if(hoverState == "false"){
								timeout3 = setTimeout(setFadeOut3,delayTime);
							}
						}
					});//.fadeIn
				}
			}
			cycle(1);
			function slideOver() {
				if(pauseStart == "false"){
					hoverState = "true";
					if(slideNumber == 1){
						clearTimeout(timeout1);
					}
					if(slideNumber == 2){
						clearTimeout(timeout2);
					}
					if(slideNumber == 3){
						clearTimeout(timeout3);
					}
				}
			}
			function slideOut() {
				if(pauseStart == "false"){
					hoverState = "false";
					if(slideNumber == 1){
						timeout1 = setTimeout(setFadeOut1,rollOutDelay);
					}
					if(slideNumber == 2){
						timeout2 = setTimeout(setFadeOut2,rollOutDelay);
					}
					if(slideNumber == 3){
						timeout3 = setTimeout(setFadeOut3,rollOutDelay);
					}
				}
			}
			var slideConfig = {interval: 100, sensitivity: 7, over: slideOver, timeout: 100, out: slideOut};
			jQuery(".panel").hoverIntent(slideConfig);
			jQuery(".play").click(function(){
				pauseStart = "true";
				if(jQuery(this).hasClass("start")){
					playCarousel = "started";
					jQuery(".controls .play").removeClass("start");
					jQuery(".controls .play").addClass("pause");
					if(slideNumber == 1){
						timeout1 = setTimeout(setFadeOut1,rollOutDelay);
					}
					if(slideNumber == 2){
						timeout2 = setTimeout(setFadeOut2,rollOutDelay);
					}
					if(slideNumber == 3){
						timeout3 = setTimeout(setFadeOut3,rollOutDelay);
					}
				}
				else{
					playCarousel = "paused";
					jQuery(".controls .play").removeClass("pause");
					jQuery(".controls .play").addClass("start");
					if(slideNumber == 1){
						clearTimeout(timeout1);
					}
					if(slideNumber == 2){
						clearTimeout(timeout2);
					}
					if(slideNumber == 3){
						clearTimeout(timeout3);
					}
				}
			});
			jQuery(".control").click(function(){
				pauseStart = "true";
				playCarousel = "paused";
				jQuery(".controls .play").removeClass("start");
				jQuery(".controls .play").removeClass("pause");
				jQuery(".controls .play").addClass("start");
				jQuery(".panel .slides .slide").hide();
				jQuery(".controls .control").removeClass("on");
				jQuery(".controls .control").removeClass("off");
				jQuery(".controls .control").addClass("off");
				currentControlID = jQuery(this).attr("id");
				if(slideNumber == 1){
					clearTimeout(timeout1);
				}
				if(slideNumber == 2){
					clearTimeout(timeout2);
				}
				if(slideNumber == 3){
					clearTimeout(timeout3);
				}
				if(currentControlID == "control1"){
					slideNumber = 1;
					jQuery("#slide1").show();
					jQuery("#control1").addClass("on");
				}
				if(currentControlID == "control2"){
					slideNumber = 2;
					jQuery("#slide2").show();
					jQuery("#control2").addClass("on");
				}
				if(currentControlID == "control3"){
					slideNumber = 3;
					jQuery("#slide3").show();
					jQuery("#control3").addClass("on");
				}
			});
		} // end plugin
		
		jQuery.fn.merchantSorting = function(options) {
			jQuery(this).each(function() {					   
				var settings = jQuery.extend({
					merchID : '1'
				},options||{});						
					
				jQuery(".ordering-link").live("click",function() {
					
					var sort_method = jQuery(this).attr("id");
					var sort_type = jQuery(this).attr("rel");
					
					jQuery('#' + sort_type).load(
							'/ajax/merchant/' + sort_type + '?&merchant_id=' + settings.merchID + '&sorting_method='+sort_method, 
							function(){jQuery("a.report-error").colorbox({
								inline:true, href:".modal-report-error", opacity:0.6
								});
							});
					jQuery(this).parent().parent().find("a").removeClass("active");
					jQuery(this).addClass("active");
					return false;
					
				}); // end click	
				
			}); // end each
			
		} // end plugin	
		
		jQuery.fn.referralProgress = function(options){
			jQuery(this).each(function() {					   
				var settings = jQuery.extend({
					numberReferred : '0',
					numberRegistered : '0'
				},options||{});	
				
				var ratio = (settings.numberRegistered / settings.numberReferred);
				var pixels = Math.ceil(ratio * 398);
				
				jQuery(".transaction-bubble").css("left", pixels + "px");
				jQuery("li.progress-wrapper .progress-bar").css("width", pixels + "px");
				
			});//end each
		}//end plugin
		
		jQuery.fn.referralSnippet = function(options){
			jQuery(this).each(function() {
				var settings = jQuery.extend({
					snippetLink : '.get-banner-snippet'
				},options||{});
				
				jQuery(settings.snippetLink).colorbox({inline:true, href:".modal-banner-refer", opacity:0.6, initialWidth:"330px", initialHeight:"330px"});
				jQuery(settings.snippetLink).click(function(){
					
					var bannerDetails = jQuery(this).attr("rel").split(',');				
					var pattern = /x[0-9]+/gi;
					var camp_id = jQuery(this).parents(".refer-methods").attr("id");
					
					jQuery(".banner-modal-size").html("<b>Size:</b> " + bannerDetails[0]);
					jQuery("#banner-modal-image").attr('src', "http://www.quidco.com/static/uploads/a/downloads/banners/" + bannerDetails[1] + bannerDetails[2]);
					jQuery("#banner-modal-image").attr('alt', bannerDetails[3]);
					jQuery("#banner-modal-image").attr('width', bannerDetails[4]);
					jQuery("#banner-modal-image").attr('height', bannerDetails[5]);
					jQuery("#banner-modal-code").html('&lt;a href="' + jQuery("#banner-modal-base-url").val() + "user/" + jQuery("#banner-modal-user-id").val() + "/" + camp_id + "/banner/" + bannerDetails[1] + '" /&gt;&lt;img src="http://www.quidco.com/static/uploads/a/downloads/banners/' + bannerDetails[1] + bannerDetails[2] + '" alt="' + bannerDetails[3] + '" /&gt;&lt;/a&gt;');
					
				});//end click
				
				jQuery(".close-modal").click(function() {
					jQuery(this).colorbox.close();
					return false;
				});//end click
				
			});//end each
		}//end plugin
		
		jQuery.fn.bacsModal = function() {
			jQuery("#content").quidcoModal({href : ".modal-bacs", closeDisable : true, 
				complete : function(){
					jQuery("bacs_modal_acc_holder").val('');
					jQuery("bacs_modal_acc_pass").val('');
				}
			});
			
			jQuery("#content").trigger("click");
			
			jQuery('#modal-bacs form').formValidator({
				onError:function(e,message){
					e.parent().find("p").html(message);
					e.parent().find("p").removeClass("success-message");
					e.parent().find("p").addClass("error-message");
				},
				onSuccess:function(e){
					e.parent().find("p").html("");
					e.parent().find("p").removeClass("error-message");
					e.parent().find("p").addClass("success-message");
				},
				rules:{
					'#bacs_modal_sort_code':{
						validate:{
							required:{
								errorMessage:'Oops, that\'s required'
							},
							minLength:{
								value:6,
								errorMessage:'Oops, that\'s too short'
							},
							regex:{
								value:'^\\d{6}$',
								errorMessage:'Oops, only numbers'
							}
						}
					},
					'#bacs_modal_acc_num':{
						validate:{
							required:{
								errorMessage:'Oops, that\'s required'
							},
							minLength:{
								value:8,
								errorMessage:'Oops, that\'s too short'
							},
							regex:{
								value:'^\\d{8}$',
								errorMessage:'Oops, only numbers'
							}
						}
					},
					'#bacs_modal_acc_holder':{
						validate:{
							required:{
								errorMessage:'Oops, that\'s required'
							},
							maxLength:{
								value:18,
								errorMessage:'Oops, that\'s too long'
							}
						}
					},
					'#bacs_modal_acc_pass':{
						validate:{
							required:{
								errorMessage:'Oops, that\'s required'
							}
						}
					}
				}
			});
			
			jQuery("#bacs_modal_sort_code").focus(function() {
				jQuery(this).parent().find("p").html("6 Digits no spaces, no dashes");
				jQuery(this).parent().find("p").removeClass("error-message");
				jQuery(this).parent().find("p").removeClass("success-message");
			});
			
			jQuery("#bacs_modal_acc_num").focus(function() {
				jQuery(this).parent().find("p").html("8 Digits no spaces, no dashes");
				jQuery(this).parent().find("p").removeClass("error-message");
				jQuery(this).parent().find("p").removeClass("success-message");
			});
			
			jQuery("#bacs_modal_acc_holder").focus(function() {
				jQuery(this).parent().find("p").html("name associated with the account <br />Maximum 18 characters");
				jQuery(this).parent().find("p").removeClass("error-message");
				jQuery(this).parent().find("p").removeClass("success-message");
			});
			
			jQuery("#bacs_modal_acc_pass").focus(function() {
				jQuery(this).parent().find("p").html("For your protection");
				jQuery(this).parent().find("p").removeClass("error-message");
				jQuery(this).parent().find("p").removeClass("success-message");
			});
			
			jQuery("#bacs_modal_sort_code").blur(function() {
				postcodeAnywhereCheck($("#bacs_modal_sort_code"), $("#bacs_modal_acc_num"), $('#content'));
				modalBacsValidator.validate($(this));
			});
			
			jQuery("#bacs_modal_acc_num").blur(function() {
				postcodeAnywhereCheck($("#bacs_modal_sort_code"), $("#bacs_modal_acc_num"), $('#content'));
				modalBacsValidator.validate($(this));
			});
			
			var modalBacsValidator = jQuery('#modal-bacs form').data('formValidator');
			
			jQuery('#modal-bacs form').submit(function(ev) {
				var isFormValid = modalBacsValidator.validate(jQuery(this));
				var isBacsError = jQuery('#bacs_msg').attr('class') == 'bacs-error';
				
				if(!isFormValid || isBacsError) {
					ev.preventDefault();
				}
			});	
		}
		
		jQuery.fn.verificationForm = function(options) {
			jQuery(this).each(function() {
				var defaultTextFirstName = 'Your first name';
				var defaultTextSurname = 'Your last name';
								
				if (jQuery("#verify_first_name").val() == '') {
					jQuery("#verify_first_name").val(defaultTextFirstName);
				}
				
				jQuery("#verify_first_name").click(function() {				
					if (jQuery(this).val() == defaultTextFirstName) {
						jQuery(this).val('');
					}
				});
				
				if (jQuery("#verify_surname").val() == '') {
					jQuery("#verify_surname").val(defaultTextSurname);
				}
				
				jQuery("#verify_surname").click(function() {				
					if (jQuery(this).val() == defaultTextSurname) {
						jQuery(this).val('');
					}
				});
				
				jQuery('#verify-insurance-purchase').formValidator({
					onError:function(e,message){
						e.next('div.textbox-alert').unbind("click").remove();
						e.after('<div class="textbox-alert error">' + message + '</div>');
						e.addClass('error');
					},
					onSuccess:function(e){
						e.next('div.textbox-alert').unbind("click").remove();
						e.after('<div class="textbox-alert success"></div>');
						e.removeClass('error');
					},
					rules:{
						'#verify_surname':{
							validate:{
								required:{
									errorMessage:'Oops, that\'s required'
								},
								maxLength:{
									value:100,
									errorMessage:'Oops, that\'s too long'
								}
							}
						},
						'#verify_address':{
							validate:{
								required:{
									errorMessage:'Oops, that\'s required'
								},
								maxLength:{
									value:100,
									errorMessage:'Oops, that\'s too long'
								}
							}
						},
						'#verify_postcode':{
							validate:{
								required:{
									errorMessage:'Oops, that\'s required'
								},
								maxLength:{
									value:100,
									errorMessage:'Oops, that\'s too long'
								}
							}
						},
						'#verify_email':{
							validate:{
								required:{
									errorMessage:'Oops, that\'s required'
								},
								maxLength:{
									value:100,
									errorMessage:'Oops, that\'s too long'
								},
								email:{
									errorMessage:'Oops, that\'s not an email'
								}
							}
						},
						'#verify_insurance_provider':{
							validate:{
								required:{
									errorMessage:'Oops, that\'s required'
								}
							}
						},
						'#verify_quote_reference':{
							validate:{
								required:{
									errorMessage:'Oops, that\'s required'
								},
								maxLength:{
									value:100,
									errorMessage:'Oops, that\'s too long'
								}
							}
						}
					}
				});
				
				var validator = jQuery('#verify-insurance-purchase').data('formValidator');
				
				jQuery('#verify_title').blur(function(){
					if ($('#verify_title').val().length == 0) {
						$('#verify_surname').next('div.textbox-alert').remove();
						$('#verify_surname').after('<div class="textbox-alert error">Oops, that\'s required</div>');
						$('#verify_title').addClass('error');
					}
				}).focus(function(){
					validator.reset('timeout');
					jQuery('#verify_surname').next('div.textbox-alert').remove();
					jQuery('#verify_surname').after('<div class="textbox-alert"></div>');
					$('#verify_title').removeClass('error');
				});
				
				jQuery('#verify_first_name').blur(function() {
					if ($('#verify_first_name').val().length == 0) {
						$('#verify_surname').next('div.textbox-alert').remove();
						jQuery('#verify_surname').after('<div class="textbox-alert error">Oops, that\'s required</div>');
						$('#verify_first_name').addClass('error');
					}
				}).focus(function(){
					validator.reset('timeout');
					jQuery('#verify_surname').next('div.textbox-alert').remove();
					jQuery('#verify_surname').after('<div class="textbox-alert"></div>');
					$('#verify_first_name').removeClass('error');
				});
				
				jQuery('#verify_surname').blur(function(){
					validator.validate($(this));
				}).focus(function(){
					validator.reset('timeout');
					jQuery(this).next('div.textbox-alert').unbind("click").remove();
					jQuery(this).after('<div class="textbox-alert"></div>');
					$('#verify_surname').removeClass('error');
				});
				
				jQuery('#verify_address').blur(function(){
					validator.validate($(this));
				}).focus(function(){
					validator.reset('timeout');
					jQuery(this).next('div.textbox-alert').unbind("click").remove();
					jQuery(this).after('<div class="textbox-alert"></div>');
					$('#verify_address').removeClass('error');
				});
				
				jQuery('#verify_postcode').blur(function(){
					validator.validate($(this));
				}).focus(function(){
					validator.reset('timeout');
					jQuery(this).next('div.textbox-alert').unbind("click").remove();
					jQuery(this).after('<div class="textbox-alert"></div>');
					$('#verify_postcode').removeClass('error');
				});
				
				jQuery('#verify_email').blur(function(){
					validator.validate($(this));
				}).focus(function(){
					validator.reset('timeout');
					jQuery(this).next('div.textbox-alert').unbind("click").remove();
					jQuery(this).after('<div class="textbox-alert"></div>');
					$('#verify_email').removeClass('error');
				});
				
				jQuery('#verify_insurance_provider').blur(function(){
					validator.validate($(this));
				}).focus(function(){
					validator.reset('timeout');
					jQuery(this).next('div.textbox-alert').unbind("click").remove();
					jQuery(this).after('<div class="textbox-alert"></div>');
					$('#verify_insurance_provider').removeClass('error');
				});
				
				jQuery('#verify_quote_date_day').blur(function(){
					if ($('#verify_quote_date_day').val().length == 0) {
						$('#verify_quote_date_year').next('div.textbox-alert').remove();
						$('#verify_quote_date_year').after('<div class="textbox-alert error">Oops, that\'s required</div>');
						$('#verify_quote_date_day').addClass('error');
					}
				}).focus(function(){
					validator.reset('timeout');
					jQuery('#verify_quote_date_year').next('div.textbox-alert').remove();
					jQuery('#verify_quote_date_year').after('<div class="textbox-alert"></div>');
					$('#verify_quote_date_day').removeClass('error');
				});
				
				jQuery('#verify_quote_date_month').blur(function(){
					if ($('#verify_quote_date_month').val().length == 0) {
						$('#verify_quote_date_year').next('div.textbox-alert').remove();
						$('#verify_quote_date_year').after('<div class="textbox-alert error">Oops, that\'s required</div>');
						$('#verify_quote_date_month').addClass('error');
					}
				}).focus(function(){
					validator.reset('timeout');
					jQuery('#verify_quote_date_year').next('div.textbox-alert').remove();
					jQuery('#verify_quote_date_year').after('<div class="textbox-alert"></div>');
					$('#verify_quote_date_month').removeClass('error');
				});
				
				jQuery('#verify_quote_date_year').blur(function(){
					if ($('#verify_quote_date_year').val().length == 0) {
						$('#verify_quote_date_year').next('div.textbox-alert').remove();
						$('#verify_quote_date_year').after('<div class="textbox-alert error">Oops, that\'s required</div>');
						$('#verify_quote_date_year').addClass('error');
					}
				}).focus(function(){
					validator.reset('timeout');
					jQuery('#verify_quote_date_year').next('div.textbox-alert').remove();
					jQuery('#verify_quote_date_year').after('<div class="textbox-alert"></div>');
					$('#verify_quote_date_year').removeClass('error');
				});
				
				jQuery('#verify_quote_reference').blur(function(){
					validator.validate($(this));
				}).focus(function(){
					validator.reset('timeout');
					jQuery(this).next('div.textbox-alert').unbind("click").remove();
					jQuery(this).after('<div class="textbox-alert"></div>');
					$('#verify_quote_reference').removeClass('error');
				});
				
				jQuery('#verify_purchase_date_day').blur(function(){
					if ($('#verify_purchase_date_day').val().length == 0) {
						$('#verify_purchase_date_year').next('div.textbox-alert').remove();
						$('#verify_purchase_date_year').after('<div class="textbox-alert error">Oops, that\'s required</div>');
						$('#verify_purchase_date_day').addClass('error');
					}
				}).focus(function(){
					validator.reset('timeout');
					jQuery('#verify_purchase_date_year').next('div.textbox-alert').remove();
					jQuery('#verify_purchase_date_year').after('<div class="textbox-alert"></div>');
					$('#verify_purchase_date_day').removeClass('error');
				});
				
				jQuery('#verify_purchase_date_month').blur(function(){
					if ($('#verify_purchase_date_month').val().length == 0) {
						$('#verify_purchase_date_year').next('div.textbox-alert').remove();
						$('#verify_purchase_date_year').after('<div class="textbox-alert error">Oops, that\'s required</div>');
						$('#verify_purchase_date_month').addClass('error');
					}
				}).focus(function(){
					validator.reset('timeout');
					jQuery('#verify_purchase_date_year').next('div.textbox-alert').remove();
					jQuery('#verify_purchase_date_year').after('<div class="textbox-alert"></div>');
					$('#verify_purchase_date_month').removeClass('error');
				});
				
				jQuery('#verify_purchase_date_year').blur(function(){
					if ($('#verify_purchase_date_year').val().length == 0) {
						$('#verify_purchase_date_year').next('div.textbox-alert').remove();
						$('#verify_purchase_date_year').after('<div class="textbox-alert error">Oops, that\'s required</div>');
						$('#verify_purchase_date_year').addClass('error');
					}
				}).focus(function(){
					validator.reset('timeout');
					jQuery('#verify_purchase_date_year').next('div.textbox-alert').remove();
					jQuery('#verify_purchase_date_year').after('<div class="textbox-alert"></div>');
					$('#verify_purchase_date_year').removeClass('error');
				});
				
				jQuery('#verify-insurance-purchase').submit(function(ev){
					
					if (jQuery('#verify_first_name').val() == defaultTextFirstName) {
						jQuery('#verify_first_name').val('');
					}
					
					if (jQuery('#verify_surname').val() == defaultTextSurname) {
						jQuery('#verify_surname').val('');
					}
					
					validator.reset('timeout');
					var isfalse = validator.validate(jQuery(this));
					if (!isfalse) { 
						ev.preventDefault();
					}
				});
			});
		}
		
		/**
		 * part 2 of referrals
		 * 
		 * when the user auths with the email provider in teh new window, the window calls this function.
		 * It passes in an array of all the emails with the email owner's name as the key
		 * 
		 * @param contacts_list
		 * @return
		 */
		function fillContacts(contacts_list) {
			
	    	var contacts_string = "";
	    	// first we hide the referral form and show the import form
	    	jQuery("#modal-refer-this .pos-1").toggleClass("content-hidden");
	    	jQuery("#modal-refer-this .pos-2").toggleClass("content-hidden");
	    	
	    	var tooLong = 0;
	    	
	    	//create the html for the list. NOTE: the email is put into the name attribute of each check box
	    	for(var email in contacts_list){ 
	    		if (contacts_list[email] != '') {
	    			contacts_string += '<div class="content-item"><ul><li class="select-column"><input type="checkbox" name="emails[]" /><input type="hidden" name="' + jQuery('<div/>').text(email).html() + '" value="' + jQuery('<div/>').text(contacts_list[email]).html() + '" /></li><li class="name-column">' + jQuery('<div/>').text(email).html() + '</li><li class="address-column">' + jQuery('<div/>').text(contacts_list[email]).html() + '</li></ul></div><!-- content-item -->';
	    			tooLong ++;
	    		}
	    	}  
	    	jQuery("#modal-refer-this .contacts-list-wrapper").html(contacts_string);
	    	
	    	//if user already imported contacts
			if(jQuery("#imported-email-list").val().length > 2) {
				var imported = jQuery("#imported-email-list").val();
				imported = imported.split(', ');
				for (var checked in imported){
					jQuery("#modal-refer-this input[value='" + imported[checked] + "']").parent().parent().find("input:checkbox").attr("checked", "checked");
				}
			}
	    	
	    	//colorBox hilarity again
	    	jQuery.fn.colorbox.resize();
	    	jQuery.fn.colorbox.resize();
	    	
	    	if(tooLong > 12) {
	    		var currentWidth = jQuery("#modal-refer-this .import-contacts .contacts-list-wrapper").width();
	    		jQuery("#modal-refer-this .import-contacts .contacts-list-wrapper").width(currentWidth - 15);
	    		currentWidth = jQuery("#modal-refer-this .import-contacts .module-content .content-item").width();
	    		jQuery("#modal-refer-this .import-contacts .module-content .content-item").width(currentWidth - 15);
	    		currentWidth = jQuery("#modal-refer-this .import-contacts .module-content .address-column").width();
	    		jQuery("#modal-refer-this .import-contacts .module-content .address-column").width(currentWidth - 15);
	    	}
	    	
	    	//uncheck each checkbox
	    	jQuery(".unselect-all").click(function(){
	    		jQuery(this).parent().parent().find("input:checkbox").removeAttr('checked');
	    		return false;
	    	});
	    	
	    	//check each checkbox
	    	jQuery(".select-all").click(function(){
	    		jQuery(this).parent().parent().find("input:checkbox").attr('checked', 'checked');
	    		return false;
	    	});
	    	

	    }//end function
		
		jQuery.fn.janBan = function(){
			jQuery(".jan-banner li:first").css("left", "0px");
			jQuery(".jan-banner li:last").css("left", "0px");
			var animating = false;
			
			jQuery(".jan-banner .scroll-button a").click(function() {
				if(jQuery(this).parent().hasClass("right-button")){
					var scrollLimit = (jQuery(this).parent().parent().find("li").length - 4) * -163;
					if(animating == false){
						animating = true;
						
						if(jQuery(this).parent().parent().find("li:last").css("left") == scrollLimit + "px"){
							var nodeToSwap = jQuery(".jan-banner li:first");
							jQuery(".jan-banner ul").append(nodeToSwap);
							jQuery(".jan-banner li").css('left', scrollLimit + 163 + "px");
						}
						
						jQuery(this).parent().parent().find("li").animate({
							left: '-=163'
						}, 600, function() {
							animating = false;
						});
					}
				}else{
					if(animating == false){
						animating = true;
						
						if(jQuery(this).parent().parent().find("li:last").css("left") == "0px"){
							var nodeToSwap = jQuery(".jan-banner li:last");
							jQuery(".jan-banner ul").prepend(nodeToSwap);
							jQuery(".jan-banner li").css('left',  "-163px");
						}
						
						jQuery(this).parent().parent().find("li").animate({
							left: '+=163'
						}, 600, function() {
							animating = false
						});
					}
				}
				return false;
			});
			
			jQuery(".jan-banner .module-header").hover(function() {
				jQuery(this).toggleClass("jan-active");
			});
			
			jQuery(".jan-banner .scroll-button").hover(function() {
				jQuery(this).toggleClass("jan-active-scroll-button");
			});
			
			jQuery(".jan-banner .right-button").hover(function() {
				jQuery(this).toggleClass("jan-active-right-button");
			});
			
			if(jQuery(".jan-landing").length > 0){
				jQuery(".jan-landing .module-footer a").hover(function() {
					jQuery(this).toggleClass("hover");
				});
			}
			
		};
		
		jQuery.fn.landingPageReveal = function(options) {
			jQuery(this).each(function() {							   
				var settings = jQuery.extend({
					revealModule : '.landing-page-reveal',
					revealedContainer : '.module-content',
					revealLink : 'h3 a'
				},options||{});					  
				jQuery(settings.revealModule).find(settings.revealLink).click(function(e) {
					e.preventDefault();
					if(jQuery(this).hasClass("open")){
						jQuery(this).removeClass("open");
						jQuery(this).parent().parent().parent().parent().find(settings.revealedContainer).slideUp();
					}
					else{
						jQuery(this).addClass("open");
						jQuery(this).parent().parent().parent().parent().find(settings.revealedContainer).slideDown();		
					}		
					return false;
				});		
			}); // end each
		}; // end plugin	
		
		
		/**
		 * twitter modal
		 */
		
		jQuery.fn.twitterModal = function(options) {
			jQuery(".twitterLink").quidcoModal({href : ".modal-twitter",
				complete:function(){
				
				  	twttr.anywhere(function (T) {
	
					    T("#tbox").tweetBox({
					      height: 100,
					      width: 530,
					      label: "Tell your friends about the spa day giveaway!",
					      defaultContent: "Win a luxury spa day and feel like a millionaire with Quidco! http://www.quidco.com/one-million-members"
					    });
	
				  	})
				
				  	twttr.anywhere(function (T) {
				  	  T("#follow-placeholder").followButton('quidco');
				  	});
				  	
				  	jQuery(this).quidcoModal("resize",{href:".twitterLink"})
				  	
				},
				closed:function(){
					
					jQuery("#tbox").html('');
					jQuery("#follow-placeholder").html('');
					
				}
			});
		}
		
		/**
		 * facebook modal
		 */
		jQuery.fn.facebookModal = function(options) {
			jQuery(".facebookLink").quidcoModal({href : ".modal-facebook"});
		}
				
				
		jQuery.fn.inStoreCashbackReveal = function(options) {
			jQuery(this).each(function() {							   
				var settings = jQuery.extend({
					revealModule : '#content-1 .group-content .module',
					revealedContainer : '.module-content',
					revealLink : '.module-header p a'
				},options||{});					  
				jQuery(settings.revealModule).find(settings.revealLink).click(function(e) {
					e.preventDefault();
					if(jQuery(this).hasClass("open")){
						jQuery(this).removeClass("open");
						jQuery(this).parent().parent().parent().parent().find(settings.revealedContainer).slideUp();
						jQuery(this).html("Show details");
					}
					else{
						jQuery(this).addClass("open");
						jQuery(this).parent().parent().parent().parent().find(settings.revealedContainer).slideDown();
						jQuery(this).html("Hide details");
					}		
					return false;
				});		
			}); // end each
		}; // end plugin
		
		
		//adds default tip text to input fields which disappears when they are clicked and reappears on blur if they are left empty
		//also toggles input selected class
		//input text is defined in a hidden label with class 'hidden-label' which is a sibling element to the input
		//define a 'selected' class for the input if you wish to change its style when it is selected
		jQuery.fn.addInputTipText = function() {
			jQuery(this).live('focus', function() {
				var tipText = jQuery(this).parent().find('.hidden-label').html();
				
				if(jQuery(this).val() == tipText) {
					jQuery(this).val('');
				}
				
				jQuery(this).addClass('selected');
			});
			
			jQuery(this).live('blur', function() {
				var tipText = jQuery(this).parent().find('.hidden-label').html();
				
				if(jQuery(this).val() == '') {
					jQuery(this).val(tipText);
				}
				
				jQuery(this).removeClass('selected');
			});
		};	
		
		jQuery.fn.findAStoreHandler = function() {
			
			var mapMarkers = [];
		    
		    function deleteMapOverlays() {
		  		if (mapMarkers) {
		    		for (i in mapMarkers) {
		      			mapMarkers[i].setMap(null);
		    		}
		    		
		    		mapMarkers.length = 0;
		  		}
			}
		    
		    jQuery('#find-a-store-form').submit(function(e) {
		    	  
		    	e.preventDefault();
		    	
		    	$.ajax({
					type: 'POST',
					cache: false,
					url: '/ajax/locality/get_nearest_in_store_merchant_map_markers',
					dataType:'json',
					data:{
						'merchant_id':jQuery('#find-a-store-merchant').val(),
						'postcode':jQuery('#find-a-store-postcode').val(),
						'limit':jQuery('#find-a-store-limit').val(),
						'distance':jQuery('#find-a-store-distance').val(),
						'user_id':jQuery('#find-a-store-user-id').val()
					},
					success: function(data) {
						
						if(!data){
							return false;
						} else {
							
							deleteMapOverlays();
							
							if(data.status == 'success') {
								
								var distanceText = '';
									
								if(jQuery('#find-a-store-distance').val() > 0) {
									distanceText = ' within <b>' + jQuery('#find-a-store-distance').val() + ' miles</b> of this postcode';
								}
								
								if(data.data.result_markers.length > 0) {
									jQuery('#google-map-container').slideDown();
									
									var results = 0;
									var center_point = new google.maps.LatLng(data.data.central_marker.latitude, data.data.central_marker.longitude);
							    	var myOptions = {
							      		zoom: 10,
							      		center: center_point,
							      		mapTypeId: google.maps.MapTypeId.ROADMAP
							    	}
							    	
							    	var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
							    	var bounds = new google.maps.LatLngBounds();
							    	
							    	var marker = new google.maps.Marker({
										    position:center_point,
										    map:map,
										    title:data.data.central_marker.postcode + ', ' + data.data.central_marker.locality
									});
									
									mapMarkers.push(marker);
									
									bounds.extend(center_point);
							    						
									$.each(data.data.result_markers, function(i, item) {
										var infowindow = new google.maps.InfoWindow({
									    	content:item.content
										});
										
										var point = new google.maps.LatLng(item.locality.latitude, item.locality.longitude);
										var marker = new google.maps.Marker({
										    position:point,
										    map:map,
										    title:item.title
										});
										
										mapMarkers.push(marker);
										
										google.maps.event.addListener(marker, 'click', function() {
											infowindow.open(map,marker);
										});
										
										bounds.extend(point);
										results++;
									});
									
									jQuery('#find-a-store-message').removeClass('success failure');
																
									jQuery('#find-a-store-message').addClass('success');
									jQuery('#find-a-store-message').html(results + ' stores were found' + distanceText);
									map.fitBounds(bounds);
									
								} else {
									jQuery('#find-a-store-message').addClass('failure');
									jQuery('#find-a-store-message').html('No stores were found' + distanceText);
								}
							} else if(data.status == 'invalid_postcode') {
								jQuery('#find-a-store-message').addClass('failure');
								jQuery('#find-a-store-message').html('You have entered an invalid postcode.');
							}
							
							jQuery('#find-a-store-message').show();
						}
					}
				});					 	    
		    });				
		};
		
		jQuery.fn.refreshInStoreCards = function() {
			
			$.ajax({
				type: 'POST',
				cache: false,
				url: '/ajax/in_store/get_user_cards',
				dataType:'html',
				success: function(html) {
					jQuery('#cards-list').html(html);
					jQuery('#add-card-number').val(jQuery('#add-card-number').parent().find('.hidden-label').html());
					jQuery(this).countCards();
				}
			});			
		};
		
		jQuery.fn.loadInStore = function() {
			jQuery('.add-card').click(function(e) {
				e.preventDefault();
				jQuery('#add-card').slideDown();		
			});			
			
			jQuery('#add-form').submit(function(e) {		
				
				e.preventDefault();
				jQuery('#add-card-submit').attr('disabled', 'disabled');
				jQuery('#add-card-submit').addClass('disabled');
				
				$.ajax({
					type: 'POST',
					cache: false,
					url: '/ajax/in_store/add_card',
					dataType:'json',
					data:{
						'card_number':jQuery('#add-card-number').val()
					},
					success: function(data) {
										
						if(!data){
							return false;
						} else {
							jQuery('#in-store-alert').removeClass('success failure');
							jQuery('#in-store-alert').addClass(data.status);
							jQuery('#in-store-alert').html(data.message);
							jQuery('#in-store-alert').show();
							jQuery('#add-card-submit').removeAttr('disabled');
							jQuery('#add-card-submit').removeClass('disabled');
							
							if(data.data.credit_card_id != 0) {
								jQuery('#content').refreshInStoreCards();
							}
						}
					}
				});
			});
			
			jQuery('.remove-card').live('click', function(e) {
				e.preventDefault();
				
				$.ajax({
					type: 'POST',
					cache: false,
					url: '/ajax/in_store/remove_card',
					dataType:'json',
					data:{
						'credit_card_id':jQuery(this).parent().find('.hidden-label').html()
					},
					success: function(data) {
						
						if(!data){
							return false;
						} else {
							jQuery('#content').refreshInStoreCards();
							jQuery('#in-store-alert').removeClass('success failure');
							jQuery('#in-store-alert').addClass(data.status);
							jQuery('#in-store-alert').html(data.message);
							jQuery('#in-store-alert').show();
							jQuery(this).countCards();
						}
					}
				});
			});
			
			jQuery.fn.countCards = function() {
				
				var count = jQuery('.card-container').length;
				var count_string = count + ' card';
				
				if(count != 1) {
					count_string += 's';
				}
				
				jQuery('#card-count').html(count_string);
			};			
		};
		
		jQuery.fn.closeNotificationHandler = function(options) {
			
			jQuery('#user-notification-spacer').slideDown('slow');
			jQuery('#user-notification').slideDown('slow');
			
			jQuery(this).click(function(e) {
				e.preventDefault();
				jQuery.ajax({ 
					type: "POST", 
					url: "/ajax/notifications/mark_as_read", 
					dataType: "json", 
					data: {
						user_notification_id:jQuery(this).attr('id')
					}, 
					success: function(data) {
						jQuery('#user-notification-spacer').slideUp();
						jQuery('#user-notification').slideUp();
					}
				});
			});			
		};
		
		jQuery.fn.onekChallenge = function(){
			
			var progress = jQuery(".onek-summary h1 .amount").html().substring(1) / 1000;
			var theWidth = Math.round(jQuery(".progress-bar").width() * progress);
			jQuery(".progress-bar span").width(theWidth);
			
			jQuery(".sub-title").click(function() {
				jQuery(this).parent().find("ul").slideToggle("slow");
				
				if(jQuery(this).hasClass("expanded")){
					jQuery(this).removeClass("expanded");
				}else{
					jQuery(this).addClass("expanded");
				}
				
			});
			
			
			jQuery(".onek-table .content-item li .pos-4 a").live('click', function(e) {
				e.preventDefault();
				
				var id = jQuery(this).attr("rev");
				var intoTheVo_id = jQuery(this).attr("rel");
				var theAmount = jQuery("#" + id).val();
				
				if(jQuery(this).hasClass("delete")){
					var del = '1';
				}else{
					var del = '0';
				}
				
				if(jQuery(this).html() == "Edit"){
					jQuery(this).html("Save");
					jQuery("#" + id).removeAttr("disabled", "false");
					jQuery("#" + id).addClass("active");
					return false;
				}else{
					$.post("/onek-challenge", {vo_id: intoTheVo_id, amount: theAmount, is_deleted: del, link_click_id: id}, function(data){
						window.location=window.location.href;
					});
				}
				
			});
			
		}
		
		/**
		 * UK Postcode Validation
		 *
		 * http://www.braemoor.co.uk/software/postcodes.shtml
		 */
		function checkPostCode(toCheck){var alpha1="[abcdefghijklmnoprstuwyz]";var alpha2="[abcdefghklmnopqrstuvwxy]";var alpha3="[abcdefghjkpmnrstuvwxy]";var alpha4="[abehmnprvwxy]";var alpha5="[abdefghjlnpqrstuwxyz]";var pcexp=new Array();pcexp.push(new RegExp("^("+alpha1+"{1}"+alpha2+"?[0-9]{1,2})(\\s*)([0-9]{1}"+alpha5+"{2})$","i"));pcexp.push(new RegExp("^("+alpha1+"{1}[0-9]{1}"+alpha3+"{1})(\\s*)([0-9]{1}"+alpha5+"{2})$","i"));pcexp.push(new RegExp("^("+alpha1+"{1}"+alpha2+"{1}"+"?[0-9]{1}"+alpha4+"{1})(\\s*)([0-9]{1}"+alpha5+"{2})$","i"));pcexp.push(/^(GIR)(\s*)(0AA)$/i);pcexp.push(/^(bfpo)(\s*)([0-9]{1,4})$/i);pcexp.push(/^(bfpo)(\s*)(c\/o\s*[0-9]{1,3})$/i);pcexp.push(/^([A-Z]{4})(\s*)(1ZZ)$/i);var postCode=toCheck;var valid=false;for(var i=0;i<pcexp.length;i++){if(pcexp[i].test(postCode)){pcexp[i].exec(postCode);postCode=RegExp.$1.toUpperCase()+" "+RegExp.$3.toUpperCase();postCode=postCode.replace(/C\/O\s*/,"c/o ");valid=true;break;}}if(valid){return postCode;}else return false;}
		
		/**
		 * Cookie plugin
		 *
		 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
		 * Dual licensed under the MIT and GPL licenses:
		 * http://www.opensource.org/licenses/mit-license.php
		 * http://www.gnu.org/licenses/gpl.html
		 * http://plugins.jQuery.com/files/jQuery.cookie.js.txt
		 */
		jQuery.cookie=function(a,b,c){if(typeof b!='undefined'){c=c||{};if(b===null){b='';c.expires=-1}var d='';if(c.expires&&(typeof c.expires=='number'||c.expires.toUTCString)){var e;if(typeof c.expires=='number'){e=new Date();e.setTime(e.getTime()+(c.expires*24*60*60*1000))}else{e=c.expires}d='; expires='+e.toUTCString()}var f=c.path?'; path='+(c.path):'';var g=c.domain?'; domain='+(c.domain):'';var h=c.secure?'; secure':'';document.cookie=[a,'=',encodeURIComponent(b),d,f,g,h].join('')}else{var j=null;if(document.cookie&&document.cookie!=''){var k=document.cookie.split(';');for(var i=0;i<k.length;i++){var l=jQuery.trim(k[i]);if(l.substring(0,a.length+1)==(a+'=')){j=decodeURIComponent(l.substring(a.length+1));break}}}return j}};

		/**
		* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
		* <http://cherne.net/brian/resources/jQuery.hoverIntent.html>
		* 
		* @param  f  onMouseOver function || An object with configuration options
		* @param  g  onMouseOut function  || Nothing (use configuration options object)
		* @author    Brian Cherne <brian@cherne.net>
		*/
		(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);		

		/*
		 * jQuery Autocomplete plugin 1.1
		 *
		 * Copyright (c) 2009 J̦rn Zaefferer
		 *
		 * Dual licensed under the MIT and GPL licenses:
		 *   http://www.opensource.org/licenses/mit-license.php
		 *   http://www.gnu.org/licenses/gpl.html
		 *
		 * Revision: $Id: jQuery.autocomplete.js 14 2009-08-22 10:29:29Z joern.zaefferer $
		 */
		eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}(';(3($){$.2e.1u({19:3(b,d){5 c=W b=="1B";d=$.1u({},$.M.1T,{Y:c?b:P,y:c?P:b,1J:c?$.M.1T.1J:10,X:d&&!d.1D?10:48},d);d.1y=d.1y||3(a){6 a};d.1v=d.1v||d.1R;6 A.I(3(){1M $.M(A,d)})},L:3(a){6 A.11("L",a)},1k:3(a){6 A.14("1k",[a])},2b:3(){6 A.14("2b")},28:3(a){6 A.14("28",[a])},24:3(){6 A.14("24")}});$.M=3(o,r){5 t={2Y:38,2S:40,2N:46,2I:9,2E:13,2B:27,2x:3I,2v:33,2p:34,2n:8};5 u=$(o).3r("19","3o").Q(r.2Q);5 p;5 m="";5 n=$.M.3c(r);5 s=0;5 k;5 h={1F:C};5 l=$.M.32(r,o,1Z,h);5 j;$.1Y.2X&&$(o.2U).11("45.19",3(){4(j){j=C;6 C}});u.11(($.1Y.2X?"43":"42")+".19",3(a){s=1;k=a.2M;3V(a.2M){O t.2Y:a.1d();4(l.N()){l.30()}w{12(0,D)}R;O t.2S:a.1d();4(l.N()){l.2D()}w{12(0,D)}R;O t.2v:a.1d();4(l.N()){l.2C()}w{12(0,D)}R;O t.2p:a.1d();4(l.N()){l.2A()}w{12(0,D)}R;O r.17&&$.1c(r.S)==","&&t.2x:O t.2I:O t.2E:4(1Z()){a.1d();j=D;6 C}R;O t.2B:l.Z();R;3J:1P(p);p=1O(12,r.1J);R}}).2t(3(){s++}).3E(3(){s=0;4(!h.1F){2r()}}).2q(3(){4(s++>1&&!l.N()){12(0,D)}}).11("1k",3(){5 c=(1r.7>1)?1r[1]:P;3 1N(q,a){5 b;4(a&&a.7){16(5 i=0;i<a.7;i++){4(a[i].L.J()==q.J()){b=a[i];R}}}4(W c=="3")c(b);w u.14("L",b&&[b.y,b.F])}$.I(15(u.K()),3(i,a){21(a,1N,1N)})}).11("2b",3(){n.1o()}).11("28",3(){$.1u(r,1r[1]);4("y"2h 1r[1])n.1e()}).11("24",3(){l.1p();u.1p();$(o.2U).1p(".19")});3 1Z(){5 e=l.2g();4(!e)6 C;5 v=e.L;m=v;4(r.17){5 b=15(u.K());4(b.7>1){5 f=r.S.7;5 c=$(o).18().1I;5 d,1H=0;$.I(b,3(i,a){1H+=a.7;4(c<=1H){d=i;6 C}1H+=f});b[d]=v;v=b.3f(r.S)}v+=r.S}u.K(v);1l();u.14("L",[e.y,e.F]);6 D}3 12(b,c){4(k==t.2N){l.Z();6}5 a=u.K();4(!c&&a==m)6;m=a;a=1m(a);4(a.7>=r.29){u.Q(r.26);4(!r.1s)a=a.J();21(a,3a,1l)}w{1q();l.Z()}};3 15(b){4(!b)6[""];4(!r.17)6[$.1c(b)];6 $.4h(b.23(r.S),3(a){6 $.1c(b).7?$.1c(a):P})}3 1m(a){4(!r.17)6 a;5 c=15(a);4(c.7==1)6 c[0];5 b=$(o).18().1I;4(b==a.7){c=15(a)}w{c=15(a.22(a.37(b),""))}6 c[c.7-1]}3 1G(q,a){4(r.1G&&(1m(u.K()).J()==q.J())&&k!=t.2n){u.K(u.K()+a.37(1m(m).7));$(o).18(m.7,m.7+a.7)}};3 2r(){1P(p);p=1O(1l,4g)};3 1l(){5 c=l.N();l.Z();1P(p);1q();4(r.36){u.1k(3(a){4(!a){4(r.17){5 b=15(u.K()).1n(0,-1);u.K(b.3f(r.S)+(b.7?r.S:""))}w{u.K("");u.14("L",P)}}})}};3 3a(q,a){4(a&&a.7&&s){1q();l.35(a,q);1G(q,a[0].F);l.20()}w{1l()}};3 21(f,d,g){4(!r.1s)f=f.J();5 e=n.31(f);4(e&&e.7){d(f,e)}w 4((W r.Y=="1B")&&(r.Y.7>0)){5 c={4f:+1M 4e()};$.I(r.2Z,3(a,b){c[a]=W b=="3"?b():b});$.4d({4c:"4b",4a:"19"+o.49,2V:r.2V,Y:r.Y,y:$.1u({q:1m(f),47:r.X},c),44:3(a){5 b=r.1A&&r.1A(a)||1A(a);n.1i(f,b);d(f,b)}})}w{l.2T();g(f)}};3 1A(c){5 d=[];5 b=c.23("\\n");16(5 i=0;i<b.7;i++){5 a=$.1c(b[i]);4(a){a=a.23("|");d[d.7]={y:a,F:a[0],L:r.1z&&r.1z(a,a[0])||a[0]}}}6 d};3 1q(){u.1h(r.26)}};$.M.1T={2Q:"41",2P:"3Z",26:"3Y",29:1,1J:3W,1s:C,1f:D,1w:C,1g:10,X:3U,36:C,2Z:{},1X:D,1R:3(a){6 a[0]},1v:P,1G:C,E:0,17:C,S:", ",1y:3(b,a){6 b.22(1M 3T("(?![^&;]+;)(?!<[^<>]*)("+a.22(/([\\^\\$\\(\\)\\[\\]\\{\\}\\*\\.\\+\\?\\|\\\\])/2K,"\\\\$1")+")(?![^<>]*>)(?![^&;]+;)","2K"),"<2J>$1</2J>")},1D:D,1E:3S};$.M.3c=3(g){5 h={};5 j=0;3 1f(s,a){4(!g.1s)s=s.J();5 i=s.2H(a);4(g.1w=="3R"){i=s.J().1k("\\\\b"+a.J())}4(i==-1)6 C;6 i==0||g.1w};3 1i(q,a){4(j>g.1g){1o()}4(!h[q]){j++}h[q]=a}3 1e(){4(!g.y)6 C;5 f={},2G=0;4(!g.Y)g.1g=1;f[""]=[];16(5 i=0,2F=g.y.7;i<2F;i++){5 c=g.y[i];c=(W c=="1B")?[c]:c;5 d=g.1v(c,i+1,g.y.7);4(d===C)1V;5 e=d.3Q(0).J();4(!f[e])f[e]=[];5 b={F:d,y:c,L:g.1z&&g.1z(c)||d};f[e].1U(b);4(2G++<g.X){f[""].1U(b)}};$.I(f,3(i,a){g.1g++;1i(i,a)})}1O(1e,25);3 1o(){h={};j=0}6{1o:1o,1i:1i,1e:1e,31:3(q){4(!g.1g||!j)6 P;4(!g.Y&&g.1w){5 a=[];16(5 k 2h h){4(k.7>0){5 c=h[k];$.I(c,3(i,x){4(1f(x.F,q)){a.1U(x)}})}}6 a}w 4(h[q]){6 h[q]}w 4(g.1f){16(5 i=q.7-1;i>=g.29;i--){5 c=h[q.3O(0,i)];4(c){5 a=[];$.I(c,3(i,x){4(1f(x.F,q)){a[a.7]=x}});6 a}}}6 P}}};$.M.32=3(e,g,f,k){5 h={H:"3N"};5 j,z=-1,y,1t="",1S=D,G,B;3 2y(){4(!1S)6;G=$("<3M/>").Z().Q(e.2P).T("3L","3K").1Q(1K.2w);B=$("<3H/>").1Q(G).3G(3(a){4(U(a).2u&&U(a).2u.3F()==\'2s\'){z=$("1L",B).1h(h.H).3D(U(a));$(U(a)).Q(h.H)}}).2q(3(a){$(U(a)).Q(h.H);f();g.2t();6 C}).3C(3(){k.1F=D}).3B(3(){k.1F=C});4(e.E>0)G.T("E",e.E);1S=C}3 U(a){5 b=a.U;3A(b&&b.3z!="2s")b=b.3y;4(!b)6[];6 b}3 V(b){j.1n(z,z+1).1h(h.H);2o(b);5 a=j.1n(z,z+1).Q(h.H);4(e.1D){5 c=0;j.1n(0,z).I(3(){c+=A.1a});4((c+a[0].1a-B.1b())>B[0].3x){B.1b(c+a[0].1a-B.3w())}w 4(c<B.1b()){B.1b(c)}}};3 2o(a){z+=a;4(z<0){z=j.1j()-1}w 4(z>=j.1j()){z=0}}3 2m(a){6 e.X&&e.X<a?e.X:a}3 2l(){B.2z();5 b=2m(y.7);16(5 i=0;i<b;i++){4(!y[i])1V;5 a=e.1R(y[i].y,i+1,b,y[i].F,1t);4(a===C)1V;5 c=$("<1L/>").3v(e.1y(a,1t)).Q(i%2==0?"3u":"3P").1Q(B)[0];$.y(c,"2k",y[i])}j=B.3t("1L");4(e.1X){j.1n(0,1).Q(h.H);z=0}4($.2e.2W)B.2W()}6{35:3(d,q){2y();y=d;1t=q;2l()},2D:3(){V(1)},30:3(){V(-1)},2C:3(){4(z!=0&&z-8<0){V(-z)}w{V(-8)}},2A:3(){4(z!=j.1j()-1&&z+8>j.1j()){V(j.1j()-1-z)}w{V(8)}},Z:3(){G&&G.Z();j&&j.1h(h.H);z=-1},N:3(){6 G&&G.3s(":N")},3q:3(){6 A.N()&&(j.2j("."+h.H)[0]||e.1X&&j[0])},20:3(){5 a=$(g).3p();G.T({E:W e.E=="1B"||e.E>0?e.E:$(g).E(),2i:a.2i+g.1a,1W:a.1W}).20();4(e.1D){B.1b(0);B.T({2L:e.1E,3n:\'3X\'});4($.1Y.3m&&W 1K.2w.3l.2L==="1x"){5 c=0;j.I(3(){c+=A.1a});5 b=c>e.1E;B.T(\'3k\',b?e.1E:c);4(!b){j.E(B.E()-2R(j.T("2O-1W"))-2R(j.T("2O-3j")))}}}},2g:3(){5 a=j&&j.2j("."+h.H).1h(h.H);6 a&&a.7&&$.y(a[0],"2k")},2T:3(){B&&B.2z()},1p:3(){G&&G.3i()}}};$.2e.18=3(b,f){4(b!==1x){6 A.I(3(){4(A.2d){5 a=A.2d();4(f===1x||b==f){a.4n("2c",b);a.3h()}w{a.4m(D);a.4l("2c",b);a.4k("2c",f);a.3h()}}w 4(A.3g){A.3g(b,f)}w 4(A.1C){A.1C=b;A.3e=f}})}5 c=A[0];4(c.2d){5 e=1K.18.4j(),3d=c.F,2a="<->",2f=e.3b.7;e.3b=2a;5 d=c.F.2H(2a);c.F=3d;A.18(d,d+2f);6{1I:d,39:d+2f}}w 4(c.1C!==1x){6{1I:c.1C,39:c.3e}}}})(4i);',62,272,'|||function|if|var|return|length|||||||||||||||||||||||||else||data|active|this|list|false|true|width|value|element|ACTIVE|each|toLowerCase|val|result|Autocompleter|visible|case|null|addClass|break|multipleSeparator|css|target|moveSelect|typeof|max|url|hide||bind|onChange||trigger|trimWords|for|multiple|selection|autocomplete|offsetHeight|scrollTop|trim|preventDefault|populate|matchSubset|cacheLength|removeClass|add|size|search|hideResultsNow|lastWord|slice|flush|unbind|stopLoading|arguments|matchCase|term|extend|formatMatch|matchContains|undefined|highlight|formatResult|parse|string|selectionStart|scroll|scrollHeight|mouseDownOnSelect|autoFill|progress|start|delay|document|li|new|findValueCallback|setTimeout|clearTimeout|appendTo|formatItem|needsInit|defaults|push|continue|left|selectFirst|browser|selectCurrent|show|request|replace|split|unautocomplete||loadingClass||setOptions|minChars|teststring|flushCache|character|createTextRange|fn|textLength|selected|in|top|filter|ac_data|fillList|limitNumberOfItems|BACKSPACE|movePosition|PAGEDOWN|click|hideResults|LI|focus|nodeName|PAGEUP|body|COMMA|init|empty|pageDown|ESC|pageUp|next|RETURN|ol|nullData|indexOf|TAB|strong|gi|maxHeight|keyCode|DEL|padding|resultsClass|inputClass|parseInt|DOWN|emptyList|form|dataType|bgiframe|opera|UP|extraParams|prev|load|Select|||display|mustMatch|substring||end|receiveData|text|Cache|orig|selectionEnd|join|setSelectionRange|select|remove|right|height|style|msie|overflow|off|offset|current|attr|is|find|ac_even|html|innerHeight|clientHeight|parentNode|tagName|while|mouseup|mousedown|index|blur|toUpperCase|mouseover|ul|188|default|absolute|position|div|ac_over|substr|ac_odd|charAt|word|180|RegExp|100|switch|400|auto|ac_loading|ac_results||ac_input|keydown|keypress|success|submit||limit|150|name|port|abort|mode|ajax|Date|timestamp|200|map|jQuery|createRange|moveEnd|moveStart|collapse|move'.split('|'),0,{}))
		
		/**
		 * jQuery Quidco Validator Plugin
		 *
		 */
		var FormValidator=function(element,options){element=$(element);var obj=this;var settings=$.extend({onError:function(e,message){},onSuccess:function(e){},rules:{}},options||{});var timeoutBusy=false;var timeout=null;var waitingForResponse=false;var validation={remote:function(e,param){waitingForResponse=true;if(typeof(settings.rules[e.selector].validate.remote.onRun)!="undefined"){settings.rules[e.selector].validate.remote.onRun()}$.ajax($.extend(true,{type:"GET",url:"",dataType:"text",data:"",success:function(data,textStatus){if(typeof(settings.rules[e.selector].validate.remote.onSuccess)!="undefined"){settings.rules[e.selector].valid=settings.rules[e.selector].validate.remote.onSuccess(data,textStatus)}else{settings.rules[e.selector].valid=data=="true"?true:false}waitingForResponse=false},error:function(XMLHttpRequest,textStatus,errorThrown){if(typeof(settings.rules[e.selector].validate.remote.onError)!="undefined"){settings.rules[e.selector].valid=settings.rules[e.selector].validate.remote.onError(XMLHttpRequest,textStatus,errorThrown)}waitingForResponse=false}},param));return"checking"},minLength:function(e,min){return e.val().length>=min},maxLength:function(e,max){return e.val().length<=max},match:function(e,object){return((typeof(object)=="object")&&(object.val()==e.val()))||(e.val()==object)},required:function(e){switch(e[0].tagName.toLowerCase()){case"select":var options=$("option:selected",e);return options.length>0&&options[0].value.length>0;case"input":if(e[0].type=="checkbox"||e[0].type=="radio"){return e.filter(":checked").length>0}default:return $.trim(e.val()).length>0;break}},regex:function(e,regex){regex=RegExp(regex);return regex.test(e.val())},email:function(e){var qtext="[^\x0d\x22\x5c\x80-\xff]";var dtext="[^\x0d\\x5b-\\x5d\x80-\xff]";var atom="[^\x00-\x20\x22\x28\x29\x2c\\x2e\x3a-\x3c\x3e\x40\\x5b-\\x5d\x7f-\xff]+";var quotedPair="\x5c\x00-\x7f";var domainLiteral="\\x5b("+dtext+"|"+quotedPair+")*\\x5d";var quotedString="\x22("+qtext+"|"+quotedPair+")*\x22";var domainRef=atom;var subDomain="("+domainRef+"|"+domainLiteral+")";var word="("+atom+"|"+quotedString+")";var domain=subDomain+"(\\x2e"+subDomain+")*";var localPart=word+"(\\x2e"+word+")*";var addressSpec=localPart+"\x40"+domain;var regex="^"+addressSpec+"$";if(e.val().length < 1){return true;}return this.regex(e,regex)},alpha:function(e){return this.regex(e,"^[a-zA-Z]*$")},alphaNumeric:function(e){return this.regex(e,"^[a-zA-Z0-9]*$")},alphaDash:function(){return this.regex(e,"^[a-zA-Z0-9_-]*$")},numeric:function(e){return this.regex(e,"^[0-9]*$")}};this.reset=function(selector){if(selector=="timeout"){clearTimeout(timeout)}else{settings.rules[selector].valid=null}return true};this.validate=function(e){var completeResult=true;clearTimeout(timeout);jQuery.each(settings.rules,function(selector,actions){if(typeof(settings.rules[selector].valid)=="undefined"){settings.rules[selector].valid=null}if((e[0].tagName.toLowerCase()=="form")||(e[0]==$(selector)[0])){if((e[0].tagName.toLowerCase()=="form"&&settings.rules[selector].valid===null)||e[0].tagName.toLowerCase()!="form"){var errorMessage=false;jQuery.each(actions.validate,function(validationName,arguments){switch(validationName){case"minLength":settings.rules[selector].valid=validation.minLength($(selector),arguments.value);break;case"maxLength":settings.rules[selector].valid=validation.maxLength($(selector),arguments.value);break;case"match":settings.rules[selector].valid=validation.match($(selector),arguments.value);break;case"email":settings.rules[selector].valid=validation.email($(selector));break;case"regex":settings.rules[selector].valid=validation.regex($(selector),arguments.value);break;case"required":settings.rules[selector].valid=validation.required($(selector));break;case"remote":settings.rules[selector].valid=validation.remote($(selector),arguments.value);break;case"custom":if(typeof(arguments.onValidate)!="undefined"){if(typeof(arguments.value)!="undefined"){settings.rules[selector].valid=arguments.onValidate(arguments.value)}else{settings.rules[selector].valid=arguments.onValidate()}}break}if(settings.rules[selector].valid===false){errorMessage=arguments.errorMessage}return settings.rules[selector].valid});if(errorMessage===false&&settings.rules[selector].valid==true){if(typeof(actions.onSuccess)!="undefined"){actions.onSuccess($(selector))}else{if(typeof(settings.onSuccess)!="undefined"){settings.onSuccess($(selector))}}}else{if(settings.rules[selector].valid==false){if(typeof(actions.onError)!="undefined"){actions.onError($(selector),errorMessage)}else{if(typeof(settings.onError)!="undefined"){settings.onError($(selector),errorMessage)}}completeResult=false}}}}});if(e[0].tagName.toLowerCase()=="form"){if(waitingForResponse==true&&timeoutBusy==false){timeoutBusy=true;timeout=setTimeout(function(){timeoutBusy=false;obj.validate(e)},100);return false}jQuery.each(settings.rules,function(selector,values){return completeResult=values.valid==true?true:false})}return completeResult}};
		
		/**
		 * email validator
		 *
		 */
		function isValidEmailAddress(emailAddress) {
			var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
			return pattern.test(emailAddress);
		}
		
