/* Javascript stylesheet */
document.write("<link rel=\"stylesheet\" href=\"http://assets.fish4.co.uk/live/styles/fish4Js.css\" type=\"text/css\" media=\"screen\" />");

// e3 javascript for fish4

$(document).ready(function(evt) {
    // add a callCost link for phone numbers starting 0871, 0872, 0800 or 0808
    if ($(".contactBox p strong").length == 0) { return false; }
    
    var adPhone = $(".contactBox p strong").html().substring(0,4);
    var callInfo = "";
    var callLink = "";

    if (adPhone == '0871' || adPhone == '0872' || adPhone == '0800' || adPhone == '0808') {
        if (adPhone == '0800' || adPhone == '0808') {
            callLink = "BT free phone call";
            callInfo = "<h2>How much will this "+adPhone+" number cost me?</h2><p>When calling from a BT landline this call is free. Call charges from other operators may vary.</p>";
        }
        if (adPhone == '0871' || adPhone == '0872') {
            callLink = "BT 10p/min";
            callInfo = "<h2>How much will this "+adPhone+" number cost me?</h2><p>You will only be charged 10 pence per minute, anytime, when calling from a BT landline. Call charges from other operators may vary.</p>";
        }
        $(".contactBox p").append('<a class="call_cost" href=\"javascript:void(0)\">' + callLink + '</a>');

        $(".call_cost").click( function(evt){
            var x=0, y=0;
            var fixY = 10;
            if (document.all) {//IE
                x = (document.documentElement && document.documentElement.scrollLeft) ? document.documentElement.scrollLeft : document.body.scrollLeft;
                y = (document.documentElement && document.documentElement.scrollTop) ? document.documentElement.scrollTop : document.body.scrollTop;
                x += window.event.clientX;
                y += window.event.clientY + fixY;
            }
            else {//Good Browsers
                x = evt.pageX;
                y = evt.pageY + fixY;
            }
            $(document.body).append('<div class="cost_popup">' + callInfo + '</div>');
            $(".cost_popup").css('left', x);
            $(".cost_popup").css('top', y);

            $(".cost_popup").show();
        });
        $(document).click(function(e) {
            var $clicked=$(e.target); // get the element clicked
            if( !( $clicked.is('.call_cost')) && $(".cost_popup").is(':visible') ) {
                $(".cost_popup").hide();
            }
        });
    }
       
});



// when the document is loaded
function init(){	
	fnTabs();						// tabbed content
	if($("#wrapper.fish4Money").length==0) fnBlockLinks();					// create bigger links - make blocks clickable
	fnGallery();					// prep image gallery
	fnClearFieldsBeforeSubmit();	// search widget form behaviours
	fnAdditional();					// show-hide on additional info
	fnFlashCalculatorsCheck();		// hides link to users without flash support
	fnPopups();						// handles all elements with class="popup"
	fnFish4prizes();
};

/**************************************************************
Function:	fnBrowser
Purpose:	Check we're in a supported browser
Notes:		
**************************************************************/
// Global Variables
var iepc,firefox,ns7,ns8,mozilla,safari;
function fnBrowser() {	
	var ua = navigator.userAgent.toLowerCase();
	
	iepc = (((ua.indexOf("msie 7") != -1)||(ua.indexOf("msie 6") != -1)||(ua.indexOf("msie 5.5") != -1))&&(ua.indexOf("windows") != -1)&&(ua.indexOf("opera") == -1))? true:false;
	firefox = ua.indexOf("firefox") != -1 ? true:false; // pc or mac
	ns7 = ua.indexOf("netscape/7") != -1 ? true:false; // firefox mode
	ns8 = ua.indexOf("netscape/8") != -1 ? true:false; // firefox mode
	mozilla = (ua.indexOf("gecko") != -1) && (ua.indexOf("netscape") == -1) ? true:false; 
	safari = ua.indexOf("safari") != -1 ? true:false;	
	opera = ua.indexOf("opera/9") != -1 ? true:false;
	if (iepc||firefox||mozilla||safari||opera) {
		return true;
	} else {
		return false;
	}
}

