﻿var config = { excludePostcodes: ['SW19 1BJ']};
var templates = {email: '<span id="email"><a href="mailto:{$email}">Email address {$email}</a></span>',
				panelTopLinks: '<ul class="panelTopLinks" id="panellinks_{$id}">' +
								'{$innerLinks}' +
								 //'<li id="print_{$id}" class="print"><a href="#print">Print</a></li>' + 
								 '</ul>' +
								'<a href="#close" class="close" id="close_{$id}">close</a>',
				innerLinks: '<li id="{$id}" class="{$className}"><a href="#">{$innerText}</a></li>',
				option: '<option value="{$value}" selected="{$selected}">{$text}</option>',
				moreLink: '<div class="leftItem"><a href="#more_details" class="link_more" id="more_{$id}">More details</a></div>'
			};
var priceRange = {  buy: { priceRange: [['any', '--any--', 'selected'], ['100,000', '100,000'], ['150,000', '150,000'], ['200,000', '200,000'], ['250,000', '250,000'], ['300,000', '300,000'], ['350,000', '350,000'], ['400,000', '400,000'], ['500,000', '500,000'], ['550,000', '550,000'], ['600,000', '600,000'], ['650,000', '650,000'], ['700,000', '700,000'], ['750,000', '750,000'], ['800,000', '800,000'], ['850,000', '850,000'], ['900,000', '900,000'], ['950,000', '950,000'], ['1,000,000', '1,000,000'], ['999,000,000', 'over 1,000,000']] },
					rent: { priceRange: [['any', '--any--', 'selected'], ['250', '250'], ['500', '500'], ['750', '750'], ['1000', '1000'], ['1500', '1500'],['2000', '2000'], ['3000', '3000'], ['5000', '5000'], ['~', 'No limit']]}
				}
jQuery(function init(){

	jQuery('#resultList ul.item').each(function(cnt){
		var innerLinks = ''; 
		var a = [];
		jQuery(this).attr({id: 'item_' + cnt});
		jQuery(this).find('li.renderHidden').css({display: 'none'})
			.removeClass('renderHidden')
			.each(function(){
				var id = jQuery(this).attr('class');
				a.push({id: id + '_' + cnt, innerText: jQuery(this).attr('title'), className: 'link_' + id});
				jQuery(this).attr({id: id + 'panel_' + cnt})
		});
		for (var c = 0; c < a.length; c++ ) {
			innerLinks += templates.innerLinks.tpl(a[c]);	
		}
		var data = {id: cnt, innerLinks: innerLinks };
		jQuery('#descriptionpanel_' + cnt).prepend(templates.panelTopLinks.tpl(data));
		
		var container = jQuery('#item_' + cnt);
		container.find('div.more').prepend(templates.moreLink.tpl({id: cnt}));
		jQuery('#close_' + cnt + ', #more_' + cnt + ', .thumbs img', jQuery(this)).click(function(e){
			var p = jQuery('#descriptionpanel_' + cnt);
			if (p.is(':visible')) {
				p.slideUp('fast');
			} else {
				p.slideDown('fast');
			}
			e.preventDefault();
		});
		var tabbedContent = container.find('div.tabbedContent')
		jQuery('#panellinks_' + cnt + ' li').click(function(e){
			window.gmap = function() {};
			var type = jQuery(this).attr('id').split('_')[0];
			switch(type) {
				case 'print':
					var the_pdf = container.find('li.print a')
					if (the_pdf.length > 0) {
						document.location.href = the_pdf.attr('href');
					}
					// window.print();
					break;
				case 'description':
					container.find('div.tabbedContent').slideUp('fast', function() {
						container.find('ul.galleryThumbs').slideDown('fast');
					});
					break;
				case 'map':
						window.gmap = function (){
							var the_map = container.find('div.tabbedContent div.map');
							var the_streetView = container.find('div.tabbedContent div.streetView');
							if (GBrowserIsCompatible()) {
								//log(the_map.get(0))
								var map = new GMap2(the_map.get(0));
								//map.setCenter(new GLatLng(37.4419, -122.1419), 13);
								//map.setUIToDefault();
								var mapControl = new GMapTypeControl();
								map.addControl(mapControl);
								map.addControl(new GLargeMapControl3D());
								
								// var map = new GMap2(document.getElementById("map_canvas"));
								var postcode = container.find('li.details div.address em.postcode').attr('postcode');
								var addr = container.find('li.details div.address em.main').html();
								
								if (config.excludePostcodes.toString().indexOf(postcode) == -1) { //don't show undesired postcodes
									findAddress(addr, postcode, function(point){
										map.setCenter(point, 16);
										var marker = new GMarker(point);
										map.addOverlay(marker);
										//var fenwayPark = new GLatLng(42.345573,-71.098326);
										//panoramaOptions = { latlng:point };
										var myPano = new GStreetviewPanorama(the_streetView.get(0), {latlng: point});
									});
								} else {
									container.find('div.tabbedContent div.mapsWrapper').css({visibility: 'hidden'});
								}
								//map
							}
						}
					//break;
				default:
					var t = container.find('ul.galleryThumbs');
					if (t.is(':visible')) {
						container.find('ul.galleryThumbs').slideUp('fast', function() {
							tabbedContent.html(container.find('#' + type + 'panel_' + cnt).html());
							container.find('div.tabbedContent').slideDown('fast');
							if (window.gmap){
								gmap();
							}
						});
					} else {
						container.find('div.tabbedContent').slideUp('fast', function() {
							tabbedContent.html(container.find('#' + type + 'panel_' + cnt).html());
							container.find('div.tabbedContent').slideDown('fast');
							if (window.gmap){
								gmap();
							}
						});
					}
					break;
			}
			e.preventDefault();
		});
	});
	jQuery('#resultList .galleryThumbs').each(function(){
		jQuery('li a', this).lightBox();
	});
	
	if (typeof pageId !== 'undefined') {
		switch(pageId) {
			case 'home':
				//jQuery('#buyOrRent input').change()
				jQuery('#quickSearch').submit(function(e) {
					var rent = jQuery('#radio2:checked'); //check is rent radio is checked
					if (rent.length >0 ) {
						//letSearchUrl
						if (letSearchUrl) jQuery('#quickSearch').attr('action', letSearchUrl);
						else jQuery('#quickSearch').attr('action', jQuery('#nav15 a, #nav75 a, #nav39 a, #nav57 a, #nav121 a, #nav101 a').attr('href'));
						jQuery('#pageId').attr('value', 'let');
					}	
					//e.preventDefault();
				});
				var check = jQuery('#quickSearch ul.list input');
				if (jQuery.browser.msie){
					check.focus(function() {
						jQuery(this).attr({selected: 'selected'});
						var v = jQuery(this).attr('value');
						updateList(jQuery('#minPrice'), v)
						updateList(jQuery('#maxPrice'), v)
					});
				} else {
					check.change(function() {
						var v = jQuery(this).attr('value');
						updateList(jQuery('#minPrice'), v)
						updateList(jQuery('#maxPrice'), v)
					});
				}
				
				break;
			default:
				break;
		}
	}

	var f = jQuery('#flash');
	if (f.length == 1 && !jQuery('body').hasClass('landing')) {
		var vars = { sw15URL: '/sw15/', 
					sw17URL: '/sw17/',
					sw19URL: '/sw19/',
					sw20URL: '/sw20/',
					swPlusURL: '/swplus/',
					swNewURL: '/newhomes/'
		};
		swfobject.embedSWF("assets/flash/landing.swf", "flash", "100%", "100%", "9.0.0", "assets/flash/expressInstall.swf", vars, {bgcolor: '#000000'});
	}
	
	if (!jQuery('body').hasClass('landing')) {
		switch (postcode){
			case 'SW15':
				jQuery('#email').replace(templates.email.tpl({email: 'info' + '@' + 'sw15.com'}));
				break;
			case 'SW20':
				jQuery('#email').replace(templates.email.tpl({email: 'info' + '@' + 'allinthepostcode.com'}));
				break;
			case 'newhomes':
			case 'SW17':
				jQuery('#email').replace(templates.email.tpl({email: 'info' + '@' + 'allinthepostcode.com'}));
				break;
			case 'swplus':
				jQuery('#email').replace(templates.email.tpl({email: 'info' + '@' + 'allinthepostcode.com'}));
				break;
			default:
				jQuery('#email').replace(templates.email.tpl({email: 'info' + '@' + 'sw19.com'}));
				break;
		}
	} else {
		jQuery('#email').replace(templates.email.tpl({email: 'info' + '@' + 'allinthepostcode.com'}));
	}

	jQuery('em.postcode').each(function(){
		var a = jQuery(this);
		var p = a.html();
		var b = p.split(' ');
		if (b.length > 1){
			a.attr({'postcode': p});
			a.html(b[0]);
		}
	});
	jQuery('#nav29 a, #nav65 a, #nav4 a, #nav47 a').attr({title: 'back to homepage'});
	jQuery('.showJsOnly').removeClass('showJsOnly');
});

