﻿var app = app || {
	context: {
		culture: 'fr', // en | fr
		cultureParam: 'c',
		path: '' // application path
	},
	flashvars: {
		cultureCode: '',
		baseUrl: '',
		assetsUrl: '',
		tab: '',
		CMContentUrl: ''
	},
	flash: function(id, src, width, height, flashvars) {
		if (swfobject.hasFlashPlayerVersion("9.0.0") && src != '') {
			if (typeof (flashvars) == 'undefined')
				flashvars = {};
			if (typeof (width) == 'undefined')
				width = 480; ;
			if (typeof (height) == 'undefined')
				height = 360;
			var params = { allowfullscreen: "false", allowScriptAccess: "always", wmode: "transparent" };
			swfobject.embedSWF(src, id, width + "px", height + "px", "9.0.0", "", flashvars, params, {});
		}
	},
	location: function(uri, params) {
		if (typeof (params) == 'undefined' || typeof (params) == 'null')
			document.location = uri;
		else {
			var urlparts = uri.split('?');
			if (typeof (params) == 'string' && params == 'clear')
				document.location = urlparts[0];
			else if (urlparts.length > 1) {
				var kv = urlparts[1].split('&');
				var q = {};
				for (var p in kv) {
					var t = kv[p].split('=');
					q[t[0]] = t[1];
				}
				document.location = urlparts[0] + '?' + $.param($.extend(q, params));
			}
			else
				document.location = urlparts[0] + '?' + $.param(params);
		}
	},
	params: function(name, url) {
		var urlparams = typeof url == 'undefined' 
			? location.search : url.substr(url.indexOf('?'));
		var params = null;
		var singleValue = typeof (name) != 'undefined';
		if (urlparams.length > 1) {
			params = new Object();
			urlparams = urlparams.substr(1);
			var kv = urlparams.split('&');
			for (var p=0; p<kv.length; p++) {
				var t = kv[p].split('=');
				if (singleValue && t[0] == name)
					return t[1];
				else {
					var decodedName = decodeURIComponent(t[0]);
					if(decodedName.indexOf('[]') > -1){
						var arrayName = decodedName.replace("[]", "");	
						if(typeof params[arrayName] == 'undefined')
							params[arrayName] = [];
						params[arrayName].push(t[1]);
					} else
						params[decodedName] = t[1];
				}
			}
		}
		return singleValue ? null : params;
	},
	autoclear: function(sel) {
		var o = typeof (sel) == 'string' ? $(sel) : sel;
		$(o).each(function() {
			var me = $(this);
			me.data('defaultText', me.val());
		}).focus(function() {
			var me = $(this);
			if (me.val() == me.data('defaultText'))
				me.val('');
		}).blur(function() {
			var me = $(this);
			if (me.val() == '')
				me.val(me.data('defaultText'));
		});
	},
	initBanner: function(linksSel, bannersSel, params, showReflection) {
		if(typeof showReflection == 'undefined')
			showReflection = true;
		var opts = {
			target: bannersSel,
			onChange: function(index, target) {
				var videoUrl = $(linksSel).find('li:eq(' + index + ')').find('.video').text();
				var externalUrl = $(linksSel).find('li:eq(' + index + ')').find('.externalLink').text();
				var internalUrl = $(linksSel).find('li:eq(' + index + ')').find('.internalLink').text();
				var parent = target.parent();
				parent.children('.video').remove();
				if (videoUrl != '') {
					if (!parent.is('a')) {
						target.wrap('<a></a>');
						parent = target.parent();
					}
					parent.attr({
						'href': app.context.path + '/resources/swf/player.swf?plugins=gapro-1&gapro.accountid=UA-2814131-1&gapro.trackcompletes=true&file=' + videoUrl
					}).fancybox({ type: 'swf' });
					$('<div></div>').addClass('gui video').prependTo(parent);
				}
				else if (externalUrl != '') {
					if (!parent.is('a')) {
						target.wrap('<a></a>');
						parent = target.parent();
					}
					parent.attr({ 'href': externalUrl, 'target': '_blank' });
				}
				else if (internalUrl != '') {
					if (!parent.is('a')) {
						target.wrap('<a></a>');
						parent = target.parent();
					}
					parent.attr({ 'href': internalUrl, 'target': '_self' });
				}
				if(showReflection)
					app.anim.unreflection(index, target);
			},
			onChangeComplete: showReflection ? app.anim.reflection : $.noop,
			autoStartSlideshow: true,
			targetContent: null,
			slideshowSpeed: 5000
		};
		var opts = $.extend(opts, params);
		$(linksSel).banners(opts);
	},
	init: function() {
		// Si on change la valeur ici, on doit changer la valeur
		// dans le global.css pour la classe .corner aussis
		if ($.browser.msie) $('.corner').corner('8px');

		// Liens externes
		$('a[rel=external], a[href$=pdf], a[href^=http]').attr('target', '_blank');

		this.autoclear('input[type=text].autoclear');
	},
	initSearch: function(url, paramName) {
		// global search
		$('#search').bind('keydown', function(event) { if (event.wich == 13) app.search(url, paramName, $(this).val()); });
		$('#search-button').bind('click', function() { app.search(url, paramName, $('#search').val()); return false; });
	}
};
app.search = function(url, paramName, q) {
	var params = {};
	params[app.context.cultureParam] = app.context.culture;
	params[paramName] = q;
	app.location(url, params);
};
app.login = app.login || {
	dialog: undefined,
	showPopup: function() {
		if (this.dialog == undefined) {
			$.get(app.context.path + '/Login.aspx', function(data, textStatus) {
				if (textStatus == 'success') {
					app.login.dialog = $(data).find('#login-form').appendTo('body').dialog({ 'modal': true, 'title': app.res().get("login") });
					app.autoclear(app.login.dialog.find('.autoclear'));
				}
			});
		} else {
			this.dialog.dialog('open');
		}
	},
	showLoginRequiredPopup: function() {
		if (this.dialog == undefined) {
			$.get(app.context.path + '/Login.aspx', function(data, textStatus) {
				if (textStatus == 'success') {
					app.login.dialog = $(data).find('#login-form').appendTo('body').dialog({ 'modal': true });
				}
			});
		} else {
			this.dialog.dialog('open');
		}
	},
	logout: function(paramName) {
		$.post(app.context.path + '/Login.aspx?' + paramName + '=logout',
        function(data, textStatus) {
        	data = $(data)
        	if (data.attr('id') == 'logout-success')
        		document.location = data.text();
        });
	},
	submit: function(paramName) {
		$.post(app.context.path + '/Login.aspx?' + paramName + '=login',
            { 'login': document.getElementById('login').value, 'password': document.getElementById('password').value, 'redirectUrl': document.URL },
            function(data, textStatus) {
            	data = $(data)
            	if (data.attr('id') == 'login-success')
            		document.location = data.text();
            	else
            		$('#login-form > #login-message').text(data.text());
            });
	}
};
app.killerapp = app.killerapp || {
	init: function(tab) {
		if (swfobject.hasFlashPlayerVersion("9.0.0")) {
			var flashvars = app.flashvars;
			flashvars.appUrl = flashvars.baseUrl.substring(0, flashvars.baseUrl.length - 1);
			flashvars.cultureCode = app.context.culture;
			flashvars.tab = tab;
			var params = { allowfullscreen: "false", allowScriptAccess: "always", wmode: "window" };
			swfobject.embedSWF(app.context.path + '/resources/swf/killerapp.swf', 'killerapp', "100%", '390px', '9.0.0', '', flashvars, params, {});
		} else
			this.html.init();
	},
	html: {
		_currentPage: 1,
		_itemWidth: -1,
		_highlights: undefined,
		_itemCount: -1,
		_itemPerPage: 4,
		swap: function(sender, sel) {
			$(sender).addClass('active').siblings().removeClass('active');
			$(sel).show().siblings().not('.swap').hide();
		},
		init: function() {
			this._highlights = $('#highlights');
			this._itemCount = this._highlights.find('ul > li').each(function() {
				var me = $(this);
				var index = $('#highlights > ul > li').index(me);
				/* montre les 4 premières images */
				if (index < 4) {
					var imgsrc = me.children('.imgsrc');
					var alt = me.children('.title');
					// ajoute l'image
					var image = new Image();
					image.src = imgsrc.text();
					image.alt = alt;
					me.prepend(image);
					imgsrc.remove();
				}
				app.killerapp.html._itemWidth = me.width() + 25;
				me.css({ 'position': 'absolute', 'left': (index * app.killerapp.html._itemWidth) + 'px' });
			}).length;
			this._highlights.show().css('visibility', 'visible');
			this._highlights.children('.prev').hide().click(app.killerapp.html.prev);
			this._highlights.children('.next').show().click(app.killerapp.html.next);
		},
		next: function() {
			if (app.killerapp.html._itemCount < (app.killerapp.html._currentPage + 1) * app.killerapp.html._itemPerPage) {
				// affiche le bouton previous
				app.killerapp.html._highlights.children('.prev').show();
				// anime les highlights
				var comingtoscreen = app.killerapp.html._highlights.find('ul > li');
				for (var k = app.killerapp.html._currentPage * app.killerapp.html._itemPerPage; k < (app.killerapp.html._currentPage + 1) * app.killerapp.html._itemPerPage; k++) {
					var li = comingtoscreen.eq(k);
					var imgsrc = li.children('.imgsrc');
					if (imgsrc.length) {
						var image = new Image();
						image.src = imgsrc.text();
						image.alt = li.children('.title').text();
						li.prepend(image);
						imgsrc.remove();
					}
				}
				comingtoscreen.animate({ 'left': '-=' + app.killerapp.html._itemWidth * app.killerapp.html._itemPerPage + 'px' });

				app.killerapp.html._currentPage++;
				/* show/hide le bouton next s'il y a une autre page après ou non */
				if (app.killerapp.html._itemCount < (app.killerapp.html._currentPage + 1) * app.killerapp.html._itemPerPage)
					app.killerapp.html._highlights.children('.next').hide();
			} else {
				app.killerapp.html._highlights.children('.next').hide();
			}
		},
		prev: function() {
			if (app.killerapp.html._currentPage > 1) {
				app.killerapp.html._currentPage--;
				app.killerapp.html._highlights.children('.next').show();
				app.killerapp.html._highlights.find('ul > li').animate({ 'left': '+=' + app.killerapp.html._itemWidth * app.killerapp.html._itemPerPage + 'px' });
				if (app.killerapp.html._currentPage <= 1)
					app.killerapp.html._highlights.children('.prev').hide();
			} else {
				app.killerapp.html._highlights.children('.prev').hide();
			}
		}
	}
};

