// <![CDATA[
// JavaScript Document

//  check for valid numeric strings 
function IsNumeric(strString){

var strValidChars = "0123456789.";
var strChar;
var blnResult = true;

if (strString.length == 0) return false;

//  test strString consists of valid characters listed above
for (i = 0; i < strString.length && blnResult == true; i++)
  {
  strChar = strString.charAt(i);
  if (strValidChars.indexOf(strChar) == -1)
	 {
	 blnResult = false;
	 }
  }
return blnResult;
}


//======================================================================================
//Dynamically load up JS/CSS files
//Author: DA
//Date: 10/09/2008

//Example
//loadjscssfile("myscript.js", "js") //dynamically load and add this .js file
//loadjscssfile("javascript.php", "js") //dynamically load "javascript.php" as a JavaScript file
//loadjscssfile("mystyle.css", "css") ////dynamically load and add this .css file

function loadjscssfile(filename, filetype){
	if (filetype=="js"){ //if filename is a external JavaScript file
		var fileref=document.createElement('script')
		fileref.setAttribute("type","text/javascript")
		fileref.setAttribute("src", filename)
	}
	else if (filetype=="css"){ //if filename is an external CSS file
		var fileref=document.createElement("link")
		fileref.setAttribute("rel", "stylesheet")
		fileref.setAttribute("type", "text/css")
		fileref.setAttribute("href", filename)
	}
	if (typeof fileref!="undefined")
		document.getElementsByTagName("head")[0].appendChild(fileref)
}

//======================================================================================
function isEmail(str) {
  var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
  var r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$");
  return (!r1.test(str) && r2.test(str));
}

//======================================================================================
//Make sure search value is not empty before submiting / Valid Email
//Author: DA
//Date: 09/09/2008
function submit_subscribe(){

	if( !isEmail($('txt_subscribe_email').value) ) { 
		//If theres is no existing error
		if (!$('err_subscribe')) {
			$('form_subscribe').insert({before:'<p id="err_subscribe" class="err">Please enter a valid Email Address.</p>'});
			return false;
		}
	}
	else{
		$('form_subscribe').submit(); 
	}
}

//======================================================================================
//Make sure search value is not empty before submiting
//Author: DA
//Date: 09/09/2008
function submit_search(){
	if( $('txt_search_qry').value == "" ){ 
		return false;
	}
	else{
		$('form_searchbar').submit(); 
	}
}
//======================================================================================
//Converts Feet/Metres - also changes TH.meter/feet innerHTML
//Author: DA
//Date: 08/09/2008
function toggle_meters_feet() {

	var	m = 0.304; 
	var	f = 3.2808399; 
		
	//Convert Headers
	if ($$('th.metres').length > 0) {
	
		$$('th.metres').each(function(s) {
			x = s.innerHTML;
			x = s.innerHTML.gsub('metres' , 'feet'); 
			s.innerHTML = x;
			s.className = "feet";
		});
	}else{
		$$('th.feet').each(function(s) {
			x = s.innerHTML;
			x = s.innerHTML.gsub('feet' , 'metres'); 
			s.innerHTML = x;
			s.className = "metres";
		});
	}
	
	//Convert Units
	if ($$('td.metres').length > 0) {
		$$('td.metres').each(function(s) {
			//ONLY CONVERT IF NUMBER
			if ( IsNumeric(s.innerHTML.strip()) ){
				s.innerHTML = (s.innerHTML * f).round(2);
			}
			s.className = "feet";
	});
	}else{
		$$('td.feet').each(function(s) {
			//ONLY CONVERT IF NUMBER
			if ( IsNumeric(s.innerHTML.strip()) ){
				s.innerHTML = (s.innerHTML * m).round(2);		
			}
			s.className = "metres";		
			
		});
	}

}//function



//Desc: Used on register.asp - Shows/Hides div depending on Radio Button selection 
//Author: DA
//Date: 21/08/2008
function usage_type(x){

	//personal
	if (x == 0) {
		//document.getElementById("register_co_details_box").className = "yui-g first hide";
		$("register_co_details_box").className = "yui-g first hide";
//		$("register_personal").className = "show_b" ;
//		$("register_business").className = "hide";

	//business
	}else{
		//document.getElementById("register_co_details_box").className = "yui-g first";
		$("register_co_details_box").className = "yui-g first";
//		$("register_personal").className = "hide" ;
//		$("register_business").className = "show_b" ;		
	}

}
//DESC: Same function as usage_type with blank css styling
function usage_type_v2(x) {

    //personal
    if (x == 0) {
        $("service_details_box_v2").className = "hide";

        //business
    } else {
        $("service_details_box_v2").className = "first";
        }

}


