var _selectHeight = 25;

var _forms = document.getElementsByTagName('form');
var inputs = new Array();
var selects = new Array();
var labels = new Array();
var radios = new Array();
var radioLabels = new Array();
var checkboxes = new Array();
var checkboxLabels = new Array();
var buttons = new Array();
var selects = new Array();
var all_selects = false;
var active_select = null;
var agt = navigator.userAgent.toLowerCase();
var isMac = is_mac();
var selectText = "please select";
var IN_CFORMS = true;

/**
 * Display alternative images when one fails to load.
 */

/*
   Using the fancy image error recovery:
   
   <img class="image_error" src="first_image.jpg">
   <span class="image_error" title="second_image.jpg"></span>
   <span class="image_error" title="third_image.jpg"></span>

*/

function addImageErrorHandlers()
{
   if(typeof(jQuery) != 'undefined')
   {
      // Add error handlers to all images with the image_error class, and remove the class.
      jQuery('img.image_error').removeClass("image_error").error(function(){
   
            // The next span will contain the URL of another image.
            var failoverImage = jQuery(this).next('span.image_error');
   
            if(1 == failoverImage.length)
            {
               // Assign a new URL to this image.
               jQuery(this).attr('src', failoverImage.attr('title'));

               // Remove this failover image, so we'll move on to the next one in the chain.
               failoverImage.remove();
            }
         });
   }
}

/**
 * sprintf() for JavaScript v.0.4
 *
 * Copyright (c) 2007 Alexandru Marasteanu <http://alexei.417.ro/>
 * Thanks to David Baird (unit test and patch).
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place, Suite 330, Boston, MA 02111-1307 USA
 */

function str_repeat(i, m)
{
    for(var o = []; m > 0; o[--m] = i);
    {
        return(o.join(''));
    }
}

function sprintf ()
{
    var i = 0, a, f = arguments[i++], o = [], m, p, c, x;
    while (f)
    {
        if(m = /^[^\x25]+/.exec(f))
        {
            o.push(m[0]);
        }
        else if(m = /^\x25{2}/.exec(f)) 
        {
            o.push('%');
        }
        else if(m = /^\x25(?:(\d+)\$)?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(f))
        {
            if (((a = arguments[m[1] || i++]) == null) || (a == undefined))
                throw("Too few arguments.");
            if (/[^s]/.test(m[7]) && (typeof(a) != 'number'))
                throw("Expecting number but found " + typeof(a));
            
            switch (m[7])
            {
                case 'b': a = a.toString(2); break;
                case 'c': a = String.fromCharCode(a); break;
                case 'd': a = parseInt(a); break;
                case 'e': a = m[6] ? a.toExponential(m[6]) : a.toExponential(); break;
                case 'f': a = m[6] ? parseFloat(a).toFixed(m[6]) : parseFloat(a); break;
                case 'o': a = a.toString(8); break;
                case 's': a = ((a = String(a)) && m[6] ? a.substring(0, m[6]) : a); break;
                case 'u': a = Math.abs(a); break;
                case 'x': a = a.toString(16); break;
                case 'X': a = a.toString(16).toUpperCase(); break;
            }
            a = (/[def]/.test(m[7]) && m[2] && a > 0 ? '+' + a : a);
            c = m[3] ? m[3] == '0' ? '0' : m[3].charAt(1) : ' ';
            x = m[5] - String(a).length;
            p = m[5] ? str_repeat(c, x) : '';
            o.push(m[4] ? a + p : p + a);
        }
        else
            throw ("Huh ?!");
            
        f = f.substring(m[0].length);
    }
    return o.join('');
}

function is_mac() {
	if (navigator.appVersion.indexOf("Safari") != -1)
	{
		if(!window.getComputedStyle)
		{
			return true;
		}
	}
	
	return false;
}

function initCastomForms() {
	if(!document.getElementById) {return false;}
	getElements();
	separateElements();
	//replaceSelects();

	var _selects = document.getElementsByTagName('select');
	var _SelctClassName = [];
	if (_selects) {
		for (var i = 0; i < _selects.length; i++) {
			if (_selects[i].className != '' && _selects[i].className != 'outtaHere')
				_SelctClassName[i] = ' drop-'+_selects[i].className;
		}
		for (var i = 0; i < _SelctClassName.length; i++) {
			var _selectDrop = document.getElementById('optionsDiv'+i);
			if (_selectDrop) {
				if (_SelctClassName[i]) 
					_selectDrop.className += _SelctClassName[i];
			}
		}
	}
}