/* app.Resources

---------------------------------------------- */
app.resources = app.resources || {};

app.resources.Repository = function() {
	this._rep = new Array();
};

app.resources.Repository._instance = undefined;

app.resources.Repository.Instance = function() {
	if (app.resources.Repository._instance == undefined)
		app.resources.Repository._instance = new app.resources.Repository();

	return app.resources.Repository._instance;
};

app.resources.Repository.prototype.add = function(key, val) {
	this._rep[key] = val;
};

app.resources.Repository.prototype.get = function(key) {
	return this._rep[key];
};

/* shortcuts */
app.res = app.resources.Repository.Instance;

/* app.ajax

---------------------------------------------- */
app.ajax = {
	getStockQuotesTable: function(sel, proxyUrl, param, uri) {
		$.get(proxyUrl + '?' + param + '=' + uri,
            function(data) {
            	var response = $(data);
            	response.find('img').each(function() {
            		this.src = 'http://www.tmx.com/' + this.src.substr(this.src.indexOf('/images') - 2);
            	});
            	$(sel).append(response.find('table'));
            }
        );
	},
	highlights: function(startRowIndex, callback, callbackArgs) {
		FjordCMS.CMServices.pagesByModel({
			'modelCode': 'HighLight',
			'orderBy': 'NodeOrder',
			'startRowIndex': startRowIndex,
			'maximumRows': 4
		}, function(data, startRowIndex, maximumRows, totalCount) {
			var container = $('#highlights');
			if (startRowIndex == 0)
				startRowIndex = 1;
			var html = '';
			for (var p in data) {
				var page = data[p];
				html += '<li class="hidden" style="left:' + parseInt(p) * (211 + 25) + 'px;">' +
                    '<img src="' + page.getImage('Image', FjordCMS.Enums.ImageSize.source) + '" alt="' + page.pageName + '"/>' +
                    page.pageName + '<br />' +
                    '<a href="' + page.getItem('ExternalLink') + '">' + app.res().get('MoreDetails') + '</a>' +
                    '</li>';
			}

			var ul = container.children('ul');
			if (!ul.length)
				ul = $('<ul></ul>').appendTo(container);

			ul.append(html);
			ul.find('li').each(function(index) {
				$(this).delay(75 * index).fadeIn('fast', function() { $(this).removeClass('hidden').find('img').reflect({ 'height': 0.1 }); });
			});

			var next = container.find('.next');
			if (!next.length)
				next = $('<a href="javascript:;" class="i rgt next">&gt;</a>').appendTo(container);
			if ((startRowIndex + maximumRows) < totalCount) {
				next.show().click(function() {
					app.anim.highlights('right', app.ajax.highlights, startRowIndex + maximumRows);
				});
			} else
				next.hide();

			var prev = container.find('.prev');
			if (!prev.length)
				prev = $('<a href="javascript:;" class="i lft prev">&lt;</a>').prependTo(container);
			if (startRowIndex > 1) {
				prev.show().click(function() {
					app.anim.highlights('left', app.ajax.highlights, (startRowIndex - maximumRows > 0 ? startRowIndex - maximumRows : 0));
				});
			} else
				prev.hide();
			if (typeof (callback) != 'undefined' && typeof (callbackArgs) != 'undefined')
				callback(callbackArgs);
		});
	}
};
app.anim = {
	highlights: function(direction, callback, callbackArgs) {
		var li = $('#highlights li');
		var count = li.length;
		li.each(function(index) {
			$(this).unreflect().delay(75 * index).fadeOut('fast', function() {
				if (index == count - 1) {
					li.remove();
					callback(callbackArgs);
				}
			});
		});
	},
	unreflection: function(index, sel) {
		if (!$.browser.msie)
			$('.reflected').siblings().fadeOut(200, function() { $(this).prev('.reflected').unreflect(); });
		else
			$('.reflected').unreflect();
	},
	reflection: function(index, sel) {
		if (!$.browser.msie)
			$(sel).reflect({ 'height': 25, 'opacity': 0.2 }).next().hide(0).fadeIn(200);
		else
			$(sel).reflect({ 'height': 25, 'opacity': 0.2 });
	}
};

