
$.widget( "custom.catcomplete", $.ui.autocomplete, {
	_renderMenu: function( ul, items ) {
		var self = this,
			currentCategory = "";
		$.each( items, function( index, item ) {
			if ( item.category != currentCategory ) {
				ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
				currentCategory = item.category;
			}
			self._renderItem( ul, item );
		});
	}
});

$(function() {
	$('#keyphrase').autocomplete({
		source: '/get_data_json.php?type=keyphrase'
	});

	$('#name').autocomplete({
		source: '/get_data_json.php?type=name'
	});

	$('#location').catcomplete({
		source: '/get_data_json.php?type=location'
	});

	$('input:submit[value="Search"]').button().click( function() {
			Go_search();
			return false;
	});

	$('#signIn').click(function() {
		$('#loginDialog').load('/login.php').dialog('open');
	});
	
	$('#signIn2').click(function() {
		$('#loginDialog').load('/login.php').dialog('open');
	});
	
	$('#signIn3').click(function() {
		$('#loginDialog').load('/login.php').dialog('open');
	});
	
	$('#forgot').click(function() {
		$('#loginDialog').load('/forgot-password.php').dialog('open');
	});
	
	$('#forgot2').click(function() {
		$('#loginDialog').load('/forgot-password.php').dialog('open');
	});
	
	$('#register').click(function() {
		$('#loginDialog').load('/registration.php').dialog('open');
	});
	
	$('#loginDialog').dialog({
		bgiframe: true,
		autoOpen: false,
		modal: true,
		resizable: false,
		draggable: false,
		width: 520,
		height: 340,
		title: 'Sign in'
	});
	
	$('.freeAd').click(function() {
		alert('This requires an active advert on the edFirst website.');
	});
	
	$('#schoolRegisterForm').validate();
	
	$('#schoolSubmit').button().click(function(){ $('#schoolRegisterForm').submit(); });

//	jQuery.validator.addMethod("password", function( value, element ) {
//		var result = this.optional(element) || value.length >= 6 && /\d/.test(value) && /[a-z]/i.test(value);
//		if (!result) {
//			element.value = "";
//			var validator = this;
//			setTimeout(function() {
//				validator.blockFocusCleanup = true;
//				element.focus();
//				validator.blockFocusCleanup = false;
//			}, 1);
//		};
//		return result;
//	}, "Your password must be at least 6 characters long and contain at least one number and one character.");
	
	// a custom method making the default value for companyurl ("http://") invalid, without displaying the "invalid url" message
	jQuery.validator.addMethod("defaultInvalid", function(value, element) {
		return value != element.defaultValue;
	}, "");
	
	jQuery.validator.addMethod("billingRequired", function(value, element) {
		if ($("#bill_to_co").is(":checked"))
			return $(element).parents(".subTable").length;
		return !this.optional(element);
	}, "");
	
	jQuery.validator.messages.required = "Required";
	
	$("#actionForm").validate({
		invalidHandler: function(e, validator) {
			var errors = validator.numberOfInvalids();
			if (errors) {
				var message = errors == 1
					? 'You missed 1 field. It has been highlighted below'
					: 'Required information';
					
					/*: 'You missed ' + errors + ' fields.  They have been highlighted below';*/
				$("div.error span").html(message);
				$("div.error").show();
			} else {
				$("div.error").hide();
			}
		},
		onkeyup: false,
		submitHandler: function() {
			$("div.error").hide();
			//alert("submit! use link below to go to the other step");
			 document.actionForm.submit();
		},
		messages: {
			password2: {
				required: " ",
				equalTo: "Please enter the same password as above"	
			},
			email: {
				required: " ",
				email: "Please enter a valid email address, example: you@yourdomain.com"	
			}
		},
		debug:true
	});
	
	//uncomment to change search results button style
	$(".view_more_details").button();
	$(".visit_website").button();
	
	$('#existing_company').hide();
	
	$("#company_name").blur(function () {
		var name = $("#company_name").val();
		var search = {type: 'reg_check', term: name};
		$.getJSON('/get_data_json.php', search, function(data) {
			$.each(data, function(key, val) {
				if (val == name) { $('#existing_company').show(); }
				else { $('#existing_company').hide(); };
			});
		});
	});

});

