/*
 * Company:					Vivid Red (http://www.vividred.com.au)
 * Author:					Matthew Dickson (novak6@iinet.net.au)
 * Copy Right:				This code is the sole property of Vivid Red.
 
 * File Name:				search.js
 * Date Created:			7th of December, 2007 (13h:24m:02s)
 * Last Modified:			13th of December, 2007 (20h:39m:11s)
 * Modification Reason:		AJAX JavaScript was changed out for Prototype.
 * Modification History:	~ General code cleaning and commenting.								[13d/12m/2007y 22h:20m:54s]
 							~ File created														-
 							
 * Known problems			Many.
 
 * Descrpiton:				This file provides AJAX searching functionallity for 
 							the relevant form, for the Australian property site
							(www.realestate.com.au).
*/

var graphic_base		= null;
var graphic_loading     = "<div align=\"center\"><img src=\"RealAgent/Images/ajax_loader_cube.gif\"></div>";
var graphic_logo		= null;
var property_id 		= "";

function initalizeRealAgent() {
	graphic_base		= $('real_agent_home').readAttribute('value');
	graphic_logo		= $('agent_logo').readAttribute('value');
}  

/* The eventAction method cathes hyperlink clicks and then 
 * determines a coures of action.
 * @returns boolean value that determines navagate away from page (Always false).
 */
function eventAction(eventLink)
{
	var url = eventLink.href;
	
	// The user has chosen to email the selected property to a friend.
	if(url.indexOf("http://www.realestate.com.au/cgi-bin/rsearch?a=eptff") == 0)	EmailFriendWindow(property_id);
	else if(url.indexOf("http://www.realestate.com.au/cgi-bin/rsearch?a=pf") == 0)  PrintWindow(navigate_url);
	
	// The user has selected to navigate to another page of results, otherwise, retrieve
	// the selected property an display it in the 'detail' panel.
	else if(url.indexOf("http://www.realestate.com.au/cgi-bin/rsearch?a=d&t=res&ty=&f") == -1 && 
	   	    url.indexOf("http://www.realestate.com.au/cgi-bin/rsearch?a=d&t=ren&ty=&f") == -1 )
		 updateContent(url, 'detail');		
	else updateContent(url, 'result');
	
	return false;
}


function updateContent(navigate_url, tab) {		

	var params = null;	
		
	$(tab).update(graphic_loading);	
	(tab == 'result') ? realAgent.expandit(1) : realAgent.expandit(2);		
	if(navigate_url != null) { params = navigate_url.toQueryParams();	}
	else {params = $('realAgent').serialize(true) }
	
	new Ajax.Request('RealAgent/Scrape.php',
	{
    	method:'get',
		parameters: params,
    	onSuccess: function(transport) {
      		var response = transport.responseText || "no response text";
			var formatted_html = parseHtml(response);
			$(tab).update(formatted_html);
    	},
    	onFailure: function() { 
			alert('There was a problem with the connection. Please try again.');
		}
  	});	
	
}