//Desc: SWAP CAT NAV TABS - NEED TO MAKE GENERIC
function cat_tab_select(tab){

	//members
	if(tab == "venues") {
		
		document.getElementById("sidenav_links_wrapper_events").className = "accordion hide";
		document.getElementById("sidenav_links_wrapper_venues").className = "accordion show_b";
		
		document.getElementById("venues_tab").className = "tab selected";
		document.getElementById("events_tab").className = "tab";
		
	//admin
	}else if(tab == "events") {
		document.getElementById("sidenav_links_wrapper_venues").className = "accordion hide";
		document.getElementById("sidenav_links_wrapper_events").className = "accordion show_b";
		
		document.getElementById("events_tab").className = "tab selected";
		document.getElementById("venues_tab").className = "tab";
	}

}

//Desc: NEED TO MAKE GENERIC
//Author: DA
//Date: 21/08/2008
function admin_tab_select(tab){

	//members
	if(tab == "members") {
		
		document.getElementById("sidenav_links_wrapper_admin").className = "accordion hide";
		document.getElementById("sidenav_links_wrapper_members").className = "accordion ";
		
		document.getElementById("client_tab").className = "tab selected";
		document.getElementById("admin_tab").className = "tab";
		
	//admin
	}else if(tab == "admin") {
		document.getElementById("sidenav_links_wrapper_members").className = "accordion hide";
		document.getElementById("sidenav_links_wrapper_admin").className = "accordion ";
		
		document.getElementById("admin_tab").className = "tab selected";
		document.getElementById("client_tab").className = "tab";
	}

}


//======================================================
//Focus/Unfocus on textfields with prefilled help text
function focus_textbox(el, org_text){
	if (el.value == org_text) {
		el.value = "";
	}
}
function unfocus_textbox(el, org_text){
	if (el.value == "") {
		el.value = org_text;
	}
}

//Focus/Unfocus on password with prefilled help text. Change textbox to password on Focus
function focus_password(el, org_text){
	if (el.value == org_text) {
		$(el).value = "";
		$(el).type = "password";
	}
}

function unfocus_password(el, org_text){
	if (el.value == "") {
		$(el).type = "text";
		$(el).value = org_text;
	} 
}


//======================================================
//MAKES rel="external"  = target = "_blank". target is not valid into XHTML - STRICT
function externalLinks() {
	if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName("a");
	for (var i=0; i<anchors.length; i++) {
		var anchor = anchors[i];
		if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external") anchor.target = "_blank";
	}//for
}//func


//======================================================
//				ADMIN - TOGGLE LEAD INFO 
//======================================================
function toggle_leads(el){
	row_id = el.id + "_info";
	if ($(row_id).className == "hide" ) {
		$(row_id).className = "";	
	}
	else{
		$(row_id).className = "hide";			
	}
}

// -----------------------------------------------------------------------------

function setupDateFields() {
	//  Get everything that has a class of "date"
	var dateFields = document.getElementsByClassName("date");

	//	Added 19/09/2008
	var timeFields = document.getElementsByClassName("time");	
	var timeTrue = false;
	if ((timeFields.length) > 0 ){
		timeTrue = true;
	}
	//	=================

	for (var i=0; i < dateFields.length; i++) {
		// Now just deal with the ones that are INPUT boxes
		if (dateFields[i].tagName.toLowerCase() == "input") {
			// Create a new date picker control and add it to the date field
			new Control.DatePicker(dateFields[i].id, 
				{icon: '/images/calendar.png', 
				timePicker: timeTrue, 
				timePickerAdjacent: false,
				locale: 'en_GB'									
				});
		}
	}
}

// -----------------------------------------------------------------------------
function init_carousel() {
	hCarousel = new UI.Carousel("horizontal_carousel");
}
// -----------------------------------------------------------------------------