// getting all the required elements
function getElements() {
	for (var nf = 0; nf < document.getElementsByTagName("form").length; nf++) {
		for(var nfi = 0; nfi < document.forms[nf].getElementsByTagName("input").length; nfi++) {inputs.push(document.forms[nf].getElementsByTagName("input")[nfi]);}
		for(var nfl = 0; nfl < document.forms[nf].getElementsByTagName("label").length; nfl++) {labels.push(document.forms[nf].getElementsByTagName("label")[nfl]);}
		for(var nfs = 0; nfs < document.forms[nf].getElementsByTagName("select").length; nfs++) {selects.push(document.forms[nf].getElementsByTagName("select")[nfs]);}
	}
}

// separating all the elements in their respective arrays
function separateElements() {
	var r = 0; var c = 0; var t = 0; var rl = 0; var cl = 0; var tl = 0; var b = 0;
	for (var q = 0; q < inputs.length; q++) {
		if(inputs[q].type == "radio") {
			radios[r] = inputs[q]; ++r;
			for(var w = 0; w < labels.length; w++) {
				if((inputs[q].id) && labels[w].htmlFor == inputs[q].id)
				{
					radioLabels[rl] = labels[w];
					++rl;
				}
			}
		}
		if(inputs[q].type == "checkbox") {
			checkboxes[c] = inputs[q]; ++c;
			for(var w = 0; w < labels.length; w++) {
				if((inputs[q].id) && (labels[w].htmlFor == inputs[q].id))
				{
					checkboxLabels[cl] = labels[w];
					++cl;
				}
			}
		}
		if((inputs[q].type == "submit") || (inputs[q].type == "button")) {
			buttons[b] = inputs[q]; ++b;
		}
	}
}

//check event
function checkEvent(e) {
	if (!e) var e = window.event;
	if(e.keyCode == 32) {for (var q = 0; q < checkboxes.length; q++) {if(this == checkboxes[q]) {changeCheckboxes(q);}}} //check if space is pressed
}

function replaceSelects() {
	for(var q = 0; q < selects.length; q++) {
	if (!selects[q].replaced && selects[q].offsetWidth)
	{
		selects[q]._number = q;
		//create and build div structure
		var selectArea = document.createElement("div");
		var left = document.createElement("span");
		left.className = "left";
		selectArea.appendChild(left);
		
		var disabled = document.createElement("span");
		disabled.className = "disabled";
		selectArea.appendChild(disabled);
		
		selects[q]._disabled = disabled;
		var center = document.createElement("span");
		var button = document.createElement("a");
		var text = document.createTextNode(selectText);
		center.id = "mySelectText"+q;
		
		var stWidth = selects[q].offsetWidth;
		selectArea.style.width = stWidth + "px";
		if (selects[q].parentNode.className.indexOf("type2") != -1){
			button.href = "javascript:showOptions("+q+",true)";
		} else {
			button.href = "javascript:showOptions("+q+",false)";
		}
		button.className = "selectButton";
		selectArea.className = "selectArea";

		selectArea.className += " " + selects[q].className;
		selectArea.id = "sarea"+q;
		center.className = "center";
		center.appendChild(text);
		selectArea.appendChild(center);
		selectArea.appendChild(button);
		
		//hide the select field
		selects[q].className += " outtaHere";
		//insert select div
		selects[q].parentNode.insertBefore(selectArea, selects[q]);
		//build & place options div

		var optionsDiv = document.createElement("div");
		
		var optionsList = document.createElement("ul");
		optionsDiv.innerHTML += "<div class='select-top'><div></div></div>";
		optionsDiv.appendChild(optionsList);
		
		selects[q]._options = optionsList;
		
		optionsDiv.style.width = stWidth + "px";
		optionsDiv._parent = selectArea;
		
		optionsDiv.className = "optionsDivInvisible";
		optionsDiv.id = "optionsDiv"+q;
		
	
		populateSelectOptions(selects[q]);
		optionsDiv.innerHTML += "<div class='select-bottom'><div class='select-bottom-left'></div><div class='select-bottom-right'></div></div>";
		document.getElementsByTagName("body")[0].appendChild(optionsDiv);
		selects[q].replaced = true;
		}
	all_selects = true;
	}
}

