
function switch_to_dynamic() {
  $('static_content').hide();
  $('dynamic_content').hide();
  top();
  //window.location.href="#dynamic";
  Effect.toggle('dynamic_content','blind');
}



function show_dynamic() {
  $('static_content').hide();
  $('dynamic_content').hide();
  Effect.toggle('dynamic_content','blind');
}

function switch_to_static() {
  $('dynamic_content').hide();
  $('static_content').hide();
  Effect.toggle('static_content','blind');
}


function switch_main_to_dynamic() {
  $('main_static').hide();
  $('main_dynamic').show();
}

function switch_main_to_static() {
  $('main_dynamic').hide();
  $('main_static').show();
}

var t;
function top() {
  if (document.body.scrollTop!=0 || document.documentElement.scrollTop!=0){
    window.scrollBy(0,-50);
    t=setTimeout('top()',10);
  }
  else clearTimeout(t);
}


//* Guestlist/reservation validation functions 
var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
function reservation_validate_guests(no_of_guests)
{
	var strNotification = 'please make sure you have filled out the following fields:\n\n';
	var errors = 0;
	for (i=1;i<=no_of_guests;i++)
	{
		if ($F('reservation_first_name_'+i).length < 2)
		{
			strNotification += '- the first name of guest number ' + i + '\n';	
			errors++;
		}
		
		if ($F('reservation_last_name_'+i).length < 2)
		{
			strNotification += '- the last name of guest number ' + i + '\n';	
			errors++;
		}
			
		//str =$('email_lookup').value;
		if(!$F('reservation_email_'+i).match(emailRegEx)){
			strNotification += '- the email of guest number ' + i + ' should be a real email address\n';
			errors++;	
		}
		
	}
	if (errors > 0)
	{
		alert(strNotification);
		return false;
	}
	else
	{
		return true;
	}
}
function reservation_validate_restaurant()
{
	var strNotification = 'please make sure you have filled out the following fields:\n\n';
	var errors = 0;
	
	if ($F('reservation_first_name_1').length < 2)
	{
		strNotification += '- the first name of the main contact\n';	
		errors++;
	}
	
	if ($F('reservation_last_name_1').length < 2)
	{
		strNotification += '- the last name of the main contact\n';	
		errors++;
	}
		
	//str =$('email_lookup').value;
	if(!$F('reservation_email_1').match(emailRegEx)){
		strNotification += '- the email of the main contact should be a real email address\n';
		errors++;	
	}
	
	if (errors > 0)
	{
		alert(strNotification);
		return false;
	}
	else
	{
		return true;
	}	
}


checked = false;
function checkedAll (form_id) {
  if (checked == false){checked = true}else{checked = false}
//  for (var i = 0; i < document.getElementById(form_id).elements.length; i++) {
//    document.getElementById(form_id).elements[i].checked = checked;
//  }

  $$('input[name=\'records[]\']').findAll(function(el) { el.checked = checked })
}

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

var current_lat = null;
var current_lng = null;

function showMapForm(cls, lat, lng, url) {

    $("location_class").value = cls;
    $("location_lat").value = lat;
    $("location_lng").value = lng;

    $("main_static").hide();                                                                   
    $("main_map_form").show();

    initialize(lat, lng);

}


// These are for ticket purchase form

function hide_username(index) {
  $('members_username_' + index).hide();
} 

function hide_names(index) {
  $('members_first_name_' + index).hide();
  $('members_last_name_' + index).hide();
  $('members_email_' + index).hide();
}  

function show_username(index) {
  $('members_username_' + index).show();
} 

function show_names(index) {
  $('members_first_name_' + index).show();
  $('members_last_name_' + index).show();
  $('members_email_' + index).show();
}  

