function check_email(form) {
	// check format of email address
	if (parseInt(form.email.value.length,10) > 0) {
		var emailpat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
		var testString = form.email.value;
		if (!emailpat.test(testString)) {
			return false;
		}
	} else {
		return false;
	}
	return true;
}

function IDSrchSubmit() {
	if($('id_num').value.length == 0) {
		alert("Please enter an ID number");
		$('id_num').focus();
		return false;
	}
	return true;
}

function popup(html_file,x,y,windowname) {
	option_params = 'width='+x+',height='+y+',menubar=no,toolbar=no,status=yes,resizable=yes,personalbar=no,location=no,directories=no,scrollbars=yes';
	pop=window.open(html_file,windowname,option_params);
}

// This will remove the helper input text
function handleInput(inputID,helpText) {
	
	if($(inputID).value == helpText) {
		$(inputID).value="";
		$(inputID).focus();
	} 
}
// This will restore the helper input text if the field is left blank
function restoreInput(inputID,helpText) {
	if($(inputID).value == '') {
		$(inputID).value=helpText;
	}
}

function formChecker() {
	if($('property_name_id')) {
		if($('property_name_id').value=="Property/Station Name") {
			$('property_name_id').value="";
		}
	}
	return true;

}
function getListingMapIcons(){
	var ret=new Array();
	
	//create a default icon
	var listing_icon = new GIcon(G_DEFAULT_ICON);
	listing_icon.shadow = "/listing/images/map_shadow.png";
	listing_icon.image = "/listing/images/map_marker.png";
	listing_icon.printImage = "/listing/images/map_print_marker.gif";
	listing_icon.mozPrintImage = "/listing/images/map_marker.png";
	listing_icon.transparent = "/listing/images/map_transparent.png";
	//we do not want to print the shadow as it must be a gif, which will cover map detail
	listing_icon.printShadow = null;
	listing_icon.iconSize = new GSize(14, 26);
	listing_icon.shadowSize = new GSize(25, 26);
	listing_icon.iconAnchor = new GPoint(6, 26);
	//large icons
	//listing_icon.imageMap = [0,6, 2,4, 3,3, 7,0, 15,0, 17,1, 20,5, 21,7, 21,13, 20,16, 16,20, 14,21, 10,21, 10,33, 8,33, 8,21, 6,21, 1,14, 0,8];
	//small icons
	listing_icon.imageMap = [0,3, 3,0, 9,0, 14,3, 14,9, 9,13, 8,13, 8,25, 6,25, 6,13, 4,13, 0,9];
	listing_icon.infoWindowAnchor = new GPoint(9, 2);
	
	//now use it as a base to create the others
	
	//array references should be ret['<realist_type>']
	//residential
	ret['R']=new GIcon(listing_icon);
	ret['R'].image = "/listing/images/map_marker_teal.png";
	ret['R'].printImage = "/listing/images/map_print_teal.gif";
	ret['R'].mozPrintImage = "/listing/images/map_marker_teal.png";
	
	//holiday rental
	ret['H']=ret['R'];
	
	//rural residential
	ret['RU']=ret['R'];
	
	//rural
	ret['RP']=new GIcon(listing_icon);
	ret['RP'].image = "/listing/images/map_marker_red.png";
	ret['RP'].printImage = "/listing/images/map_print_red.gif";
	ret['RP'].mozPrintImage = "/listing/images/map_marker_red.png";
	
	//lifestyle
	ret['L']=new GIcon(listing_icon);
	ret['L'].image = "/listing/images/map_marker_green.png";
	ret['L'].printImage = "/listing/images/map_print_green.gif";
	ret['L'].mozPrintImage = "/listing/images/map_marker_green.png";
	
	//land
	ret['V']=new GIcon(listing_icon);
	ret['V'].image = "/listing/images/map_marker_orange.png";
	ret['V'].printImage = "/listing/images/map_print_orange.gif";
	ret['V'].mozPrintImage = "/listing/images/map_marker_orange.png";
	
	//commercial
	ret['C']=new GIcon(listing_icon);
	ret['C'].image = "/listing/images/map_marker_blue.png";
	ret['C'].printImage = "/listing/images/map_print_blue.gif";
	ret['C'].mozPrintImage = "/listing/images/map_marker_blue.png";
	
	//business
	ret['B']=ret['C'];
	
	return ret;
}

// Use this function to share the current page on facebook
function fbs_click() {
	u=location.href;t=document.title; 
	window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
	return false;
}

//search by map form
function do_mapsearch(state){
	$('map_state').setProperty('value', state);
	$('map_search_form').submit();
	return false;
}

function addError(errors, msg){
    errors[errors.length] = msg;
}