function parseHtml(html) {

	var message_error = "";
	html.stripScripts();
	
	// An error message been returned from the site. Display it before other results.
	if (html.include('<div class="message error')) {
		message_error = html.substr(html.indexOf("<div class=\"message error"), html.length);
		message_error = message_error.substr(0, (message_error.indexOf("</div>") + 6));
		message_error = message_error + '<br />';
	}	

	/* If the propOverview element is included in the results, it's most likely probable that
	 * the html response is of an overview (multiple properties summary) nature; therefore it 
	 * is safe to assume that it should be displayed on the results tab. If this tag is not 
	 * found, then it is also safe to assume that user has clicked a view more details link. 
	 * In this senario the relevant formating for a detailed result should be displayed in
	 * the 'details' tab of the Real Agent component. */
	if(html.include("propOverview")){	
		var pages = html;
		
		pages = pages.substr(pages.indexOf('<div id="minorResultsNav'), pages.length);
		pages = pages.substr(0, (pages.indexOf('</div>') + 6));
		pages = replaceAll(pages, '<a h', '<a onclick="eventAction(this); return false" h');
	
		html = html.substr((html.indexOf('<div class="propOverview')), html.length);
		html = html.substr(0, html.indexOf('<div id="minor'));
		html = '<div id="searchResults">' + html + '</div>';		
		html = replaceAll(html, '<a h', 					'<a onclick="eventAction(this); return false" h');
		html = replaceAll(html, '<a class="moreInfo" h', 	'<a class="moreInfo" onclick="eventAction(this); return false" h');	
		html = replaceAll(html, '<a class="photo" h', 		'<a class="photo" onclick="eventAction(this); return false" h');		
		html = "<div id=\"searchHeader\">Search Results</div><div style=\"padding: 10px;\">" + message_error + html + "</div>";
		html = html + "<div id=\"searchFooter\">" + pages + "</div>";
	}
	else {		

		var tools = html;	
						
		property_id = html;
		property_id = property_id.substr(property_id.indexOf('function Email'), property_id.length);
		property_id = property_id.substr(property_id.indexOf('window.open(')+12, property_id.length);
		property_id = property_id.substr(property_id.indexOf("'"), property_id.length);
		property_id = property_id.substr(1, property_id.indexOf("',")-1);						
						
		var bhtml = html.include("CUL-DE-SAC LOCATION");
		if(bhtml == false)
		{
			var html1 = html.substr(0, html.indexOf('<a name="editorialLocalitySummary'));
			html = html1 + html.substr(html.indexOf('<a name="contactAgent"'), html.length);
		}
		html = html.substr((html.indexOf('<div class="major')), html.length);
		html = html.substr(0, html.indexOf('<div class="minor">'));				
	
		tools = tools.substr(tools.indexOf('<div id="propertyTools"'), tools.length);
		tools = tools.substr(0, tools.indexOf('<div class="minor"'));
		tools = '<div class="minor">' + tools + '</div>';
		
		html = replaceAll(html, "View sold properties in area", "");		
		html = replaceAll(html, "Show Visits", "");
		html = html.replace("/objects/agents/MHXMOR/20050914181921,p,2,logo.gif", "RealAgent/Images/logo.gif");	
						
		html = '<div id="majorContent"><div id="propertyDetail">' + html + tools + '</div></div>';
		html = "<div id=\"searchHeader\">Details of Selected Property</div><div style=\"padding: 10px;\">" + message_error + html + "</div>";					
				
	}	
	
	return html;
}

// Replaces all values in a string
function replaceAll(source, original, replacement)
{ 	
	var copy  = source;
    var index = copy.indexOf(original);      
   	while (index > 0) {
		copy   = copy.replace(original, replacement);      
     	index  = copy.indexOf(original);
    }      
	 
	return copy;
}


var width = 640;
var height = 480;

if (screen.width > 800) {
	width = 800;
    height = 600;
}

// Not implemted
function VirtualTourWindow() {}

function ImageWindow(imgURL) {

	//bypass norton internet security popup blocker
    if (typeof SymRealWinOpen != 'undefined') 
	{
    	if(navigator.appVersion.indexOf("MSIE")!=-1) 
        	window.open = SymRealWinOpen;
		else 
        	alert('Norton Internet Security may block this popup.\nPlease disable your popup blocker if you experience any problems.');
    }
    // pop appropriately sized window
    if (screen.width > 800)
        w=window.open(imgURL,'ImageWindow','menubar=no,toolbar=no,status=no,width='+(width+60)+',height='+(height+150)+',resizable=yes,scrollbars=yes');
    else
        w=window.open(imgURL,'ImageWindow','menubar=no,toolbar=no,status=no,width='+(width+40)+',height='+(height+120)+',resizable=yes,scrollbars=yes');
		
    w.focus();
}

function PopupWindow(URL, width, height, title) {

	if (!title) 
	{
    	title='Information';
    }
    
	//bypass norton internet security popup blocker
    if (typeof SymRealWinOpen != 'undefined') 
	{
    	if (navigator.appVersion.indexOf("MSIE")!=-1) 
        	window.open = SymRealWinOpen;
        else
          alert('Norton Internet Security may block this popup.\nPlease disable your popup blocker if you experience any problems.');        
	}
      
	 w=window.open(URL, title, 'menubar=no,toolbar=no,status=no,width='+width+',height='+height+',resizable=no,scrollbars=yes');
     w.focus();
}

function EmailAgentWindow(url) {
  window.open(property_id,
    'EmailAgentWindow',
    'menubar=no,toolbar=no,status=no,resizable=no,scrollbars=yes,' +
    'width=440,' +
    'height=385'
  );
}

function EmailFriendWindow() {
  window.open('Email.html',
    'EmailAgentWindow',
    'menubar=no,toolbar=no,status=no,resizable=no,scrollbars=yes,' +
    'width=289,' +
    'height=346'
  );
}

function PrintWindow(url) {
  window.open('url',
    'EmailAgentWindow',
    'menubar=no,toolbar=no,status=no,resizable=no,scrollbars=no,' +
    'width=800,' +
    'height=500'
  );
}

initalizeRealAgent();