function initialize(lat, long, map_id)
{
	var point = new GLatLng(lat, long);
    var map = new GMap2(document.getElementById(map_id));
    map.setCenter(point, 13);

    map.addOverlay(new GMarker(point));
    map.addControl( new GSmallMapControl() );
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

GB_myShow = function(caption, url, height, width, top, callback_fn) {
    var options = {
        caption: caption,
        height: height || 260,
        width: width || 490,
        fullscreen: false,
		top:100,
        show_loading: false,
        callback_fn: callback_fn
    };
    var win = new GB_Window(options);
    return win.show(url);
};

GB_myShow_forgod = function(caption, url, height, width, callback_fn) {
    var options = {
        caption: caption,
        height: height || 238,
        width: width || 490,
        fullscreen: false,
        show_loading: false,
        callback_fn: callback_fn
    };
    var win = new GB_Window(options);
    return win.show(url);
};


GB_myShow_reg = function(caption, url, height, width, callback_fn) {
    var options = {
        caption: caption,
        height: height || 138,
        width: width || 490,
        fullscreen: false,
        show_loading: false,
        callback_fn: callback_fn
    };
    var win = new GB_Window(options);
    return win.show(url);
};

/*sfHover = function() {
    var sfEls = document.getElementById("navbar").getElementsByTagName("li");
    for (var i=0; i<sfEls.length; i++) {
        sfEls[i].onmouseover=function() {
            this.className+=" hover";
        }
        sfEls[i].onmouseout=function() {
            this.className=this.className.replace(new RegExp(" hover\\b"), "");
        }
    }
}
if (window.attachEvent) window.attachEvent("onload", sfHover);*/

function list_hide_map(list_div_name)
{
	document.getElementById(list_div_name).style.visibility="Hidden";
	document.getElementById(list_div_name).style.display="none";
}

function list_show_map(list_div_name)
{
	document.getElementById(list_div_name).style.visibility="Visible";
	document.getElementById(list_div_name).style.display="";
}


function show_map1()
{
	$("#region_div").slideDown("slow");
}

function hide_map1()
{
	$("#region_div").slideUp("slow");
}

function clearWhat(thefield){
if (thefield.value=="What are you searching for?")
thefield.value = ""
}

function populateWhat(thefield){
if (thefield.value=="")
thefield.value = "What are you searching for?"
}

function clearWhere(thefield){
if (thefield.value=="Where do you need it? (town or postcode)")
thefield.value = ""
} 

function populateWhere(thefield){
if (thefield.value=="")
thefield.value = "Where do you need it? (town or postcode)"
} 

function clearCompany(thefield){
if (thefield.value=="Enter the company name")
thefield.value = ""
} 

function populateCompany(thefield){
if (thefield.value=="")
thefield.value = "Enter the company name"
} 

function toggleSearchForm(){

	var ksa = document.getElementById("keyword_search_area");
	var csa = document.getElementById("company_search_area");
	var ksl = document.getElementById("keyword_search_link");
	var csl = document.getElementById("company_search_link");
	var keyphrase = document.getElementById("keyphrase");
	var location = document.getElementById("location");
	
	if(ksa.style.display == "inline") {
    		ksa.style.display = "none";
    		ksl.style.display = "none";
			csa.style.display = "inline";
			csl.style.display = "inline";
  	}
	else {
    		ksa.style.display = "inline";
    		ksl.style.display = "inline";
			csa.style.display = "none";
			csl.style.display = "none";
			populateWhat(keyphrase);
			populateWhere(location);
	}
} 

function Go_top_search()
{
	var business_type =document.getElementById('business_type').value;
	var com_name =document.getElementById('com_name').value;
	var post_code =document.getElementById('post_code').value;
	
	com_name=escape(com_name);
	
	if(com_name=='' && business_type=='' && post_code=='')
	{
		list_show('business_type_msg');
	} 
	else 
	{
		var url=siteurl + "/search-result.php?business_type="+business_type+"&com_name="+com_name+"&post_code="+post_code;
		location.href=url;
	}
}

function Go_search()
{	
	var business_type = document.getElementById('keyphrase').value;
	var com_name = document.getElementById('name').value;
	var post_code = document.getElementById('location').value;
	
	if(business_type=='What are you searching for?'){
		business_type = ""
	}
	
	if(post_code=='Where do you need it? (town or postcode)'){
		post_code = ""
	}
	
	if(com_name=='Enter the company name'){
		com_name = ""
	}
	
	com_name=escape(com_name);
	
	if(business_type=='' && com_name=='' && post_code=='')
	{
		alert('Please enter something to search for and try again.');
		return false;
	}
	
	if(business_type=='' && post_code!='')
	{
		alert('Please enter something to search for and try again.');
		return false;
	}

	if (business_type != '' || com_name != '' || post_code != '')
	{
		var url = "/search-result.php?business_type=" + escape(business_type) + "&com_name=" + com_name + "&post_code=" + escape(post_code);
		location.href=url;
		//document.search_frm.submit();
	}
	return false;
}

function validateForm()
{
	var keyphrase = document.getElementById('keyphrase').value;
	var name = document.getElementById('name').value;
	var location = document.getElementById('location').value;

	alert("Hello!");

	if (location!=null || location!="")
	{
		if (keyphrase==null || keyphrase=="")
		{
		alert("Please enter a keyphrase and search again.");
		return false;
		}
	}
}

function clearField(id) 
{
	document.getElementById(id).value = "";
}

function toggle() {
	var ele = document.getElementById("toggleText");
	if(ele.style.display == "block") {
    	ele.style.display = "none";
  	}
	else {
		ele.style.display = "block";
	}
} 

