//$(document).ready(myNewsletterDomReady);

var popupOffset;
var comboSearch="";
var comboTO=0;
var comboCurr;
var comboH;
var comboyText;
var customCombos=false;
function myNewsletterDomReady()
{
	// Subscriber popup
	$('.subscribeLink').click(function(){
		var pp=$("#subscriberForm");

		pp.find('#panelForm').show();
		pp.find('#panelPolicy').hide();
		pp.find('#panelSubscribeOk').hide();

		pp.fadeIn('slow');


	});
	$('#subscriberForm .btnClose').click(function() {$("#subscriberForm").fadeOut('fast');} );

	if( customCombos)
	{
		makeComboBox('#subscriberForm',"country", "- Please select a country -");
		makeComboBox('#subscriberForm',"industry", "- Please select an industry -");
	}
	$('.agreePolicy a').click(showPanelPolicy);
	$('#panelPolicy .btnBack').click(function(){
		$('#titlePolicy').fadeOut('fast');
		$('#panelPolicy').fadeOut('fast',function(){ $('#panelForm').fadeIn('fast'); $('#titleSubscribe').fadeIn('fast') });
	});

	$('#subscriberForm .btnSignUp').click(function(){commitSubscribe();});
	

	// Temp add err message div
	$('#subscriberForm .inputControl').before("<div class=\"errMsg\">Error</div>");




	
/*	
	$('#FormInput_firstname').installFieldValidation({f:function(){	return $(this).val()? 1: 0;	}},commitSubscribe);
	$('#FormInput_lastname').installFieldValidation({f:function(){	return $(this).val()? 1: 0;	}},commitSubscribe);
	$('#FormInput_firm').installFieldValidation({f:function(){	return $(this).val()? 1: 0;	}},commitSubscribe);
	$('#FormInput_jobPosition').installFieldValidation({f:function(){	return $(this).val()? 1: 0;	}},commitSubscribe);
	$('#FormInput_emailConfirm').installFieldValidation({f:function(){	return $('#FormInput_email input').val()==$(this).val()? 1: 0;	}},commitSubscribe);
	$('#FormInput_agreePolicy').installFieldValidation({f:function(){	return $(this).is(":checked")? 1: 0;	}},commitSubscribe);
	$('#FormInput_email').installFieldValidation({
	live:true,
	f:function(){ return ValidationFunctionEmail($(this).val())?1:0;	}
	});
*/



	// initial test	
	$('.formInput.wasFocused').find("input,select,textarea").focus().blur();

}

function myEnquiriesDomReady()
{
	// Enquiry popup
	$('.enquiryLink').click(function(){
		var pp=$("#enquiryForm");
		pp.find('#panelEnquiry1').show();
		pp.find('#panelEnquiry2').hide();
		pp.find('#panelEnquiry3').hide();
		pp.fadeIn('slow');
	});


	$('#enquiryForm .btnClose').click(function() {$("#enquiryForm").fadeOut('fast');} );
	$('#enquiryForm .btnNext').click(function(){ validateEnquiryNext(); });
	$('#enquiryForm .btnSubmit').click(function(){ validateEnquiry(); });
	
	$('.agreePolicyEnquiry a.clickPolicy').click(function()
	{	
		$('#titleEnquiry').fadeOut('fast');
		$('#panelEnquiry2').fadeOut('fast',function(){ $('#panelPolicyEnquiry').fadeIn('fast');$('#titlePolicyEnquiry').fadeIn('fast');});

	});
	$('#panelPolicyEnquiry .btnBack').click(function(){
		$('#titlePolicyEnquiry').fadeOut('fast');
		$('#panelPolicyEnquiry').fadeOut('fast',function(){ $('#panelEnquiry2').fadeIn('fast');$('#titleEnquiry').fadeIn('fast');});
	});


	$('#enquiryForm .inputControl').before("<div class=\"errMsg\">Error</div>");

	if( customCombos)
	{
		makeComboBox('#enquiryForm',"countryEnquiry", "- Please select a country -");
		makeComboBox('#enquiryForm',"industryEnquiry", "- Please select an industry -");
	}
}

