// JavaScript Document

// EDIT THESE VALUES IF REQUIRED
var alertText = 'Are you sure you wish to perform this action' + "\n"; //DEFAULT TEXT DISPLAYED ON CONFIRM BUTTONS/LINKS WHEN NO ALT/TITLE
var newWindowLink = true; //OPEN EXTERNAL LINKS BY DEFAULT IN A NEW WINDOW (TRUE/FALSE)?

/*
	objToggle
	takes the state of the current element and switches it
	between visible/invisible
*/
function objToggle(obj) { 

	var obj = document.getElementById(obj);

	if(obj.style.display == "block") { 
		obj.style.display = "none";
	} else { 
		obj.style.display = "block";
	}

}


/*
	ajaxSearch
*/
function ajaxSearch(){
	return true;
}


/*
	beginTabbing
	this is fired at page load
	controls the tabs internally
*/
function beginTabbing(){

	// get the page name
	var sPath = window.location.pathname;
	var sPage = sPath.substring(sPath.lastIndexOf('/') - 1);
	var container = '';

	// if we are on the property or profile page, the content needs to be put in a seperate div
	if(sPath.search('buy/') > -1 || sPath.search('profile') > -1){
		container = 'profileContent';
	}else{
		container = 'content';
	}
	
	// loop through all Tabs on the page
	$('li[id$="Tab"]').each(function(){
		  
		  //get the page to display
		  if(this.id.search('subpageMain') > -1)
		  {
			var myId = this.id;
			var urlPage = myId.replace('Tab', '');
			urlPage = urlPage.replace('subpageMain', '');
		  	myPage = "subpage.php?subpageMain="+urlPage;
		  }
		  else if(this.id.search('subpage') > -1)
		  {
			var myId = this.id;
			var urlPage = myId.replace('Tab', '');
			urlPage = urlPage.replace('subpage', '');
		  	myPage = "subpage.php?subpage="+urlPage;
		  }
		  else
		  {
		  	var myId = this.id;
		  	myId = myId.replace('Tab', '');
		  	//var myPage = myId.replace('_', '-');
			var myPage = myId.replace(/_/g, '-');
		  	myPage = myPage+".php";
		  }
		  // bind the click function to the link
		  $('#'+this.id).click(function() {switch_tab(this.id, myPage, container); return false});

	});
}


/*
	switch_tab
	function is bound to onclick tabs by function beginTabbing at start up
	this switches all other tabs off, selects the one clicked and loads AJAX page content
*/
function switch_tab(id, content, container){

	var propertyid = '';

	if(document.getElementById('propertyid')){propertyid = document.getElementById('propertyid').value;}

	$.ajax({
	  url: "pages/"+content,
	  cache: false,
	  type: "GET",
	  data: 'propertyid='+propertyid,
	  success: function(html){
		$("#"+container).fadeOut('slow', function() 
		{
			$("#"+container).html(html).fadeIn('slow');
			
			//loop throught the ids of li's within the tabbing div and remove all (the selected) classes
			$('li[id$="Tab"]').each(function(){

				  $(this).attr("class","");

			});

			// now set the actual li of the a that we clicked on to be true
			$("#"+id).attr("class","selected");
			
			initialisePageLoad();

		});
	  }
	});

	return false;

}


/*
	login
	AJAX function to correctly log a user in to the site
*/
function login()
{
	var username = $("#username").val();
	var password = $("#password").val();
	
	if ((username == '') || (password ==''))	
	{
		$("#warning").html("Please enter your username and password!");
	}
	else
	{
		$.get("loginCheck.php?username="+username+"&password="+password, function(result) 
		{
			if (result != true)
			{	
				$("#warning").html(result);
			}
			else if (result == true)
			{
				$('#signInRegister').html('<a href="account">Account</a> | <a href="logout.html">Log out</a>');
				$('#loginForm').html('');
				
				//re-attach thickbox
                tb_init('a.thickbox');
				
				$("#warning").html("Login successful!");
			
				//setTimeout("window.location.reload()",1000);
				setTimeout("tb_remove()",1000);
			}
		});
	
	}
	return false;
}


/*
	logout
	AJAX function to correctly log out a user from the site
*/
function logout()
{
	$.ajax({
	  url: "logoutCheck.php",
	  cache: false,
	  success: function(html){
		
		$('#signInRegister').html('<a href="login.php?height=290&amp;width=280&amp;modal=true" class="thickbox" title="Sign In">Sign In</a> | <a href="register">Register</a>');
		$('#logoutForm').html('');
		
		//re-attach thickbox
        tb_init('a.thickbox');
		
		$("#warning").html("You are now logged out");
			
		setTimeout("window.location.reload()",1000);
		setTimeout("tb_remove()",1000);
		
	  }
	});

	return false;
}


/*
	toggleMap
	Talks with a cookie to decide whether you want to view the maps on the site
	or if you have turned them off
*/
function toggleMap(){
	
	if ( $("#toggleMap").length > 0 ) {

		// slide map in and out
		var mapShow = $.cookie('showMap');
		
		if(mapShow == 'true'){
			$('#toggleMap').attr("class","selected rightMenuItem");
			loadGoogleMapsSearch();
		}else{
			$('#toggleMap').attr("class","rightMenuItem");
			$('#mapWrap').hide();
			$('#toggleMap a').html('Show map');
		}
	
		$('#toggleMap').click(function() 
		{ 
			$('#mapWrap').slideToggle();
			
			if(mapShow == 'true')
			{
				mapShow = 'false';
				
				$('#toggleMap a').html('Show map');
				$('#toggleMap').attr("class","rightMenuItem");
				$.cookie('showMap', 'false');
			}
			else
			{
				
				loadGoogleMapsSearch();
				mapShow = 'true';
				
				$('#toggleMap a').html('Hide map');
				$('#toggleMap').attr("class","selected rightMenuItem");
				$.cookie('showMap', 'true');
		}
		});

	}
}