// Return true if any of the names are filled
function names_filled(index) {
  if (($('members_first_name_' + index).value.length + $('members_last_name_' + index).value.length + $('members_email_' + index).value.length) > 0) {
    return true;
  } else {
    return false;
  }
}
function username_filled(index) {
  if ($('members_username_' + index).value.length > 0) {
    return true;
  } else {
    return false;
  }
}
//Return true if they have filled in All names + email || just username
function check_ticket_names_and_submit() {
	var myErrors = new Array();
	for (i= 0;i< $('quantity').value; i++) {
		if(username_filled(i) || names_filled(i)) {
			//good
		} else {
			//bad
			alert('Please enter details for all tickets. Or select less tickets.');
			return false;
		}
	}

	new Ajax.Request('/parties/check_ticket_names', { parameters: $('create_ticket_order_form').serialize() });
}


function group_message_sent(group) {
	$('message_content').value = 'Let\'s…';
	var form_id = 'group_message_panel_' + group;
	var result_id = 'group_message_sent_panel_' + group;
	$(form_id).hide();
	$(result_id).show();
//	Effect.toggle('form_id','blind');	
//	Effect.toggle('result_id','blind');	
	Effect.toggle(result_id, 'blind', { delay: 1.5 });
	Effect.toggle(form_id, 'blind', { delay: 3.0 });
	
}

function click_radio(sender,e)
 {
   e = (!e)? sender.getAttribute("action") : e;
   sender.checked = (e.indexOf("check") != -1);
   if(sender["action"]) 
      sender.action = (sender.checked)? "clear" : "check";
   else 
      sender.setAttribute(
            "action",
            (sender.checked)? "clear" : "check"
      );
 }

var importer_moved = false;

function show_contacts_importer() {
  startFind();  
  browser = BrowserDetect.browser
  var container = $('column_1');
  if (browser == "Explorer") {
    var obj = container.getBoundingClientRect();
    container_x = obj.left-2;
    container_y = 142;
  } else {
    container_x = container.offsetLeft;
    container_y = container.offsetTop;
  }

  $('contacts_overlay').hide();
  $('contacts_overlay').setStyle({ top: container_y + "px", left: container_x + "px", width: container.getWidth() + 'px', height: container.getHeight() + 'px' });
  new Effect.Appear('contacts_overlay', { duration: 1, from: 0.0, to: 0.7 });
  if (!importer_moved) {
    var contacts_sub = $('contacts_sub');
    var importer = $('contacts_importer');
    if (browser == "Explorer") {
      var obj2 = contacts_sub.getBoundingClientRect();
      pos_x = obj2.left;
      pos_y = 275;
    } else {
      pos_x = contacts_sub.offsetLeft;
      pos_y = contacts_sub.offsetTop;
    }
    importer.setStyle({top: pos_y + "px", left: (pos_x - importer.getWidth()) + "px"});
    importer_moved = true;
  }

  //$('email').focus();
  Effect.toggle('contacts_importer', 'appear', { duration: 1 });

}

function hide_contacts_importer() {
  $('contacts_importer').hide();
  $('contacts_overlay').hide();
}

function completeFind(email_or_finder) {
  complete_group = typeof(email_or_finder) != 'undefined' ? email_or_finder : 42;
	
  $('contacts_importer_links').hide();
  $('otherNets').hide();
  $('byEmail').hide();
  $('find_completed').show();  
  if (complete_group != 42)
  {
	  $('find_completed_sub1').hide();
	  $(complete_group).show();
  }
}   

function completeInvite() {
  $('contacts_importer_links').hide();
  $('otherNets').hide();
  $('byEmail').hide();
  $('invite_completed').show();  
}   

function startFind() {
  $('contacts_importer_links').show();
  $('otherNets').show();
  $('find_completed').hide();
  $('invite_completed').hide();
  $('contact_form_container').show();
  $('contact_form_progress').hide();
}

function track_action(action_name) {
  new Ajax.Request('/members/ajax_track_action', { parameters: {action_name: action_name}});
  return true;
}

function track_ajax_signup() {
  new Ajax.Request('/ajax_signup/track_ajax_signup');
  return true;
}

function setLocationId(text, li) {
  $('location_id').value = li.id;
}

function searchSelect(text, li) {
  window.location.href = li.id;
}

function setHomeLocationId(text, li) {
  $('home_location_id').value = li.id;
}

function setWorkLocationId(text, li) {
  $('work_location_id').value = li.id;
}

function setOutLocationId(text, li) {
  $('out_location_id').value = li.id;
}