function commitSubscribe(noSend)
{
	var is;
	formValidate( 'firstname'		,$('[name=firstname]').val().length>=2			, "Please enter your first name");
	formValidate( 'lastname'		,$('[name=lastname]').val().length>=2			, "Please enter your last name");
	formValidate( 'firm'			,$('[name=firm]').val().length>=2				, "Please enter your company name");
	formValidate( 'jobPosition'		,$('[name=jobPosition]').val().length>=2		, "Please enter your job title");
	formValidate( 'agreePolicy'		,$('[name=agreePolicy]').is(':checked')			, "Please read and agree to the privacy policy terms in order to sign up");
	formValidate( 'email'			,is=ValidationFunctionEmail($('[name=email]').val()), "Please enter a valid email address");
	formValidate( 'emailConfirm'	,(!is)|| $('[name=emailConfirm]').val()==$('[name=email]').val(), "Please confirm your email address");
	formValidate( 'country'			,$('[name=country]').val().length>0				, "Please select the country you live in");
	formValidate( 'industry'		,$('[name=industry]').val().length>0				, "Please select the industry you work in");

	if( (!$('#subscriberForm .hasError').length) && (!noSend))
	{	RQAjaxPost('async.php?code='+sRqSessionCode+'&module='+"Newsletter" ,'formSubscribe',function(m,e){
			if(!e) eval(m);
		});
	}
}
function validateEnquiryNext()
{
	var is;
	formValidate( 'firstnameEnquiry'	,$('[name=firstnameEnquiry]').val().length>=2			, "Please enter your first name");
	formValidate( 'lastnameEnquiry'		,$('[name=lastnameEnquiry]').val().length>=2			, "Please enter your last name");
	formValidate( 'phoneEnquiry'		,$('[name=phoneEnquiry]').val().length>=7				, "Please enter your phone number");
	formValidate( 'emailEnquiry'		,is=ValidationFunctionEmail($('[name=emailEnquiry]').val()), "Please enter a valid email address");
	formValidate( 'emailConfirmEnquiry'	,(!is)|| $('[name=emailConfirmEnquiry]').val()==$('[name=emailEnquiry]').val(), "Please confirm your email address");
	formValidate( 'countryEnquiry'		,$('[name=countryEnquiry]').val().length>0				, "Please select the country you live in");
	formValidate( 'industryEnquiry'		,$('[name=industryEnquiry]').val().length>0				, "Please select the industry you work in");

	if( !$('#enquiryForm .hasError').length)
	{
		$('#enquiryForm #panelEnquiry1').fadeOut('slow',function(){  $('#enquiryForm #panelEnquiry2').fadeIn('slow'); } );
	}


}
function validateEnquiry()
{
	formValidate( 'textEnquiry'	,$('[name=textEnquiry]').val().length>=10			, "Please tell us more about your request");
	formValidate( 'agreePolicyEnquiry'		,$('[name=agreePolicyEnquiry]').is(':checked')			, "Please read and agree to the privacy policy terms in order to submit an enquiry");

	if( !$('#enquiryForm .hasError').length)
	{
			RQAjaxPost('async.php?code='+sRqSessionCode+'&module='+"ListEnquiries" ,'formEnquiry',function(m,e){
			if(!e) eval(m);
		});
	}

}
function enquiryOK()
{
	$("#panelEnquiry2").fadeOut('fast',function(){ 
        $("#panelEnquiry3").fadeIn('fast');
        $("#waitABit").css({opacity:1}).animate({opacity:0},5000,'linear',function(){
			$('#enquiryForm').fadeOut('fast');		
		})
    } );

}


function formValidate(name, is,errTxt)
{
	if(is)
	{	formHideErrorMsg(name);
	}
	else
	{
		formShowErrorMsg(name,errTxt);
	}
}
function formHideErrorMsg(name)
{
	$('#FormInput_'+name).find('.errMsg').removeClass('hasError').hide();
}
function formShowErrorMsg(name,txt)
{
	$('#FormInput_'+name).find('.errMsg').html(txt).addClass('hasError').show();

}