//collecting select options
function populateSelectOptions(me) {
	me._options.innerHTML = "";
	
	for(var w = 0; w < me.options.length; w++) {
		
		var optionHolder = document.createElement('li');
		var optionLink = document.createElement('a');
		var optionTxt;
		if (me.options[w].title.indexOf('image') != -1) {
			optionTxt = document.createElement('img');
			optionSpan = document.createElement('span');
			optionTxt.src = me.options[w].title;
			optionSpan = document.createTextNode(me.options[w].text);
		} else {
			optionTxt = document.createTextNode(me.options[w].text);
		}
		
		optionLink.href = "javascript:showOptions("+me._number+"); selectMe('"+me.id+"',"+w+","+me._number+");";
		if (me.options[w].title.indexOf('image') != -1) {
			optionLink.appendChild(optionTxt);
			optionLink.appendChild(optionSpan);
		} else {
			optionLink.appendChild(optionTxt);
		}
		optionHolder.appendChild(optionLink);
		me._options.appendChild(optionHolder);
		//check for pre-selected items
		if(me.options[w].selected) {
			selectMe(me.id,w,me._number);
		}
	}
	if (me.disabled) {
		me._disabled.style.display = "block";
	}
	else {
		me._disabled.style.display = "none";
	}
}

//selecting me
function selectMe(selectFieldId,linkNo,selectNo) {
	selectField = selects[selectNo];
	for(var k = 0; k < selectField.options.length; k++) {
		if(k==linkNo) {
			selectField.options[k].selected = true;
		}
		else {
			selectField.options[k].selected = false;
		}
	}
	
	//show selected option
	textVar = document.getElementById("mySelectText"+selectNo);
	var newText;
	var optionSpan;
	if (selectField.options[linkNo].title.indexOf('image') != -1) {
		newText = document.createElement('img');
		newText.src = selectField.options[linkNo].title;
		optionSpan = document.createElement('span');
		optionSpan = document.createTextNode(selectField.options[linkNo].text);
	} else {
		newText = document.createTextNode(selectField.options[linkNo].text);
	}
	if (selectField.options[linkNo].title.indexOf('image') != -1) {
		if (textVar.childNodes.length > 1) textVar.removeChild(textVar.childNodes[0]);
		textVar.replaceChild(newText, textVar.childNodes[0]);	
		textVar.appendChild(optionSpan);	
	} else {
		if (textVar.childNodes.length > 1) textVar.removeChild(textVar.childNodes[0]);
		textVar.replaceChild(newText, textVar.childNodes[0]);	
	}
	if (selectField.onchange && all_selects)
		{
			eval(selectField.onchange());
		}
}

//showing options
function showOptions(g) {
		_elem = document.getElementById("optionsDiv"+g);
		var divArea = document.getElementById("sarea"+g);
		if (active_select && active_select != _elem) {
			active_select.className = active_select.className.replace('optionsDivVisible','');
			active_select.className += " optionsDivInvisible";
			active_select.style.height = "auto";
		}
		if(_elem.className.indexOf("optionsDivInvisible") != -1) {
			_elem.style.left = "-9999px";
			_elem.style.top = findPosY(divArea) + _selectHeight + 'px';
			_elem.className = _elem.className.replace('optionsDivInvisible','');
			_elem.className += " optionsDivVisible";
			if (_elem.offsetHeight > 200)
			{
				_elem.style.height = "200px";
			}
			_elem.style.left = findPosX(divArea) + 'px';
			
			active_select = _elem;
			if(document.documentElement)
			{
				document.documentElement.onclick = hideSelectOptions;
			}
			else
			{
				window.onclick = hideSelectOptions;
			}
		}
		else if(_elem.className.indexOf("optionsDivVisible") != -1) {
			_elem.style.height = "auto";
			_elem.className = _elem.className.replace('optionsDivVisible','');
			_elem.className += " optionsDivInvisible";
		}
		
		// for mouseout
		/*_elem.timer = false;
		_elem.onmouseover = function() {
			if (this.timer) clearTimeout(this.timer);
		}
		_elem.onmouseout = function() {
			var _this = this;
			this.timer = setTimeout(function(){
				_this.style.height = "auto";
				_this.className = _this.className.replace('optionsDivVisible','');
				if (_elem.className.indexOf('optionsDivInvisible') == -1)
					_this.className += " optionsDivInvisible";
			},200);
		}*/
}