function highlightField(elt, isError, errors, errmsg){
    container = elt.parentNode;
    if (!container)
        return;

    if (isError) {
        addError(errors, errmsg);
        container.className = 'error';
    }
    else
        container.className = '';

    if (isError) {
        elt.focus();
    }

	$(container).getElements('.error-msg').each(function(elt){
		if (isError) {
			elt.setHTML(errmsg);
		}
		else{
			elt.setHTML('');
		}
	});
}

function validateEnquiryForm(frm){
	$(frm);
    var errors = [];
    highlightField(frm.name,
                   frm.name.value.length == 0,
                   errors,
                   'Please enter your name');

    emailErr = '';
    if (frm.email.value.length == 0){
        emailErr = 'Please enter your email address';
	}
    else if (!check_email(frm)){
        emailErr = 'Please enter a valid email address';
	}

    highlightField(frm.email,
                   emailErr.length > 0,
                   errors,
                   emailErr);

    highlightField(frm.inquiry,
                   frm.inquiry.value.length == 0,
                   errors,
                   'Please enter your enquiry');
	
	var method_checked=false;
	var container=frm.getElement('.pref_contact');
	container.getElements('input').each(function(elt){
		var related_class=elt.className.substring(13);
		input_elt=frm.getElement('.pref_contact_'+related_class);
		if(input_elt){
			if(related_class !='email'){
				highlightField(input_elt,
							   elt.checked && input_elt.value.length < 10,
							   errors,
							   'Please enter your contact details. Include the area code.');
			}
			if(elt.checked){
				method_checked=true;
			}
		}
	});
	
	if (!method_checked) {
		var errmsg='Please select a preferred contact method';
		addError(errors, errmsg);
		container.getElements('.error-msg').each(function(elt){elt.setHTML(errmsg);});
		container.addClass('error');
	}
	else{
		container.getElements('.error-msg').each(function(elt){elt.setHTML('');});
		container.removeClass('error');
	}

	if (frm.id=='enquiry_form'){
		enquiry_panel.slideIn();
	}
    return errors.length == 0;
}

function EnquiryFormSubmit(e){
	//stop the submit event
	new Event(e).stop();
	if(validateEnquiryForm($("enquiry_form"))){
		var frm_action=this.action.replace(/contact/, "ajax_contact").replace(/listing/, "/");
		new Ajax(frm_action, {method: 'post', data: this.toQueryString(), update: $('enquiry_form_holder'), onComplete:ResizeEnquiryForm}).request();
		$('enquiry_form_holder').setHTML('<p>Sending Enquiry, please wait...</p>');
	}
}
function ResizeEnquiryForm(){ 
	if($('enquiry_form')){
		//reset ajax submission
		$('enquiry_form').addEvent('submit', EnquiryFormSubmit.bindWithEvent($('enquiry_form')));
	}
	enquiry_panel.slideIn();
}

function toggleIncludeOptionClass(elt){
	if(elt.getElement('input').checked){
		elt.addClass('active');
	}
	else {
		elt.removeClass('active');
	}
}

//Shortlist/saved search functions
function addToShortlist(url) {
	if($('my_shortlists')){
		var url = url.replace("shortlist_add.php","shortlist_add_ajax.php");
		new Ajax(url, {
			method: 'get',
			update: $('my_shortlists'),
			onComplete: function() {
				my_searches_panel.slideIn();
                removeAjaxLoader();
			}
		}).request();
		return false;
	}
	return true;
}
function addToShortlistButton(url,id) {
	if($('my_shortlists')){
        addAjaxLoaderButton(id);
		var url = url.replace("shortlist_add.php","shortlist_add_ajax.php");
		new Ajax(url, {
			method: 'get',
			update: $('my_shortlists'),
			onComplete: function() {
				my_searches_panel.slideIn();
                removeAjaxLoaderButton();
			}
		}).request();
		return false;
	}
	return true;
}