/**************************************************************
Function:	fnTabs
Purpose:	Prepare tabbed content in show-hide pattern
Notes:		
**************************************************************/
function fnTabs(){
	$(".rcTabsInr .panel:first").show();							// all panels hidden by default but show the first one
	fnFitLinks($(".rcTabsInr .panel:first"));						// shrinks the font-size and line-height to make links fit
	$(".rcTabsWrap ul:first li a")									// for all links in the first ul's li's
		.click(function() {			
			$(".rcTabsInr .panel").hide();							// hide all panels			
			$(this.hash).show();									// show the clicked panel
			fnFitLinks($(this.hash));
			$(".rcTabsWrap ul:first li a").removeClass('selected');	// turn off selected
			$(this).addClass('selected');							// set selected state on this link
			return false;											// don't jump down the page when link is clicked
		});
	
	function fnFitLinks(panel){
		var tagCloud = panel.find(".tagCloud");
		var links    = tagCloud.find("a");
		fnFitLinksInTagCloud_height(panel);
		
		function fnFitLinksInTagCloud_height(panel){
			var linesCount         = 1;
			var accumulatedWidth   = 0;
			var expandedLineHeight = 0;
			var lineHeight;
			var minFontThreshold   = 100;
			var currentFontSize;
			
			links.css("line-height", getLineHeight(links, tagCloud) + "px");
			for(var i=0; i<10; i++){
				if(tagCloud.attr("offsetHeight") < tagCloud.attr("scrollHeight") && minFontThreshold >= 10){
					links.each(function(){
						currentFontSize = parseInt($(this).css("font-size"));
						minFontThreshold = (minFontThreshold > currentFontSize) ? currentFontSize : minFontThreshold;
						//$(this).css("font-size", parseInt($(this).css("font-size")) - 1 + "px");
						$(this).css("font-size", castPercentAsPixels(getComputedStyle($(this)).fontSize) - 1 + "px");
						links.css("line-height", getLineHeight(links, tagCloud) + "px");
					});
				}else{
					fnFitLinksInTagCloud_width(panel);
					links.each(function(){
						accumulatedWidth += $(this).width();
						if(accumulatedWidth > tagCloud.width()){
							accumulatedWidth = $(this).width();
							linesCount++;
						};
					});
					lineHeight =  parseInt(tagCloud.height() / linesCount);
					links.css("line-height", lineHeight + "px");
					tagCloud.height(lineHeight * linesCount);
					break;
				};
			};
		};
		function fnFitLinksInTagCloud_width(){
			links.each(function(){
				while($(this).width() > tagCloud.width()) fnShrinkFontSize($(this).css("font-size"));
			});
		};
		function getLineHeight(links, tagCloud){
			var lineHeight     = 0;
			var tagCloudHeight = tagCloud.attr("offsetHeight");
			links.each(function(){
				lineHeight     = ($(this).height() > lineHeight) ? $(this).height() : lineHeight;
			});
			return lineHeight;
		};
		function getComputedStyle(element){
			var result;
			if(typeof element[0].currentStyle!="undefined"){
				result = element[0].currentStyle;
			}else{
				result = document.defaultView.getComputedStyle(element[0], null);
			};
			return result;
		};
		function castPercentAsPixels(val){
			var result = parseInt(val);
			if(typeof val=="string") result = (val.indexOf("%")>0) ? result/100*12 : result;
			return result;		
		};
	};
}	