function setCampaignLocationId(text, li) {
  $('campaign_location_id').value = li.id;
}

function setNoticeLocationId(text, li) {
  $('notice_location_id').value = li.id;
}

function submitLocationForm(form_id) {
  var formobj = $(form_id);
  formobj.submit();
}


function refresh_buttons() {
  setTimeout('var req = new Ajax.Request("/members/refresh_buttons")', 2000);
}

var ot_divs = new Array();
var ot_els = new Array();

function refresh_out_tonight(limit) {
  if (ot_divs.length == 0) {
    ot_divs = $$("div[class='otchanger']");
    ot_divs.each(function(e,i) {ot_els[i] = e.innerHTML});
  }

  var ot_top = "<img src='/images/whosOutTab.gif'/>";
  var newstr = ot_top;

  limit = (ot_divs.length < limit ? ot_divs.length : limit);
  var ar = [];
  while(ar.length < limit) {
    index = parseInt(Math.random() * limit);
    if (ar.indexOf(index) == -1) {
      ar.push(index);
    }
  }

  ar.each(function(i) {newstr += ot_els[i]});

  $('members_out_tonight').innerHTML = newstr;

}


var browse_recipient_ids = new Array();
var recipient_limit = 4;

function add_browse_recipient(member_id) {
  if (browse_recipient_ids.length == recipient_limit) {
    clear_recipients();
  }

  if (browse_recipient_ids.indexOf(member_id) == -1) {
    browse_recipient_ids.push(member_id);
    //$('recipient_ids').value = browse_recipient_ids.join(",");
    $('preset_recipient_ids').value = browse_recipient_ids.join(",");
    $('recipient_thumbs').innerHTML += $('recipient_thumb_' + member_id).innerHTML;
    if (browse_recipient_ids.length == recipient_limit) {
      show_browse_notice();
    }
  }
}

function show_browse_notice() {
    $('browse_content').hide();
    $('browse_notice').show();
}

function show_browse_content() {
    $('browse_content').show();
    $('browse_notice').hide();
}

function clear_recipients() {
    browse_recipient_ids.clear();
    $('recipient_thumbs').innerHTML="";
    $('yc_success').innerHTML="";
}

function val_checkout_form(){
	var iErrs = 0;
	var sErrs = 'Please fill in the following fields:\n\n'
	var sTitle = $('order_title').value;
	if (sTitle.length < 1 )
	{
		sErrs += "- Title\n"
		iErrs++;
	}
	var sFirstName = $('order_first_name').value;
	if (sFirstName.length < 1 )
	{ //
		sErrs += "- First Name\n"
		iErrs++;
	}
	var sLastName = $('order_last_name').value;
	if (sLastName.length < 1 )
	{
		sErrs += "- Last Name\n"
		iErrs++;
	}
	var sAddress = $('order_address').value;
	if (sAddress.length < 1 )
	{ //
		sErrs += "- Billing Address\n"
		iErrs++;
	}
	var sPostCode = $('order_postcode').value;
	if (sPostCode.length < 1 )
	{
		sErrs += "- Post Code\n"
		iErrs++;
	}
	
	if (iErrs > 0)
	{
		alert(sErrs);
		return false;
	}else{
		return true;
	}
}

function goto_signup_stage(stage) {
  new Ajax.Request("/ajax_signup/goto_stage/", {parameters: {stage: stage}});
}

function complete_signup_stage(stage) {
  new Ajax.Request("/ajax_signup/complete_stage/", {parameters: {stage: stage}});
}

function show_signup_progress(message) {
  if (message) {
    $('signup_box').hide();
//    $('progress_box').innerHTML = message;
    $('progress_box').show();
  }
}

function showHelper(element, helper) {
  if(!helper.style.position || helper.style.position=='absolute') {
    helper.style.position = 'absolute';
    Position.clone(element, helper, {
      setHeight: false,
      offsetTop: element.offsetHeight
    });
  }
  Effect.Appear(helper,{duration:0.15});
}


function show_popup_signup() {
  myLightWindow.activate(null,$('signup_popup_link'));
  new Ajax.Request('/ajax_signup/track_ajax_signup');
}

