﻿/* Functionality common to most, if not all, pages */


function SetUpConcertina(obj, options) {
    $(obj).addClass('concertinaActivated');
    if (options) {
        if (options.autoCollapse) {
            if (options.onChange) {
                $('.concertinaButton, .concertinaLink', obj).bind('click', function() { AutoCollapse.call(this,options) });
            }
            else { $('.concertinaButton, .concertinaLink', obj).bind('click', AutoCollapse); }


        } else {
            if (options.onChange) {
                $('.concertinaButton, .concertinaLink', obj).bind('click', function() { ExpandConcertina.call(this,options) });
            }
            else {
                $('.concertinaButton, .concertinaLink', obj).bind('click', ExpandConcertina);
            }
        }
    } else {
        $('.concertinaButton, .concertinaLink', obj).bind('click', ExpandConcertina);
    }
}

function photoCarousel_initCallback(carousel) { }


function AutoCollapse(options) {
    var parentObj = $(this).parents('li:eq(0)'), container = parentObj.parents('ul:eq(0)');
    if (!parentObj.hasClass('concertinaExpanded') && !parentObj.hasClass('concertinaExpandDefault')) {
        if (container.data("currentToggle")) {
            ToggleConcertina(container.data("currentToggle"));
        }
        else {
          
            ToggleConcertina(container.find(".concertinaExpandDefault:eq(0)"));
        }
         if (options && options.onChange) {options.onChange.call(this,false); }
     }
     container.data("currentToggle", ToggleConcertina(parentObj));
     if (options && options.onChange) {options.onChange.call(this,true); }
}

function ToggleConcertina(obj) {
    var objReturn = null;
   
     if (obj) {
        if (obj.hasClass('concertinaExpanded') || obj.hasClass('concertinaExpandDefault')) {

             if ($.browser.msie) {
                 obj.removeClass('concertinaExpanded').find('.concertinaContent').hide();
             }
             else {

                 obj.removeClass('concertinaExpanded').find('.concertinaContent').slideUp();
             }
         }
         else {
             objReturn = obj;
            if ($.browser.msie) {
                 obj.addClass('concertinaExpanded').find('.concertinaContent').show();
             }
             else {
                 obj.addClass('concertinaExpanded').find('.concertinaContent').slideDown(500);
            }
         }
         obj.removeClass('concertinaExpandDefault');
     }
     return objReturn;
 }

 function ExpandConcertina(options) {

    var parentObj = $(this).parents('li:eq(0)');
    ToggleConcertina(parentObj);
   
    if (options && typeof options.onChange == "function") { options.onChange.call(this,true);}
}