/**************************************************************
Function:	fnGallery
Purpose:	Create sliding and loading functionality for gallery
Notes:		Doesn't work in safari 1.3 but jquery still attempts
			to work, so turn it off for saf 1.3
**************************************************************/
function fnGallery(){	
	
	// Doesn't work in safari 1.3
	if ($.browser.safari && $.browser.version < 400) {
    	return false;
 	}
 	// for other browsers
 	else if (fnBrowser()){ 		
 		// variables
		var list = $(".shThInr");
		var thumbs = $("ul li a", list);		
		var step = '110';
		
		var listW = (step * thumbs.length)-7;
					
		var imgWrap = $('#shImg');
		var img = $('img', imgWrap);
		
		// add buttons
		list
			.before('<a href="#" title="" class="prevImage">Previous</a>')		
			.after('<a href="#" title="" class="nextImage">Previous</a>')		
			.css({
				overflow: 'hidden'		
			});
		
		$(".nextImage").click(function(){
			$(".shThInr").animate({scrollLeft: "+="+step}, 250);		
			return false;
		});
		
		$(".prevImage").click(function(){
			$(".shThInr").animate({scrollLeft: "-="+step}, 250);		
			return false;
		});
		
	 	// tie event to thumbnail links - load the image into the main image holder
		thumbs			
			.click(function() {						
				img.fadeOut(350);
				imgWrap.addClass('loading');							
				img
					.attr("src", this.href)
					.fadeIn(350);
				return false;
			});
		$("a:last", list) .css('margin-right', '0'); 		
 	}	 	
}



/**************************************************************
Function:	fnClearFieldsBeforeSubmit
Purpose:	clears fields onfocus, restores help text onblur
			clears the help text before submitting			
Notes:		
**************************************************************/
function fnClearFieldsBeforeSubmit(){
	$("input[helpText], textarea[helpText]")
		.blur()
        .bind("focus", function(event){
			if($(this).val().indexOf($(this).attr("helpText"))>=0) $(this).val("").removeClass("dimmed");
        })
        .bind("blur", function(event){
			if($(this).val()=="") $(this).val($(this).attr("helpText")).addClass("dimmed");
        });
	$("form").submit(function(){
		$(this).find("input[helpText]").each(function(){
			if($(this).val()==$(this).attr("helpText")) $(this).val("");
		});
	});
}


/**************************************************************
Function:	fnAutocomplete
Purpose:	autocomplete feature for fish4Jobs
Notes:		needs the jquery/autocomplete/*.* files,
			fails silently if they're not included
**************************************************************/
function fnAutocomplete(){
	if(typeof doAutocomplete=="undefined") return null;
	doAutocomplete({
		id:"jobTitle", 
		list:ac_complist
	}, {
		delay:10,
		minChars:1,
		matchSubset:1,
		maxItemsToShow:15,
		header:"Search suggestions",
		closeButton: true,
		width: 250
	});
}


/**************************************************************
Function:	fnBlockLinks
Purpose:	Create sliding and loading functionality for gallery
Notes:		uses jcarousellite plugin (2KB)
**************************************************************/
function fnBlockLinks(){
	$('.fbWhiteAd').biggerlink();	
	$('#newCarSearch').biggerlink();	
	$('.bnLeft,.bnRight').biggerlink();	
	$('#refundPolicy').biggerlink();	
	// $('.bnRight').biggerlink();	
}

/**************************************************************
Function:	fnAdditional
Purpose:	Create show/hide functionality for additional info on detail pages
Notes:		
**************************************************************/
function fnAdditional(){
	// Doesn't work in safari 1.3 or 2
	if ($.browser.safari && $.browser.version < 420) {
    	return false;
 	}
	
	$('#additionalInfo .infoWrap').hide();
	$('#additionalInfo').addClass('closed');
	$('#additionalInfo .topBar').prepend('<a href="#" class="openBtn">+</a>');
	$('#additionalInfo .topBar .openBtn').click(
		function(){
			$('#additionalInfo .infoWrap').slideToggle('fast');
			$('#additionalInfo').toggleClass('closed').toggleClass('open');
			return false;
		});
	};
	
/**************************************************************
Function:	fnJobSalaryCalculator
Purpose:	display the link if the visitor has Flash >=7 installed
Notes:		
**************************************************************/
function fnFlashCalculatorsCheck(){
	if(typeof flashDetection=="undefined") return null;
	if(flashDetection(7) == false){
		$("#howMuch").empty();
		return null;
	};
};