function submit_new_member_form(caller) {
  if (check_form_b()) {
    $('submit_button').toggle();
    $('creating_button').toggle();
    myLightWindow.activate(null,$('signup_popup_link'));
    new Ajax.Request('/ajax_signup/create', { parameters: $('new_member_form').serialize() });
  }
}

function submit_lander_form() {
    $('submit_button').hide();
    $('creating_button').show();
    myLightWindow.activate(null,$('signup_popup_link'));
    new Ajax.Request('/ajax_signup/create', { parameters: $('new_member_form').serialize() });
}

function submit_ajax_form() {
    $('submit_button').hide();
    $('creating_button').show();
    new Ajax.Request('/ajax_signup/create', { parameters: $('new_member_form').serialize() });
}

function launch_popup_signup() {
  myLightWindow.activate(null,$('signup_popup_link'));
}

function start_song_signup() {
  track_action("start_song_signup");
  myLightWindow.activate(null,$('signup_popup_link'));
  new Ajax.Request('/ajax_signup/external_contact_signup');
}

function display_photo_comments(photo_id) {
    myLightWindow.activate(null,$('standard_popup_link'));
    new Ajax.Request('/photos/display_photo_comments', { parameters: { "photo_id": photo_id } });
}


function check_find_friends_form()
{
  iErrs = 0;
  if ($F('invitor_email').length < 6) {
    $('invitor_email_message').update('<b style="color:red;">Required</b>');
    iErrs++;
  } else {
    $('invitor_email_message').update('');
  }

  if ($F('invitor_password').length < 1) {
    $('invitor_password_message').update('<b style="color:red;">Required</b>');	
    iErrs++;	
  } else {
    $('invitor_password_message').update('');
  }
  return (iErrs == 0);
}

// song signup....
function song_signup_step1()
{
	if(check_create_form()){$('new_member_form').submit();}
	return false;
}
function song_signup_step2()
{
	myLightWindow.activate(null,$('signup_popup_link'));
	new Ajax.Request('/ajax_signup/complete_stage?stage=play_song', { }); 
	return false;
}

function upgrade_invite()
{
	lightwindowInit();
	myLightWindow.activate(null,$('signup_popup_link'));
	new Ajax.Request("/ajax_signup/goto_stage/", {parameters: {stage: 'select_invite'}});
	return false;	
}
function upgrade_pay()
{
	lightwindowInit();
	myLightWindow.activate(null,$('signup_popup_link'));
	new Ajax.Request("/ajax_signup/goto_stage/", {parameters: {stage: 'payment'}});
	return false;	
}

function check_create_form(){
  	var val_all_good = false;
   
        new Ajax.Request('/signup_song/val_check_all',
                {asynchronous:true, evalScripts:true, parameters:Form.serialize('new_member_form'),
                onSuccess: function(transport) {if ((transport.getHeader('FormCheck') || '').match(/OK/)){$('new_member_form').submit();}}
                })
}

function check_song_lander(){
        var val_all_good = false;
    
        new Ajax.Request('/signup_song/val_check_all', {asynchronous:true, evalScripts:true, parameters:Form.serialize('new_member_form'), 
                                                        onComplete: function(transport) {$('column_1').setStyle({background:'none'});}});
}

function submit_song_lander() {
  myLightWindow.activate(null,$('signup_popup_link'));
  new Ajax.Request('/ajax_signup/create', {asynchronous:true, evalScripts:true, parameters:Form.serialize('new_member_form')});
}