/* Page advertising promos

--------------------------------------------*/
app.RichDocumentList = {
	docs: undefined,
	docsParentID: undefined,
	pager: undefined,
	itemModel: null,
	init: function(list, docsParentID, startRowIndex, maximumRows) {
		this.docs = $(list);
		this.docsParentID = docsParentID;
		this.itemModel = this.docs.find('li:eq(0)').clone();
		this.show(startRowIndex, maximumRows);
	},
	show: function(startRowIndex, maximumRows) {
		var self = app.RichDocumentList;
		FjordCMS.CMServices.pagesByModel(
			{ "modelCode": "RichDocument", "query": "ParentID = " + self.docsParentID, "startRowIndex": startRowIndex, "maximumRows": maximumRows },
			function(pages, startRowIndex, maximumRows, totalRows) {
				var container = $('<div></div>');
				/* paging */
				if (self.pager == undefined) {
					self.pager = new FjordCMS.Pager({
						"selector": '#pager',
						"startRowIndex": startRowIndex,
						"maximumRows": maximumRows,
						"totalRows": totalRows,
						"onClick": app.RichDocumentList.show
					});
				}
				for (var i in pages) {
					var p = pages[i];
					if(typeof p != 'object')
						continue;
					var item = self.itemModel.clone();
					var previewSrc = p.getImage('Image', FjordCMS.Enums.ImageSize.small);
					
					if (previewSrc != undefined)
						item.find('.bg-img').append('<img src="'+previewSrc+'" alt="'+p.pageName+'" />');
					else
						item.find('.bg-img').remove();
					item.find('h3').text(p.pageName);
					item.find('.download').attr({ "href": p.getAsset('File') });
					item.find('.filesize').text(p.getItem('Filesize'));
					item.find('p').html(p.getItem('Summary'));
					container.append(item);
				}

				self.docs.empty().append(container.children());
				delete container;
			}
		);
	}
};