function hideSelectOptions(e)
{
	if(active_select)
	{
		if(!e) e = window.event;
		var _target = (e.target || e.srcElement);
		if(isElementBefore(_target,'selectArea') == 0 && isElementBefore(_target,'optionsDiv') == 0)
		{
			active_select.className = active_select.className.replace('optionsDivVisible', '');
			active_select.className = active_select.className.replace('optionsDivInvisible', '');
			active_select.className += " optionsDivInvisible";
			active_select = false;

			if(document.documentElement)
			{
				document.documentElement.onclick = function(){};
			}
			else
			{
				window.onclick = null;
			}
		}
	}
}

function isElementBefore(_el,_class)
{
	var _parent = _el;	
	do
	{
		_parent = _parent.parentNode;
	}
	while(_parent && _parent.className != null && _parent.className.indexOf(_class) == -1)
	
	if(_parent.className && _parent.className.indexOf(_class) != -1)
	{
		return 1;
	}
	else
	{
		return 0;
	}
	
}

function findPosY(obj) {
	var posTop = 0;
	while (obj.offsetParent) {posTop += obj.offsetTop; obj = obj.offsetParent;}
	return posTop;
}

function findPosX(obj) {
	var posLeft = 0;
	while (obj.offsetParent) {posLeft += obj.offsetLeft; obj = obj.offsetParent;}
	return posLeft;
}

window.onload = initCastomForms;

/*--- tabs ---*/
function initTabs(){
	$('ul.tabset').each(function(){
		var btn_h = $(this);
		var _btn = $(this).find('a.tab');
		var _a = _btn.index(_btn.filter('.active:eq(0)'));
		if(_a == -1) _a = 0;
		_btn.removeClass('active').eq(_a).addClass('active');
		_btn.each(function(_i){
			this._box = this.href.substr(this.href.indexOf("#") + 1);
			if(this._box){
				this._box = $('#'+this._box);
				if(_i == _a) this._box.show();
				else this._box.hide();
			}
			this.onclick = function(){
				changeTab(_i);
				return false;
			}
        });
		function changeTab(_ind){
			if(_ind != _a){
				if(_btn.get(_a)._box) _btn.get(_a)._box.hide();
				if(_btn.get(_ind)._box) _btn.get(_ind)._box.show();
				_btn.eq(_a).removeClass('active');
				_btn.eq(_ind).addClass('active');
				_a = _ind;
			}
		};
	});
	$('.hp_main_tab_area ul.tabset').each(function(){
		var btn_h = $(this);
		var _btn = $(this).find('a.tab');
		var _a = _btn.index(_btn.filter('.active:eq(0)'));
		if(_a == -1) _a = 0;
		_btn.removeClass('active').eq(_a).addClass('active');
		_btn.each(function(_i){
			this._box = this.href.substr(this.href.indexOf("#") + 1);
			if(this._box){
				this._box = $('#'+this._box);
				if(_i == _a) this._box.show();
				else this._box.hide();
			}
			this.onclick = function(){
				changeTab(_i);
				return false;
			}
        });
		function changeTab(_ind){
			if(_ind != _a){
				if(_btn.get(_a)._box) _btn.get(_a)._box.hide();
				if(_btn.get(_ind)._box) _btn.get(_ind)._box.show();
				_btn.eq(_a).removeClass('active').css('color','#868686').find('strong').css('color','#000');
				_btn.eq(_ind).addClass('active');
				_a = _ind;
			}
		};
	});
}

/*--- IE6 hover ---*/
function ieHover(h_list, h_class){
	if($.browser.msie && $.browser.version < 7){
		if(!h_class) var h_class = 'hover';
		$(h_list).mouseenter(function(){
			$(this).addClass(h_class);
		}).mouseleave(function(){
			$(this).removeClass(h_class);
		});
	}
}