function move_selector(move_amount, new_grp_id, new_photo_id){
        new Effect.Move($('ot_select_member_content'),{x: move_amount, y: 0, duration: 1, mode:'relative'});
        $('out_tonight_form_group_id').value = '';
        $('out_tonight_form_member_photo_id').value = new_photo_id;
        //now update buttons
        //new Ajax.Request('/feed/refresh_member_status?update_id=out_tonight_buttons&form_id=out_tonight_form&group_id='+new_grp_id, {asynchronous:true, evalScripts:true});
        return false;
}
function move_group_selector(move_amount, new_grp_id, new_photo_id){
        new Effect.Move($('ot_select_group_content'),{x: move_amount, y: 0, duration: 1, mode:'relative'});
        $('out_tonight_form_group_id').value = new_grp_id;
        $('out_tonight_form_last_group_id').value = new_grp_id;

        //now update buttons
        new Ajax.Request('/feed/refresh_member_status?update_id=out_tonight_buttons&form_id=out_tonight_form&group_id='+new_grp_id, {asynchronous:true, evalScripts:true});
        return false;
}
function ot_select_type(e)
{
        if (e.id == 'ot_select_member') { $('ot_select_group').className = '';$('out_tonight_form_group_id').value = '';}
        else if (e.id == 'ot_select_group')     { $('ot_select_member').className = '';$('out_tonight_form_group_id').value = $('out_tonight_form_last_group_id').value;}
        e.className = 'ot_selected';
        //now update buttons
        new Ajax.Request('/feed/refresh_member_status?update_id=out_tonight_buttons&form_id=out_tonight_form&group_id='+$('out_tonight_form_group_id').value, {asynchronous:true, evalScripts:true});
}

function check_form_a(){
	var iErrs = 0;
	var sErrs = 'Please fill in the following fields:\n\n'
	var sUserName = $('member_login').value;
	if (sUserName.length < 3 )
	{
		sErrs += "- Username\n"
		iErrs++;
	}
	var sEmail = $('member_email').value;
	if (sEmail.length < 6 )
	{ //
		sErrs += "- Email\n"
		iErrs++;
	}
	var sPassword = $('member_password').value;
	if (sPassword.length < 6 )
	{
		sErrs += "- Password\n"
		iErrs++;
	}
	
	if (iErrs > 0)
	{
		alert(sErrs);
		return false;
	}else{
		return true;
	}
}
function check_form_b(){
	var iErrs = 0;
	var sErrs = 'Please fill in the following fields:\n\n'
	var sUserName = $('member_login').value;
	if (sUserName.length < 3 )
	{
		sErrs += "- Username\n"
		iErrs++;
	}
	var sEmail = $('member_email').value;
	if (sEmail.length < 6 )
	{ //
		sErrs += "- Email\n"
		iErrs++;
	}
	var sPassword = $('member_password').value;
	if (sPassword.length < 6 )
	{
		sErrs += "- Password\n"
		iErrs++;
	}
	var sFname = $('member_first_name').value;
	if (sFname.length < 2 )
	{ //
		sErrs += "- First name\n"
		iErrs++;
	}
	var sLname = $('member_last_name').value;
	if (sLname.length < 2 )
	{
		sErrs += "- Last name\n"
		iErrs++;
	}
	var sGender = $F('member_gender');
	if (sGender == '')
	{
		sErrs += "- I am\n"
		iErrs++;		
	}
	var sPreference = $F('member_preference');
	if (sPreference == '')
	{
		sErrs += "- I like\n"
		iErrs++;		
	}
	if($F('member_date_of_birth_3i') == '' || $F('member_date_of_birth_2i') == '' || $F('member_date_of_birth_1i') == '')
	{
		sErrs += "- Date of birth\n"
		iErrs++;		
	}
	
	if (iErrs > 0)
	{
		alert(sErrs);
		return false;
	}else{
		return true;
	}
	
}


function clear_song_choice() {
  $('message_song_id_selector_0').show();
  $('message_song_id_content_0').hide();
  $('message_song_id_0').value="";
}

