app = new oapps('quotes');
user = false;
container = false;
function logEvent(params) {
	try {
		var url = '/?';
		params = params || {};
		for (var i in params ) {
			url += '&' + i + '=' + params[i];
		}
		pageTracker._trackPageview(url);
	} catch (e) {}
}

function fbs_click(id, is_c) {
	is_c = is_c || false;
	var q = (is_c) ? 'id=' : 'q=';
	q = q + id;
	var u = 'http://quotescollections.com/?' + q;
	var t='Quotes Collections';
	var url = 'http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t);
	logEvent({view: 'fbs_click'});
	window.open(url,'_blank','toolbar=0,status=0,width=626,height=436');
	//$('<a href="'+url+'" class="iframe"></a>').fancybox({frameWidth:626,frameHeight:436}).click();
	return false;
}
function twt_click(quote_id) {
	var quote = $('#slot' + quote_id + ' .qq span').text().substr(0,97);
	var status = quote + '... http://quotescollections.com/?q=' + quote_id;
	var url = 'http://twitter.com?status=' + encodeURIComponent(status);
	logEvent({view: 'twt_click'});
	window.open(url,'_blank','toolbar=0,status=0,width=626,height=436');
	return false;
}

function mys_click(quote_id) {
	var quoted_by = $('#slot' + quote_id + ' .qby span').text();
	var quote = '<p><strong>' + $('#slot' + quote_id + ' .qq span').text() + '</strong></p><br><i>- ' + quoted_by + '</i>';
	var title = 'A nice quote by ' + quoted_by;
	var url = 'http://quotescollections.com/?q=' + quote_id;
	var loc = 2;
	logEvent({view: 'mys_click'});
	var target_url = 'http://www.myspace.com/index.cfm?fuseaction=postto&' + 't=' + encodeURIComponent(title)
+ '&c=' + encodeURIComponent(quote) + '&u=' + encodeURIComponent(url) + '&l=' + loc;
	window.open(target_url, '_blank','toolbar=0,status=0,width=626,height=436');
	return false;
}

function okt_click(quote_id) {
	var quoted_by = $('#slot' + quote_id + ' .qby span').text();
	var quote = $('#slot' + quote_id + ' .qq span').text();
	var img = $('#slot' + quote_id + ' .qpic').css('background-image').match(/h[^\)]+/i);
	var title = 'A nice quote by ' + quoted_by;
	var url = 'http://quotescollections.com/?q=' + quote_id;
	logEvent({view: 'okt_click'});
	var target_url = 'http://promote.orkut.com/preview?nt=orkut.com&' + 'tt=' + encodeURIComponent(title)
+ '&cn=' + encodeURIComponent(quote) + '&du=' + encodeURIComponent(url) + '&tn=' + encodeURIComponent(img);
	window.open(target_url, '_blank','toolbar=0,status=0,width=626,height=436');
	return false;
}

function share(s, quote_id) {
	var quoted_by = $('#slot' + quote_id + ' .qby span').text();
	var quote = $('#slot' + quote_id + ' .qq span').text();
	var img = $('#slot' + quote_id + ' .qpic').css('background-image').match(/h[^\)]+/i);
	var title = 'A nice quote by ' + quoted_by;
	if (s == 'twitter') quote = quote.substr(0,80 - title.length);

	var url = 'http://api.addthis.com/oexchange/0.8/forward/'+s+'/offer?';
	url += '&url=http://quotescollections.com/?q=' + quote_id;
	url += '&title=' + encodeURIComponent(title);
	url += '&description=' + encodeURIComponent(quote);
	url += '&template=' + encodeURIComponent('#quote {{title}} {{url}} {{description}}...');
	url += '&username=y1426i';
	window.open (url, null,"location=0,status=1,scrollbars=1, width=600,height=500"); 
}

function setheight() {
	if ($(window).height() >= $('#wrap').height()) {
		$('#wrap').height($(window).height());
	} else {
		$('#wrap').height('100%');
	}
	if (oapps.container == 'OPENSOCIAL' )setTimeout('gadgets.window.adjustHeight()', 1000);
}

function submitFeedback() {
	var u = (oapps.container == 'OPENSOCIAL') ? os : (user) ? user.user_id : {};
	var params = {name: $('#feedbackform input[name="name"]').attr('value'),
		email: $('#feedbackform input[name="email"]').attr('value'),
		message: $('#feedbackform textarea').attr('value'),
		misc: [navigator.userAgent, u]};
	
	app.processRequest('html_feedback', params, function(r) {
		$('#feedbackform').html('Thank you for your message!');
	}, {method: 'POST'});
}