/*--- slide gallery ---*/
function slideGallery(){
	var _speed = 1000; //in ms
	$('#carousel_commercial, #carousel_rental').each(function(){
		var _hold = $(this);
		var list_hold = _hold.find('> div > ul');
		var btn_prev = _hold.find('a.link-prev');
		var btn_next = _hold.find('a.link-next');
		var list_w = list_hold.children().length*list_hold.children().outerWidth();
		var hold_w = list_hold.parent().width();
		var _step = hold_w;
		
		btn_prev.click(function(){
			moveList(false);
			return false;
		});
		btn_next.click(function(){
			moveList(true);
			return false;
		});
		var _m = 0;
		function moveList(_f){
			if(_f){
				if(_m >= list_w - hold_w) _m = 0;
				else _m += _step;
			}
			else{
				if(_m > 0) _m -= _step;
				else _m = Math.ceil((list_w - hold_w)/_step)*_step;
			}
			list_hold.animate({left:-_m},{queue:false, duration:_speed});
		}
	});
}

/*--- fade gallery ---*/
function fadeGallery(){
	var _speed = 1000; //in ms
	$('div.gallery').each(function(){
		var _hold = $(this);
		var list_hold = _hold.find('div.holder > ul');
		var btn_prev = _hold.find('div.carousel a.prev');
		var btn_next = _hold.find('div.carousel a.next');
		var list_w = list_hold.children().length * list_hold.children().outerWidth();
		var hold_w = list_hold.parent().width();
		var _step = hold_w;
		
		btn_prev.click(function(){
			moveList(false);
			return false;
		});
		btn_next.click(function(){
			moveList(true);
			return false;
		});
		var _m = 0;
		function moveList(_f){
			if(_f){
				if(_m >= list_w - hold_w) _m = 0;
				else _m += _step;
			}
			else{
				if(_m > 0) _m -= _step;
				else _m = Math.ceil((list_w - hold_w)/_step)*_step;
			}
			list_hold.animate({left:-_m},{queue:false, duration:_speed});
		}
	});
}

function get_areas()
{
    $.get('/ajax_endpoint.php', {'action': 'areas', 'type': ad_type, 'county': $(this).attr('value')}, function(response)
    { 
        $('select#search_district').empty();
        $('select#search_district').append('<option value="0">No Preference</option>');
        for(var index in response)
        {
            $('select#search_district').append(sprintf('<option value="%1$s">%2$s (%3$d)</option>', response[index]['id'], response[index]['name'], response[index]['properties']));
        }
    }, 'json');
}

$(document).ready(function(){
});

function validateEmail (emailField)
{
	emailpat = /^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9])+(\.[a-zA-Z0-9_-]+)+$/;
	if( !emailpat.test( emailField) )
	{
		return false;
	}
	return true;
}