(function($) {


	$.fn.concertina = function(options) {
		return $(this).each(function() { SetUpConcertina(this, options) });
	};

	$.fn.setUpPhotoCarousel = function() {
		return $(this).jcarousel({ scroll: 5, initCallback: photoCarousel_initCallback });
	}

	$.fn.registerLocationSVC = function(stype, sval, callback) {
		var obj = this;
		return $(this).keydown(function(e) { { $(window).data('keypress', e) } }).autocomplete('/svc/locationService.asmx/GetList',
         { minChars: 2, delay: 250,
         	onItemSelect: function(li) { window.FAP.UI.onLocationSelected(li, obj, stype, sval, callback); },
         	formatItem: window.FAP.UI.formatLocation, selectFirst: false
         });
	}

	$.fn.registerAgentNameSVC = function(stype, sval) {
		var obj = this;
		return $(this).keydown(function(e) { { $(window).data('keypress', e) } }).autocomplete('/svc/agentDirectoryService.asmx/GetList',
         { minChars: 3, delay: 250,
         	onItemSelect: function(li) { window.FAP.UI.onAgentSelected(li, obj, stype, sval); },
         	formatItem: window.FAP.UI.formatAgent, selectFirst: false
         });
	}

	$.fn.preventEdit = function(options) {
		var defaults = { copy: false, cut: false, paste: false, 'select': false };
		$.each(options, function(i, v) { if (typeof defaults[i] === 'undefined') { delete options[i]; } });
		options = $.extend(defaults, options);
		if (window.opera) {	// Opera only
			return this.each(function() {
				if (/file|password|text(area)?/i.test(this.type)) {
					$(this).bind('keypress', function(e) {
						var p = false;
						if (e.ctrlKey) {
							switch (e.which) {
								case 65: p = options['select']; break; // A
								case 67: p = options.copy; break; 		// C
								case 86: p = options.paste; break; 		// V
								case 88: p = options.cut; break; 		// X
							}
							if (p) { e.preventDefault(); return false; }
						}
						return true;
					});
				}
			});
		}
		else {	// All other browsers
			var s = [];
			$.each(defaults, function(i, v) { if (v) { s.push(i); } });
			if (s.length) {
				return this.each(function() {
					if (/file|password|text(area)?/i.test(this.type)) {
						$(this).bind(s.join(' '), function(e) { e.preventDefault(); });
					}
				});
			}
		}
	};
	$.browser.msie6 = /*@cc_on@*//*@if(@_win32)(typeof document.documentElement.style.minWidth != 'string')@else@*/false/*@end@*/;
	$.browser.version = /*@cc_on@*//*@if(@_win32)(!$.browser.msie6 && parseInt($.browser.version, 10) == 6) ? '7.0' : /*@end@*/$.browser.version;
	$.extend(true, window, { FAP: {} });
	$.extend(true, window.FAP, {
		_loaded: true,
		UI: {
			openToolTip: function(obj) {
				$(obj).addClass("showToolTip").find(".closer").bind("click.closer", window.FAP.UI.closeToolTip);
				return false;
			},
			closeToolTip: function() {
				$(this).parents('.showToolTip:eq(0)').removeClass("showToolTip").find(".closer").unbind("click.closer");
				return false;
			},
			addHoverToLink: function() {
				// cache a copy of the span, at the same time changing the opacity
				// to zero in preparation of the page being loaded
				var $span = $('> span.majorHover', this);

				if ($span.length == 0) { $span = $('<span class="majorHover"/>'); $(this).append($span); }
				$span.css('opacity', 0);
				// when the user hovers in and out of the anchor
				$(this).hover(window.FAP.UI.buttonMouseOver, window.FAP.UI.buttonMouseOut);
			},
			addHoverToButton: function() {

				var $input = $('> .majorButton', this).css('opacity', 0).addClass('majorHover');
				$(this).hover(window.FAP.UI.buttonMouseOver, window.FAP.UI.buttonMouseOut);
			},
			buttonMouseOver: function(e) { $('.majorHover', this).stop().fadeTo(500, 1); },
			buttonMouseOut: function(e) { $('.majorHover', this).stop().fadeTo(500, 0); },
			editorialMenuInit: function() {
				if ($.browser.msie6) {
					$('li, #SpecialEditionLink', '#EditorialMenu').hover(function() { $(this).children('div.menuList').addClass('on'); }, function() { $(this).children('div.menuList').removeClass('on'); });
				}
			},
			toggleHidden: function(container, obj, hiddenObj, lock) {
				var isBuyLink = (obj.hasClass("buy") || !obj.hasClass("rent"));
				hiddenObj.addClass((isBuyLink) ? 'buy' : 'rent');
				hiddenObj.removeClass(isBuyLink ? 'rent' : 'buy');

				if (obj.hasClass("toggleOn")) {
					container.data("currentToggle", null);
					obj.removeClass("toggleOn");
					hiddenObj.slideUp(500);
					if (lock) { container.removeClass("locked"); }
				}
				else {
					if (container.data("currentToggle")) { container.data("currentToggle").removeClass("toggleOn"); }
					container.data("currentToggle", obj.addClass("toggleOn"));

					if (!hiddenObj.is(":visible")) {
						hiddenObj.slideDown(500);
						if (lock) { container.addClass('locked'); }
					}


				}
			},
			inlineLabelFocus: function() { $(this).prev("label.inlined").addClass("focus"); if (this.value != '') { $(this).prev("label.inlined").addClass("has-text").removeClass("focus"); } },
			inlineLabelKeyPress: function() { $(this).prev("label.inlined").addClass("has-text").removeClass("focus"); },
			inlineLabelBlur: function() {
				if ($(this).val() == "") {
					$(this).prev("label.inlined").removeClass("has-text").removeClass("focus");
				}
			},
			stopCarousel: function(carousel, where, state) {
				if (where) {
					if (!carousel) {
						carousel = where.find(".carousel:eq(0)").data("jcarousel");
					}
					if (carousel) {
						if (!where.hasClass('concertinaExpanded') && !where.hasClass('concertinaExpandDefault')) {
							if (state) {
								carousel.stopAuto(0);
								state = false;
							}
						}
						else {
							if (!storyState) {
								carousel.startAuto();
								state = true;
							}
						}
					}
				}
			},
			carousel_circleInitCallback: function(carousel) {
				// Disable autoscrolling if the user clicks the prev or next button.
				carousel.buttonNext.bind('click', function() {
					carousel.startAuto(0);
				});

				carousel.buttonPrev.bind('click', function() {
					carousel.startAuto(0);
				});

				// Pause autoscrolling if the user moves with the cursor over the clip.
				carousel.clip.hover(function() {
					carousel.stopAuto();
				}, function() {
					carousel.startAuto();
				});
			},
			onLocationSelected: function(li, loc, stype, sval, callback) {

				if (typeof window.FAP.form.resetResolvedFields == "function")
					window.FAP.form.resetResolvedFields();

				if (li && li.extra) {
					$(stype).val(li.extra[1]);
					$(sval).val(li.extra[2]);
					$(loc).val(li.extra[3]);
				}

				if (callback) callback.apply(this, [li]);

				return false;
			},
			onAgentSelected: function(li, obj, stype, sval, defaultButton) {
				if (li) {
					stype.val(li)
					sval.val(li)
				}

				var keyEvent = $(window).data("keypress");
				if (keyEvent) {
					var keyCode = keyEvent.keyCode || keyEvent.which;
					if (keyCode && keyCode == 13) {
						defaultButton.click();
					}
				}

			},
			formatLocation: function(row) { return (row[0] + ((row[1] != "") ? ", <i>" + row[1] + "</i>" : "")); },
			formatAgent: function(row) { return row[0] + "<br />"; },
			showEditions: function(e) {
				$(window).data("specialEditionMenu", $(e).siblings('.specialEditions:eq(0)'));
				$(window).data("specialEditionMenu").animate({ height: 'show' }, 500, function() {
					if ($.browser.msie) { this.append('<span class="tl"></span><span class="tr"></span><span class="br"></span><span class="bl"></span>'); }
					$(document).bind('keydown.editions', function(e) { if (e.keyCode == 27) { window.FAP.UI.hideEditions(); } }).bind('mousedown.editions', function(e) { var obj = e.target; if (obj == null) obj = e.srcElement; if ($(obj).parents().is(".specialEditions") || $(obj).is(".specialEditions") || $(obj).is("#SpecialEditionLink")) { e.preventDefault; } else { window.FAP.UI.hideEditions(); } });
				});
			},
			hideEditions: function() {
				var links = $(window).data("specialEditionMenu");
				if (links) {
					links.find('.bl, .br, .tl, .tr').remove();

					links.animate({ height: 'hide' }, 500, function() { $(document).unbind('keydown.editions').unbind('mousedown.editions'); });
					$(window).data("specialEditionMenu", null);
				}
			}
		},
		form: {
			initialValues: ['place or postcode', '£ min', '£ max'],
			jQueryInit: function() {
				if (!window.FAP._loaded) { window.setTimeout(window.FAP.form.jQueryInit, 5); return false; }
				if ($.browser.msie6) {
					$('input.text, select, textarea').each(function(i) {
						$(this).blur(function() { if ($.data(this, 'error') === true) { $(this).addClass('warning_field'); } $(this).removeClass('focus_field'); $.removeData(this, 'focused'); });
						$(this).focus(function() { if ($(this).hasClass('warning_field')) { $.data(this, 'error', true); $(this).removeClass('warning_field'); } $(this).addClass('focus_field'); $.data(this, 'focused', true); });
					});
				}
				$(".watermark").each(function(i) {
					var obj = $(this); obj.data("previousVal", obj.val()).focus(function() {
						var obj = $(this); // obj.removeClass('initialValue'); 
						window.FAP.form.resetResolvedFields(); if (obj.val() == obj.data("previousVal")) { obj.val(""); }
					})
              .blur(function() {
              	var obj = $(this); if ($.trim(obj.val()) == "") {
              		window.FAP.form.rollbackResolvedFields(); obj.val(obj.data("previousVal")); if ($.inArray(obj.data('previousVal'), window.FAP.form.initialValues) > -1) { //obj.addClass('initialValue'); 
              		}
              	}
              })
				});

			},
			resetResolvedFields: function() { $(".resolver").each(function(i) { var obj = $(this); if (this.tagName == "INPUT" && (this.type == "checkbox" || this.type == "radio")) { obj.data("previousVal", this.checked); this.checked = false; } else { obj.data("previousVal", obj.val()); obj.val(''); } }); },
			rollbackResolvedFields: function() { $(".resolver").each(function(i) { var obj = $(this); if (this.tagName == "INPUT" && (this.type == "checkbox" || this.type == "radio")) { this.checked = obj.data("previousVal"); } else { obj.val(obj.data("previousVal")); } }); },


			//Shows the login dropdown menu
			showLogin: function(obj) {

				var loginform = $('<div id="LoginMenu" class="infoPanel"><ol><li><label for="menuUser">Email</label><input type="text" id="menuUser" class="default_text" /></li><li><label for="menuPassword">Password</label><input type="password" autocomplete="off" id="menuPassword" class="default_text" /></li></ol><div class="majorButtonOuter majorButtonContinue"><div class="majorButton" onclick="window.FAP.form.authenticate($(\'#menuUser\').val(),$(\'#menuPassword\').val())"></div></div></div>').hide();

				loginform.find(":text,:password").keypress(function(e) { if (e.keyCode == 13) { $('#LoginMenu').find('.majorButton').click(); return false; } }).end().find(".majorButtonOuter").each(window.FAP.UI.addHoverToButton);
				var $obj = $(obj);
				var jObj = $obj.parent();
				if ($('#LoginMenu').length == 0) {
					jObj.append(loginform);
					loginform.animate({ width: 'show', height: 'show' }, 500, function() {
						if ($.browser.msie) {
							loginform.addClass('corneredBox').append('<span class="tl"></span><span class="tr"></span><span class="br"></span><span class="bl"></span>');
						}
						$obj.data("previousHtml", $obj.html()).html("Close");
						$(document).bind('keydown.login', function(e) {
							if (e.keyCode == 27) {

								window.FAP.form.hideLogin(null);
							}
						}).bind('mousedown.login', function(e) {

							var obj = e.target;
							if (obj == null) obj = e.srcElement;
							if ($(obj).parents().is("#LoginMenu") || $(obj).is("#LoginMenu")) {
								e.preventDefault;
							}
							else {
								window.FAP.form.hideLogin(null);
							}
						});
					});
				}
				else {
					this.hideLogin(obj);
				}
				return false;
			},
			//Hides the login dropdown menu
			hideLogin: function(obj) {


				var loginform = $('#LoginMenu');

				if (obj == null) obj = loginform.siblings('.loginLink');

				var $obj = $(obj);
				loginform.removeClass('corneredBox').find('.bl, .br, .tl, .tr').remove();

				loginform.animate({ height: 'hide', width: 'hide' }, 500, function() {

					$obj.html($obj.data("previousHtml"));
					loginform.remove();
					$(document).unbind('keydown.login')
                    .unbind('mousedown.login');
				});

			},
			//Sends and authentication web request
			authenticate: function(username, password) {

				if (username != '' && window.FAP.validators.validateEmail(username) && password != '') {


					$.ajax({
						type: 'POST',
						url: '/svc/authenticationservice.asmx/Authenticate',
						data: "{'username':'" + username + "', 'password': '" + password + "', 'keepLoggedIn':false}",
						contentType: 'application/json; charset=utf-8',
						dataType: "json",
						success: function(data) {
							var o = eval("(" + ((data.d) ? data.d : data) + ")");

							if (o.success == false) {
								//TODO: modal the error message
								alert(o.message);
							}
							else {
								if (window.location.toString().split('?')[0].indexOf("login.aspx") > -1) {
									window.location = "/";
								}
								else {
									window.location.reload();
								}
							}
						}
					});

				}
				else {
					alert('Please supply a valid username and password');
				}
				return false;
			},
			logout: function() {
				$.ajax({
					type: 'POST',
					url: '/svc/authenticationservice.asmx/Logout',
					data: "{}",
					contentType: 'application/json; charset=utf-8',
					dataType: "json",
					success: function(data) {

						window.location.reload();

					}
				});
				return false;
			},
			cleanUpValue: function(obj) {
				$(obj).val($(obj).val().replace(/(<|(&gt;)|>|(&lt;))/g, ''));
			},
			isRadioGroupSelected: function(radioGroup) {
				return ($('input:radio[name=' + radioGroup + ']:checked').length !== 0);
			},
			getPageHeight: function() {
				var windowHeight
				if (self.innerHeight) {	// all except Explorer
					windowHeight = self.innerHeight;
				} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
					windowHeight = document.documentElement.clientHeight;
				} else if (document.body) { // other Explorers
					windowHeight = document.body.clientHeight;
				}
				return windowHeight;
			},
			getWindowHeight: function() {
				// fix a jQuery/Opera bug with determining the window height
				var h = $.browser.opera && $.browser.version > "9.5" && $.fn.jquery <= "1.2.6" ? document.documentElement["clientHeight"] : $(window).height();

				return h;
			}
		},
		validators: {
			validateLocation: function(event, location, showAlert) {

				if (showAlert == null) showAlert = true;
				if ($.trim(location) == 'place or postcode' || $.trim(location) == '') {
					if (showAlert) alert('Please supply a place name or postcode');
					event.preventDefault();
					return false;
				}
				else {
					return true;
				}
			},
			validateEmail: function(email) {
				return /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test(email);
			},
			validatorUpdateDisplay: function(val) {
				originalValidatorUpdateDisplay(val);

				if (val.controltovalidate) {

					var obj = $('#' + val.controltovalidate);

					if (typeof obj.data('validator_count') == 'undefined') {
						obj.data('validator_count', 0)

						$.each(Page_Validators, function() {
							if (this.controltovalidate == val.controltovalidate) obj.data('validator_count', obj.data('validator_count') + 1);
						});
					}

					if (typeof obj.data('validator_iteration') == 'undefined') {
						obj.data('validator_iteration', 0);
						obj.removeClass('warning_field');
					}
					else {
						obj.data('validator_iteration', obj.data('validator_iteration') + 1);
					}


					if (val.isvalid) {
						if (typeof obj.data('error') == 'undefined' || obj.data('error') != true) {
							obj.removeClass('warning_field');
						}
					}
					else {
						obj.data('error', true);

						obj.addClass('warning_field');

					}

					if (obj.data('validator_iteration') == obj.data('validator_count') - 1) {
						//has completed going through validatiors - clear iterator
						obj.removeData('validator_iteration');
						obj.removeData('error');
					}

				}

			},
			validateAgentSelections: function validateAgentSelections(obj, args) {


				var validationField = $('#' + this.getValidationFieldId(obj));

				var isValid = validationField.find('input:checked').length > 0;
				args.IsValid = isValid;
			},
			validateCheckboxList: function(obj, args) {
				args.IsValid = args.CheckboxGroup ? ($('input:checkbox[id*=' + args.CheckboxGroup + ']:checked').length !== 0) : true;
			},
			validateRadioList: function(obj, args) {
				args.IsValid = args.RadioGroup ? ($('input:radio[name=' + args.RadioGroup + ']:checked').length !== 0) : true;
			},
			emailValidationExpression: '\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*',
			getValidationFieldId: function(obj) {
				return obj.className.match(/data-validator-([^\s]*)/)[1];
			}

		},
		shortlist: {
			//not used yet!
			saveproperty: function(id, link) {
				$.ajax({ type: 'POST', url: '/svc/shortlistservice.asmx/SaveProperty',
					data: "{'propertyId':'" + id + "'}",
					contentType: 'application/json; charset=utf-8',
					success: function(data) {
						result = data.d || data;
						if (result != 0) {
							var jContainer = $(link).parent();
							jContainer.empty();
							jContainer.html('<span class="myFAP_SavedProperty" title="This property is already in your shortlist">saved</span>')
							$('.myFAP_SavedPropertyCount').html(result + ' saved properties');
						}
						else {
							alert("Maximum number of saved properties reached. Please login to save more property");
						}
					}
				});
				return true;
			},
			//not used (pl)
			savesearch: function(q, f) {
				$.ajax({ type: 'POST', url: '/svc/shortlistservice.asmx/SaveSearchAsAlert',
					data: "{'nameValuePairs':'" + q + "','frequency':" + f + "}",
					contentType: 'application/json; charset=utf-8',
					success: function(data) {
						alert('Saved');
					}
				});
				return true;
			}
		},
		tooltips: {
			getmorestations: function(id) {
				$.ajax({ type: 'POST', url: '/svc/htmlservice.asmx/SaveProperty',
					data: "{'propertyId':'" + id + "'}",
					contentType: 'application/json; charset=utf-8',
					success: function(data) {

					}
				});
				return false;
			}

		}

	});
})(jQuery);