function setformButton(is)
{
	$('.btnSignUp').css("opacity",is?1:0.2);
}
function makeComboBox(fmName,name,txt)
{
	//$(window).height()
	//$(document).scrollTop()
	

	var combo = $("<div id=\"combo"+name+"\" class=\"myCombo\"></div>");
	var s="<a><span>"+txt+"</span></a>";
	s+="<ul>";
	$('#'+name+' option').each(function(){
		s+="<li id=\""+name+"_"+$(this).attr('value')+"\">"+$(this).text()+"</li>";
	});
	$('#'+name).remove();
	s+="</ul>";
	s+="<input type=\"hidden\" name=\""+name+"\" id=\""+name+"\" />";
	combo.html(s);
	combo.find("a").mousedown(function(){ return showComboPopup(fmName,this,name,true); });
	combo.find("li").click(function(){
		//alert($(this).attr('className'));
		$(this).parent().prev().addClass('hasValue').find('span').text($(this).text());
		$('#'+name).val($(this).attr('id'));
		$(this).parent().hide();
		$(window).unbind('keypress');
		$(window).unbind('mousemove');
	}).mouseover(function(){$(this).addClass("over")}).mouseout(function(){$(this).removeClass("over")});
	$('#FormInput_'+name).append(combo);
	

};
function comboClearSearch()
{
	comboTO=0;
	comboSearch="";
}
function showComboPopup(fmName,a,name,isClick,sel)
{
	
	var pp=$(a).next();
	var o=$(a).offset();
	var curr=sel?sel:$('#'+name).val();
	comboCurr =curr;
	popupOffset = $(fmName).offset();
	var hTe  = $(a).height()+13;
	yText = o.top-popupOffset.top+hTe;
	var combo = $("#combo"+name);

	pp.css({left: ""+(o.left-popupOffset.left)+"px",top:""+yText+"px",height:"auto"});
	pp.show();
	var hPp = pp.height();
	if( curr)
	{	yText -= ($('#'+curr).offset().top - pp.offset().top +hTe);
		pp.css({top:""+yText+"px"});
	}
	comboH = $(document).scrollTop()+$(window).height()-yText-20-popupOffset.top;
	if( comboH<hPp) pp.css({height:comboH}); else comboH=0;
	if( isClick)
	{	if( comboH)
		$(window).bind('mousemove',function(e)
		{	//RQDebug(""+e.pageX+","+e.pageY);
			var yMin =popupOffset.top+yText-$(document).scrollTop();
			var yMax =yMin+comboH;
			if( e.pageY> (yMax-30) && e.pageY<yMax+5)
			{	var n=comboCurr?$('#'+comboCurr).next():combo.find("li:first-child");
				if( n.length)
					showComboPopup(fmName,a,name,false,n.attr('id'));

			}
			else if( e.pageY< ( $(document).scrollTop()+30) && e.pageY>yMin)
			{	var n=comboCurr?$('#'+comboCurr).prev():combo.find("li:first-child");
				if( n.length)
					showComboPopup(fmName,a,name,false,n.attr('id'));
			}
		}
		);
		$(window).bind('keypress',function(e)
		{
			if(e.keyCode==13) combo.find('.over').click();
			else	//find country
			{	var key = e.keyCode;
				var c=String.fromCharCode(key).toUpperCase();
				if( comboTO) {self.clearTimeout(comboTO);}
				comboTO=self.setTimeout("comboClearSearch()",600);
				comboSearch+=c;
				combo.find("li").each(function(){
					if( $(this).text().substring(0,comboSearch.length).toUpperCase() ==comboSearch)
					{	$(".myCombo .over").removeClass("over");
						$(this).addClass("over");
						showComboPopup(fmName,a,name,false,$(this).attr('id'));
						return false;
					}
				});
			}
		});
	}


	return true;
}

function showPanelPolicy()
{
	$('#titleSubscribe').fadeOut('fast');
	$('#panelForm').fadeOut('fast',function(){ $('#panelPolicy').fadeIn('fast');$('#titlePolicy').fadeIn('fast');});
}

function subscribeOK()
{
	$("#panelForm").fadeOut('fast',function(){ 
        $("#panelSubscribeOk").fadeIn('fast');
        $("#waitABit2").css({opacity:1}).animate({opacity:0},5000,'linear',function(){
			$('#subscriberForm').fadeOut('fast');		
		})
    } );

}
function subscribeFormErr(name,msg)
{
	var a=$('#FormInput_'+name);
	if( !a.find('.errMsg').length)
		a.find('.inputContent').append("<div class=\"errMsg\"></div>");
	a.find('.errMsg').html(msg);
}