function updateList(el, type){
	var h = '';
	var d = priceRange[type].priceRange;
	for (var cnt = 0; cnt < d.length; cnt++) {
		h = h + templates.option.tpl({value: d[cnt][0], text: d[cnt][1], selected: (typeof d[cnt][2] == 'undefined')? '': d[cnt][2]});
	}
	el.html(h);
	el.find("option:first").attr({selected: 'selected'});
}
/* simple template */
String.prototype.tpl = function (o) {
    return this.replace(/{\$([^{}]*)}/g,
        function (a, b) {
            var r = o[b];
            return typeof r === 'string' || typeof r === 'number' ? r : a;
        }
    );

};

/* test for empty object */
function emptyObject(o) {
	for (var i in o) { 
		return false;
	}
	return true;
}

/* link blurring extends jQ */
jQuery.fn.nb = function() {
	this.blur();
	return this.focus(function(){
		this.blur();
	});
}

/* replaces DOM element and returns the new jQuery object*/
jQuery.fn.replace = function() {
    var stack = [];
    return this.domManip(arguments, true, 1, function(a){
        this.parentNode.replaceChild( a, this );
        stack.push(a);
    }).pushStack( stack );
};

function log(a) {
	console.log(a);
}

jQuery(window).unload( function(){
	GUnload();
});

function findAddress(address, postcode, fn) {
	//remove Wimbledon from the address - that seems to confuse google maps
	address = address.replace('Wimbledon', '');
	var geocoder = new GClientGeocoder();
	geocoder.setBaseCountryCode('UK');
	address += ' ' + postcode;
	geocoder.getLatLng(address, function(point) {
		if (!point) { //not found - try postcode only
			geocoder.getLatLng(postcode, function(point) {
				if (!point) { //not found at all...

				} else {
					fn(point);
				}
			});
		} else {
			fn(point);
		}
	});
}
function gmap() {
	
}