(function($) {


    if (!$('body').is('#HomePage')) { // no 'print page' on home page

    };
    //TODO: $('a[rel*=external]').attr({ target: '_blank' }); // open external links in new window
    //TODO:?   $('.jqRemove').remove(); // remove elements not needed if script is running


    window.FAP.form.jQueryInit();
    if ($.browser.msie6) { window.FAP.UI.editorialMenuInit(); }

    $('.majorButtonOuter').each(window.FAP.UI.addHoverToButton);
    $('a.majorButton').each(window.FAP.UI.addHoverToLink);
    $("label.inlined + input.initialValue").each(function() {
        
        $(this).focus(window.FAP.UI.inlineLabelFocus);
        $(this).keypress(window.FAP.UI.inlineLabelKeyPress);
        $(this).blur(window.FAP.UI.inlineLabelBlur);
    });
})(jQuery);

$(document).ready(function() { $("label.inlined + input.initialValue").each(function() { if (this.value != "") { $(this).prev("label.inlined").addClass("has-text") } }); });


var originalValidatorUpdateDisplay = null;

function AssignValidatorUpdateDisplay() {

    originalValidatorUpdateDisplay = null;
    if (typeof (ValidatorUpdateDisplay) == 'function') {
        originalValidatorUpdateDisplay = ValidatorUpdateDisplay;
        ValidatorUpdateDisplay = window.FAP.validators.validatorUpdateDisplay;
    }
 
}

function resetValidation() {
    $("[id*='Validator']").css('display', 'none');
    $('input').removeClass('warning_field');
}
  
AssignValidatorUpdateDisplay();