app.AdvertisingPromos = function(args) {
	this.opts = $.extend({}, app.AdvertisingPromos.DefaultOptions, args);
	this.videoCount = 0;
	this.currentIndex = 0;
	this.rotationTimeout = 0;

	this.parse();
};

app.AdvertisingPromos.DefaultOptions = {
	cacheUrl:'',
	list: '',
	player: '',
	rotationSpeed: 6000,
	width: 'auto',
	onLoad: $.noop,
	onClick: $.noop,
	onChange: $.noop
};

app.AdvertisingPromos.prototype.parse = function() {
	/*	parse une liste de video pour aller chercher
	les objets embed, et bind les événements */
	var self = this;
	var opts = this.opts;
	var list = $(opts.list + ' .video');
	var player = $(opts.player);

	self.videoCount = list.length;

	for (var i = 0, l = list.length; i < l; i++) {
		var item = list.eq(i);
		(function(item, i) {
			// pour chaque item video, on obtient l'object video de l'api de vimeo
			app.Vimeo.API.OEmbed.getVideoByUrl({ videoUrl: item.find('.url').text(), width: opts.width },
				function(video) {

					item.find('.videoID').val(video.video_id);
					item.find('.video-title .video-title-mid').text(video.title);
					item.data('video', video);

					var url = app.Vimeo.playerUrl + video.video_id + '?js_api=1&js_swf_id=vimeoIframe_' + video.video_id;
					var shareUrl = item.find('.share-url').text();
					
					player.append(
						'<div class="video" id="' + video.video_id + '"> \
						  <iframe src="' + url + '" class="vimeo" style="border:0;width:' + video.width + 'px;height:' + video.height + 'px;" id="vimeoIframe_' + video.video_id + '" /> \
							<h2 class="title">' + video.title + '</h2> \
							<div class="text">' + video.description + '</div> \
							<div class="social"> \
								<h2>'+(app.context.culture == 'en' ? 'Share' : 'Partager')+'</h2> \
								<div class="share"> \
									<a class="twitter"></a>\
									<fb:like href="' + shareUrl + '" layout="button_count" show_faces="false" notify="true"></fb:like>\
								</div> \
							</div> \
						</div>'
					);
					
					//item.find('.social').remove();
					
					if (i == l - 1) {
						// lorsque tous les video ont été appelé
						// utilise un mini-timeout car sinon les elements dom ne semble pas
						// toujours avoir le temps d'être insérés.
						setTimeout(function() {
							if(typeof FB != 'undefined')
								FB.XFBML.parse(document.getElementById('vimeo-video'));
							app.Social.Twitter.TweetButton(player.find('.twitter'), {tweetUrl:shareUrl, tweetText:video.title});
							var rand = Math.floor(Math.random() * self.videoCount);
							self.show({ "domElement": $(opts.list + ' .video').get(rand) }); //$(opts.list + ' .video').eq(rand).click();
							self.opts.onLoad(self);
						}, 100);
					}
				}
			);

			/* lorsqu'on cliquer sur un item de la liste des videos */
			item.click(function() { if(typeof self.opts.onClick == 'function') self.opts.onClick(this); self.stop(); self.show({ "domElement": this }); });

		})(item, i);
	}

};