function deleteShortlist(branch_id) {
    // Need to get all of the selected properties
    var checked_shortlists = [];
    $$('#my_shortlists input[type=checkbox]').each( function(el) {
        if (el.checked == Boolean(true)) {
            checked_shortlists[checked_shortlists.length] = el.getValue();
        }
    });
    if (checked_shortlists.length == "0"){
        alert("No shortlists selected");
        return false;
    } else {

    // JavaScript confirm deletion
    var answer = confirm('Are you sure you want to remove this selection from your shortlist?');
    if (answer) {
        branch_id = (branch_id) ? branch_id : "";
        // Update status message
        $('shortlist_status').addClass('deleting_shortlist');
        $('shortlist_status').setHTML('<a href="/branch/shortlist.php?branch_id=' + branch_id + '">My Shortlist</a> <span>removing</span>');
        var checked_shortlists = [];
        $$('#my_shortlists input[type=checkbox]').each( function(el) {
            if (el.checked == Boolean(true)) {
                checked_shortlists[checked_shortlists.length] = el.getValue();
            }
        });
        var url = "/branch/delete_shortlist_ajax.php?"+$('delete_shortlist').toQueryString();
        var shortlist_el = "";
        new Ajax(url, {
            method: 'get',
            update: $('my_shortlists'),
            onComplete: function() {
                // remove "Added to shortlist" from deleted properties
                for (var i=0; i < checked_shortlists.length; i++) {
                    shortlist_el = "sl_" + checked_shortlists[i];
                    if ($(shortlist_el)) {
                        $(shortlist_el).removeClass('ajax_loading_done');
                        $(shortlist_el).setHTML('Add to shortlist');
                        my_searches_panel.slideIn();
                    }
                }
                $$('.ajax_loading_button_done').each(function(el) {
                    el.removeClass('ajax_loading_button_done');
                    el.setHTML('Add to shortlist');
                });
                // Shortlist deleted 
                $('shortlist_status').removeClass('deleting_shortlist');
                $('shortlist_status').setHTML('<a href="/branch/shortlist.php?branch_id=' + branch_id + '">My Shortlist</a>');
                my_searches_panel.slideIn();
            }
        }).request();
        return false;
    } else {
        return false;
    }
    }
}
function saveSearch(a,branch_id) {
	if ($('my_searches')){
        branch_id = (branch_id) ? branch_id : "";
        // Update status message
        a.setHTML('Saving...');
        $('saved_searches_status').addClass('saving_search');
        $('saved_searches_status').setHTML('<a href="/branch/listing_saved_saerches.php?branch_id=' + branch_id + '">Saved Searches</a> <span>saving</span>');
		var url = a.href.replace("listing_search_save.php", "listing_saved_search_save_ajax.php");
		new Ajax(url, {
			method: 'get',
			update: $('my_searches'),
			onComplete: function() {
                a.setHTML('Saved');
                $('saved_searches_status').removeClass('saving_search');
                $('saved_searches_status').setHTML('<a href="/branch/listing_saved_searches.php?branch_id=' + branch_id + '">Saved Searches</a>');
				my_searches_panel.slideIn();
			}
		}).request();
		return false;
	}
	return true;
}
function deleteSavedSearch(search_id,branch_id) {
	var frm=$('saved_search_form_'+search_id);
	if($('my_searches') && frm){
    // JavaScript confirm, just in case
		if (confirm("Are you sure you want to delete this saved search?")) {
            branch_id = (branch_id) ? branch_id : "";
            // Update status message
            $('saved_searches_status').addClass('deleting_saved_search');
            $('saved_searches_status').setHTML('<a href="/branch/listing_saved_searches.php?branch_id=' + branch_id + '">Saved Searches</a> <span>deleting</span>');
			// delete the selected saved search
			var url = "/branch/listing_saved_search_delete_ajax.php?"+frm.toQueryString();
			new Ajax(url, {
				method: 'get',
				update: $('my_searches'),
				onComplete: function() {
                    $('saved_searches_status').removeClass('deleting_saved_search');
                    $('saved_searches_status').setHTML('<a href="/branch/listing_saved_searches.php?branch_id=' + branch_id + '">Saved Searches</a>');
					my_searches_panel.slideIn();
				}
			}).request();
		}
		return false;
	}
	return true;
}
function addAjaxLoader(el) {
    el.setHTML('Adding to shortlist');
    el.addClass('ajax_loading');
}
function addAjaxLoaderButton(el) {
    $(el).setHTML('Adding..');
    $(el).addClass('ajax_loading_button');
}
function removeAjaxLoader() {
    $$('.ajax_loading').each(function(el) {
        el.removeClass('ajax_loading');
        el.addClass('ajax_loading_done');
        el.setHTML('Added to shortlist');
	});
}
function removeAjaxLoaderButton() {
    $$('.ajax_loading_button').each(function(el) {
        el.removeClass('ajax_loading_button');
        el.addClass('ajax_loading_button_done');
        el.setHTML('Added to Shortlist');
	});
}