function init_forgot_pass() {
	//alert("asdasd");
	if($('forgot_password_sl')){ $('forgot_password_sl').className = ""; }
	if($('forgot_password_sign_in')){ $('forgot_password_sign_in').className = ""; }
	if($('forgot_password_top')){ $('forgot_password_top').className = ""; }					
}
// -----------------------------------------------------------------------------

function initialisePage(AAdType, AOrder) {
	// This function setups up everything that needs to run when the dom is loaded

	document.observe("dom:loaded", function(){

		//LOAD PUBLIC NAV
		if ( $('sidenav_links_venues') || $('sidenav_links_event') ){
			accordion_v = new Accordion("sidenav_links_venues", AAdType==3 ? AOrder : 0);
			accordion_e = new Accordion("sidenav_links_events", AAdType==4 ? AOrder : 0);
		
			if (AAdType == 4) {
				$("sidenav_links_wrapper_venues").hide();	
			} else {
				$("sidenav_links_wrapper_events").hide();	
			}
		}

		externalLinks();	// Change all link attributes that have rel="external" to target="_blank"
	
		// For tables with the class of list, put the class of "alt" on each row
		var results_alt_rows = $$('table.list tbody > tr:nth-child(even)');
		for (i=0, l=results_alt_rows.length; i != l ; i++){
			results_alt_rows[i].className += " alt";			
		}
		
		setupDateFields();
		
		init_forgot_pass();
		
		if($("horizontal_carousel")){
			init_carousel();
		}
	})
	
	
}
// -----------------------------------------------------------------------------
//Desc: Used for Ajax autocomplete
//		WRITE THE SELECTED ITEMS ID INTO A HIDDEN FIELD CALLED "[id of autocomplete txtbox]_id"
function getSelectionId(el, li) {
	//alert (el.id + "\n" + li.inspect() );
	$(el.id + "_id").value = li.id;
}

// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
/*
Desc:	find ul with class .toggle_li . only shows the first x(max_li) lists 
Requires: expand_li(),collapse_li()
Author: DA
Date: 08/01/2008
*/
function init_long_lists(){

	var max_li 			= 5; 											//Default no of li to show
	var ul_to_toggle	= $$('ul.toggle_li'); 							// only apply to ul with class ul.toggle_li

	if(ul_to_toggle.length > 0 ){

		for (i=0, l=ul_to_toggle.length; i != l ; i++){

			if( ul_to_toggle[i].childElements().length > max_li ){		//hide list with > max_li children

				ul_to_toggle[i].childElements().each(Element.hide);		//hide all li

				$R(0, max_li, true).each(function(value){				//show li[] from 0 - max_li
					ul_to_toggle[i].childElements()[value].show();
				});
				
				//insert more link after last child
				ul_to_toggle[i].childElements().last().insert({ after:'<li class="li_more_link"><span>show all (' + ul_to_toggle[i].childElements().length + ')</span></li>' });			
				//attach listener to .li_more_link
				ul_to_toggle[i].childElements().last().observe('click', expand_li.bindAsEventListener(  ul_to_toggle[i], max_li ) );		
			}//if
		}//for
	}//if
}//function
//----------------------------------------------------
function expand_li( list, max_li ){

	var aList = $A( this.childElements() );
	
	this.childElements().last().stopObserving('click', expand_li );
	
	//show all li
	$R(max_li, this.childElements().length , true).each(function(el){
		//aList[el].show();
		Effect.Appear(aList[el], { duration: 0.5 });
	});
	
	aList.last().remove();	//remove last li 

	this.childElements().last().insert({ after:'<li class="li_less_link"><span>show less</span></li>' });
	
	this.childElements().last().observe('click', collapse_li.bindAsEventListener(  this, max_li ) );
	
}//function

//----------------------------------------------------
function collapse_li( list, max_li ){

	var aList = $A( this.childElements() );
	
	this.childElements().last().stopObserving('click', collapse_li );
	
	//hide all li form max_li - length of li
	$R(max_li, this.childElements().length , true).each(function(el){
		//aList[el].hide();
		Effect.Fade(aList[el], { duration: 0.5 });
	});
	
	aList.last().remove();	//remove last li 
	
	this.childElements().last().insert({ after:'<li class="li_more_link"><span>show all (' + this.childElements().length  + ')</span></li>' });
	
	this.childElements().last().observe('click', expand_li.bindAsEventListener(  this, max_li ) );
}

