var Ayi = {};
Ayi.Vars = {};
Ayi.Page = {};
Ayi.Func = {};

Ayi.Class = function() {
	var parent = null;
	var properties = {};
	if (arguments.length == 1) {
		properties = arguments[0];
	} else if (arguments.length == 2) {
		parent = arguments[0];
		properties = arguments[1];
	}
	function klass() {
		this.init.apply(this, arguments);
	}
	if (parent) {
		var subclass = function() {
		};
		subclass.prototype = parent.prototype;
		klass.prototype = new subclass();
	}
	ForEach(properties, function(name, fn) {
		klass.prototype[name] = fn;
	});
	if (!klass.prototype.init) {
		klass.prototype.init = function() {
		};
	}
	klass.prototype.constructor = klass;
	return klass;
};

var dateFormat = function() {
	var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g, timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g, timezoneClip = /[^-+\dA-Z]/g, pad = function(
			val, len) {
		val = String(val);
		len = len || 2;
		while (val.length < len) {
			val = "0" + val;
		}
		return val;
	};

	// Regexes and supporting functions are cached through closure
	return function(date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask
		// prefix)
		if (arguments.length == 1 && (typeof date == "string" || date instanceof String) && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date();
		if (isNaN(date)) {
			throw new SyntaxError("invalid date");
		}

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var _ = utc ? "getUTC" : "get", d = date[_ + "Date"](), D = date[_ + "Day"](), m = date[_ + "Month"](), y = date[_ + "FullYear"](), H = date[_
				+ "Hours"](), M = date[_ + "Minutes"](), s = date[_ + "Seconds"](), L = date[_ + "Milliseconds"](), o = utc ? 0 : date.getTimezoneOffset(), flags = {
			d :d,
			dd :pad(d),
			ddd :dF.i18n.dayNames[D],
			dddd :dF.i18n.dayNames[D + 7],
			m :m + 1,
			mm :pad(m + 1),
			mmm :dF.i18n.monthNames[m],
			mmmm :dF.i18n.monthNames[m + 12],
			yy :String(y).slice(2),
			yyyy :y,
			h :H % 12 || 12,
			hh :pad(H % 12 || 12),
			H :H,
			HH :pad(H),
			M :M,
			MM :pad(M),
			s :s,
			ss :pad(s),
			l :pad(L, 3),
			L :pad(L > 99 ? Math.round(L / 10) : L),
			t :H < 12 ? "a" : "p",
			tt :H < 12 ? "am" : "pm",
			T :H < 12 ? "A" : "P",
			TT :H < 12 ? "AM" : "PM",
			Z :utc ? "UTC" : (String(date).match(timezone) || [ "" ]).pop().replace(timezoneClip, ""),
			o :(o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
			S : [ "th", "st", "nd", "rd" ][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
		};

		return mask.replace(token, function($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default" :"ddd mmm dd yyyy HH:MM:ss",
	shortDate :"m/d/yy",
	mediumDate :"mmm d, yyyy",
	longDate :"mmmm d, yyyy",
	fullDate :"dddd, mmmm d, yyyy",
	shortTime :"h:MM TT",
	mediumTime :"h:MM:ss TT",
	longTime :"h:MM:ss TT Z",
	isoDate :"yyyy-mm-dd",
	isoTime :"HH:MM:ss",
	isoDateTime :"yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime :"UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames : [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ],
	monthNames : [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "January", "February", "March", "April", "May", "June",
			"July", "August", "September", "October", "November", "December" ]
};

function mergeObjectsShallow(){
	var d = {};
	for ( var i = 0; i < arguments.length; i++) {
		for ( var k in arguments[i]) {
			d[k] = arguments[i][k];
		}
	}
	return d;
}

function unserialize(s) {
	if (typeof (s) !== 'string') {
		return {};
	}
	var o = {};
	function _p(k, v) {
		o[decodeURIComponent(k)] = decodeURIComponent(v);
	}

	var j = s.replace(/\+|%20/g, ' ').split('&');
	for ( var i = 0; i < j.length; i++) {
		var p = j[i].split('=');
		_p(p[0], p[1]);
	}
	return o;
}

// For string convenience
String.prototype.stripWS = function(){
	return this.replace(/[ \s\n\r\t\f]+/g, ' ');
};
String.prototype.trim = function(){
	return this.replace(/^[ \s\n\r\t\f]+|[ \s\n\r\t\f]+$/, '');
};
String.prototype.unserialize = function(){
	return unserialize(String(this));
};
String.prototype.truncate = function(length, str, undef) {
	return (this.length > (length || 30)) ? this.slice(0, (length || 30) - (str === undef ? '...' : str).length) + (str === undef ? '...' : str) : (this + '');
};
String.prototype.capitalize = function(length, str, undef) {
	return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
};
// For date convenience...
Date.prototype.format = function(mask, utc) {
	return dateFormat(this, mask, utc);
};
Date.prototype.getUnixTime = function(){
	return Math.round(this.getTime() * 1000);
};
Date.prototype.getISOTime = function(){
	return this.format("UTC:yyyy-mm-dd'T'HH:MM:ss'Z'");
};
// For function convenience
Function.prototype = {};
Function.prototype.proxy = function(context){
	var fn = this;
	return function(){
		return fn.apply(context, Array.prototype.slice.call(arguments, 0));
	};
};

//misc functions
Ayi.Func.exist = function(o) {
	return !!(o || o === 0);
};
Ayi.Func.isArray = function(o) {
	return (typeof (o) === 'object' && o instanceof Array);
};
Ayi.Func.rand = function(l, h) {
	return Math.floor((Math.random() * ((h + 1) - l)) + l);
};
Ayi.Func.randArray = function(a) {
	return a[$.rand(0, a.length - 1)];
};
Ayi.Func.size = function(o) {
	var n, i = 0, l = o.length;
	if (l === undefined) {
		for (n in o) {
			i++;
		}
		return i;
	}
	return l;
};
Ayi.Func.empty = function(o) {
	return !Ayi.Func.exist(o) || Ayi.Func.size(o) === 0;
};
Ayi.Func.dateDistance = function(time) {
	var seconds = Math.abs(parseInt(time, 10) - Math.round(new Date().getTime() / 1000)), minutes = seconds / 60, hours = minutes / 60, days = hours / 24, years = days / 365;
	return seconds < 45 && "seconds" || seconds < 90 && "a minute" || minutes < 45 && ("%d minutes").replace(/%d/i, Math.round(minutes)) || minutes < 90 && "about an hour" || hours < 24 && ("about %d hours").replace(/%d/i, Math.round(hours)) || hours < 48 && "a day" || days < 30
	&& ("%d days").replace(/%d/i, Math.round(days)) || days < 60 && "about a month" || days < 365 && ("%d months").replace(/%d/i, Math.floor(days / 30)) || years < 2 && "about a year" || ("%d years").replace(/%d/i, Math.floor(years));
};

function ForEach(o, fn){
	var n, i = 0, l = o.length, undef;
	if (l === undef) {
		for (n in o) {
			if (fn.call(o[n], n, o[n]) === false) {
				break;
			}
		}
	} else {
		for ( var v = o[0]; i < l && fn.call(v, i, v) !== false; v = o[++i]) {
		}
	}
	return o;
}

//New javascript Template engine v2
function Template(template, data){
	var template = template || '';
	this.data = clone(data) || {};
	function clone(o, c){
		if (o == null || typeof(o) != 'object') {
			return o;
		}
		var c = c || new o.constructor();
		for (var k in o)
			c[k] = clone(o[k], c);
		return c;
	}
	this.set = function(k, v){
		if(k in this.data){
			delete(this.data[k]);
		}
		this.data[k] = v;
	};
	this.commit = function(data){
		this.data = clone(data) || {};
	};
	this.parseTemplate = function(){
		var x = template;
		for (var k in this.data) {
			x = x.replace(new RegExp('\\*\\*' + k + '\\*\\*', 'g'), ((this.data[k] == null) ? '' : this.data[k]));
		}
		delete(this.data);
		this.data = {};
		return x;
	};
}
String.prototype.template = function(data){
	return new Template(this, data).parseTemplate();
};

(function($){
	$.fn.inputtip = function(options){
		var defaults = {
						tipClass : 'tip'
						};
		var options = $.extend(defaults, options);

		return this.each(function(){
			var o = $(this);
			var tip = o.attr('title');

			if(tip != '' && o.val() == ''){
				o.val(tip);
				o.addClass(options.tipClass);
			}

			o.focus(function(){
				var v = o.val();
				if(v == '' || v == tip){
					o.removeClass(options.tipClass);
					o.val('');
				}
			});
			o.blur(function(){
				var v = o.val();
				if(v == '' || v == tip){
					o.addClass(options.tipClass);
					o.val(tip);
				} else {
					o.removeClass(options.tipClass);
				}
			});
		});
	};

	$.fn.clearBind = function(event){
		return this.unbind(event).attr('on' + event, '').bind(event, function(){
			return false;
		});
	};

	$.fn.tinytooltip = function(options){
		var defaults = {};
		var options = $.extend(defaults, options);
		return this.each(function(){
			var t = null, e = this;
			$('.tiny-tooltip', e).show().hide();
			$(this).hover(function(){
				clearTimeout(t);
				$('.tiny-tooltip', e).show();
			}, function(){
				t = setTimeout(function(){
					$('.tiny-tooltip', e).hide();
				}, 1000);
			});
		});
	};
})(jQuery);

(function($){$.fn.imageTooltip = function(o){
	var d = {
		x : -250,
		y : 10
	};
	var o = $.extend(d, o);

	function calcPosition(e, p){
		return e + p > 0 ? e + p : e;
	}

	return this.each(function() {
		var ele = $(this);
		var itag = $('.biguserpictag',this);
		ele.hover(function(e){
			$("body").append("<div id='popup-preview'></div>");
			$("#popup-preview").append(itag.show());
			$("#popup-preview")
				.css("top",(calcPosition(e.pageY, o.y)) + "px")
				.css("left",(calcPosition(e.pageX, o.x)) + "px")
				.fadeIn("fast");
	    },
		function(){
			$("#popup-preview").remove();
	    });
		ele.mousemove(function(e){
			$("#popup-preview")
				.css("top",(calcPosition(e.pageY, o.y)) + "px")
				.css("left",(calcPosition(e.pageX, o.x)) + "px");
		});
	});
};})(jQuery);

function reportSpammer() {
	var _self = this;
	this.appendString = 'reportSpammer';
	this.showModal = function(uid_them) {
		$($('#' + this.appendString + 'Modal_container').html()).dialog( {
			bgiframe : true,
			modal : true,
			width : 350,
			resizable : false,
			title : 'Report This User:',
			close : function(e, ui) {
				$(this).remove();
			},
			open : function(e, ui) {
				$('input[name=reportSpammer_uid_them]', this).val(uid_them);
				$('input:checkbox', this).attr('checked', '');
				$('form', this).submit( function() {
					return _self.send(this);
				});
			},
			buttons : {
				Cancel : function() {
					$(this).dialog('close');
				},
				Submit : function() {
					$('form', this).submit();
				}
			}
		});
		return false;
	};

	this.send = function(form) {
		formData = $(form).serialize();
		$.ajax( {
			url : 'controller.php?action=' + this.appendString,
			data : formData,
			type : 'POST',
			dataType : 'json',
			error : function() {
			},
			success : function(reply) {
				$('.rsm').dialog('close');
				alert(reply.msg);
			}
		});
		return false;
	};
}

function reportBugs() {
	var _self = this;
	this.appendString = 'reportBugs';
	this.showModal = function() {
		$($('#' + this.appendString + 'Modal_container').html()).dialog( {
			bgiframe : true,
			modal : true,
			width : 450,
			resizable : false,
			title : 'Send Feedback (Report a bug, Request a feature, etc.):',
			close : function(e, ui) {
				$(this).remove();
			},
			open : function(e, ui) {
				$('input[name=' + _self.appendString + '_subject]', this).val('Feedback: ');
				$('textarea[name=' + _self.appendString + '_body]', this).val('');
				$('input[name=' + _self.appendString + '_subject]', this).focus();
				$('form', this).submit( function() {
					return _self.send(this);
				});
			},
			buttons : {
				Cancel : function() {
					$(this).dialog('close');
				},
				Submit : function() {
					$('form', this).submit();
				}
			}
		});
		return false;
	};

	this.send = function(form) {
		var formData = $(form).serialize().unserialize();
		formData.reportBugs_page = window.location.toString();
		formData.reportBugs_browserCookie = ((navigator.cookieEnabled) ? 'yes' : 'no');
		formData.reportBugs_resolution = window.screen.width + 'x' + window.screen.height;

		$.ajax( {
			url : 'controller.php?action=' + this.appendString,
			data : formData,
			type : 'POST',
			dataType : 'json',
			success : function(reply) {
				$('.rbm').dialog('close');
				if (reply.code == true) {
					alert("Bug reported, Thank you!");
				}
			}
		});
		return false;
	};
}

function reportBugsGlobal() {
	var _self = this;
	this.appendString = 'reportBugsGlobal';
	this.showModal = function() {
		$($('#' + this.appendString + 'Modal_container').html()).dialog( {
			bgiframe : true,
			modal : true,
			width : 450,
			resizable : false,
			title : 'Send Feedback (Report a bug, Request a feature, etc.):',
			close : function(e, ui) {
				$(this).remove();
			},
			open : function(e, ui) {
				$('input[name=' + _self.appendString + '_name]', this).val('');
				$('input[name=' + _self.appendString + '_email]', this).val('');
				$('input[name=' + _self.appendString + '_subject]', this).val('Feedback: ');
				$('textarea[name=' + _self.appendString + '_body]', this).val('');
				$('input[name=' + _self.appendString + '_name]', this).focus();
				$('form', this).submit( function() {
					return _self.send(this);
				});
			},
			buttons : {
				Cancel : function() {
					$(this).dialog('close');
				},
				Submit : function() {
					$('form', this).submit();
				}
			}
		});
		return false;
	};

	this.send = function(form) {
		var formData = $(form).serialize().unserialize();
		formData.rbg_page = window.location.toString();
		formData.rbg_browserCookie = ((navigator.cookieEnabled) ? 'yes' : 'no');
		formData.rbg_resolution = window.screen.width + 'x' + window.screen.height;

		$.ajax( {
			url : 'controller.php?action=' + this.appendString,
			data : formData,
			type : 'POST',
			dataType : 'json',
			success : function(reply) {
				if (reply.code == 0) {
					alert(reply.message);
				} else {
					alert("Bug reported, Thank you!");
					$('.rbgm').dialog('close');
				}
			}
		});
		return false;
	};
}

function reportPhotos(uid_them, pictures_json){
	var pictures = pictures_json || [];
	var uid_them = uid_them;
	var _self = this;
	this.append_string = 'reportPhotos';

	this.showModal = function(){
		if(pictures.length == 0){
			return false;
		}

		$($('#' + this.append_string + 'Modal_container').html()).dialog( {
			bgiframe : true,
			modal : true,
			width : 500,
			resizable : false,
			title : 'Report Inappropriate Photos:',
			close : function(e, ui) {
				$(this).remove();
			},
			open : function(e, ui) {
				$('input[name=reportPhotos_uid_them]', this).val(uid_them);
				var img_html = '';
				for(var i = 0; i < pictures.length; i++){
					img_html += '<div class="image-checkbox"><span class="img_cont"><span></span><img src="' + pictures[i].url + '" alt="" /></span><br /><input type="checkbox" name="reportPictures_id[]" value="' + pictures[i].image_id + '" /></div>';
				}
				$('.photo_area', this).html(img_html);
				$('input[type=checkbox]', this).change(function(){
					$(this).parents('.image-checkbox').click();
				});

				$('form', this).submit( function() {
					return _self.send(this);
				});
			},
			buttons : {
				Cancel : function() {
					$(this).dialog('close');
				},
				Submit : function() {
					$('form', this).submit();
				}
			}
		});
		return false;
	};

	this.send = function(form){
		var formData = $(form).serialize();

		$.ajax( {
			url : 'controller.php?action=' + this.append_string,
			data : formData,
			type : 'POST',
			dataType : 'json',
			error : function() {
			},
			success : function(reply) {
				$('.rpsm').dialog('close');
				alert(reply.msg);
			}
		});
		return false;
	};

	$('.image-checkbox').live('click', function(){
		var checkbox = $('input[type=checkbox]', this).get(0);
		if(checkbox.checked){
			checkbox.checked = false;
			$(this).removeClass('checked-off');
		} else {
			checkbox.checked = true;
			$(this).addClass('checked-off');
		}
	});
}

function fullProfile(link) {
	var p = this;
	this.appendString = 'fullProfile';

	this.showModal = function(uid, modifier) {
		this.getProfile(uid, modifier);
		return false;
	};

	this.getProfile = function(uid, modifier) {
		var formData = 'uid=' + uid;
		var modifier = modifier || '';
		if(link){
			$(link).addClass('active-ldr');
		}

		$.ajax( {
			url :'controller.php?action=' + this.appendString,
			data :formData,
			type :'POST',
			dataType :'json',
			error : function() {
			},
			success : function(reply) {
				if(link){
					$(link).removeClass('active-ldr');
				}
				if (reply.code == 0) {
					var t = new Template($('#fullProfileModal_template' + modifier).html());
					t.commit(reply.profile);
					t.set('rn_comma', (reply.profile.region_narrow != '' && reply.profile.region_broad != '') ? ', ' : '');
					t.set('rb_comma', (reply.profile.region_narrow != '' || reply.profile.region_broad != '') ? ', ' : '');
					t.set('userpicurl', '<img src="' + reply.profile.userpicurl + '" alt="" border="0" />');
					t.set('userpictag', reply.profile.userpictag);
					t.set('username', reply.profile.vanity_name);
					var photos = '';
					for(var photo_id in reply.photos){
						try {
							photos += '<a href="#" class="image-changer" rel="' + reply.photos[photo_id].d.url + '"><img src="' + reply.photos[photo_id].q.url + '" alt="" /></a>';
						} catch (error){}
					}
					t.set('additional_photos', photos);

					$(t.parseTemplate()).dialog({
						bgiframe :true,
						modal:true,
						resizable :false,
						width: 820,
						position: ['center','center'],
						title: reply.profile.vanity_name + ' ' + reply.profile.status,
						close : function(e, ui) {
							$(this).remove();
						},
						open: function(e, ui){
							var _self = this;

							$('#modal-tabs div.mtab-node', _self).hide();
							$('#modal-tabs div#' + reply.profile.uid_them + '-mtab-1', _self).show(); // Show the first div
							$('#modal-tabs ul#mtablist li#' + reply.profile.uid_them + '-first', _self).addClass('active'); // Set the class of the first link to active
							$('#modal-tabs ul#mtablist li a').click(function(){ //When any link is clicked
								$('#modal-tabs ul#mtablist li').removeClass('active'); // Remove active class from all links
								$(this).parent().addClass('active'); //Set clicked link class to active
								var currentTab = $(this).attr('href'); // Set variable currentTab to value of href attribute of clicked link
								$('#modal-tabs div.mtab-node').hide(); // Hide all divs
								$(currentTab).show(); // Show div with id equal to variable currentTab
								return false;
							});
							$('a.image-changer', _self).click(function(){
								var new_img_url = $(this).attr('rel');
								if(new_img_url != ''){
									$('#pic img', _self).attr('src', new_img_url);
								}
								return false;
							});

							if (reply.photos.length == 0) {
								$('#fprof-photo-album-pop-'+reply.profile.uid_them).hide();
								$('#no-photos-fp-pop-'+reply.profile.uid_them).show();
							}
							if(reply.gifts.length == 0) {
								$('#fprof-trophy-case-pop-'+reply.profile.uid_them).hide();
								$('#no-gifts-fp-pop-'+reply.profile.uid_them).show();
							} else {
								(new Ayi.Gifts()).buildProfileTrophyCase(reply.gifts,$('#profile-trophy-case-'+reply.profile.uid_them));
							}

						}
					});
				} else {
					$('<div>This account is no longer active</div>').dialog({
						bgiframe :true,
						modal:true,
						resizable :false,
						width: 820,
						title: '',
						close : function(e, ui) {
							$(this).remove();
						},
						open: function(e, ui){
						}
					});
				}
			}
		});
		return false;
	};
}

function AppLabeler(element){
	var _self = this;
	var element = element;

	var _label = function(element, data, e, successCallback){
		var _block = $(element).parents('.listItemNew').get(0);

		return _AppLabeler(data, function(){
			$(element).attr({onclick:'return false'}).html('Updating...').unbind('click').click(function(){
				return false;
			});
		}, function(reply){
			if(successCallback){
				successCallback.call(element, reply);
			} else {
				$(element).html("<span style='font-weight: bold'>Done!</span>");
			}
		});
	};

	var _remove = function(element, data, e, successCallback){
		var _block = $(element).parents('.listItemNew').get(0);

		return _AppLabeler(data, function(){
			$(element).attr({onclick:'return false'}).html('Updating...').unbind('click').click(function(){
				return false;
			});
		}, function(reply){
			if(successCallback){
				successCallback.call(element, reply);
			} else {
				$(_block).hide(500);
			}
		});
	};

	var _extract_data = function(element){
		var data = {};
		data.uid_them = $(element).attr('l:uid_them') || '';
		data.label_action = $(element).attr('l:label') || '';
		data.privacy = $(element).attr('l:privacy') || '';
		data.ls_data = $(element).attr('l:ls_data') || '';
		data.like_state = $(element).attr('l:like_state') || '';
		data.Label_type = $(element).attr('l:type') || '';
		return data;
	};

	var _AppLabeler = function(data, beforeSendCallback, successCallback, errorCallback){
		var form_data = data || {};
		if(beforeSendCallback){
			beforeSendCallback();
		}
		$.ajax( {
			url :'controller.php?action=AppLabeler',
			data :form_data,
			type :'POST',
			dataType :'json',
			error : function() {
				if(errorCallback){
					errorCallback();
				}
			},
			success : function(reply) {
				if (reply.code == 0 || reply.code == 1) {
					if(successCallback){
						successCallback(reply);
					}
				} else {
					if(errorCallback){
						errorCallback(reply);
					}
				}
			}
		});
		return false;
	};

	this.label = function(successCallback, e){
		var data = _extract_data(element);

		switch(data.label_action){
			case 'labelStranger':
			case 'switchToNo':
				return _label(element, data, e, successCallback);
				break;
			case 'removeUser':
				return _remove(element, data, e, successCallback);
				break;
			case 'labelAwaiting':
				return _label(element, data, e, successCallback);
				break;
			case 'blockUser':
				if (!confirm('Block this user? This person will no longer be able to contact you.')) {
					return false;
				}
				return _label(element, data, e, successCallback);
				break;
			default:
				return false;
		}
		return false;
	};
}

function PostalCodeTester(localityCountry){
	this.localityCountry = localityCountry;
	this.alphabetReg = new RegExp('[a-z]', 'i');
	this.isDigit = function(value){
		return (value == (parseInt(value) + ""));
	};
	this.isAlphabet = function(value){
		return this.alphabetReg.test(value);
	};
	this.test = function(value){
		var return_val = false;
		var substring;
		switch (this.localityCountry) {
			case 1: // US
				return_val = (this.isDigit(value) && (value.length < 6));
				break;
			case 2: // CA
				value = value.replace(/\s/, '');
				if (value.length > 6) {
					return_val = false;
				}
				else {
					return_val = true;
					for (var x = 0; x < value.length; x++) {
						substring = value[x];
						if (x % 2 == 0) {
							this_val = this.isAlphabet(substring);
						}
						else {
							this_val = this.isDigit(substring);
						}
						return_val = return_val && this_val;
					}
				}
				break;
			case 62: // DK
				break;
			case 77: // FI
				break;
			case 78: // FR
				break;
			case 214: // SE
				break;
			case 226: // TR
				break;
			default:
				break;
		}
		return return_val;
	};
}

function Cropper(imgId, type, redir, errorId, buttonId, errorMessage, callback){
	this.imgInnerPadding = 10;
	this.squareSide = 0;
	this.x = 0;
	this.y = 0;
	this.w = 0;
	this.h = 0;
	this.imgId = imgId;
	this.errorId = errorId;
	this.buttonId = buttonId;
	this.type = type;
	this.redir = redir;
	this.errorMessage = errorMessage;
	this.callback = (typeof(callback) == 'function') ? callback : false;

	this.crop = function(){
		var parent = this;
		if (parseInt(this.w) && parseInt(this.h)) {
			formData = 'redir=' + this.redir + '&adt=' + this.adt + '&type=' + this.type + '&x=' + this.x + '&y=' + this.y + '&w=' + this.w + '&h=' + this.h;
			$.ajax({
				url: 'controller.php?action=crop',
				data: formData,
				type: 'POST',
				dataType: 'json',
				error: function(){
				},
				success: function(reply){
					if (reply.code == 0) {
						if (parent.callback) {
							parent.callback(reply);
						}
						else {
							top.location = 'index.php?action=' + reply.redir;
						}
					}
					else {
						$('#' + parent.errorId).html(reply.msg);
					}
				}
			});
		}
		else {
			alert(this.errorMessage);
		}
		return false;
	};

	/*
	this.createModal = function(img_url, adt){
		this.adt = adt;
		var str = '<div id="cropperModal"><h1>Crop your photo!</h1>' + '<span id="' + this.errorId + '"></span>' + '<p>Use the crosshairs to crop your photo to highlight that beautiful mug of yours so we can use it to show you off around the site.</p><div style="position:relative;"><img src="' + img_url + '" id="' + this.imgId + '" /></div>' + '<br /><input type="button" value="Complete Upload" id="cropButton" /></div>'
		$.modal(str, {containerCss: { height: 550 }});
		var parent = this;
		$('#' + this.imgId).load(function(){
			parent.prepareCrop();
		});
	};*/

	this.createModal = function(img_url, adt){
		this.adt = adt;
		$.modal('<div id="cropperModal"><h1>Crop your photo!</h1>' + '<span id="' + this.errorId + '"></span>' +
		'<p style="margin-bottom: 5px">Use the crosshairs to crop your photo to highlight that beautiful face of yours so we can use it to show you off around the site and find you more matches.</p><div style="position:relative;"><img src="' +
		img_url +
		'" id="' +
		this.imgId +
		'" /></div>' + '<br /><input type="image" src="http://images.static.areyouinterested.com/site/update.png" width="109" height="25" id="' + this.buttonId + '" />' +
		'</div>', {containerCss: { height: 550 }});
		var parent = this;
		$('#' + this.imgId).load(function(){
			parent.prepareCrop();
		});
	};

	this.prepareCrop = function(){
		var imgWidth = $('#' + this.imgId).width();
		var imgHeight = $('#' + this.imgId).height();
		var parent = this;

		this.squareSide = ((imgWidth > imgHeight) ? imgHeight : imgWidth) - this.imgInnerPadding;

		var jCropper = $.Jcrop('#' + this.imgId, {
			aspectRatio: 1,
			sideHandles: false,
			onSelect: function(c){
				parent.x = c.x;
				parent.y = c.y;
				parent.w = c.w;
				parent.h = c.h;
			},
			setSelect: [parent.imgInnerPadding, parent.imgInnerPadding, parent.squareSide, parent.squareSide]
		});
		jCropper.setSelect([this.imgInnerPadding, this.imgInnerPadding, this.squareSide, this.squareSide]);
		this.x = this.imgInnerPadding;
		this.y = this.imgInnerPadding;
		this.w = this.squareSide;
		this.h = this.squareSide;
		$('#' + this.buttonId).click(function(){
			parent.crop();
		});
	};
}

// this is used when you're JUST uploading photo
function ajaxFileUpload(elemName) {
	submitAjaxForm(elemName);
	return false;
}
// these are the functions that actually perform the AJAXy submit and handle the response
function submitAjaxForm(elemName) {
	AIM.submit(document.getElementById(elemName), {
		'onStart' :ajaxFileStart,
		'onComplete' :ajaxFileComplete
	});
}
function ajaxFileStart() {
	$('#loading').show(0);
}
function ajaxFileComplete(response) {
	reply = eval('(' + response + ')');
	if (reply.code == 0) {
		if (reply.adt > 0) {
			cropper.createModal(reply.img_url, reply.adt);
		} else {
			var qs = (reply.qs || '').replace(/&amp;/g, '&');
			facebook.getPermission("email", function() {
				top.location = 'index.php?action=email_inviter_reg&' + qs;
			});
		}
	} else {
		$(".reg_error").html('');
		for ( var field in reply.errors) {
			$("#" + field + "_error").html(reply.errors[field]);
		}
	}
}

function goToPage(page) {
	var formData = 'page=' + page_adts[page];

	$.ajax( {
		url :'controller.php?' + (document.location.toString().substring(document.location.toString().indexOf('?') + 1).replace(/\#.*$/, '')),
		data :formData,
		type :'POST',
		dataType :'json',
		error : function() {
		},
		success : function(reply) {
			cur_page = page;
			outputBlocks(reply);
		}
	});
	return false;
}

function createPaginate(prev, next) {
	$('a.prevPage').unbind('click');
	if (prev == true) {
		$('a.prevPage').removeClass('disablePageLink').click( function() {
			return goToPage((parseInt(cur_page) - 1));
		});
	} else {
		$('a.prevPage').addClass('disablePageLink').click( function() {
			return false;
		});
	}
	$('a.nextPage').unbind('click');
	if (next == true) {
		$('a.nextPage').removeClass('disablePageLink').click( function() {
			return goToPage((parseInt(cur_page) + 1));
		});
	} else {
		$('a.nextPage').addClass('disablePageLink').click( function() {
			return false;
		});
	}
}

function ACAttachAutoComplete(textElem, valueElem, localityCountryElem, postalCodeTesterObject, dontAutoComplete, showHelp) {
	if (!dontAutoComplete) {
		textElem.autocomplete("controller.php", {
			extraParams : {
				'action' :'getLocationsByLocalityCountryAndTitle',
				'locality_country' :localityCountryElem.val()
			},
			maxItemsToShow :25,
			autoFill :true,
			delay :200,
			scroll: true,
			minChars :2,
			mustMatch :false,
			matchSubset :false,
			matchContains :false,
			cacheLength :100,
			showHelp : showHelp && true,
			selectFirst :true,
			alwaysSelect :true,
			cancelAutoCompleteTest : function(value) {
				var return_val = postalCodeTesterObject.test(value);
				if (return_val) {
					valueElem.val('');
				}
				return return_val;
			}
		});
		textElem.result(function(event, data, formatted){
			if(typeof(data[1]) != 'undefined'){
				valueElem.val(data[1]);
			}
		});
	}
}

function ACCollegeAutoComplete(textElem, valueElem) {
	textElem.autocomplete("controller.php", {
		extraParams : {
			'action' :'getCollegesByTitle'
		},
		maxItemsToShow :15,
		autoFill :false,
		delay :200,
		minChars :2,
		mustMatch :false,
		matchSubset :false,
		matchContains :true,
		cacheLength :100,
		selectFirst :true,
		alwaysSelect :true
	});
	textElem.result(function(event, data, formatted){
		if(typeof(data[1]) != 'undefined'){
			valueElem.val(data[1]);
		}
	});
}

function UpdateLocalityRegionNarrow(localityCountry) {
	formData = 'locality_country=' + localityCountry;

	$.ajax( {
		url :'controller.php?action=getLocalityCountry',
		data :formData,
		type :'POST',
		dataType :'json',
		error : function() {
		},
		success : function(reply) {
			if (reply.code == 0) {
				locality_country_user_input = parseInt(reply.data['user_input']);
				postalCodeTester.localityCountry = reply.data['location_id'];
				$('#locality_region_narrow_label').html(reply.data['locality_region_narrow_label']);
				$('#locality_region_narrow').val(0);
				$('#code_container').html('<input type="text" name="code" id="code" value="">');
				ACAttachAutoComplete($("#code"), $('#locality_region_narrow'), $('#locality_country'), postalCodeTester, (locality_country_user_input == 1 ? true : false));
			} else {
				// cry about it
			}
		}
	});
	return false;
}

function registerModal(closable, height, qs) {
	var _self = this;
	this.closable = closable || false;
	this.height = height || 500;
	this.hideHideables = false;
	this.showModal = function(title, closable) {
		var reg_form = $('#registerFormModal_container').html();
		$(reg_form).dialog( {
			bgiframe : true,
			modal : true,
			width : 640,
			resizable : false,
			title : title || 'Register',
			beforeclose : function(){
				return _self.closable;
			},
			close : function(e, ui) {
				$(this).remove();
			},
			open : function(e, ui){
				var $self = this;
				var form = $('form', $self).get(0);
				$(form).submit(function(){
					_self.createAccount(this);
					return false;
				});
				if(_self.hideHideables){
					$('.registration_hideable', $self).hide();
				}else{
					$('.registration_hideable', $self).show();
				}
			}
		});
		return false;
	};
	this.closeModal = function(){
		$('.registerFormModal').dialog('destroy');
	};
	this.createAccount = function(form){
		copybb(form,0);
		var form_data = $(form).serialize();
		$.ajax({
			url: $(form).attr('action'),
			data: form_data,
			type: 'POST',
			dataType: 'json',
			error: function() {},
			success: function(reply) {
				if(reply.code==0){
					top.location='/index.php?action=register2&qs='+qs + (reply.qs ? '&' + reply.qs : '');
				}else if(reply.code==17 && typeof(reply.errors.fb_error)!='undefined'){
					facebook.login();
				}else{
					$(".error", form).html('');
					for(var field in reply.errors){
						$("#"+field+"_error", form).html(reply.errors[field]);
					}
				}
			}
		});
		return false;
	}
}

function requestPasswordResetModal() {
	this.appendString = 'requestPasswordResetForm';
	this.showModal = function() {
		$.modal($('#' + this.appendString + 'Modal'), {containerCss: {height: 200}});
		return false;
	};
}
function loginModal(){
	this.appendString = 'loginForm';
	this.showModal = function() {
		$($('#' + this.appendString + 'Modal_container').html()).dialog( {
			bgiframe : true,
			modal : true,
			width : 620,
			resizable : false,
			title : 'Login',
			close : function(e, ui) {
				$(this).remove();
			},
			buttons : {
				Cancel : function() {
					$(this).dialog('close');
				},
				Submit : function() {
					$('form', this).submit();
				}
			}
		});
		return false;
	};
}

function log_stats_master(stat, bucket, version, device, extras){
	var formData = {
		stat: stat,
		bucket: bucket || 0,
		version: version || '',
		device: device || 0,
		extras: extras || ''
	};
	$.ajax({
		url: 'controller.php?action=log_stats_master',
		data: formData,
		type: 'POST',
		dataType: 'json',
		error: function(){},
		success: function(reply){
			if (reply.code == 0) {
				//it worked!
			}
		}
	});
	return false;
}

function logout(){
	top.location = 'controller.php?action=logout&rel=0';
	return false;
}

function FBLogin(uid,showModal){
	var showModal = showModal || false;
	var formData = 'mode=ajax&device=2&qs='+qs;
	$.ajax({
		url: 'controller.php?action=login',
		data: formData,
		type: 'POST',
		dataType: 'json',
		error: function(){},
		success: function(reply){
			if (reply.code == 0) {
				top.location = reply.redir;
			}else{
				if (reply.code==28){
					$('.facebook_reminder').html('Thanks for connecting with Facebook. Continue registering below.');
					//this is called when they've connected but don't have an account
					if(showModal){register_form.showModal();}
				}else if (reply.code==37){
					$('.facebook_reminder').html('Thanks for connecting with Facebook. Continue registering below.');
					//this is called when they've connected, but only installed previously
					register_form.showModal();
				}else if (reply.code==35){
					$('.facebook_reminder').html('Thanks for connecting with Facebook. Continue registering below.');
					//they've connected, have an unfinished account
					register_form.hideHideables=true;
					register_form.showModal(null,true);
				}
			}
		}
	});
	return false;
}

function showLoggedInFBUser(uid){
	var containerElem=$('#profilelink_top');
	containerElem.html('<span id="fb_identity_profilepic" uid="'+uid+'" linked="false" facebook-logo="true" width="16px" height="16px" style="width:16px;height:16px;"></span> <span id="fb_identity_name" linked="false" useyou="false" uid="'+uid+'"></span>');
	var profilePicContainer=$('#fb_identity_profilepic');
	var nameContainer=$('#fb_identity_name');
	FB.XFBML.Host.addElement(new FB.XFBML.ProfilePic(profilePicContainer[0]));
	FB.XFBML.Host.addElement(new FB.XFBML.Name(nameContainer[0]));
}

function FBDelayBatch(callback){
	clearTimeout(facebook_timeout);
	facebook_timeout = setTimeout(function(){callback();},100);
}

//Facebook Object
function faceBook(api_key,hasPreviouslyConnected,ifUserConnectedCallback,ifUserNotConnectedCallback){

	//defined variables
	this.hasPreviouslyConnected = hasPreviouslyConnected;
	this.uid = 0;
	this.statusText = '';
	this.us_attachment = '';
	//publish stream variables
	this.ps_user_message = null;
	this.ps_attachment = null;
	this.ps_action_links = null;
	this.ps_target_id = null;
	this.ps_user_message_prompt = null;
	this.ps_callback = null;
	this.ps_auto_publish = null;
	this.ps_actor_id = null;

	var me = this;


	//what to call if they are connected and we want to do something specific
	//callback needs to have one parameter, which is the uid of the logged in user!
	this.ifUserConnected = function(){
		FB.ensureInit(function() {
			me.uid=FB.Connect.get_loggedInUser();
			if(typeof(ifUserConnectedCallback)=='function'){
				ifUserConnectedCallback(me.uid);
			}
			FB.XFBML.Host.refresh();
		});
	};

	//what to call if they haven't connected and we want to do something specific
	this.ifUserNotConnected = function(){
		FB.ensureInit(function() {
			if(typeof(ifUserNotConnectedCallback)=='function'){
				ifUserNotConnectedCallback(me.hasPreviouslyConnected);
			}
		});
	};

	//logging out
	this.logOut = function(logOutCallback){
		FB.ensureInit(function() {
			FB.Connect.logout(function(answer){
				if(typeof(logOutCallback)=='function'){
					logOutCallback();
				}
				return false;
			});
		});
	};

	//multi friend inviter
	this.showMultiFriendSelector = function(postback, content, action_text, title, method, show_border, opencallback, closecallback){
		var container = '<div></div>';

		var postback = postback || 'http://www.areyouinterested.com/';

		var callback_action = /action=([A-Za-z0-9_]+)/.exec(document.location.href);
		if(callback_action != null && callback_action[1]){
			postback += ((postback.indexOf('?') >= 0) ? '&' : '?') + 'callback_action=' + callback_action[1];
		}

		var content = content || "&lt;fb:req-choice url='http:\/\/www.areyouinterested.com\/' label='Check Out AreYouInterested.com!' \/&gt;";
		var action_text = action_text || 'Ask your friends to check out AreYouInterested.com!';
		var method = method || 'post';
		var show_border = show_border || 'false';

		var title = title || 'Invite Friends!';


		var fbstring =	'<script type="text/fbml"><fb:fbml>' +

						'<fb:request-form action="' + postback + '" method="' + method + '" invite="true" type="AreYouInterested.com" content="' + content + '">' +
						'<div style="position:relative"><fb:multi-friend-selector showborder="' + show_border + '" selected_rows="10" unselected_rows="10" condensed="true"></div>' +
						'<div style="text-align:center"><fb:request-form-submit /></div>';
						'</fb:request-form></fb:fbml><\/script>';

		FB.Connect.requireSession(function(){
			$(container).dialog({
				bgiframe :true,
				modal:true,
				width: 700,
				height: 550,
				resizable :false,
				title :title,
				close : function(e, ui) {
					if(closecallback){
						closecallback();
					}
					$(this).remove();
				},
				open: function(e, ui){
					$(this).append(fbstring);
					var _this = this;
					FB.XFBML.Host.addElement(new FB.XFBML.ServerFbml(_this));
					if(opencallback){
						opencallback();
					}
				}
			});
		}, false);
		return false;
	};

	//status functionality
	this.setStatusText = function(status_text){
		this.statusText = status_text;
	};
	this.updateStatusGrantCallback = function(granted){
		if(granted){
			me.updateStatusSend();
		}else{
			//they didn't give us permission to update status!
		}
	};
	this.updateStatusSend = function(){
		var action_links = null;
		if (this.us_attachment != null) {
			action_links = [{ "text": "Visit AreYouInterested", "href": "http://www.areyouinterested.com/?ref=ff_usss"}];
		}

		FB.Connect.streamPublish(this.statusText+' on http://www.AreYouInterested.com',this.us_attachment,action_links,'','',function(answer){
			log_stats_master('fb_connect_status');
		},true);
	};
	this.updateStatus = function(status_text, attachment){
		this.setStatusText(status_text);
		this.us_attachment = attachment || null;
		FB.ensureInit(function() {
			FB.Connect.requireSession(function(){
				FB.Facebook.apiClient.users_hasAppPermission('publish_stream',function(answer){
					if(answer==0){
						FB.Connect.showPermissionDialog('publish_stream',me.updateStatusGrantCallback);
					}else{
						me.updateStatusSend();
					}
				});
			},false);
		});
		return false;
	};

	//publish stream
	this.publishSteamGrantCallback = function(granted){
		if(granted){
			me.publishSteamSend();
		}
	};
	//publish stream
	this.publishSteamSend = function(){
		FB.Connect.streamPublish(this.ps_user_message,this.ps_attachment,this.ps_action_links,this.ps_target_id,this.ps_user_message_prompt,me.ps_callback,this.ps_auto_publish);
	};
	//publish stream
	this.publishStream = function(user_message, attachment, action_links, target_id, user_message_prompt, callback, auto_publish, actor_id) {
		this.ps_user_message = user_message;
		this.ps_attachment = attachment;
		this.ps_action_links = action_links;
		this.ps_target_id = target_id;
		this.ps_user_message_prompt = user_message_prompt;
		this.ps_callback = callback;
		this.ps_auto_publish = auto_publish;
		this.ps_actor_id = actor_id;
		FB.ensureInit(function() {
			FB.Connect.requireSession(function(){
				FB.Facebook.apiClient.users_hasAppPermission('publish_stream',function(answer){
					if(answer==0){
						FB.Connect.showPermissionDialog('publish_stream',me.publishSteamGrantCallback);
					}else{
						me.publishSteamSend();
					}
				});
			},false);
		});
		return false;
	};
	//retrieve friends with app installed
	this.retrieveAppFriends = function(columns, callback) {
		me.ifConnected(
			function() {
				FB.Facebook.apiClient.fql_query('SELECT '+ columns.join(', ')+' FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1="'+facebook.uid+'") AND is_app_user = "true" ORDER BY first_name',function(answer) {
					if (callback) {
						callback(answer);
					}
				})
			}
		);
		return false;
	};

	//get any facebook permission
	this.getPermission = function(permission_type, callback){
		FB.ensureInit(function() {
			FB.Connect.ifUserConnected(function(){
				FB.Facebook.apiClient.users_hasAppPermission(permission_type,function(answer){
					if(answer==0){
						FB.Connect.showPermissionDialog(permission_type, callback);
					} else {
						callback();
					}
				});
			},callback);
		});
		return false;
	};
	this.ifConnected = function(hasPermissionCallback,noPermissionCallback){
		FB.ensureInit(function() {
			FB.Connect.ifUserConnected(function(){
				if(typeof(hasPermissionCallback)=='function'){hasPermissionCallback();}
			},function(){
				if(typeof(noPermissionCallback)=='function'){noPermissionCallback();}
			});
		});
		return false;
	};
	this.login = function(){
		FB.ensureInit(function() {
			FB.Connect.requireSession(function(){
				FBLogin(me.uid,true);
			},false);
		});
	};
	this.register = function(){
		FB.ensureInit(function() {
			FB.Connect.requireSession(function(){
				$('.facebook_reminder').html('Thanks for connecting with Facebook. Continue registering below.');
				register_form.closeModal();
				register_form.showModal();
			},false);
		});
	};
	this.register_friend = function(){
		FB.ensureInit(function() {
			FB.Connect.requireSession(function(){
				$('.facebook_reminder').html('Great! Now that we\'re connected your Facebook account, please fill out the information below so we can help you find potential matches!');
			},false);
		});
	};
	this.attachFBML = function(){
		FB.ensureInit(function() {
			$('.fbml').each(function(i){
				$(this).removeClass('fbml');
				if($(this).hasClass('fbprofilepic')){
					$(this).removeClass('fbprofilepic');
					FB.XFBML.Host.addElement(new FB.XFBML.ProfilePic(this));
				}
				if($(this).hasClass('fbname')){
					$(this).removeClass('fbname');
					FB.XFBML.Host.addElement(new FB.XFBML.Name(this));
				}
			});
		});
	};
	this.getFriends = function(callback){
		FB.Connect.requireSession(function(){
			FB.Facebook.apiClient.friends_get(null, callback);
		});
		return false;
	};
	this.generateProfilePic = function(fbuid, height, width){
		var height = height || 50;
		var width = width || 50;
		var size = 'q';
		return '<span class="fbprofilepic" size="' + size + '" linked="false" width="' + width + 'px" height="' + height + 'px" uid="' + fbuid + '"></span>';
	};

	FB_RequireFeatures(["XFBML"], function(){
		FB.init(api_key, "/3rdparty/facebook/xd_receiver.htm",{"ifUserConnected":me.ifUserConnected,"ifUserNotConnected":me.ifUserNotConnected});
	});
}

function parseISOTime(iso8601) {
      var s = $.trim(iso8601);
      s = s.replace(/-/,"/").replace(/-/,"/");
      s = s.replace(/T/," ").replace(/Z/," UTC");
      s = s.replace(/([\+-]\d\d)\:?(\d\d)/," $1$2"); // -04:00 -> -0400
      return Math.floor(new Date(s).getTime() / 1000);
}

function email_validate(email) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   if(reg.test(email) == false) {
      return false;
   }
   return true;
}


///////////////GIFTS////////////////

Ayi.Gifts = Ayi.Class({
	buildProfileTrophyCase : function(gifts, container) {
		var gift_count = gifts.length || 0;
		var self = this;
		ForEach(gifts, function(k, v) {
			container.append(self.buildGift(v));
		});
	},
	buildGift : function(gift) {
		var self = this;
		var a = $('<a>').attr('href','#').click(function(){
			self.previewGift(gift.gift_id);
			return false;
		});
		var img = $('<img>').attr('src',gift.url_t);
		a.append(img);
		return a;
	},
	previewGift : function(gift_id, buttons) {
		$('<div>').dialog( {
			modal : false,
			width : 500,
			position : ["center", 100],
			dialogClass : 'gft-preview-frame-gftsdr',
			open : function() {
				var content = $('<iframe frameborder="0" height="495" width="460" marginheight="0" marginwidth="0" scrolling="no"></iframe>').attr({
					'src': 'http://www.areyouinterested.com/scripts/showGift.php?g=' + gift_id
				}).css('height','495px');
				$(this).append(content);
			},
			buttons : buttons || {
				'Ok' : function() {
					$(this).dialog('close');
					return false;
				}
			}
		});
		return false;
	}
});

function InviteFriends(form, ref, callback) {
	$.ajax({
		url: 'controller.php?action=FriendInvite',
		data: form.serialize() + '&ref='+ref,
		type: 'POST',
		dataType: 'json',
		error: function(){},
		success: function(reply){
			if (callback) {
				callback(reply);
			}
		}
	});
}

function RetrieveEmailFriends(provider, form, ref, email_provider, callback) {
	$.ajax({
		url: 'controller.php?action='+provider,
		data: form.serialize() + '&ref='+ref+'&email_provider='+email_provider,
		type: 'POST',
		dataType: 'json',
		error: function(){},
		success: function(reply){
			if (callback) {
				callback(reply);
			}
		}
	});
}

Ayi.FriendInviteAuth = Ayi.Class({
	popup_window:null,
    interval:null,
    interval_time:80,
    waitForPopupClose: function(close_callback) {
         if(this.isPopupClosed()) {
              this.destroyPopup();
              if (this.close_callback) { this.close_callback(); }
              //window.location = location.href + '&' + this.reload_to;
         }
    },
    destroyPopup: function() {
         this.popup_window = null;
         window.clearInterval(this.interval);
         this.interval = null;
    },
    isPopupClosed: function() {
         return (!this.popup_window || this.popup_window.closed);
    },
    open: function(url, width, height, close_callback) {
    	this.close_callback = close_callback || null;
         this.popup_window = window.open(url,"",this.getWindowParams(width,height));
         this.interval = window.setInterval(this.waitForPopupClose.proxy(this), this.interval_time);

         return this.popup_window;
    },
	getWindowParams: function(width,height) {
		var center = this.getCenterCoords(width,height);
		return "width="+width+",height="+height+",status=1,location=1,resizable=yes,left="+center.x+",top="+center.y;
	},
	getCenterCoords: function(width,height) {
		var parentPos = this.getParentCoords();
		var parentSize = this.getWindowInnerSize();

		var xPos = parentPos.width + Math.max(0, Math.floor((parentSize.width - width) / 2));
		var yPos = parentPos.height + Math.max(0, Math.floor((parentSize.height - height) / 2));

		return {x:xPos,y:yPos};
	},
	getWindowInnerSize: function() {
		var w = 0;
		var h = 0;

		if ('innerWidth' in window) {
			// For non-IE
			w = window.innerWidth;
			h = window.innerHeight;
		} else {
			// For IE
			var elem = null;
			if (('BackCompat' === window.document.compatMode) && ('body' in window.document)) {
				elem = window.document.body;
			} else if ('documentElement' in window.document) {
				elem = window.document.documentElement;
			}
			if (elem !== null) {
				w = elem.offsetWidth;
				h = elem.offsetHeight;
			}
		}
		return {width:w, height:h};
	},
	getParentCoords: function() {
		var w = 0;
		var h = 0;

		if ('screenLeft' in window) {
			// IE-compatible variants
			w = window.screenLeft;
			h = window.screenTop;
		} else if ('screenX' in window) {
			// Firefox-compatible
			w = window.screenX;
			h = window.screenY;
	  	}
		return {width:w, height:h};
	}
});

function publishFriendInviteToFacebook(referral_url, version) {
	var attachment = {'media': [{'type': 'image', 'src': 'http://images.static.areyouinterested.com/site/fb_ff_tiles/tile_logo.png', 'href': referral_url+'&ref=ff_fiimg'}]};
	attachment.caption = '{*actor*} wants to connect with more friends on AreYouInterested.com ' + referral_url;
	var action_links = [{ "text": "Meet Singles", "href": referral_url},
						{ "text": "Help {*actor*} Earn Points", "href": referral_url}];
	var callback = function() { log_stats_master('friend_invite_fb',0,version); };
	facebook.publishStream(null, attachment, action_links, null, null, callback, false, null);
}

function togglePasswordField(email, password_field) {
	if (isEmailApiProvider(email)) {
		password_field.hide();
	} else {
		password_field.show();
	}
}

/**
 * check if email address belongs to a company that we use
 * an api for to retrieve contacts
 * @param string email
 * @return bool
 */
function isEmailApiProvider(email) {
	//don't waste time if not a valid email address
	if (!email_validate(email)) { return false; }

	var supported_providers = ['@yahoo.','@ymail.','@live.','@hotmail.','@msn.','@windowslive.'];
	var email_length = email.length;
	var indexOfAt = email.indexOf('@',0);
	if (indexOfAt == -1) { return false; }
	var pl = supported_providers.length;
	//check if email domain exists in current email address
	for (var x = 0; x < pl; x++) {
		if (email.indexOf(supported_providers[x],0) > 0) {
			return true;
		}
	}
	return false;
}

function loginVsList(option) {
	if (option == 'list') {
		$('#email-friends').show();
		$('#email-services').hide();
		$('#email-selector').hide();
	} else {
		$('#email-friends').hide();
		$('#email-services').show();
		$('#email-selector').hide();
	}
}

function retrieveEmailFriendsCallback(reply) {
	if (reply.code == 0 && reply.contacts != '') {
		var contacts = reply.contacts;
		var c_count = contacts.length;
		$('#email-results').html("");
		for (var x=0; x<c_count;x++) {
			$('#email-results').append('<input name="check_list[]" type="checkbox" checked="checked" value="'+contacts[x].email+'"/> '+contacts[x].name+' ('+contacts[x].email+')<br />');
		}
		var pe = Ayi.Flags.friend_invite.points * c_count
		$('#potential_earnings').text(Math.min(pe, Ayi.Flags.friend_invite.max));
		$('#email-selector').show();
		$('#email-friends').hide();
		$('#email-services').hide();
		$('#email_address').val('');
		$('#email_pswd').val('');
		$('#inviter-form-response-success').html("").hide();
		$('#inviter-form-response-error').html("").hide();
	} else {
		$('#email_pswd').val('');
		$('#inviter-form-response-success').html("").hide();
		$('#inviter-form-response-error').html(reply.msg).show();
	}
	$('#inviter-form-submit').removeAttr('disabled').attr('value','Import Contacts');
}

function showActiveTab(controller_action) {
	switch (controller_action) {
		case 'OnlineNowBrowser':
			$('#browse').addClass('active');
			break;
		case 'LikesMe':
		case 'ILike':
		case 'WhoViewedMe':
		case 'wvm_tsr':
			$('#connections').addClass('active').removeClass('new');
			break;
		case 'Match':
		case 'match_tsr':
			$('#matches').addClass('active').removeClass('new');
			break;
		case 'Inbox':
		case 'WinkInbox':
		case 'Outbox':
		case 'WinkOutbox':
			$('#messages').addClass('active').removeClass('new');
			break;
		case 'MyProfile':
		case 'EditProfile':
		case 'EditPhotos':
		case 'settings':
			$('#my-profile').addClass('active').removeClass('new');
			break;
		case 'FBFriendMatch':
			$('#friends').addClass('active').removeClass('new');
			break;
		case 'premium_status':
			$('#upgrade').addClass('active').removeClass('new');
			break;
	}
}