app.AdvertisingPromos.prototype.start = function() {
	/* démarre la rotation automatique */
	var self = this;
	var nextIndex = Math.floor(Math.random() * self.videoCount);
	while(self.currentIndex == nextIndex)
		nextIndex = Math.floor(Math.random() * self.videoCount);
	self.rotationTimeout = setInterval(function() {
		self.show({ index: (Math.floor(Math.random() * self.videoCount)) });
	}, self.opts.rotationSpeed);
};

app.AdvertisingPromos.prototype.stop = function() {
	/* arrête la rotation automatique */
	clearInterval(this.rotationTimeout);
	this.rotationTimeout = 0;
};

app.AdvertisingPromos.prototype.show = function(args) {
	var opts = $.extend({ domElement: undefined, index: undefined, id: undefined }, args);
	var item = opts.domElement != undefined
		? $(opts.domElement)
		: opts.index != undefined
			? $(this.opts.list).children('.video:eq(' + opts.index + ')')
			: opts.id != undefined
				? $(this.opts.list).find('.videoID[value=' + opts.id + ']').closest('.video')
				: undefined;
	
	if (item == undefined || !item.length)
		return;

	this.currentIndex = item.index();
	
	var vid = item.find('.videoID').val();
	$('#' + vid).css({ 'z-index': '3', 'top': '0' }).show(0, function() {
		$(this).css({ 'z-index': '2' }).siblings().css({ 'z-index': '1', 'top': '-1000px' });
		item.addClass('active').siblings().removeClass('active');
	});

	this.opts.onChange(item.data('video'));
};