$(document).ready(function() {

	ieHover('.results-panel div');
	slideGallery();
	fadeGallery();
	initTabs();
    
    $('select#search_county').change(get_areas);
    
    if($('select#search_county').val() != 1)
    {
        $('select#search_county').change();
    }
    
    /* Email Reply Starts */
    
    $('#smi_send_button').click(function (){
        error_check = false;
        
        $("#form_error_reply").empty();
        
        // reset form borders
        $('#your_name').css('border','1px #d9d9d9 solid');
        $('#your_email').css('border','1px #d9d9d9 solid');
        $('#your_message').css('border','1px #d9d9d9 solid');
        
        // check fields are filled out
        if($('#your_name').val() == '')
        {
            $('#your_name').css('border','1px red solid');
            $("#form_error_reply").append('Please enter your name. ');
            error_check = true;
        }
        else if($('#your_email').val() == '')
        {
            $('#your_email').css('border','1px red solid');
            $("#form_error_reply").append('Please enter your email address. ');
            error_check = true;
        }
        else if($('#your_message').val() == '')
        {
            $('#your_message').css('border','1px red solid');
            $("#form_error_reply").append('Please enter a message. ');
            error_check = true;
        }
        else if($('#your_email').val() != '')
        {
            var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            
            if($('#your_email').val().match(re) === null)
            {
                $('#your_email').css('border','1px red solid');
                $("#form_error_reply").append('Please check email address is correct. ');
                error_check = true;
            }
        }
        
        if(error_check == false) // no errors
        {
            // hide form details and show loading image
            $('#reply_form_fields').hide();
            $('#reply').append('<div style="padding-top:35px; width:100%; text-align:center;"><img src="/images/ajax-loader.gif" alt="Sending Reply"/><br /><br />Sending Email</div>');
            
            $.post('/ajax_endpoint.php', {
                'action': 'email_reply', 
                'ad_type': ad_type, 
                'ad_id': ad_id, 
                'name' : $('#your_name').val(), 
                'email' : $('#your_email').val(), 
                'phone' : $('#your_phone').val(), 
                'message' : $('#your_message').val()
            }, function(response)
            {
                $('#reply').empty().append('<div style="padding-top:50px; text-align:center; font-weight:bold; color:red;">' + response + '</div>');
                
                // Track this event in Google Analytics.
                pageTracker._trackEvent("ad_reply", ad_type, ad_id);
                
            }, 'json');
        }
        return false;
    });
    
    /* Email Reply Ends */
    
    /* STF Starts */
    
    var return_message;
            
    $('#sf_submit').click(function (){
    
        error_check = false;
        
        $("#stf_error_reply").empty();
        
        // reset form borders
        $('#sf_yn').css('border','1px #d9d9d9 solid');
        $('#sf_ye').css('border','1px #d9d9d9 solid');
        $('#sf_fn').css('border','1px #d9d9d9 solid');
        $('#sf_fe').css('border','1px #d9d9d9 solid');
        
        // check fields are filled out
        if($('#sf_yn').val() == '')
        {
            $('#sf_yn').css('border','1px red solid');
            $("#stf_error_reply").append('Please enter a name. ');
            error_check = true;
        }
        else if($('#sf_ye').val() == '')
        {
            $('#sf_ye').css('border','1px red solid');
            $("#stf_error_reply").append('Please enter an email address. ');
            error_check = true;
        }
        else if($('#sf_fn').val() == '')
        {
            $('#sf_fn').css('border','1px red solid');
            $("#stf_error_reply").append('Please enter a name. ');
            error_check = true;
        }
        else if($('#sf_fe').val() == '')
        {
            $('#sf_fe').css('border','1px red solid');
            $("#stf_error_reply").append('Please enter an email address. ');
            error_check = true;
        }
        else if($('#sf_ye').val() != '')
        {
            var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            
            if($('#sf_ye').val().match(re) === null)
            {
                $('#sf_ye').css('border','1px red solid');
                $("#stf_error_reply").append('Please check email address is correct. ');
                error_check = true;
            }
        }
        else if($('#sf_fe').val() != '')
        {
            var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            
            if($('#sf_fe').val().match(re) === null)
            {
                $('#sf_fe').css('border','1px red solid');
                $("#stf_error_reply").append('Please check email address is correct. ');
                error_check = true;
            }
        }
        
        if(error_check == false) // no errors
        {
            // hide form details and show loading image
            $('#sf_form').hide();
            $('#sf_bg').append('<div style="padding-top:40px; width:100%; text-align:center;"><img src="/images/ajax-loader.gif" alt="Sending Email"/><br /><br />Sending Email</div>')
            
            //send to ajax endpoint
            $.post('/ajax_endpoint.php', {
                'action': 'send_to_friend', 
                'sf_yn' : $('#sf_yn').val(), 
                'sf_ye' : $('#sf_ye').val(), 
                'sf_fn' : $('#sf_fn').val(), 
                'sf_fe' : $('#sf_fe').val(), 
                'sf_url' : $('#sf_url').val()
            }, function(response){
                $('#sf_bg').empty().append('<div style="padding-top:80px; text-align:center; font-size:14px; font-weight:bold; color:red;">' + response + '</div>');
            }, 'json');
        }
        return false;
    });
    
    
    $('#sf_close').hover(
        function () {
            $(this).attr('src', '/images/pb_close_on.png');
            $(this).css('cursor', 'pointer');
        },
        function () {
            $(this).attr('src', '/images/pb_close_off.png');
        }
    ).click(function(){
        tb_remove();
    });
    
    $('#sf_submit').hover(
        function () {
            $(this).attr('src', '/images/btn-send_on.gif');
        },
        function () {
            $(this).attr('src', '/images/btn-send.gif');
        }
    );

    $('.send').click(function(){
        tb_show(null, '#TB_inline?width=370&amp;height=390&amp;inlineId=send_friend', null);
    });
    
    /* STF Ends */
	
	/* Contact Us Starts */
    
    $('#submit_contact').click(function (){
        
		error_check = false;
        
        $("#cf_form_error_reply").empty();
        
        // reset form borders
        $('#cf_your_name').css('border','1px #d9d9d9 solid');
        $('#cf_your_email').css('border','1px #d9d9d9 solid');
        $('#cf_your_message').css('border','1px #d9d9d9 solid');
        
        // check fields are filled out
        if($('#cf_your_name').val() == '')
        {
            $('#cf_your_name').css('border','1px red solid');
            $("#cf_form_error_reply").append('Please enter your name. ');
            error_check = true;
        }
        else if($('#cf_your_email').val() == '')
        {
            $('#cf_your_email').css('border','1px red solid');
            $("#cf_form_error_reply").append('Please enter your email address. ');
            error_check = true;
        }
        else if($('#cf_your_message').val() == '')
        {
            $('#cf_your_message').css('border','1px red solid');
            $("#cf_form_error_reply").append('Please enter a message. ');
            error_check = true;
        }
        else if($('#cf_your_email').val() != '')
        {
            var pattern = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            
            if($('#cf_your_email').val().match(pattern) === null)
            {
                $('#cf_your_email').css('border','1px red solid');
                $("#cf_form_error_reply").append('Please check email address is correct. ');
                error_check = true;
            }
        }
        
        if(error_check == false) // no errors
        {
            // hide form details and show loading image
            $('#contact_form_fields').hide();
            $('#contact_form_holder').append('<div style="padding-top:85px; width:100%; text-align:center;"><img src="/images/ajax-loader.gif" alt="Sending Reply"/><br /><br />Sending Email</div>');
            
            $.post('/ajax_endpoint.php', {
                'action': 'contact',
                'cf_name' : $('#cf_your_name').val(), 
                'cf_email' : $('#cf_your_email').val(), 
                'cf_phone' : $('#cf_your_phone').val(), 
                'cf_message' : $('#cf_your_message').val()
            }, function(response)
            {
                $('#contact_form_holder').empty().append('<div style="padding-top:100px; text-align:center; font-weight:bold; color:red;">' + response + '</div>');
			}, 'json');
        }
        return false;
    });
	/* Contact us Ends */

    /* Form hovers for IEstupid */
    $('#your_name, #your_email, #your_phone, #your_message, #sf_form input, #cf_your_name, #cf_your_email, #cf_your_phone, #cf_your_message').focus(
        function () {
            $(this).css({'background': '#cbe6f1', 'border' : '1px solid #9dc4d4'});
        }
    );
    $('#your_name, #your_email, #your_phone, #your_message, #sf_form input, #cf_your_name, #cf_your_email, #cf_your_phone, #cf_your_message').blur(
        function () {
            $(this).css({'background': '#fff', 'border' : '1px solid #d9d9d9'});
        }
    );

    /* SR hovers for IEveryStupid */
	if ( $.browser.msie && $.browser.version.substr(0,3) <= 6.0 )
	{
		$('.results-panel .item:hover .description .second .image').css({
            'display': 'block',
    	    'border': '1px solid #bec1c1',
	        'text-align': 'center',
        	'background': '#f4f4f4',
	        'margin': '0 0 8px'
        });
	}

    /* HP section hovers */
    $('.search_tab, .advertise_tab, .quicksearch_tab').hover(
        function () {
            $(this).css('background', '#33b9f1');
            $(this).find('a strong').css('color','#fff');
            $(this).find('a').css('color','#fff');
        },
        function () {
            $(this).css('background', '#fff');
            $(this).find('a strong').css('color','#000');
            $(this).find('a').css('color','#868686');
            $(this).find('a.active').css('color','#fff');
            $(this).find('a.active strong').css('color','#fff');
        }
    );
    
	$('.create-alert').click(function() {
		$.blockUI({message: $('#sr_email_alert'), css: {margin: '-200px 0 0 -289px', width: '578px', height: '263px', 'left': '50%', background: '#ffffff'}, fadeIn: false});
		$('.blockUI').css('cursor', 'default');
	});
	
	$('#sr_email_alert_cancel').hover(
		function() {
			$(this).css({'cursor': 'pointer', 'background': '#0d6083'});
		},
		function() {
			$(this).css({'cursor': 'default', 'background': '#23b4f1'});
		}
	).click(function() {
		$.unblockUI({fadeOut: false});
	});
	
	var ea_loaded = 0;
	$('#email_alert_email').focus(function() {
		if ($(this).val() == 'john.smith@example.com' && !ea_loaded) // hack to ensure input div is blurred on page load
		{
			$(this).blur();
			ea_loaded = 1;
		}
		else if ($(this).val() == 'john.smith@example.com')
		{
			$(this).val('');
			$(this).css({'color': '#000', 'font-style': 'normal'});
		}
	});
	
	$('#email_alert_email').blur(function() {
		if ($(this).val() == '')
		{
			$(this).val('john.smith@example.com');
			$(this).css({'color': '#888', 'font-style': 'italic'});
		}
	});
	$('#sr_email_alert_create').hover(
		function() {
			$(this).css({'cursor': 'pointer', 'background': '#0d6083'});
		},
		function() {
			$(this).css({'cursor': 'default', 'background': '#23b4f1'});
		}
	).click(function() {
		if (!validateEmail($('#email_alert_email').val()))
		{
			$('#sr_email_alert_error').text('* Invalid');
		}
		else if ($('#email_alert_email').val() == '' || $('#email_alert_email').val() == 'john.smith@example.com')
		{
			$('#sr_email_alert_error').text('* Required');
		}
		else
		{
			$('#sr_email_alert_main').css('display', 'none');
			$('#sr_email_alert_sending').css('display', 'block');
			var frequency = '';
			if ($('#email_alert_frequency_daily').attr('checked') == true)
				frequency = 'daily'
			else
				frequency = 'instantly';
			
			$.post('/alerts.php',
				{
					'email_address': $('#email_alert_email').val(),
					'frequency': frequency,
					'affiliate': $('#affiliate').val(),
					'search_url': $('#search_url').val(),
					'search_text': $('#search_text').val(),
					'ip_address': $('#ip_address').val()
				},
				function (data) {
					var resp = $(data).find('resp').text();
					$('#sr_email_alert_sending').css('display', 'none');
					$('#sr_email_alert_main').css('line-height', '18px');
					if (resp == 'bad email')
					{
						$('#sr_email_alert_error').html('* Invalid');
					}
					else if (resp == 'ok')
					{
						$('#sr_email_alert_main').html("Your request to set up an email alert has been successful. A verification email will be sent to <b>"+$('#email_alert_email').val()+"</b> shortly. Please click on the link in this email in order to activate your email alert.<br/><div style=\"float: right; padding: 6px 8px; margin-top: 14px; color: #fff; background: #23b4f1; font-size: 13px; font-family: Helvetica, Arial, sans-serif; font-weight: bold;\" onclick=\"javascript:$.unblockUI({fadeOut: 100});\" onmouseover=\"javascript:$(this).css({'cursor': 'pointer', 'text-decoration': 'underline'});\" onmouseout=\"javascript:$(this).css({'cursor': 'default', 'text-decoration': 'none'});\">Close</div>");
					}
					else
					{
						$('#sr_email_alert_main').html("There has been an error with setting up this email alert. Please try again later.<br/><div style=\"float: right; padding: 6px 8px; margin-top: 14px; color: #fff; background: #23b4f1; font-size: 13px; font-family: Helvetica, Arial, sans-serif; font-weight: bold;\" onclick=\"javascript:$.unblockUI({fadeOut: 100});\" onmouseover=\"javascript:$(this).css({'cursor': 'pointer', 'text-decoration': 'underline'});\" onmouseout=\"javascript:$(this).css({'cursor': 'default', 'text-decoration': 'none'});\">Close</div>");
					}
					$('#sr_email_alert_main').css('display', 'block');
				}, 'xml');
			
		}
	});
	
	$(".email_alert_frequency").hover(
		function () {
			$(this).css('cursor', 'pointer');
		},
		function () {
			$(this).css('cursor', 'default');
		}
	);
	$(".email_alert_frequency").click(
		function () {
			var id = $(this).attr('id').split('_');
			var other_id;
			id = id[3];
			$('#email_alert_frequency').val(id);
			if (id == 'daily')
				other_id = 'instantly';
			else
				other_id = 'daily'
			$('#email_alert_frequency_'+id).attr('checked', 'checked');
			$('#email_alert_frequency_'+other_id).attr('checked', '');
		}
	);
	$('#hp_search_button, #sr_refine_button, #smi_send_button').hover(
		function() {
			$(this).css({'cursor': 'pointer', 'background': '#0d6083'});
		},
		function() {
			$(this).css({'cursor': 'default', 'background': '#23b4f1'});
		}
	);
    $('#hp_search_button').click(function(){
        $('form.search-rent').submit();
    });
    $('#sr_refine_button').click(function(){
        $('form.refine_bar').submit();
    });
});