/**************************************************************
Function:	fnPlaceAd
Purpose:	Modifies the DOM to place an accipter filled position into a waiting <div>
Notes:		
**************************************************************/
function fnPlaceAd(position, adcontent) {
    var adposition = document.getElementById(position);
    var testForBlankAd = /^<a.*>.*AE[0-9]{1}.gif.*<\/a>$|^<a.*\/>$/i;
    /*
    If the adcontent is not null, the holding div was display:none and content is not an empty anchor
    then make this holding div displayed. This is basically making collapsed ads displayed if they have content
     */
    if(adcontent != null && adposition.style.display == 'none' && !testForBlankAd.test(adcontent)) {
        adposition.style.display = 'block';
    }
    adposition.innerHTML = adcontent;
    $(adposition).addClass('adLoaded');
    $(adposition).removeClass('loadingAd');
    adposition.style.visibility = 'visible';

}

/**************************************************************
Function:	fnBrowser
Purpose:	Browser Detection
Notes:		
**************************************************************/
	
	
var iepc,firefox,ns7,ns8,mozilla,safari,OS;
function fnBrowser() {
	var ua = navigator.userAgent.toLowerCase();

	iepc = (((ua.indexOf("msie 7") != -1)||(ua.indexOf("msie 6") != -1)||(ua.indexOf("msie 5.5") != -1))&&(ua.indexOf("windows") != -1)&&(ua.indexOf("opera") == -1))? true:false;
	firefox = ua.indexOf("firefox") != -1 ? true:false; // pc or mac
	ns7 = ua.indexOf("netscape/7") != -1 ? true:false; // firefox mode
	ns8 = ua.indexOf("netscape/8") != -1 ? true:false; // firefox mode
	mozilla = (ua.indexOf("gecko") != -1) && (ua.indexOf("netscape") == -1) ? true:false;
	safari = ua.indexOf("safari") != -1 ? true:false;
	OS = ua.indexOf("windows") != -1? "PC":"MAC";
	opera = ua.indexOf("opera/9") != -1 ? true:false;
	if (iepc||firefox||ns7||ns8||mozilla||safari||opera) {
		return true;
	} else {
		return false;
	}
}

/**************************************************************
Function:	Flash Detection
Purpose:	Detects flash plugin
Notes:		
**************************************************************/
	
// Flash detect. boolean true/false if installed and version number accessed via flash.version
var flash = new Object();
flash.installed = false;

if (navigator.plugins && navigator.plugins.length) {
	for (x=0; x < navigator.plugins.length; x++) {

		if (navigator.plugins[x].name.indexOf('Shockwave Flash') != -1) {
			flash.installed = true;
			flash.version = eval(navigator.plugins[x].description.split('Shockwave Flash ')[1].split('.')[0]);
			break;
		}
	}
}
else if (window.ActiveXObject) {
	for (x = 2; x <= 20; x++) {
		try {
			oFlash = eval("new ActiveXObject('ShockwaveFlash.ShockwaveFlash." + x + "');");
			if(oFlash) {
				flash.installed = true;
				flash.version = x;
			}
		}
		catch(e) {}
	}
}

/********************************************************************************

Name: 				Flash embed
Description:		Writeout flash code. Fixes Eolas update for IE as well.
@param	swf			String path to swf file
@param	width		Number value of movie width
@param	height		Number value of movie height
@param  flashVer	Version of flash
@param nonFlashId	(Optional) Non-flash content id.

*********************************************************************************/
flash.insert = function(swf,width,height,flashVer,nonFlashId) {

	if(!flashVer){minVer = 6;}
	else {minVer = flashVer;}
	if(!nonFlashId){nonFlashId = "nonFlashContent";}

// Handle errors
	var errMsg ="";
	if (!fnBrowser()) { // NOT supported browser
		errMsg += '<p class="err">Unfortunately, this website cannot be viewed by your browser. Please go to <a href="http://www.getfirefox.com">www.getfirefox.com</a> or <a href="http://www.microsoft.com/windows/ie/">www.microsoft.com/</a> to download a recommended browser.</p>';
	}
	if (!flash.installed) { // NOT flash
		errMsg += '<p class="err">This website requires the adobe&trade; Flash player. Go to the adobe website to install the <a href="http://www.adobe.com/products/flashplayer/">latest version of flash</a></p>';
	}
	if($.browser.msie){
		swf = swf.replace(/\./g,"%2E"); 	 // encode periods as %2e
		swf = swf.replace(/\%2E\%2E/g,".."); // replace %2e%2e back as ..
	}
	
	if(flash.installed && fnBrowser() && flash.version >= minVer) {
		document.write('<embed src="'+swf+'" menu="false" width="'+width+'" height="'+height+'" scale="noscale" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" salign="T" />');
		fnHide(nonFlashId);
	}
}