/* Vimeo stuff

-------------------------------------------- */
app.Vimeo = {
	playerUrl: 'http://player.vimeo.com/video/'
};
app.Vimeo.API = {};
app.Vimeo.API.OEmbed = {
	videoUrl: function(format, videoUrl) {
		return 'http://vimeo.com/api/oembed.' + format + '?url=' + encodeURIComponent(videoUrl);
	},
	getVideoByUrl: function(args, callback) {
		var opts = { videoUrl: '', format: 'json', width: '' };
		opts = $.extend(opts, args);
		// Tell Vimeo what function to call
		var id = opts.videoUrl.substr(opts.videoUrl.lastIndexOf('/') + 1);
		var callbackName = 'Vimeo_OEmbedAPI_' + id;// + '_' + (new Date()).getTime();
		window[callbackName] = callback;
		// Put together the URL
		var url = '/services/CachedProxy.aspx?dataType='+ encodeURIComponent('application/x-javascript') 
		+ '&id=' + id + '&url=' + encodeURIComponent('http://vimeo.com/api/oembed.' + opts.format + '?url=' + opts.videoUrl + '&js_api=1&callback=' + callbackName + (opts.width != '' ? '&width=' + opts.width : ''));

		var js = document.createElement('script');
		js.setAttribute('type', 'text/javascript');
		js.setAttribute('src', url);
		document.getElementsByTagName('head').item(0).appendChild(js);
	}
};

/* Facebook stuff, Feel free to override

-------------------------------------------- */
app.Facebook = {
	apikey: '',
	appid: '',
	onlogin: function(p) { },
	onlogout: function(p) { },
	onlike: function(p) { ga_facebookLike(p); }
};

