﻿/*
Javascript for AllInThePostcode
Date: September 2010
Version: 2.0.0 - complete gmaps rewrite API 3
Developer: S. Cmakal
*/

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="{$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']]}
				};
var map;
var geocoder;		// the gmaps geocoder object
var gmap = function() {};

jQuery(function init(){
	// gmaps init
	geocoder = new google.maps.Geocoder();

	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, href: (id == 'print')? jQuery(this).find('a').attr('href') : '#'});
				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').get(0);
							var the_streetView = container.find('div.tabbedContent div.streetView').get(0);

							getLatLng(container.find('li.details div.address'), function(latlng) {
								map = new google.maps.Map(the_map, {			// create instance of the map
									zoom: 16,
									center: latlng,
									streetViewControl: true,
									mapTypeId: google.maps.MapTypeId.ROADMAP
								});
								var marker = new google.maps.Marker({			// add marker point
									map: map, 
									position: latlng
								});

								var panorama = new  google.maps.StreetViewPanorama(the_streetView, {
									position: latlng,
									addressControl: false,
									pov: {
										heading: 0,
										pitch: 0,
										zoom: 1
									}
								});
								map.setStreetView(panorama);

								$.scrollTo(the_map, 500);
							});
						}
					//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);
}

// get Latitute and Longitude from DOM structure
// use geo location if present
var getLatLng = function(htmlData, fn) {
	var latlng = false;
	
	var d = htmlData.find('em.latlng');
	if (d.length == 1 ) {
		var l = d.html().split(',');
		if (l.length == 2) {
			latlng = new google.maps.LatLng(l[0], l[1]);
		}
	}
	
	if (latlng == false) {		// try to get location from the address field
		var address = [];
		address.push(htmlData.find('em.hsno').html());
		address.push(htmlData.find('em.main').html());
		address.push(htmlData.find('em.postcode').attr('postcode'));

		geocoder.geocode( { 'address': address.join()}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				if (typeof fn == 'function') {
					fn(results[0].geometry.location);
				}
			} else {
				//alert("Geocode was not successful for the following reason: " + status);
			}
		});
		
	} else if (typeof fn == 'function') {
		fn(latlng);
	}
	
};