function fnHide(id) {
	if(!document.getElementById(id)){return false};
	var oTarg = document.getElementById(id).style;
	oTarg.position = "absolute";
	oTarg.top = "-5000px";
	oTarg.left = "0";
}

function fnShow(id) {
	if(!document.getElementById(id)){return false};
	var oTarg = document.getElementById(id).style;
	oTarg.position = "static";
	oTarg.top = "";
	oTarg.left = "";
}

/**************************************************************
Function:	fnPopups
Purpose:	handles all elements with class="popup"
Notes:		
**************************************************************/
function fnPopups(){
	var defaultFurniture = "location=0,statusbar=0,scrollbars=1,menubar=0,resizable=";
	var fullFurniture    = "location=1,statusbar=1,scrollbars=1,menubar=1,directories=1,resizable=yes,";
	    fullFurniture   += "width="  + screen.width + " ,";
	    fullFurniture   += "height=" + screen.height;
	
	function popupHandler(element, popupProperties, removeTarget){
		$(element).bind("click", function(event){
			if(removeTarget==true) this.target = "_self";
			if($(this).hasClass("full")) popupProperties = fullFurniture;
			window.open(this, "", popupProperties);
			return false;
		});
	};

	popupHandler("#question-mark.popup", defaultFurniture + "yes, width=680, height=500");
	popupHandler(".howMuch a.popup", defaultFurniture + "no, width=1000, height=530");
	popupHandler("#attachingCv a.popup", defaultFurniture + "yes, width=500, height=500", true);
	popupHandler("#singleMyFish4Cv a.popup", defaultFurniture + "yes, menubar=0, width=500, height=500", true);
    popupHandler("#rssmenu a.popup", defaultFurniture + "yes, width=500, height=500", true);
	popupHandler("a.mapLink.popup", defaultFurniture + "yes, width=730, height=610");
	//popupHandler("#calculator.popup2", defaultFurniture + "yes, width=980, height=535");
    popupHandler("#calculator.popup3", defaultFurniture + "yes, width=500, height=515");
    popupHandler(".externalPopupPage", "location=0");
    popupHandler("#boldchat.popup", defaultFurniture + "yes, width=680, height=500");
};
	
var submitted = 0;
function checkFormSubmit() {
    if (submitted) {
        alert("Page already submitted, please wait...");
        return false;
    }
    if (!submitted) {
        submitted = 1;
        return true;
    }
}

var submitted = 0;
function checkFormSubmit() {
    if (submitted) {
        alert("Page already submitted, please wait...");
        return false;
    }
    if (!submitted) {
        submitted = 1;
        return true;
    }
}