/* Facebook SDK - No need for change

-------------------------------------------- */
window.fbAsyncInit = function() {
	FB.init({
		status: true, // check login status
		cookie: true, // enable cookies to allow the server to access the session
		xfbml: true		// parse XFBML
	});
	FB.Event.subscribe('edge.create', app.Facebook.onlike);
};

$(document).ready(function() {
	var e = document.createElement('script');
	e.async = true;
	e.src = document.location.protocol + '//connect.facebook.net/' + (app.context.culture == 'en' ? 'en_US' : 'fr_CA') + '/all.js';
	document.getElementById('fb-root').appendChild(e);
});

/* Twitter
-------------------------------------------- */
app.Social = app.Social || {};
app.Social.Twitter = {};
app.Social.Twitter.TweetButton = function(selector, params){
	if(typeof selector == 'string')
		selector = $(selector);
	
	var opts = $.extend({}, app.Social.Twitter.TweetButton.DefaultsOptions, params);
	
	if(opts.culture == '')
		opts.culture = app.context.culture;
	
	selector.attr({
		'href': 'http://twitter.com/share',
		'class': 'twitter-share-button',
		'data-count': opts.type,
		'data-lang': opts.culture
	}).text('Tweet');
	
	if(opts.tweetText != '')
		selector.attr({'data-text': opts.tweetText});
	if(opts.tweetUrl != '')
		selector.attr({'data-url': opts.tweetUrl});
	
	if(typeof window.twttr != 'object'){
		var e = document.createElement('script');
		e.src = 'http://platform.twitter.com/widgets.js';
		document.body.appendChild(e);
	}
	
};

app.Social.Twitter.TweetButton.Type = {
	vertical:'vertical', /* 65px x 62px */ 
	horizontal:'horizontal', /* 110px x 20px */
	noCount:'none' /* 65px x 20px */
};

app.Social.Twitter.TweetButton.DefaultsOptions = {
	type: app.Social.Twitter.TweetButton.Type.noCount,
	tweetText:'',
	tweetUrl:'',
	culture:'',
	mentionedAccount: '',
	relatedAccount:'',
	relatedAccountDescription:''
};

/* recherche des logos */

app.Logos = {
	
	FIND_OPTIONS: { g: [], kw: '' },
	DEFAULT_OPTIONS: { findUrl:'' },
	
	_gatherInputs: function(){
		var self = this;
		var fopts = { g: [], kw: '' },
				checkboxes = self.dom.groups.filter(':checked'),
				keyword = self.dom.kw;
		
		fopts.kw = keyword.data('defaultText') != keyword.val()
			? keyword.val() : '';
		
		for(var i=0, l=checkboxes.length; i<l; i++)
			fopts.g.push(checkboxes.eq(i).val());
		
		return fopts;
	},
	
	init: function(opts){
		var self = this;
		self.opts = $.extend({}, self.DEFAULT_OPTIONS, opts);
		
		/* dom elements */
		self.dom = {
			groups: $('input[name=logoFilter]'),
			kw: $('input[name=logo_search]'),
			reset: $('#logo-search-reset')
		}
		
		self.restoreState(self._gatherInputs());
		self.bindEvents();
	},
	
	restoreState: function(values){
		var self = this;
		var kw = app.params('kw');
		if(kw)
			self.dom.kw.val(kw);
		if(values.kw == '' && values.g.length == 0)
			self.dom.reset.hide();
	},
	
	bindEvents: function(){
		var self = this;
		
		$('#logo-search').bind('click', function(){
			self.find();		
		});
		
		self.dom.kw.bind('keypress', function(e){
			switch(e.which){
				case 13: self.find(); e.preventDefault(); break;
			}
		});
		
	},
	
	find: function(){
		var self = this;
		var inputs = self._gatherInputs();
		if(inputs.kw != '' || inputs.g.length > 0)
			app.location(self.opts.findUrl, inputs);
	}
	
};