//onload events go in here
var enquiry_panel='';
var new_search_panel='';
var my_searches_panel='';
window.addEvent('domready', function() {
	//remove noscript elements
	$$('.noscript').each(function(elt){
		elt.remove();
	});
	
	//remove onlyscript class
	$$('.onlyscript').each(function(elt){
		elt.removeClass('onlyscript');
	});
	
	//branch details scroller
	var office_panel_elt=$('offices_panel');
	if(office_panel_elt){
		//opening hours toggle
		var slide=new Array();
		office_panel_elt.getElements('h6').each( function(a, i) {
			//set the height of the panel to auto while sliding, so it resizes
			slide[i]=new Fx.Slide("p_"+a.id, {onComplete:function(){$('d_'+a.id).setStyle('height', $('d_'+a.id).scrollHeight+'px');}});
			slide[i].hide();
			a.addEvent('click', function(e){
				a.toggleClass('active');
				$('d_'+a.id).setStyle('height','auto');
				slide[i].toggle();
			});
		});
		var accordion = new Accordion('.office_head', 'div.office', {
			opacity:false,
			onActive: function(toggler, element){
				toggler.addClass('office_head');
				toggler.removeClass('office_head_closed');
			},
			onBackground: function(toggler, element){
				toggler.addClass('office_head_closed');
				toggler.removeClass('office_head');
			}
		});
	}
	
	//enquiry form
	if($('enquiry_panel')){
		enquiry_panel= new Fx.SlidePlus($('enquiry_panel_holder'), $('enquiry_panel_heading'));
		enquiry_panel.hide();
		$('enquiry_form').addEvent('submit', EnquiryFormSubmit.bindWithEvent($('enquiry_form')));
	}
	if($('tools_panel')){
		var tools_panel= new Fx.SlidePlus($('tools_panel_holder'), $('tools_panel_heading'));
		//tools_panel.hide();
	}
	if($('my_searches_panel')){
		my_searches_panel= new Fx.SlidePlus($('my_searches_holder'), $('my_searches_heading'));
	}
	if($('new_search_panel')){
		new_search_panel= new Fx.SlidePlus($('new_search_panel_holder'), $('new_search_panel_heading'));
		new_search_panel.hide();
		$$('#new_search_panel_holder .knob_from', '#new_search_panel_holder .knob_to').each(function(elt){
			elt.addClass('hidden_abs');
		});
		new_search_panel.addEvent('onComplete', function(){
			if(!this.toggle_elt.hasClass('closed')){
				$$('#new_search_panel_holder .knob_to', '#new_search_panel_holder .knob_from').each(function(elt){
					elt.removeClass('hidden_abs');
					elt.removeClass('hidden');
				});
			}
		});
	}
	//search include options
	$$('.include_option').each(function(elt){
			elt.addEvent('click', toggleIncludeOptionClass.pass(elt));
	});
	var weather_outer_elt=$('weather_outer');
	if(weather_outer_elt){
		//var weather_feature=new FeatureScroller('weather_outer', '.weather');
		var weather_feature=new FeatureFader(weather_outer_elt.getElements('.ew-box'), {delay:4000});
	}
	if($('home_img_header')){
		var hero_images=new FeatureScroller('home_img_header', '.hero', {automatic: ['left', 6000]});
	}
	if($('branch_scroll_text')){
		var scroll_text=new FeatureScroller('branch_scroll_text', '.scroll_text', {automatic: ['left', 0], duration: 15000, transition: Fx.Transitions.linear, minItems:1});
	}
	if($('latest_notices')){
		var scroll_text=new FeatureScroller('notices_outer', '.news', {automatic: ['up', 4000]});
	}
	if($('feature_properties')){
		//var feature_properties=new FeatureScroller('feature_prop_outer', '.feat', {automatic: ['right', 4000]});
		var feature_properties=new FeatureFader($$('#feature_prop_outer .feat'), {delay:5000});
	}
	
	//set up tooltips
	tips = new ShimTips($$('.tip'));
	//larger tooltops
	wide_tips = new ShimTips($$('.tip-wide'), {className: 'wide-tool'});
	// Normal un-clickable property features icons
	icon_tips = new ShimTips($$('.icon-tip'), {className: 'icon-tool'});
	// Clickable property features icons
	icon_tips_clickable = new ShimTips($$('.icon-tip-clickable'), {className: 'icon-tool-clickable'});
	
	new SmoothScroll({ duration: 1000 });
});
function fadeOut() {
     var fadeOut = new Fx.Style('notifications','opacity',{duration:700}).start(0); 
}
// Display Notifications function
function displayNotification(text) {
    var not_height = window.getScrollTop() + (window.getHeight() / 2) + "px";
    var not_padding_top = window.getScrollTop() + (window.getHeight() / 3) + "px";
   $('notifications').setStyles('height: ' + not_height + '; text-align: center; padding-top: ' + not_padding_top + '; opacity: 0;'); 
    var fadeIn = new Fx.Style('notifications', 'opacity', {onComplete: function() { setTimeout(fadeOut,1400); } }).start(1);
    $('notifications').setHTML('<span>' + text + '</span>');
}