//----------------------------------------------------
//----------------------------------------------------
/*
Desc:	find textbox|textarea with class .countdown . if maxlenght attribute exists display a countdown.
Requires: limit_text()
Author: DA
Date: 16/01/2009
*/
function init_limit_text(){
	var nb_countdowns = $('bd').select('input.countdown',  'textarea.countdown'); //get all textbox|textarea with class countdown within element #bd
	//alert(nb_countdowns.inspect());
	
	if(nb_countdowns.length > 0 ){
		nb_countdowns.each(function(s) {

			var maxlen = $(s.id).readAttribute('maxlength'); //console.log(maxlen);
			//alert( "maxlen " + maxlen );
			if( maxlen!="" && maxlen!=null && isNaN(maxlen)!=true ) {

				var countdown_span = $(s.id).id +'_countdown';
				var el = '<span class="show_countdown" id="' + countdown_span + '">' + (maxlen - s.value.length) + ' characters left</span>';
				$(s.id).insert({ after: el });

				$(countdown_span).absolutize();
				$(countdown_span).clonePosition( $(s.id), {setHeight: false , offsetTop: $(s.id).getHeight() } );	//posision span undernieth textbox/textarea

				s.observe('keyup', limit_text.bindAsEventListener( s, maxlen ) );
			}//if
		});//each
	}//if
}//function


function limit_text( i , maxlen ) {

	var limit = $(this.id + "_limit");	//textbox/area el
	if ( this.value.length > maxlen ) {
		this.value = this.value.substring(0, maxlen);
		$(this.id + "_countdown").innerHTML = (maxlen - this.value.length) + " characters left";
	} 
	else {
		$(this.id + "_countdown").innerHTML = (maxlen - this.value.length) + " characters left";
	}

}//function

//----------------------------------------------------
//----------------------------------------------------
//init shortlist step 2
function init_user_type(){
	//existing user

	if (( $('existing_user_type').value == 1 ) || ( $('existing_user_type').value == 9 )) {
		//alert("existing_user");
		$('new_user').hide();
		$('existing_user').show();
	}
	//new user
	else if ( $('existing_user_type').value == 0 ) {
		//alert("new_user");
		$('existing_user').hide();
		$('new_user').show();
	}
}

//toggle shortlist step 2
function toggle_user_type(){
	//existing user
	if (this.id == 'rdo_existing_user_1') {
		$('new_user').hide();
		$('existing_user').show();
	}
	//new user
	else if (this.id == 'rdo_existing_user_0') {
		$('existing_user').hide();
		$('new_user').show();
	}
}

document.observe("dom:loaded", function(){
	if ($('rdo_existing_user_1')){
		init_user_type();
		Event.observe('rdo_existing_user_1', 'click', toggle_user_type);
		Event.observe('rdo_existing_user_0', 'click', toggle_user_type);
	}
})

//======================================
//Close lightview on SL popup
function close_lightview(){
	Lightview.hide();	
}

//======================================

function getCookie(c_name){
	if (document.cookie.length>0){
		c_start=document.cookie.indexOf(c_name + "=");
		if (c_start!=-1){ 
			c_start=c_start + c_name.length+1; 
			c_end=document.cookie.indexOf(";",c_start);
			if (c_end==-1) c_end=document.cookie.length;
			return unescape(document.cookie.substring(c_start,c_end));
		} 
	}
	return "";
}
//======================================

function setCookie(c_name,value,expiredays){
	var exdate=new Date();
	exdate.setDate(exdate.getDate() + expiredays);
	document.cookie=c_name+ "=" + escape(value) + ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

//======================================

function checkcookie(){

	cookieName = getCookie('dontshow_sl');
	//alert(cookieName);

	if ($('chk_dontshow_popup').checked == true) {
		//alert("create");
		if( cookieName==null || cookieName=="" ){			
			setCookie('dontshow_sl','true',30);
		}
	}
	
	else{
		//alert("delete");
		if( cookieName!=null || cookieName!="" ){			
			setCookie('dontshow_sl','false',0);
		}	
	}
	
}


// ]]>