/**************************************************************
Function:	fillChilds
Purpose:	handles the tied make-model drop-downs for cars and subverticals
Notes:		
**************************************************************/
function fillChilds(form,name1,name2,allchilds,allparents) {

	emptySelectBox(form, name1, allchilds);
	var childid = 0;
	var start = 1;
	var name2Length = document[form][name2].length;
	if (allchilds == true) {
		childid = 1;
	}
	if (allparents == false) {
		start = 0;
	}
    var selectedvalue = 0;
	for (var i=start;i<name2Length;i++) {
		if (document[form][name2][i].selected) {

            selectedvalue = parentArr[i-start].split(";")[0];
			var tmpArr = childArr[i-start].split("|");
			for (var j=0;j<tmpArr.length;j++) {
				var tmpArr2 = tmpArr[j].split(";");
			    document[form].elements[name1].options[childid] = new Option(tmpArr2[1],tmpArr2[0]);
                childid++;
			}
		}
	}
    if (allchilds) {
        document[form].elements[name1].options[0].value = '0';
    }
	


	function emptySelectBox(form, boxname, allchilds){
		var length = Number(document.forms[form].elements[boxname].options.length);

		if (navigator.appName.indexOf("Netscape") != -1) {
			for (var i=(length); i > 0; i--) {
				document.forms[form].elements[boxname].options[i]=null;
			}
		} else if (navigator.userAgent.indexOf("Opera") != -1) {
			for(var i=(length); i > 0; i--) {
				document.forms[form].elements[boxname].options.remove(i);
			}
		} else if ((navigator.userAgent.indexOf("MSIE") != -1) && (parseInt(navigator.appVersion) >= 4)) {
			for(var i=(length); i > 0; i--) {
				document.forms[form].elements[boxname].options.remove(i);
			}
		} else if ((navigator.userAgent.indexOf("MSIE") != -1) && (parseInt(navigator.appVersion) < 4)) {
			for (var i=(length-1); i > 0; i--) {
				document.forms[form].elements[boxname].options[i].selected = false;
			}
		} else {
			for (var i=(length-1); i > 0; i--) {
				document.forms[form].elements[boxname].options[i].selected = false;
			}
		}
		if (navigator.appName.indexOf("Netscape") == -1) {
			if (allchilds) {
				document.forms[form].elements[boxname].options[0] = new Option("All","0",true,true);
			} else {
				document.forms[form].elements[boxname].options[0] = new Option("","0",true,true);
			}
			document.forms[form].elements[boxname].options[0].selected = true;
		}
	}
} 

/**************************************************************
Function:	toggle divs
Purpose:	displays/hides extra information on a page. (used in the ecom forms)
Notes:		
**************************************************************/
function blockToggle(nr,link)
{
	if (link) {openclose = link;}
	else {openclose = null;}
	if (document.layers)
	{
		current = (document.layers[nr].display == 'block') ? 'none' : 'block';
		document.layers[nr].display = current;
	}
	else if (document.all)
	{
		current = (document.all[nr].style.display == 'block') ? 'none' : 'block';
		if (openclose) {
		    if ((openclose.className=='minus') || (openclose.className=='open')) {
		        current = 'none';
		    } else {
		        current = 'block';
		    }
		}
		document.all[nr].style.display = current;
	}
	else if (document.getElementById)
	{
		current = (document.getElementById(nr).style.display == 'block') ? 'none' : 'block';
		if (openclose) {
		    if ((openclose.className=='minus') || (openclose.className=='open')) {
		        current = 'none';
		    } else {
		        current = 'block';
		    }
		}
		document.getElementById(nr).style.display = current;
	}
            if (openclose) {
                if((openclose.className=='open') || (openclose.className=='closed')) {
                    if (current=='block') {openclose.className='open'} else {openclose.className='closed'};
                } else {
                    if (current=='block') {openclose.className='minus'} else {openclose.className='plus'};
                }
            }

}

/**************************************************************
Function:	pCodeCheck
Purpose:	postcode validation - for cars only
Notes:		
**************************************************************/
function pCodeCheck(theForm, theInput) {
//var formEl = document.simplesearch.LOCATION;
var formEl = document.forms[theForm].elements[theInput];
var PostCode = formEl.value.toUpperCase();
var pcodeRegxp = /^^([A-PR-UWYZ][0-9]([0-9]|[A-HJKSTUW])? [0-9][ABD-HJLNP-UW-Z]{2}|[A-PR-UWYZ][A-HK-Y][0-9]([0-9]|[ABEHMNPRVWXY])? [0-9][ABD-HJLNP-UW-Z]{2}|GIR 0AA)$/;

// trimming leading and trailing white spaces.
var tempPostCode = PostCode.replace(/^\s+|\s+$/g,"");

if(!pcodeRegxp.test(tempPostCode)) {
  	alert ("Please enter a valid UK postcode including a space\ne.g. W6 7AF");
  	formEl.focus();
  	return false
  }
  else {
  	formEl.value = PostCode;
  	return true
  }
}