function initialisePageLoad(){
	
	var clearMePrevious = '';
	
	// clear input on focus
	$('.clearMeFocus').focus(function()
	{
		if($(this).val()==$(this).attr('title'))
		{
			clearMePrevious = $(this).val();
			$(this).val('');
		}
	});
	// if field is empty afterward, add text again
	$('.clearMeFocus').blur(function()
	{
		if($(this).val()=='')
		{
			$(this).val(clearMePrevious);
		}
	});
	
	// clear textarea on focus
	$('.clearMeFocusText').focus(function()
	{
		if($(this).html()==$(this).attr('title'))
		{
			clearMePrevious = $(this).html();
			$(this).html('');
		}
	});
	// if field is empty afterward, add text again
	$('.clearMeFocusText').blur(function()
	{
		if($(this).html()=='')
		{
			$(this).html(clearMePrevious);
		}
	});
	
	// if we want a field to have focus on page load, give it a class called it setLoadFocus
	$('.setLoadFocus').focus();

	// select on focus
	$('.autoselect').focus(function()
	{
		$(this).select();
	});
	
	toggleMap();

	// on email page?
	$('table[id^="message_body_"]').each(function(){
											  	$(this).toggle();
											   });
	
	$('a[id^="hideshow_"]').each(function(){
											  	$(this).attr("class","openBtn png_bg");
											   });

}

// externalLinks()
/*
* Allows external links to be opened in a new window without the use of target attribute
* @return bool
*/
function externalLinks() {
	
	//SETS DOMAIN OF SITE
	var domainName=document.domain;
	
	var externalLinks=document.getElementsByTagName("a"); //FIND ALL LINKS ON THE CURRENT PAGE
	
	for(var i=0; i<externalLinks.length; i++) { //LOOP THROUGH LINKS ARRAY
	
		var attribute=externalLinks[i].getAttribute("href"); //GETS CONTENT OF 'HREF' ATTRIBUTE ON CLICKED LINK
		
		var elementClass = externalLinks[i].className; //STORES CLASS NAME OF ELEMENT
		
		var contains_http=attribute.indexOf("http"); //GET VALUE http IN 'HREF' **FOR MOZILLA&&
		
		var contains_domain=attribute.indexOf(domainName); //GET VALUE domainName **FOR IE**
		
		if(newWindowLink == true) {
		
			if(contains_http>-1 && contains_domain==-1) { //DOES CONTAIN AN 'http' OR DOES NOT CONTAIN domainName
			
				setElementAttribute(externalLinks[i], 'target', '_blank');	
				
			}
		
		}
		
		if(elementClass.indexOf('new_window') > -1 ) { //FORCE LINK TO OPEN IN NEW WINDOW
			
			setElementAttribute(externalLinks[i], 'target', '_blank');
		}
		
	}
	
}

function bookmarks()
{
	$('#bookmarks a').click(function(){

	var bookmark_id = $(this).parent().attr('id');
	var bookmark_link;
	var bookmark_url = encodeURIComponent(location.href);
	var bookmark_title = encodeURIComponent(document.title);

	if ( bookmark_id == 'twitterlink' ) {
		bookmark_link = "http://www.twitter.com/bethemiddleman";
	} else if ( bookmark_id == 'deliciouslink' ) {
		bookmark_link = "http://del.icio.us/post?v=4&noui&jump=close&url="+bookmark_url+"&title="+bookmark_title;
	} else if ( bookmark_id == 'fblink' ) {
		bookmark_link = "http://www.facebook.com/sharer.php?u="+bookmark_url+"&t="+bookmark_title;
	} else if ( bookmark_id == 'stumblelink' ) {
		bookmark_link = "http://www.stumbleupon.com/submit?url="+bookmark_url+"&title="+bookmark_title;
	} else if ( bookmark_id == 'yahoolink' ) {
		bookmark_link = "http://myweb2.search.yahoo.com/myresults/bookmarklet?u="+bookmark_url+"&t="+bookmark_title;
	} else if ( bookmark_id == 'googlelink' ) {
		bookmark_link = "http://www.google.com/bookmarks/mark?op=edit&bkmk="+bookmark_url+"&title="+bookmark_title;
	}

	window.open(bookmark_link, '', '');
	return false;

});
	
}


// setElementAttribute()
/*
* Sets elements attribute
* @return bool; @param element: Element to attach attr to, attr: The attribute to be added, val: value of attribute
*/
function setElementAttribute(element, attr, val) {

	element.setAttribute(attr, val); //SET ATTRIBUTE ON ELEMENT

	return true;

}

function printLink() {
	
	$('.print a').click(function() {
		window.print();
		return false;
	});
	
}

/*
	startup
*/
$(document).ready(function(){

		initialisePageLoad();
		beginTabbing();
		externalLinks();
		bookmarks();
		printLink();

	});


function toggleMail(element){
	
	var elementid = element.id;
	
	if(element.className.indexOf('hideBtn') > -1){

		$("#"+elementid).attr("class","openBtn png_bg");

	}
	
	else{
		
		$("#"+element.id).attr("class","hideBtn png_bg");
		
		}
	
	$("#message_body_"+elementid.replace(/hideshow_/i, "")).slideToggle();
	
}