var render = {
	curr_view: 'home',
	waiting: false,
	ajaxify: {
		menu: false,
		paging: false,
		collection: false,
		search: false
	},
	view: function(v, data) {
		data = data || {};
		$('#mainmenu a').removeClass('active');
		$('#mm' + v).addClass('active');
		render.curr_view = v;
		if (data.header) {
			$('#viewheader').empty();
			$('#viewheader').replaceWith(data.header);
		}
		if (data.body) {
			clearTimeout(render.waiting);
			$(".quotation").each(function(){
				$(this).unbind();
				$(this).remove();
			});
			//$('#viewbody').html('');
			//$('#viewbody').empty();
			$('#viewbody').replaceWith(data.body);
			//$('#viewbody').remove();
			//var w = document.getElementById("viewwrap");
			//var b = document.getElementById("viewbody");
			//w.removeChild(b);
			//w.appendChild(data.body);
			//$('#viewwrap').append(data.body);
			ajaxify.paging();
		}
		//$('#loading').hide();
		setheight();

		switch(v) {
			case 'home':
				if (user) user.initaddremovelinks();
				$(".quotation:first").css("border-top","1px solid #eee");
				break;
			case 'browse':
				ajaxify.collection();
				break;
			case 'my':
				user.initcurrentlinks();
				ajaxify.mycollection();
				break;
			case 'new':
				break;
			case 'help':
				break;
		}
		if (container == 'ning') ningPatch();
		$('#viewbody').css('visibility','visible');
	},
	loading: function(p) {
		render.waiting = setTimeout("render.check("+p+")", 6000);
		$('#paging a').unbind('click');
		//$('#viewbody').css('visibility','hidden');
		$('#paging').html($('#loading').clone().attr('id','temp').show());
	},
	check: function(p) {
		var waitMsgs = ['server seems tired!', 'seems stuck in traffic!', 'sorry for the wait!', 'wish this was faster!', 'if waiting was fun!', 'oops! wanna try again in few secs!'];
		var msg = waitMsgs[Math.floor(Math.random()*waitMsgs.length)];
		if (render.waiting)	{
			$('#paging').append('... ' + msg + ' - <a href="javascript:loadXMainMenu({view:\'home\'})">cancel</a>');
		}
	}
};

var ajaxify = {
	check: {
		menu: false,
		paging: false,
		collection: false,
		search: false,
		init: false
	},
	init: function(args) {
		if (ajaxify.check.init) return false;
		for(var i in args) {
			ajaxify.check[args[i]] = true;
		}
		ajaxify.menu();
		ajaxify.paging();
		ajaxify.collection();
		ajaxify.search();
		ajaxify.check.init = true;
		if (user) user.initaddremovelinks();
		$(".quotation:first").css("border-top","1px solid #eee");
	},
	paging: function() {
		if (!ajaxify.check.paging) return false;
		$('#paging a').each(function(){
			var argstr = $(this).attr('href').replace(/^.*\?/,'').split('&');
			var arg = {};
			for (var i in argstr) {
				var t = argstr[i].split('=');
				arg[t[0]] = t[1];
			}
			$(this).attr('href','javascript:void(0)');
			$(this).bind('click', function(){
				loadXPaging(arg);
			});
		});
	},

	menu: function() {
		if (!ajaxify.check.menu) return false;
		$('#mainmenu a, #rightbar a').each(function(){
			var href = $(this).attr('href');

			if (/\?$/.test(href)) href += 'view=home';
			if (/\?view=/.test(href)) {
				var view = href.replace(/^.+=/,'');
				$(this).attr('href','javascript:void(0)');
				$(this).bind('click', function(){
					loadXMainMenu({view: view});
				});
			}
		});
	},
	
	search: function() {
		return ajaxify.check.search;
	},
	
	collection: function() {
		$('.collectioncover').each(function(){
			$(this).addClass('cborder collectionactive');
			$(this).click(function(){
				if (!ajaxify.check.collection) {
					window.location = $(this).attr('href');
				} else {
					var id = $(this).attr('href').match(/^.*\?(id=[^&]+)/)[1].split('=')[1];
					$(this).attr('href','javascript:void(0)');
					loadXCollection({id: id});
				}
			});
		});
	},

	mycollection: function() {
		if (!ajaxify.check.collection) return false;
		$('.collectioncover a, a.viewcol_link').each(function(){
			$(this).click(function(){
				var id = $(this).attr('href').match(/^.*\?(id=[^&]+)/)[1].split('=')[1];
				$(this).attr('href','javascript:void(0)');
				loadXCollection({id: id});
			});
		});
	}
};

function loadXMainMenu(params) {
	var args = {cache: true, method: 'GET'};
	if (params.view == 'my' || params.view == 'new') {
		args.cache = false;
		args.method = 'POST';
		args.auth = 'SIGNED';
	}
	if (params.view == 'browse') {
		args.auth = 'SIGNED';
	}
	render.loading();
	app.addRequest('view_header', params, args)
		.addRequest('view_body', params, args)
		.sendRequest(function(r){
			render.view(params.view, {header: r.getResponse('view_header').getData(), body: r.getResponse('view_body').getData()});
		}, args);
	logEvent(params);
}

function loadXCollection(params) {
	render.loading();
	app.addRequest('view_header', params)
		.addRequest('view_body', params)
		.sendRequest(function(r) {
		render.view('home', {header: r.getResponse('view_header').getData(), body: r.getResponse('view_body').getData()});
	});
	logEvent(params);
}

function loadXPaging(e) {
	render.loading(e.page);
	app.addRequest('view_body', e).sendRequest(function(r){
		 render.view(render.curr_view, {body: r.getResponse('view_body').getData()});
	});
	logEvent(e);
}

function search() {
	var search = $('#mainmenu input, #rightbar input').attr('value');
	search = search.replace(/^\s+|\s+$/g,"");
	search = search.replace(/%/g,"");
	if (/^.{4,20}$/.test(search)) {
		render.curr_view = (render.curr_view == 'browse') ? 'browse' : 'home';
		if (ajaxify.search())	{
			loadXMainMenu({search: search, view: render.curr_view});
		} else {
			var view = '&view='+render.curr_view;
			window.location = '?search=' + search + view;
		}
	} else {
		alert('Search text should be between 4 and 20 characters.');
	}
}

function addquote(id) {
	if (user) {
		user.addquote(id);
	} else {
		google.friendconnect.requestSignIn();
	}
}

function removequote(id) {
	if (user) {
		user.removequote(id);
	} else {
		google.friendconnect.requestSignIn();
	}
}
