var panorama;

/*
 * Initialize Google Map and Street View
 * Consider moving to a common JS file if its re-used in the future
 */
function initMap(latitude, longitude) {
	var map;
	var propertyLatLng = new google.maps.LatLng(latitude, longitude);
	
    // Set up the map
	var mapOptions = {
	  center: propertyLatLng,
	  zoom: 16,
	  mapTypeId: google.maps.MapTypeId.ROADMAP,
	  streetViewControl: false
	};
	map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);

	var propertyMarker = new google.maps.Marker({
	    position: propertyLatLng,
	    map: map,
	    icon: '/themes/www.jamestaylorproperty.com/web/images/map_icon.png'
	});

	// We get the map's default panorama and set up some defaults.
	// Note that we don't yet set it visible.
    panorama = map.getStreetView();
    panorama.setPov({
    	heading: 95,
    	zoom:1,
    	pitch:0}
    );
    // Try to get StreetView location that has data 
	var client = new google.maps.StreetViewService();
	client.getPanoramaByLocation(propertyLatLng, 50, function(result, status) {
	    if (status == google.maps.StreetViewStatus.OK) {
	    	panorama.setPosition(result.location.latLng);
	    } else {
	    	// Remove the tab
	    	$('.tab-streetview').remove();
	    }
	  });

	google.maps.event.addListener(panorama, 'closeclick', function() {
		$("ul.map-tabs li").removeClass("active");
		$("ul.map-tabs li.tab-map").addClass("active");
	});
}

function streetView() {
    panorama.setVisible(true);
    return false;
}

function mapView() {
    panorama.setVisible(false);
    return false;
}

$(document).ready(function(){
    // property full details page photo slideshow
	if($('#photo_slider').length)
	{
		$('#photo_slider').galleria({
        	transition: 'fade',
        	width:628,
        	height:420,
        	thumbEventType: 'mouseover'
		});
	}
	if($('#analog-clock').length){
		$('#analog-clock').clock({type: 'analog', medidiem: false});
	}

    $('#full_details_page .property_search_horizontal').hide();
    $('.new_property_search').show();
    $('.new_property_search').click(function(){
    	var search_form = $("#full_details_page .property_search_horizontal");
    	$(".new_property_search").attr("src", "/themes/www.jamestaylorproperty.com/web/images/" 
    			+ (search_form.is(":visible") ? "new-property-search" : "hide-property-search") + ".png");
    	search_form.slideToggle();
    });

    $('.shortlist_nav_tab').hide();
	
    if($('.is_shortlist_page').val()){
        $('.property_search_horizontal').hide();
        $('.new_property_search').show();
		$('.shortlist_nav_tab').show();
        $('.new_property_search').click(function(){
        	var search_form = $(".property_search_horizontal");
        	$(".new_property_search").attr("src", "/themes/www.jamestaylorproperty.com/web/images/" 
        			+ (search_form.is(":visible") ? "new-property-search" : "hide-property-search") + ".png");
        	search_form.slideToggle();
        });
        $('.new_property_search').show();
    }
   
    
	// Valuation 
	if($('#valuation').length){
		$("#valuation").validate();
		$("#submit").click(function() {

			if($("#valuation").valid())
			{
				var data_string = $("#valuation").serialize();

				$.ajax({
					type: "POST",
					url: "/valuation/index",
					data: data_string,
					success: function() {
						$('#valuation').html("<div id='reponse'></div>");
						$('#reponse').html("<h2>Thank you</h2>")
						.append("<p>We will be in touch shortly.</p>")
						.hide()
						.fadeIn(1500);
					}
				});

				return false;
			}
			return false;
		});
	}
	
	$('a.valuation, a.free_valuation').click(function(){
		$("a.valuation, a.free_valuation").colorbox({width:"600", height:"460px", iframe:true});
	});
	
	var arr_shortlists = new Array();
	var cookie_name = 'shortlists_' + $('.trans_type_id').val();
	if($('.location_type_id').val() && $('.trans_type_id').val() == 1){
		cookie_name = cookie_name + '_' + $('.location_type_id').val();
	}
	
	if($.cookie(cookie_name))
	{	
		arr_shortlists = $.cookie(cookie_name).split(','); 
		for(var i = 0; i < arr_shortlists.length; i++)
		{
			$('#shortlist_' + arr_shortlists[i]).attr('checked', true);
			$('#shortlist_label_' + arr_shortlists[i]).text("Remove from Shortlist");
		}
	} 
	
	// Add and removed from shortlists
	$('.shortlist').click(function(){ 
		if(this.checked)
		{ 
			// add to cookie
			arr_shortlists.push($(this).val());
			$('#shortlist_label_' + $(this).val()).text("Remove from Shortlist");
		} 
		else
		{
			for(var i = 0; i < arr_shortlists.length; i++)
			{ 
				if(arr_shortlists[i] == $(this).val())
				{
					arr_shortlists.splice(i, 1);
					$('#shortlist_label_' + $(this).val()).text("Add to Shortlist");
				}
			}
		}
		
		$.cookie(cookie_name, arr_shortlists, {path: '/'});
	});
	
	$('a.shortlist').click(function(){
		if(! $.cookie(cookie_name))
		{
			alert('Your shortlist is currently empty. Please select some properties to add to your shortlist before using this feature.');
			return false; 
		} 
		return true;
	});
	
	if($('.is_shortlist_page').val())
	{
		$('.view_shortlist').hide();
	}
	
});

$(function(){
    // Specify the ZIP/location code and units (f or c)
    var loc = 'UKXX0085'; // or e.g. SPXX0050
    var u = 'c';

    var query = "SELECT item.condition FROM weather.forecast WHERE location='" + loc + "' AND u='" + u + "'";

    var cacheBuster = Math.floor((new Date().getTime()) / 1200 / 1000);
    var url = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent(query) + '&format=json&_nocache=' + cacheBuster;

    window['wxCallback'] = function(data) {
        var info = data.query.results.channel.item.condition;
        $('#wxIcon').css({
            backgroundPosition: '-' + (61 * info.code) + 'px 0'
        }).attr({
            title: info.text
        });
        $('#wxIcon2').append('<img src="http://l.yimg.com/a/i/us/we/52/' + info.code + '.gif" width="22" height="22" title="' + info.text + '" />');
        $('#wxTemp').html(info.temp + '&deg;' + (u.toUpperCase()));
    };

    $.ajax({
        url: url,
        dataType: 'jsonp',
        cache: true,
        jsonpCallback: 'wxCallback'
    });
});
