var patt =/.*(?=(\.\w+$))/g;
var extension = location.hostname.replace(patt,"");
if(extension.length!=4) extension = ".com";

$(document).ready(function () {
var hash = getUrlVars();
var geo = parseFloat(hash["geo"]);
	$('.showForm').click(function (e) {
		e.preventDefault();
		$('#form').modal({opacity:60});		
		// autocomplete
		$( "#frm_005_Company").autocomplete({																	
			source: function( request, response ) {
				$.ajax({
					url: "http://admin.businessmonitor"+extension+"/services/grid/prospect_clients/?action=get_company",
					dataType: "jsonp",
					data: {
						company_begin: request.term
					},
					success: function( data ) {
						response( $.map( data.companies, function( item ) {
							return {
								label: item,
								value: item
							}
						}));
					}
				});
			},
			minLength: 2
		});
	});
	$('.showLogin').click(function (e) {
		e.preventDefault();
		$('#login').modal({opacity:60});
	});	
	$('.showScreen').click(function (e) {
		e.preventDefault();
		$('#lower').modal({opacity:60});
	});
	
	$('#accordion').accordion({
		autoHeight: false,
		change: function(event, ui) { 
		var active = $( "#accordion" ).accordion( "option", "active" )+"";
		//$(this).css("background-image","url(/bmo/images/"+active+".png)");
		}
	});
	$('#accordion').accordion({active:geo});
	
	$('#introFreeTrial').hover(function () {
		$(this).addClass('activeBox');
	},
	function () {
		$(this).removeClass('activeBox');
	});

	
	$(".interests").tree({
	       ui : {
	            theme_name : "checkbox",
				theme_path: '/bmo/scripts/themes/checkbox/style.css',
				selected_parent_close:false
	        },
	       types : {
			"default" : { draggable: false }
			},
			callback : { 
			      onselect : function (node, to) {
					  to.get_node(node).find("a:first").toggleClass("checked");
					  addremtags();
				  }
			}
	    });
	
	$('#frm_0013_Country').change(function() {
		setAutofill($(this).val());
	});
	$('#frm_008_Address_1').attr("autocomplete","off").focus(function() {
    showFields(document.getElementById("frm_0013_Country").value);
  });
})


	
	try{
		var objFinder=new PCAInternationalAutoComplete("GBR","ENG",document.getElementById("frm_0012_Postal_Code"),document.getElementById("frm_008_Address_1"),cb);
		objFinder.UseRoyalMailPremiseData=true;
	}
	catch(err){
		alert(err);
	}

function addremtags(g) {
	countryinterests = [];
	regioninterests = [];
	sectorinterests = [];
	$("#myinterests").html("<h3>Selected Interests:</h3>\n");
	$("#geointerest").find("a.checked").each(function(i,v) {
	  if($(this).parent().hasClass("leaf") && !$(this).text().match(/Global/)) { countryinterests.push($(this).text().substr(1)); }
	  else { regioninterests.push($(this).text().substr(1)); }
	})
	$("#sectorinterest").find("a.checked").each(function(i,v) {
	sectorinterests.push($(this).text().substr(1));
	})
}


var countryinterests = new Array();
var regioninterests = new Array();
var sectorinterests = new Array();

function remTag(tag) {
	$.each(countryinterests, function(index,value) {
	if(value==tag) {
		countryinterests.splice(index,1);
	}
	});
	$.each(regioninterests, function(index,value) {
	if(value==tag) {
		regioninterests.splice(index,1);
	}
	});
	$.each(sectorinterests, function(index,value) {
	if(value==tag) {
		sectorinterests.splice(index,1);
	}
	})
	$(".interests").find("a.checked").each(function() {
		if($(this).text().substr(1)==tag) {
		$(this).removeClass("checked");
		}
	})
}

function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

