// Some handy logging functions, comment out the actual logging lines for production since not everyone has firebug installed...
// Extend jquery with inline log function
var dummyContext = function(){
	var con  = window.console ? window.console : {log:function(){}};

	jQuery.fn.log = function (msg) {
		var a = [];
  		for(var i=0; i<arguments.length; i++) { a.push(arguments[i]); }
  		a.unshift(this);
  		if(con.firebug) {
			con.log.apply(this,a);
		} else {
			con.log("");		// Safari bug causes repeat calls to fail. Chrome is fine.
			con.log(a);
		}
		return this;
	};
	jQuery.log = function() {
		if(con.firebug) {
			con.log.apply(this,arguments)
		} else {
			con.log("");		// Safari bug causes repeat calls to fail. Chrome is fine.
			con.log(arguments);
		}
	};
}();
dummyContext = undefined;

// John Resig's class inheritance stuff
// Inspired by base2 and Prototype
(function(){
  var initializing = false, fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/;

  // The base Class implementation (does nothing)
  this.Class = function(){};

  // Create a new Class that inherits from this class
  Class.extend = function(prop) {
    var _super = this.prototype;

    // Instantiate a base class (but only create the instance,
    // don't run the init constructor)
    initializing = true;
    var prototype = new this();
    initializing = false;

    // Copy the properties over onto the new prototype
    for (var name in prop) {
      // Check if we're overwriting an existing function
      prototype[name] = typeof prop[name] == "function" &&
        typeof _super[name] == "function" && fnTest.test(prop[name]) ?
        (function(name, fn){
          return function() {
            var tmp = this._super;

            // Add a new ._super() method that is the same method
            // but on the super-class
            this._super = _super[name];

            // The method only need to be bound temporarily, so we
            // remove it when we're done executing
            var ret = fn.apply(this, arguments);
            this._super = tmp;

            return ret;
          };
        })(name, prop[name]) :
        prop[name];
    }

    // The dummy class constructor
    function Class() {
      // All construction is actually done in the init method
      if ( !initializing && this.init )
        this.init.apply(this, arguments);
    }

    // Populate our constructed prototype object
    Class.prototype = prototype;

    // Enforce the constructor to be what we expect
    Class.constructor = Class;

    // And make this class extendable
    Class.extend = arguments.callee;

    return Class;
  };
})();


