(function(Q) {
	// scrolling Interests
	// n - "li a"
	Q.fn.initInterests = function(n) {
		var q = Q(this);

		function parseIntDefault(a, b) {
			var c = parseInt(a);
			return isNaN(c) ? b : c;
		}

		function duplicateContent() {
			var b = 0;
			q.children().each(function() {
				b += Q(this).outerWidth(true);
				q.append(Q(this).clone())
			});
			q.css(
			{
				zoom: 1,
				width: (2 * b) + "px"
			});
			return b;
		}

		function initScrolling() {
			var mw = q.parent().innerWidth() * 2;
			var a = duplicateContent();
			while (a < mw) {
				a = duplicateContent();
			}
			var F = function() {
				var b = parseInt(q.css("left"));
				if (isNaN(b))
					b = 1;
				b = (b % a) - 1;
				q.css({ left: b });
			};
			q.bind("interestEnter", function() {
				clearInterval(q.data("interval"));
			})
			.bind("interestLeave", function() {
				if (q.data("interval"))
					clearInterval(q.data("interval"));
				q.data("interval", setInterval(F, 30))
			});

		}

		initScrolling();

		q.find(n).each(function() {
			var a = Q(this);
			a.mouseenter(function(e) {
				q.trigger("interestEnter");
			})
			.mouseleave(function(e) {
				q.trigger("interestLeave");
			});
		})
		.trigger("interestLeave");

		return this;
	};

	// search form
	Q.fn.initSearchForm = function(o) {

	};
})(jQuery);


// Search Block

// Advance Search
function initAdvanceSearch(o)
{
	o.a.toggle(
		function()
		{
			o.b.show();
			o.a.text(o.c);
		},
		function()
		{
			o.b.hide();
			o.a.text(o.d);
		}
	);
	
	if (o.e.val() != "") {
		o.a.trigger("click");
	}

	o.h.find("a[cat_id]").click(function(event) {
		event.preventDefault();
		var i = $(this);
		o.f.val(i.attr("cat_id"));
		i.parents("ul").find("li.active-category").removeClass("active-category");
		i.parents("li").addClass("active-category");
		o.h.parent().find(".category-menu-input").text(i.text());
		$("#search_query").focus();
	});
	var a = o.h.find("a[cat_id='" + $("#search_category").val() + "']");
	o.h.parent().find(".category-menu-input").text(a.text());
	a.parent("li").addClass("active-category");
}

function autoCompleteLocation(location, city, selLocation) {
	location.autocomplete({
		source: function(request, response) {
			$.ajax({
				url: "/autocomplete/findcity",
				dataType: "json",
				contentType: "application/json; charset=utf-8",
				data: {
					limit: 12,
					prefix: request.term
				},
				success: function(data) {
					response($.map(data, function(item) {
						return {
							label: item.location,
							value: item.location,
							city_id: item.city_id
						}
					}))
				}
			})
		},
		minLength: 2,
		select: function(event, ui) {
			city.val((ui.item) ? ui.item.city_id : '');
			selLocation.val(city.val());
		}
	});
}


// Search-Result Paging
function viewAll() {
	$("#search_category").val(0);
	$("#search_form input:text, #search_search_city, #search_sel_location").val('');
	$("#search_form").submit();
}

function prevPage()
{
	$("#search_move").val(-1);
	$("#search_form").submit();
}

function nextPage()
{
	$("#search_move").val(1);
	$("#search_form").submit();
}


// Sign Up

// Photo upload

function uplaodPhoto(btnId, imgId, url) {
	var button = $('#' + btnId), interval;
	var btnText = button.text();
	new AjaxUpload(button,
    {
    	action: url,
    	name: 'photo',
    	onSubmit: function(file, ext) {
    		if (!(ext && /^(jpg|png|jpeg|gif)$/i.test(ext))) {
    			alert('Only following image formats are allowed (*.jpg|*.jpeg|*.png|*.gif)');
    			return false;
    		}
    		button.text('Uploading');
    		this.disable();
    		interval = window.setInterval(function() {
    			var text = button.text();
    			if (text.length < 13) {
    				button.text(text + '.');
    			} else {
    				button.text('Uploading');
    			}
    		}, 200);
    	},
    	onComplete: function(file, response) {
    		window.clearInterval(interval);
    		button.text(btnText);
    		this.enable();
    		if (response == "error-size") {
    			alert("The size of the image is inadmissible.");
    			return;
    		}
    		$('#' + imgId).attr("src", response);
    	}
    });
}


// Tweets:

//  init:
function initTweets(o, url) {
	var len = 140;
	o.find("textarea").each(function(i, e) {
		var t = $(this);
		var m = t.parent().find(".proposal-mark");
		var tm = t.parent().find(".proposal-wrapper .time");
		var tx = t.parent().find(".proposal-wrapper .proposal-text");
		t.keydown(function() {
			if (e.value.length > len) {
				e.value = e.value.substr(0, len);
			}
			var x = len - e.value.length;
			m.text(x);
			if (x == 10)
				m.addClass("exceed");
			if (x == 11)
				m.removeClass("exceed");
		});
		t.parent().find("input:button").click(function() {
			var txt = $.trim(e.value);
			if (txt.length == 0) {
				alert("Please enter your proposal.\nThere is nothing to save!");
				return;
			}
			var done = 0;
			$.ajax({
				type: "post",
				data: { ind: i + 1, txt: e.value },
				url: "/proposal",
				async: false,
				success: function(data) {
					if (data == "same") {
						done = 1;
						return;
					}
					if (data == "empty") {
						done = 1;
						return;
					}
					if (data == "ex") {
						done = -1;
						return;
					}
					e.value = "";
					m.text(len);
					m.removeClass("exceed");
					t.focus();
					tm.text(data);
					tx.text(txt);
					done = 100;
					$("#search_result").load("/user/UpdateMatchResults");
				}
			});
			if (done == 1) {
				alert("This is the same as your last proposal.\nPlease send something new.");
				return;
			}
			if (done < 100) {
				alert("Unfortunately your proposal is not saved.\nPlease send it again.");
				return;
			}
			if ($(this).attr('role') == "1") {
				var u = "http://twitter.com/share?url=" + encodeURIComponent(url) + "&text=" + encodeURIComponent(txt) + "&via=GetFriended";
				window.open(u);
			}
//			if (confirm("Your proposal is saved.\nWould you like to share it with others\non Twitter?")) {
//				var u = "http://twitter.com/share?url=" + encodeURIComponent(url) + "&text=" + encodeURIComponent(txt) + "&via=GetFriended";
//				window.open(u);
//			}
		});
	});
}


// Contacts:
// inti

function initContacts() {
	$("#contacts_tab .connections-link-area a").click(function() {
		$("#contacts_tab").load("/contacts/" + $(this).text());
	});
}

function actOnRequest(id, a) {
	$.ajax({
		type: "post",
		data: { userId: id, accept: a },
		url: "/process-request",
		async: false,
		success: function(data) {
			$("#contacts_tab").html(data);
			if (a == 1) {
				var u = $("#search_result a[uid='" + id + "']");
				u.attr("class", "already-ico");
				u.attr("title", "Already Friended");
			}
			else if (a == 0) {
				var u = $("#search_result a[uid='" + id + "']");
				u.attr("class", "get-friended-ico");
				u.attr("title", "GetFriended");
				u.attr("onclick", null);
				u.click(function(event) { GetFriendedWith(u, id, u.parents("li").find(".state a").text(), 0); });
			}
			var cnt = $("#contacts_tab ul li").length;
			if (cnt == 0)
				$("#contacts_tab").load("/contacts/friends");
		}
	});
}


// Dialog
function initDialog() {
	$("#modal_dialog").dialog({
		autoOpen: false,
		modal: true,
		resizable: false,
		position: "center",
		minWidth: 350,
		dialogClass: "shadow",
		zIndex: 10000
	});
}


// Archive
function showArchive(uid) {
	$.ajax({
		type: "get",
		url: "proposal-archive/" + uid,
		cache: true,
		async: false,
		dataType: "html",
		success: function(data) {
			var dlg = $("#modal_dialog");
			dlg.html(data);
			dlg.find('#arch_2').hide();
			dlg.dialog("option", "title", "Archive");
			dlg.dialog("open");
		}
	});
}

function SwitchProposal(n) {
	if (n == 1) {
		$('#arch_a2').removeClass('active');
		$('#arch_a1').addClass('active');
		$('#arch_2').hide();
		$('#arch_1').show();
	}
	else {
		$('#arch_a1').removeClass('active');
		$('#arch_a2').addClass('active');
		$('#arch_1').hide();
		$('#arch_2').show();
	}
	$('#arch_pn1').scrollTop(0);
}

// GetFriended
function GetFriendedWith(a, uid, fr, n) {
	if (n == 1) {
		var at = $("#contacts_tab .connections-link-area a.active");
		if (at.length = 1 && at.text() == "Requests") {
			actOnRequest(uid, 1);
			alert(fr + " is added to your friends.");
			return;
		}
	}
	$.ajax({
		type: "post",
		url: "get-friended",
		data: { id: uid },
		cache: false,
		async: false,
		success: function(data) {
			if (data == "<script type=\"text/javascript\">window.location='/sign-in';</script>") {
				if (confirm("This is available only for members.\nPlease Sign In."))
					window.location = "/sign-in";
				return;
			}
			a.unbind("click");
			a.attr("class", "");
			if (n == 1) {
				a.addClass("already-ico");
				a.attr("title", "Already Friended");
				alert(fr + " is added to your friends.");
				updateCounter($("#request_counter > div"), -1);
				if (at.length = 1 && at.text() == "Friends") {
					$("#contacts_tab").load("/contacts/friends");
				}
			}
			else {
				a.addClass("pending-ico");
				a.attr("title", "Your Pending Request");
				alert("Your request for friendship was sent to " + fr + ".");
			}
		}
	});
}

function updateCounter(c, n) {
	var i = parseInt(c.text()) + n;
	c.text(i);
	if (i == 0)
		c.parent().hide();
}

function setRequestCounter(c, n) {
	c.text(n);
	if (n == 0)
		c.parent().hide();
}

/*** ********* Old ********* ***/
function isIpad() {
	return navigator.userAgent.match(/iPad|iPhone/i) != null;
}

function hideVideoObjs() {}

function showVideoObjs() {}

/*** ********* Chat ********* ***/
/*
function PositionChat() {
	var cc = $("#chat_container");
	var isIPad = isIpad();
	var wh = isIPad ? $(document).height() : $(window).height();
	var ww = isIPad ? $(document).width() : $(window).width();
	//var d = $("#data");
	cc.css({ left: ww - 152, top: wh - (isIPad ? 611 : 491) });
}
*/