function checkform(form) {
$('#error').removeClass('on');
$('#form input').removeClass('errorborder');
$('#form select').removeClass('errorborder');
$('#form textarea').removeClass('errorborder');
$('#geointerest,#sectorinterest').removeClass('errorborder');

if($('#frm_001_Title').val()=="") {
$('#frm_001_Title').addClass('errorborder');
$('#frm_001_Title').focus();
$('#error').addClass('on');
$('#error').html('Please select your title');
return false;
}
if($('#frm_001_First_Name').val()=="") {
$('#frm_001_First_Name').addClass('errorborder');
$('#frm_001_First_Name').focus();
$('#error').addClass('on');
$('#error').html('Please enter your first name');
return false;
}
if($('#frm_001_Last_Name').val()=="") {
$('#frm_001_Last_Name').addClass('errorborder');
$('#frm_001_Last_Name').focus();
$('#error').addClass('on');
$('#error').html('Please enter your last name');
return false;
}
var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test($('#frm_002_Email').val())) {
$('#frm_002_Email').addClass('errorborder');
$('#frm_002_Email').focus();
$('#error').addClass('on');
$('#error').html('Please enter a valid email address');
return false;
}
var filter = /^([0-9]|\+|\().+([0-9]|\-|\(|\)|\s){7}[0-9]$/;
if (!filter.test($('#frm_003_Telephone').val())) {
$('#frm_003_Telephone').addClass('errorborder');

$('#frm_003_Telephone').focus();
$('#error').addClass('on');
$('#error').html('Please enter a valid phone number');
return false;
}
if($('#frm_004_Position').val()=="") {
$('#frm_004_Position').addClass('errorborder');
$('#frm_004_Position').focus();
$('#error').addClass('on');
$('#error').html('Please enter your position');
return false;
}
if($('#frm_006_Industry').val()=="") {
$('#frm_006_Industry').addClass('errorborder');
$('#frm_006_Industry').focus();
$('#error').addClass('on');
$('#error').html('Please choose your industry sector');
return false;
}
if($('#frm_005_Company').val()=="") {
$('#frm_005_Company').addClass('errorborder');
$('#frm_005_Company').focus();
$('#error').addClass('on');
$('#error').html('Please enter your company name');
return false;
}
if($('#frm_007_Geographic_Interest').val()=="") {
$('#frm_007_Geographic_Interest').addClass('errorborder');
$('#frm_007_Geographic_Interest').focus();
$('#error').addClass('on');
$('#error').html('Please write down your areas of interest');
return false;
}
if($('#frm_0013_Country').val()=="") {
$('#frm_0013_Country').addClass('errorborder');
$('#frm_0013_Country').focus();
$('#error').addClass('on');
$('#error').html('Please select your country from the drop-down menu');
return false;
}
if($('#frm_0012_Postal_Code').val()=="") {
$('#frm_0012_Postal_Code').addClass('errorborder');
$('#frm_0012_Postal_Code').focus();
$('#error').addClass('on');
$('#error').html('Please enter your postcode');
return false;
}
if($('#frm_008_Adress_Line_1').val()=="") {
$('#frm_008_Adress_Line_1').addClass('errorborder');
$('#frm_008_Adress_Line_1').focus();
$('#error').addClass('on');
$('#error').html('Please enter your full postal address');
return false;
}
if($('#frm_0011_City').val()=="") {
$('#frm_0011_City').addClass('errorborder');
$('#frm_0011_City').focus();
$('#error').addClass('on');
$('#error').html('Please enter your city');
return false;
}
if(countryinterests.length<1 && regioninterests.length<1 ) {
$('#geointerest').addClass('errorborder');
$('#geointerest').focus();
$('#error').addClass('on');
$('#error').html('Please select at least one geographical interest');
return false;
}
if(sectorinterests.length<1) {
$('#sectorinterest').addClass('errorborder');
$('#sectorinterest').focus();
$('#error').addClass('on');
$('#error').html('Please select at least one sector of interest');
return false;
}
else {
if($('#mylead').val()!="") { lead = "BMO PPC"; } else { lead = "BMO Organic"; }



// store into SLX
$.ajax({ 
type: "get",
url: "/cgi-bin/slx_proxy.pl",
dataType: "text",
data: "BMIRegionOfInterest=" + encodeURIComponent(regioninterests.join(';')) +
"&INDUSTRY=" + encodeURIComponent($('#frm_006_Industry').val()) +
"&BMIIndustry=" + encodeURIComponent($('#frm_006_Industry').val()) +
"&PREFIX=" + $('#frm_001_Title').val() +
"&FIRSTNAME=" + $('#frm_001_First_Name').val() +
"&LASTNAME=" + $('#frm_001_Last_Name').val() + 
"&EMAIL=" + $('#frm_002_Email').val() + 
"&TITLE=" + $('#frm_004_Position').val() + 
"&WORKPHONE=" + encodeURIComponent($('#frm_003_Telephone').val()) +
"&COMPANY=" + encodeURIComponent($('#frm_005_Company').val()) +
"&ADDRESS1=" + encodeURIComponent($('#frm_008_Address_1').val()) +
"&ADDRESS2=" + encodeURIComponent($('#frm_009_Address_2').val()) +
"&ADDRESS3=" + encodeURIComponent($('#frm_0010_Address_3').val()) +
"&CITY=" + encodeURIComponent($('#frm_0011_City').val()) +
"&POSTALCODE=" + $('#frm_0012_Postal_Code').val() +
"&COUNTRY=" + encodeURIComponent($('#frm_0013_Country option:selected').text()) +
"&BMIIndustryOfInterest=" + encodeURIComponent(sectorinterests.join(';')) +
"&BMICountryOfInterest=" + encodeURIComponent(countryinterests.join(';')) +
"&LEADTYPE=BMO Trial Request" +
"&LEADSOURCE=" + lead +
//"&HeardAbout=" + encodeURIComponent($('#frm_018_Source').val()) +
"&INTERESTS=" + encodeURIComponent($('#frm_0017_otherinterest').val()) +
"&TRIAL_PRODUCTS=" + encodeURIComponent(location.pathname) +
"&DONOTMAIL=" + ($('#bmiMail').attr('checked') ? "t" : "f")+
"&DONOTEMAIL=" + ($('#bmiEmail').attr('checked') ? "t" : "f")+
"&DONOTFAX=" + ($('#bmiFax').attr('checked') ? "t" : "f") +
"&DONOTPHONE=" + ($('#bmiPhone').attr('checked') ? "t" : "f") +
"&BMI_DONOTRENT=" + ($('#thirdParty').attr('checked') ? "t" : "f"),
 beforeSend: function() {
  $('#error').addClass('loading');
  $('#error').html('Loading...');
 },
 timeout: 10000,
 error: function(request,error) {
  $('#error').removeClass('loading');
  $('#error').addClass('on');
  $('#error').html('Sorry, the form could not be submitted. Please try again later.');
  },
  success: function(request) {
   $('.formMain').html("<h1>Thank You</h1>\n<p>&nbsp;</p><p>&nbsp;</p><p><b>Thank you for your request, a representative will contact you regarding your trial shortly.</b></p><p>&nbsp;</p><p>&nbsp;</p>\n<img height=1 width=1 border=0 src=\"http://www.googleadservices.com/pagead/conversion/1070916780/?value=1&label=signup&script=0\" />");
   pageTracker._trackPageview("/bmo/thankyou");
  } // End success
}); // End ajax method


$.ajax({ //start AJAX method
type: "post",
url: "/cgi-bin/bmi_form_mailer.pl" ,
dataType: "text",
data:  $(form).serialize()+"&frm_0015_sector_interests="+sectorinterests+"&frm_0016_country_interests="+countryinterests+"&frm_0016_region_interests="+regioninterests,
 beforeSend: function() {
  $('#error').addClass('loading');
  $('#error').html('Loading...');
 },
 timeout: 10000// End success
}); // End ajax method

return false;
}
}

function formSubmit() {
document.bmologin.pwd.value = hex_md5( document.bmologin.pwd.value );
return;
}

// postcode anywhere
function cb()
{
	document.getElementById("frm_008_Address_1").value=objFinder.Line1;
	document.getElementById("frm_009_Address_2").value=objFinder.Line2;
	document.getElementById("frm_0011_City").value=objFinder.City;
	document.getElementById("frm_0011_State").value=objFinder.State;
	document.getElementById("frm_0012_Postal_Code").value=document.getElementById("frm_0012_Postal_Code").value.toUpperCase();
	showFields(document.getElementById("frm_0013_Country").value);
}

function setAutofill(iso){
	if (objFinder) objFinder.Country = iso; 
	else showFields(iso);
}

function showFields(iso) {
	$('.hiddenField').show();
	if(iso!="USA") $('#frm_0011_State').parent().parent().hide();
}