function distance(lat1,lng1,lat2,lng2) {
  var R = 6371; // km (change this constant to get miles)
  var dLat = (lat2-lat1) * Math.PI / 180;
  var dLon = (lng2-lng1) * Math.PI / 180;
  var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(lat1 * Math.PI / 180 ) * Math.cos(lat2 * Math.PI / 180 ) * Math.sin(dLon/2) * Math.sin(dLon/2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = R * c;
  if (d>1) return Math.round(d) + " Kms";
  if (d<=1) return Math.round(d*1000) + " metres";
  return d;
}

/* Bookmark Code JW added */

/* Modified to support Opera */
function bookmarksite(title,url){
if (window.sidebar) // firefox
	window.sidebar.addPanel(title, url, "");
else if(window.opera && window.print){ // opera
	var elem = document.createElement('a');
	elem.setAttribute('href',url);
	elem.setAttribute('title',title);
	elem.setAttribute('rel','sidebar');
	elem.click();
} 
else if(document.all)// ie
	window.external.AddFavorite(url, title);
}

/* Bookmark Code END */


function showFavouritesMode() {
  if (favourites_mode != undefined) {
    if (favourites_mode == 'compressed') {
      $$('div.compressed_subject').each(function(e){e.show()});
      $$('div.expanded_subject').each(function(e){e.hide()});
    } else {
      $$('div.compressed_subject').each(function(e){e.hide()});
      $$('div.expanded_subject').each(function(e){e.show()});
    }
  }
}



// Called on loading to populate any feed containers
function populateFeeds() {
  $$('div.feed_container').each(function(e) {
    template_names = e.className.split(" ").reject(function(s) {return s == 'feed_container'}).join(",");
    new Ajax.Updater(e, '/new_feed/populate', {parameters: {feed_name: e.id}});
  });
}

function filterTemplateNames() {
  var template_names = $$('input.filter_check_all,input.filter_check').select(function(e){return e.checked}).map(function(e){return e.name});
  return template_names.map(function(e){return e.split(",")}).flatten().join(",");
}

function filterFeed(container_id) {
  new Ajax.Updater(container_id, '/new_feed/populate', { parameters: { member_filters: filterTemplateNames(), feed_name: container_id } });
}


/* New Venues Map Stuff */

function getSearchableAddress() {
  var elements = ["name","street","town","county","postcode","country"];
  return elements.map(function(e){ return $$('.address-element-' + e) }).flatten().map(function(e){return e.value}).reject(function(e){ return e == "" }).join(", ");
}

function showAddress() {
   search = getSearchableAddress();
   name = $('venue_name').value;
   town = $('venue_town').value;

   new Ajax.Request('/new_venues/lookup_venue', {parameters: {search: search, name: name, town: town}, onComplete:function(resp){ 
     if(resp.status != 200) {
 
        geo.getLocations(search, function (result)
          {
            // If that was successful
 	    if (result.Status.code == G_GEO_SUCCESS) {
              // How many resuts were found
              // centre the map on the first result
              var p = result.Placemark[0].Point.coordinates;
              var point = new GPoint(p[0],p[1]);
              marker = createMarker(point,'<div>' + search + '</div>');
              map.centerAndZoom(point, 2);
              map.addOverlay(marker);
              document.getElementById("venue_lat").value = p[1];
              document.getElementById("venue_lng").value = p[0];
              $('new_venue_suggestion').innerHTML = "";
            } // END IF
          }  // END function
	);  // END geo.getLocations

     } 

   }});  // END new Ajax.Request

} // END function

function setLookupMarker(lat, lng) {
  var point = new GPoint(lng,lat);
  marker = createMarker(point,'<div></div>');
  map.centerAndZoom(point, 2);
  map.addOverlay(marker);
  document.getElementById("venue_lat").value = lat;
  document.getElementById("venue_lng").value = lng;
}

function createFromGooglePlace(cid) {
  $('venue_cid').value = cid;
  if(requiredFieldsFilled($('new_venue_form'), 'required')) { $('new_venue_form').submit() };
}

// Called when user moves the map, get the map bounds and call the server to refresh results
function handleMapMove() {
  var sw = map.getBounds().getSouthWest().lat() + "," + map.getBounds().getSouthWest().lng();
  var ne = map.getBounds().getNorthEast().lat() + "," + map.getBounds().getNorthEast().lng();
  var center = map.getCenter().lat() + "," + map.getCenter().lng();
  var zoom = map.getZoom();

  map.clearOverlays();

  new Ajax.Request('/new_venues/refresh_search', {parameters: {sw: sw, ne: ne, center: center, zoom: zoom, what: $('what').value, where: $('where').value},
    onComplete: function(resp){ placeMarkers() } });
}

function handleMapZoom(zoomStart, zoomEnd) {
  handleMapMove();
}

function refreshSearch() {
  $('venue_search_form').submit();
//  map.clearOverlays();

//  new Ajax.Request('/new_venues/refresh_search', {parameters: {what: $('what').value, where: $('where').value},
//    onComplete: function(resp){ setMapCenter(); placeMarkers() } });

}

function setMapCenter() {
  var fields = $('map_bounds_info').value.split(",");
  var lat = parseFloat(fields[0]);
  var lng = parseFloat(fields[1]);
  var northLimit = parseFloat(fields[2]);
  var eastLimit = parseFloat(fields[3]);
  var southLimit = parseFloat(fields[4]);
  var westLimit = parseFloat(fields[5]);

  var swLimit = new GLatLng(southLimit, westLimit);
  var neLimit = new GLatLng(northLimit, eastLimit);
  var bounds = new GLatLngBounds(swLimit, neLimit);
  var center = new GPoint(lat, lng);
  var zoom = map.getBoundsZoomLevel(bounds);
  map.centerAndZoom(center, zoom);

  return true;
}

function placeMarkers() {
  $$('input.venue-marker-info').each(function(e) {
    var fields = e.value.split(",");
    var name = fields[0];
    var letter = fields[1];
    var lat = fields[2];
    var lng = fields[3];

    var point = new GPoint(lng, lat);
    var marker = createMarker(point, letter);
    map.addOverlay(marker);
  });    
}

function setVenueType(type) {
  $$('a.venue-icons-on').each(function(e){e.className = 'venue-icons left'});
  $(type + '_icon').className = 'venue-icons-on left';
  $('venue_venue_type').value = type;
}

// Form validator, I may use this elsewhere in the future, any field with a 'required' class
// will need to be filled in.

function requiredFieldsFilled(formObj, requiredClass) {
  var compulsoryElements = $$('input.compulsory, textarea.compulsory, select.compulsory');
  var overrideElements = $$('input.override-required, textarea.override-required, select.override-required');
  var requiredElements = $$('input.' + requiredClass + ',textarea.' + requiredClass + ',select.' + requiredClass);
  if(requiredElements.all(function(e){ return e.value != '' })) {
    return true;
  } else if(overrideElements.length > 0 && overrideElements.all(function(e){ return e.value != ''}) && compulsoryElements.all(function(e){ return e.value !=	''})) {
    return true;
  } else {

    if(overrideElements.length > 0 && overrideElements.all(function(e){ return e.value != ''})) {
      highlightElements(compulsoryElements);
    } else {
      highlightElements(requiredElements);
    }

    if(!formObj.innerHTML.match(/Please fill in highlighted fields/)) {
      formObj.insert({'top': "<div class='error'>Please fill in highlighted fields</div>"});
    }

    return false;
  }
}

function highlightElements(elements) {
  elements.select(function(el){ return el.value == '' }).each(function(e) {
    if(e.alt == null || e.alt == "") {
      e.setStyle({borderColor:"#ff24ca", borderWidth:"2px"});
    } else {
      $(e.alt).setStyle({border:"2px solid #ff24ca"});
    }
  });
}

/* New Venues Toptable Stuff */
function refreshAvailability() {
  hideAvailability();
  new Ajax.Request('/new_venues/refresh_availability', { parameters: $('reservation_form').serialize(), onComplete: function(resp) {showAvailability()} });
  updateBookingDescription();
}

function showOffers(offers_str) {
  var offerIDs = offers_str.split(",");
  $$('a.offer-selector').each(function(e){
    thisOfferID = e.id.split("_")[1];
    if(offerIDs.include(thisOfferID)) {
      e.show();
      $('offer_selection').show();
    } else {
      if($("reservation_offer_id").value == thisOfferID) {$("reservation_offer_id").value = ''};
      e.hide();
    }
  });
  return true;
}

function hideAvailability() {
  $('availability_content').hide();
  $('availability_progress').show();
}

function showAvailability() {
  $('availability_content').show();
  $('availability_progress').hide();
}

function updateBookingDescription() {
  $('description_date').update($('reservation_date').value);
  $('description_time').update($('reservation_time').value);
  $('description_number_of_people').update($('reservation_number_of_people').value);
}

function setDate(selected, date) {
  $$('a.date-selector').each(function(e){ e.className = 'venue-booking-block left date-selector'});
  if(selected != null) {
    $('reservation_date').value = date;
    selected.className = 'venue-booking-block-on left date-selector';
  }
}

function setTime(selected, time) {
  $$('a.time-selector').each(function(e){ e.className = 'venue-booking-block left time-selector'});
  if(selected != null) {
    $('reservation_time').value = time;
    selected.className = 'venue-booking-block-on left time-selector';
  }
}

function setNumberOfPeople(selected, quantity) {
  $$('a.number-of-people-selector').each(function(e){ e.className = 'venue-booking-block left number-of-people-selector'});
  if(selected != null) {
    $('reservation_number_of_people').value = quantity;
    selected.className = 'venue-booking-block-on left number-of-people-selector';
  }
}

function setOfferID(selected, offerID) {
  $$('a.offer-selector').each(function(e){ e.className = 'venue-booking-block left offer-selector'});
  if(selected != null) {
    $('reservation_offer_id').value = offerID;
    selected.className = 'venue-booking-block-on left offer-selector';
  }
}

function sendReservation() {
  $('stage2_buttons').hide();
  $('stage2_progress').show();
  new Ajax.Request('/new_venues/send_reservation', {parameters: $('reservation_form').serialize()});
}

/* Favourites Stuff */

var last_favourite_id = null;

function addFavourite(member_id) {
  if (last_favourite_id) {
    $('favourite_thumb_image_' + last_favourite_id).className = 'favourite-user-photo';
  }
  var str = $('favourite_thumb_' + member_id).innerHTML;
  var result = new Insertion.Top($('favourites_box'), str);
  last_favourite_id = member_id;
}


/* Venue profile stuff */

function switchVenueTab(tab, venue_id) {
  $$('a.venue-subnav-on').each( function(e) { e.className = 'venue-subnav left' } );
  $(tab + '_tab').className = 'venue-subnav-on left';
  new Ajax.Request('/new_venues/show_' + tab, {parameters: {venue_id: venue_id}, onComplete: function(transport) { populateFeeds() } });
} 

function addMemberWords() {
  if($('venue_keywords').value.match(/[A-Za-z\'\-]+/g).length > 5) {
    var warning = "<div class='error'>No more than five words please</div>";
    if($('keyword_warning').innerHTML == '') {
      $('keyword_warning').insert(warning);
    }
    return false
  }
  if ($('venue_keywords').value != $('venue_keywords').title && $('venue_keywords').value.strip() != '') {
    new Ajax.Request('/new_venues/add_member_words', {parameters: $('keywords_form').serialize(), onComplete: function(t){$('venue_keywords').value = ''}});
  }
}

function addVenueReview() {
  if ($('review_content').value != $('review_content').title && $('review_content').value.strip() != '') {
    new Ajax.Request('/new_venues/add_review', {parameters: $('venue_review_form').serialize(), onComplete: function(t){$('review_content').value = ''}});
  }
}


// Cropper Stuff

// setup the callback function
function onEndCrop( coords, dimensions ) {
  $( 'x1' ).value = coords.x1;
  $( 'y1' ).value = coords.y1;
  $( 'x2' ).value = coords.x2;
  $( 'y2' ).value = coords.y2;
  $( 'width' ).value = dimensions.width;
  $( 'height' ).value = dimensions.height;
}

// basic example
function initializeCropper() {
  $$('img.croppable').each(function(e){
    new Cropper.Img(e.id, {onEndCrop: onEndCrop});
  });
  return true;
}

function initializeInstructionFields() {
  $$('input.instruction, textarea.instruction').each(function(e) {
    e.value = e.title;
    e.setStyle({color: '#FE0079'});
    e.observe('focus', function() {
      if(e.value == e.title) {
        e.value = '';
        e.setStyle({color: '#333333'});
      }
    });
    e.observe('blur', function() {
      if(e.value == '') {
        e.value = e.title;
        e.setStyle({color: '#FE0079'});
      }
    });
  });
}