var URooms = {
	Facebook : {
		init : function() {
			FB_RequireFeatures(["XFBML"], function(){
				FB.init("c781ed05518ab2f316e985482661c1f9","../facebook/xd_receiver.htm");
			});
		},
		test : function() {
			FB.ensureInit(function() {
				FB.Connect.showPermissionDialog("email");
			});
		},
		logout : function(path) {
			FB.Connect.logoutAndRedirect(path);
		},
		publish : function(listingViewUrl) {
			URooms.Ajax.json( (listingViewUrl && listingViewUrl.length > 0 ? "/fb" + listingViewUrl + "/fblistingpublishdata.json" : "/fb/fburoomspublishdata.json"), "", function(publishData) {
				$.log('viewURL:' + listingViewUrl);
				var message = publishData.message;
				var attachment = publishData.attachment;
				var actionLinks = publishData.actionLinks;
				var messagePrompt = publishData.messagePrompt;
				var id;

				FB.Connect.streamPublish(message, attachment, actionLinks, (id && id.length > 0 ? id : null), (messagePrompt && messagePrompt.length > 0 ? messagePrompt : null), function(post_id, exception) {
					if(exception)
					{
						alert("exception: " + exception);
					}
				});
			});
		}

	},
	Email : {
		mailTo : function(subject, body) {
			if (encodeURIComponent)
			{
				subject = encodeURIComponent(subject);
				body = encodeURIComponent(body);
			}
			else
			{
				subject = escape(subject);
				body = escape(body);
			}
			window.location.href = "mailto:?subject=" + subject + "&body=" + body;
			return false;
		}
	},
	Agent : {
		logoSubmit : function () {
			var imageUploadFile = jQuery('#image_upload_form input');
			if (imageUploadFile && imageUploadFile.length > 0)
			{
				if (imageUploadFile.val().length>0) // if we have a filename in the box
				{
					jQuery('#image_upload_form').submit();
					return false;
				}
			}

			return true;
		}
	},
	Listing : {
		swapGalleryImage : function (destination, source) {
			destination.css("background-image", "url('"+source+"')");
		}
	},
	
	Search : {
		Util: {
			cleanFeatureName: function (name) {
				if (name.length>0) {
					return name.replace(/\s+/gim, "-").replace(/\//gim, "-");
				}
				return "";
			},
			doSearch: function(type, text) {
				var searchType = (!type || type=='') ? 'property' : type.toLowerCase();
				if(text && text.length>0) {
					if (searchType == 'tenant') {
						window.location = "/tenants/" + escape(text);
					}
					else {
						window.location = "/to-rent/" + escape(searchType) + "/" + escape(text);
					}
				}
				return false;
			}
		}
	},

	/* ----- Ajax support methods ----- */
	Ajax : {
		basePath : "",
		resolvePath : function(path) {
			return URooms.Ajax.basePath.replace("/XajaxrequestX",path);
		},
		json : function(path, data, callback, failcallback) {
			
			jQuery.ajax({
				url: URooms.Ajax.resolvePath(path),
				contentType: "application/json",
				dataType: "json",
				type: "POST",
				data: JSON.stringify(data),
				success: callback,
				fail: failcallback
			});
		},
		addToFavourites : function (url, id)
		{
			$.ajax({
				type: 'POST',
				url: url+'/addToFavourites.json',
				contentType: 'application/json',
				dataType: 'json',
				success: function(data) {
					if (data.success) {
						alert("Added as a favourite listing");
					}
					else if(!data.loggedIn) {
						window.location = "/login?addToFavourites="+id;
					}
					else {
						alert('Failed set as favourite listing');
					}
				}
			});
		}
	},

	/**
	 * Google maps methods manage google maps and perform utility functions
	 */

	GMaps : {
		infoWindow : undefined,
	/*	HOSPITALS("05280371"),
		FURTHER_EDUCATION_ESTABLISHMENTS("05310376"),
		HIGHER_EDUCATION_ESTABLISHMENTS("05310381"),
		BUS_AND_COACH_STATIONS("10570731"),
		RAILWAY_STATIONS("10570738"),
		TRAM_STATIONS_AND_STOPS("10570756"),
		UNDERGROUND_STATIONS("10570761"),
		LONDON_UNDERGROUND_ENTRANCES("10570794")*/
		POIClassMap : {
			"10570761" : {
				type : "tubeStation",
				icon : "/_ui/images/search/map/underground-map-icon.png",
				width : "32",
				height : "39"
			},
			"10570794" : {
				type : "tubeStation",
				icon : "/_ui/images/search/map/underground-map-icon.png",
				width : "32",
				height : "39"
			},
			"05310381" : {
				type : "uni",
				icon : "/_ui/images/search/map/uni-map-icon.png",
				width : "32",
				height : "39"
			},
			"05310376" : {
				type : "college",
				icon : "/_ui/images/search/map/college-map-icon.png",
				width : "32",
				height : "39"
			},
			"10570731" : {
				type : "busStation",
				icon : "/_ui/images/search/map/busstation-map-icon.png",
				width : "32",
				height : "39"
			},
			"10570738" : {
				type : "railStation",
				icon : "/_ui/images/search/map/train-map-icon.png",
				width : "32",
				height : "39"
			},
			"10570756" : {
				type : "trams",
				icon : "/_ui/images/search/map/train-map-icon.png",
				width : "32",
				height : "39"
			},
			"05280371" : {
				type : "hospitals",
				icon : "/_ui/images/search/map/hospital-map-icon.png",
				width : "32",
				height : "39"
			},
			"DEFAULT" : {
				type : "default",
				icon : "/_ui/images/search/map/unknown-map-icon.png",
				width : "32",
				height : "39"
			},
			"StandardRoomListing" : {
				type : "Standard Room",
				icon : "/_ui/images/search/map/room-map-icon.png",
				width : "32",
				height : "43"
			},
			"StandardHouseListing" : {
				type : "Standard House",
				icon : "/_ui/images/search/map/house-map-icon.png",
				width : "32",
				height : "43"
			},
			"FeaturedRoomListing" : {
				type : "Featured Room",
				icon : "/_ui/images/search/map/featured-room-map-icon.png",
				width : "43",
				height : "58"
			},
			"FeaturedHouseListing" : {
				type : "Featured House",
				icon : "/_ui/images/search/map/featured-house-map-icon.png",
				width : "43",
				height : "58"
			}
		},
		createListingMarker : function(listingData) {
			var point = new google.maps.LatLng(listingData.lat, listingData.lng);
			var listIcon = undefined;

			if ("Room" == (listingData.lettingType)) {
				if (listingData.hasUpgradeFeaturedListing)
				{
					listIcon = URooms.GMaps.getPoiMarkerIcon("FeaturedRoomListing");
				} else {
					listIcon = URooms.GMaps.getPoiMarkerIcon("StandardRoomListing");
				}
			} else { // full property
				if (listingData.hasUpgradeFeaturedListing)
				{
					listIcon = URooms.GMaps.getPoiMarkerIcon("FeaturedHouseListing");
				} else {
					listIcon = URooms.GMaps.getPoiMarkerIcon("StandardHouseListing");
				}				
			}
			
			var marker = new google.maps.Marker({position:point, title:listingData.id, icon: listIcon});

			var currentListingData = listingData;

			google.maps.event.addListener(marker, "click", function(e) {
				if (URooms.GMaps.infoWindow) {
					URooms.GMaps.infoWindow.setMap(null);
				}
				URooms.GMaps.infoWindow = new InfoBox({latlng: this.getPosition(), map: this.map, listingData : currentListingData});
			});
			return marker;
		},

		/** A marker for the listing view page with no popup on click **/
		createListingDetailMarker : function(lat,lng) {
			var point = new google.maps.LatLng(lat, lng);
			var listIcon = URooms.GMaps.getPoiMarkerIcon("StandardHouseListing"); // there isn't enough data here to work out what else it would be... 
			return new google.maps.Marker({position:point, icon: listIcon});
		},

		createPoiMarker : function(poiData) {
			var point = new google.maps.LatLng(poiData.location.lat, poiData.location.lng);
			var marker = new google.maps.Marker({position:point, title:poiData.name, icon: URooms.GMaps.getPoiMarkerIcon(poiData.classCode)});

			// add popup for POI marker

			return marker;
		},
		getPoiMarkerIcon : function(POIClass) {
			var iconDetails = URooms.GMaps.POIClassMap[POIClass];
			if (!iconDetails) iconDetails = URooms.GMaps.POIClassMap["DEFAULT"];

			if (iconDetails) {
				var listIcon = new google.maps.MarkerImage(iconDetails.icon,
					new google.maps.Size(iconDetails.width,iconDetails.height)
				);
				return listIcon;
			}
			return undefined;
		}
	},
	Favourites : {
		addProfileToFavourites: function(customerPublicId, successcallback, failcallback)
		{
			if(customerPublicId) {
				URooms.Ajax.json('/tenants/addToFavouriteProfiles.json', {custPublicId: customerPublicId}, function(data){
					if (data.success) {
						if(successcallback) {
							successcallback();
						} else {
							alert("Favourite added");
						}
					}
					else if(!data.loggedIn) {
						window.location = "/login";
					}
					else {
						$.log("Failed to set customer with public id '"+customerPublicId+"' as a favourite");
						if(failcallback) failcallback();
					}
				}, function(xht, textStatus, ex) {
					$.log("Failed to set as favourite profile '"+textStatus+"'");
					if(failcallback) failcallback();
				});
			}
			return false;
		}
	}
};



// Global init
$(function(){

	// Init sliders
	//$(".superslider").sliderkit();

	var roundedBoxes = jQuery('.widget_roundedbox');
	if (roundedBoxes.length>0)
	{
		roundedBoxes.corner();
	}

	var features = jQuery('.feature');
	if (features.length>0)
	{
		jQuery('.feature').tooltip();
	}

	if (!jQuery.browser.msie)
	{
		var sliders = jQuery('.superslider');
		if (sliders.length>0)
		{
			sliders.corner();
			jQuery('.superslider a.next').corner('tr br');
			jQuery('.superslider a.prev').corner('tl bl');
		}
	}

	// Header search bar init
	$("#headermain .searchBar a").click(function(event){
		event.preventDefault();
        if($("#hiddenSearchInput").val().length != 0) {
		    URooms.Search.Util.doSearch($('select#headerSearchType').val(), "near/poi-"+$('#hiddenSearchInput').val());
        }
        else{
            URooms.Search.Util.doSearch($('select#headerSearchType').val(), $('#header input[name=\'searchTerms\']').val());
        }
	});

	$("#headermain .searchBar input").keypress(function(event){
		if(event.keyCode=='13') {
			event.preventDefault();
            if($("#hiddenSearchInput").val().length != 0) {
		        URooms.Search.Util.doSearch($('select#headerSearchType').val(), "near/poi-"+$('#hiddenSearchInput').val());
            }
            else {
			    URooms.Search.Util.doSearch($('select#headerSearchType').val(), $('#header input[name=\'searchTerms\']').val());
            }
		}
	});

    $(".searchForm .searchLocationName").keypress(function(event){
		if(event.keyCode=='13') {
			event.preventDefault();
            if($("#hiddenSearchInput").val().length != 0) {
		        URooms.Search.Util.doSearch($('select#headerSearchType').val(), "near/poi-"+$('#hiddenSearchInput').val());
            }
            else {
			    URooms.Search.Util.doSearch($('select#headerSearchType').val(), $('#header input[name=\'searchTerms\']').val());
            }
		}
	});

    //default text in the search box
    $("#searchInput").toggleVal("e.g. EC1, Bristol, Waterloo Station", "hasfocus");

    //add autocomplete to the search bar
    $("#searchInput").autocomplete({
        appendTo:"#autocompleteresult",
        source: function(request, response) {
            URooms.Ajax.json("/search/userautocompletesearch.json", {location: jQuery("#searchInput").val().toLowerCase()}, function(data){
                response(jQuery.map(data.pointsOfInterest, function(item) {
                        return {
                            label: item.name,
                            value: item.id
                        }
                    }))
//                if (!data.pointsOfInterest.length) {
//                    response(jQuery.map([0], function(item) {
//                        return {
//                            label: "No Matches",
//                            value: "No Matches"
//                        }
//                    }))
//                }
//                else{
//                    response(jQuery.map(data.pointsOfInterest, function(item) {
//                        return {
//                            label: item.name,
//                            value: item.id
//                        }
//                    }))
//                }
            })
        },
        select: function(event, ui){
            event.preventDefault();
            $("#searchInput").val(ui.item.label);
            $("#hiddenSearchInput").val(ui.item.value);
        },
        focus: function(event, ui) {
            event.preventDefault();
            $("#searchInput").val(ui.item.label);
        }
    });

    $(".searchForm .searchLocationName").autocomplete({
        appendTo:"#searchLocationNameResult",
        source: function(request, response) {
            URooms.Ajax.json("/search/userautocompletesearch.json", {location: jQuery(".searchForm .searchLocationName").val().toLowerCase()}, function(data){
                response(jQuery.map(data.pointsOfInterest, function(item) {
                        return {
                            label: item.name,
                            value: item.id
                        }
                    }))

//                if (!data.pointsOfInterest.length) {
//                    response(jQuery.map([0], function(item) {
//                        return {
//                            label: "No Matches",
//                            value: "No Matches"
//                        }
//                    }))
//                }else{
//                    response(jQuery.map(data.pointsOfInterest, function(item) {
//                        return {
//                            label: item.name,
//                            value: item.id
//                        }
//                    }))
//                }
            })
        },
        select: function(event, ui){
            event.preventDefault();
            $("#searchInput").val(ui.item.label);
            $("#hiddenSearchInput").val(ui.item.value);
        },
        focus: function(event, ui) {
            event.preventDefault();
            $(".searchForm .searchLocationName").val(ui.item.label); 
        }
    });

	$('select#headerSearchType').selectmenu({handleWidth:0, themeClass:'theme-header'});
	$('select#headerSearchType').change(function() {
		if ("Tenant" == $('select#headerSearchType').val())
			$('#headerSearchTypeFollowingText').text('looking in');
		else
			$('#headerSearchTypeFollowingText').text('to rent in');
	});
});

// Rotating homepage banner
function HomepageRotatingBanner () {
    var self = this;
	var rotateOn = true;
	var rotateTiming = 7000;
	var timerOn = false;
	var hasFocus = false;

	this.automaticSlideChange = function ()
	{
		if (rotateOn) {
			self.moveNext();
		}
		setTimeout('homepageRotatingBanner.automaticSlideChange()', rotateTiming);
	};

	this.start = function() {

		jQuery('.playPauseButton a').click(function () {
			//homepageRotatingBanner.pauseAutoSlideChange();
			if (timerOn) {
				self.stopTimer();
			} else {
				self.startTimer();				
			}
			return false;
		});
		
		//on clicking a tab, move to the contents
		jQuery('.bannerMenu a').click(function () {
			homepageRotatingBanner.rotateBanner(jQuery(this).attr('position'));
			return false;
		});

		jQuery('#rotatingHomepageSearchBanner').mouseenter(function() {
			homepageRotatingBanner.pauseAutoSlideChange();
		}).mouseleave(function() {
			homepageRotatingBanner.playAutoSlideChange();
		});

		jQuery('#rotatingHomepageSearchBanner input').focus(function() {
			self.hasFocus = true;
			homepageRotatingBanner.pauseAutoSlideChange();
		}).blur(function() {
			self.hasFocus = false;
			homepageRotatingBanner.playAutoSlideChange();
		});

		homepageRotatingBanner.startTimer();

	};

	this.startTimer = function () {
		setTimeout('homepageRotatingBanner.automaticSlideChange()', rotateTiming);
		timerOn = true;
	};

	this.stopTimer = function () {
		clearTimeout('homepageRotatingBanner.automaticSlideChange()', rotateTiming);
		timerOn = false;
	};

	this.moveNext = function()
	{
		var position = jQuery('.bannerMenu a.selected').attr('position');
		position++;
		/* UR-523
		position = position % 3;
		*/
		position = position % 2;
		self.rotateBanner(position);
		self.highlightTabInPosition(position);
	};

	this.highlightTabInPosition = function (position) {
		jQuery('.bannerMenu a').removeClass('selected');
		jQuery('.bannerMenu a[position='+position+']').addClass('selected');
	};

	this.rotateBanner = function(position) {
		var leftPosition = position * -720;
		jQuery('.bannerSlides').stop().animate({ left : leftPosition}, 900, 'easeOutQuint');
		self.highlightTabInPosition(position);
	};

	this.pauseAutoSlideChange = function () {
		rotateOn = false;
	};
	this.playAutoSlideChange = function () {
		if (!self.hasFocus) {
			rotateOn = true;
		}
	};
	this.toggleAutoSlideChange = function () {
		rotateOn = !rotateOn;
	};

}

var homepageRotatingBanner = new HomepageRotatingBanner();