/**************************************************************
Function:	mail_validateDetails
Purpose:	contact dealer validation - cars and sub-verticals, homes & lettings
Notes:		
**************************************************************/
function mail_validateDetails(form, url) {
	var validation = [
		{
			fieldName : "input/from", regExp : /^.+@.+$/g, 
			errorMessage : "Please supply a valid contact e-mail address.", helpText : "Your email address"
		},
		{
			fieldName : "input/#contact_phone#", regExp : /^.+$/g, 
			errorMessage : "You must supply your day phone number.", helpText : "Your telephone number"
		},
		{
			fieldName : "input/#contact_phone#", regExp : /^\+{0}0\d{9,10}$/g, 
			errorMessage : "The telephone number should start with a 0 and contain 10 or 11 digits.", helpText : "Your telephone number"
		},
		{
			fieldName : "input/#telephone#", regExp : /^.+$/g, 
			errorMessage : "You must supply your day phone number.", helpText : "Your telephone number"
		},
		{
			fieldName : "input/#telephone#", regExp : /^\+{0}0\d{9,10}$/g, 
			errorMessage : "The telephone number should start with a 0 and contain 10 or 11 digits..", helpText : "Your telephone number"
		},
		{
			fieldName : "input/#firstname#", regExp : /^.+$/g, 
			errorMessage : "Please enter your name.", helpText : "Your first name"
		},
		{
			fieldName : "input/#surname#", regExp : /^.+$/g, 
			errorMessage : "Please enter your surname.", helpText : "Your surname"
		},
		{
			fieldName : "input/#contact_address#", regExp : /^.+$/g, 
			errorMessage : "Please enter your contact address.", helpText : "Your address"
		},
		{
			fieldName : "input/#contact_postcode#", regExp : /^.+$/g, 
			errorMessage : "Please enter your post code.", helpText : "Your post code"
		},
		{
			fieldName : "input/#subject#", regExp : /^.+$/g, 
			errorMessage : "Please enter the subject of your question.", helpText : "The subject of your question"
		},
		{
			fieldName : "textarea/#usermessage#", regExp : /^(.|\r|\n)+$/g, 
			errorMessage : "Please enter your question.", helpText : "Your question..."
		}
	];
	var contact_phone = $("input[name=#contact_phone#]");
	var telephone     = $("input[name=#telephone#]");
	var i, field, flag;
	
	if(contact_phone.length==1){
		if(contact_phone.attr("value") !=validation[1].helpText){
			contact_phone.attr("value", contact_phone.attr("value").replace(/[\s-]/g, ""));
		};
	};
	if(telephone.length==1){
		if(telephone.attr("value") !=validation[4].helpText){
			telephone.attr("value",     telephone.attr("value").replace(/[\s-]/g, ""));
		};
	};
	
	for(i=0; i<validation.length; i++){
		flag  = 0;
		field = $(validation[i].fieldName.replace("/", "[name=")  + "]");
		if(field.length==1){
			if(typeof field.attr("value")!="undefined"){
				if(field.attr("value").match(validation[i].regExp)==null){
					flag = 1;
					break;
				};
				if(field.attr("value").indexOf(validation[i].helpText)>=0){
					flag = 2;
					break;
				}
			}else{
				flag = 3;
				break;
			};
		};
	};
	if(flag>0){
		alert(validation[i].errorMessage);
		field.focus();
		return;
	}else{
		form.action = url;
		form.submit();
	};
}


/**************************************************************
Function:	fnFish4prizes
Purpose:	failsafe for form submission
Notes:		
**************************************************************/
function fnFish4prizes(){
	$("#fish4prizes").ready(function(){
		$("form[name=registration]").submit(function(){
			if (typeof MG_Competition != 'undefined') return MG_Competition.submitCoreg($(this)[0]);
		});
	});
};
