/*jslint browser: true, evil: true, strict: true */

/*global Config */
/*global Language */
/*global jQuery */
/*global Cufon */
/*global object */
/*global alert */

////////////////
// UTILITIES //
//////////////

function isValidEmail(email) {
	var pattern = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	return pattern.test(email);
}

function isO(o) {
	return typeof o == "object";
}

function isE(o) {
	return !!(o && o.nodeType == 1);
}

function isA(o) {
	return o !== null && typeof object == "object" && 'splice' in object && 'join' in object;
}

function isF(o) {
	return typeof o === "function";
}

function isS(o) {
	return typeof o === "string";
}

function isN(o) {
	return typeof o === "number";
}

function isU(o) {
	return typeof o === "undefined";
}

/*
* PK base Javascript Class
*
* @author		Frédéric Trudeau <ftrudeau@prospek.ca>
* @author		Sylvain Hovington <sylvain@prospek.ca>
* @author		Stéphane Taurand <stephane@prospek.ca>
* @copyright	Copyright (c) 2009 Prospek Inc. All rights reserved.
* @uses			jQuery 1.4.2
* @version		1.2
*/

var PK = {

	/**
	 * Slideshow configuration
	 *
	 * @property PK.SS
	 * @type Object
	 * @static
	 * @since 1.2
	 */
	SLIDESHOW: {
		navigation: true,
		easing: 'easeInOutExpo',
		firstDelay: 5000,
		delay: 4000,
		index: 0
	},

	/**
	 * Dialog object, with default configurations
	 *
	 * @property PK.DIALOG
	 * @type Object
	 * @static
	 * @since 1.1
	 */
	DIALOG: {
		active: false,
		addclose: true,
		autodisplay: true
	},

	/**
	 * Markup template used to generate the DOM structure for the share widget dialog
	 *
	 * @property PK.SW_DIALOG
	 * @type String
	 * @static
	 * @since 1.1
	 */
	SW_DIALOG:
		'<div id="sharewidget" class="PK_sw" style="display: none; cursor: default">' +
			'<div class="head">' +
				'<a href="javascript:void(0);" id="PK_sw_ac" class="dialogclose" title="' + Language.get('window_close_title') + '">' + Language.get('window_close_text') + '</a>' +
				'<div class="clearall"></div>' +
			'</div>' +
			'<div class="content">' +
				'<ul class="h_list" id="social-media-popups">' +
					'<li><a rel="nofollow" title="' + Language.get('sharewidget_shareon') + ' Facebook" href="http://www.facebook.com/share.php?u=%LINK%" class="ico_partage facebook skipgat popup standard 800 600 noicon">Facebook</a></li>' +
					'<li><a rel="nofollow" title="' + Language.get('sharewidget_shareon') + ' Twitter" href="http://twitter.com/home?status=%LINK%" class="ico_partage twitter skipgat popup standard 800 600 noicon">Twitter</a></li>' +
					'<li><a rel="nofollow" title="' + Language.get('sharewidget_shareon') + ' LinkedIn" href="http://www.linkedin.com/shareArticle?mini=true&url=%LINK%&title=&ro=false&summary=%EXCERPT%&source=%" class="ico_partage linkedin skipgat popup standard 800 600 noicon">LinkedIn</a></li>' +
					'<li><a rel="nofollow" title="' + Language.get('sharewidget_shareon') + ' Delicious" href="http://delicious.com/save?v=5&amp;noui&amp;jump=close&amp;url=%LINK%&amp;title=" class="ico_partage delicious skipgat popup standard 800 600 noicon">Delicious</a></li>' +
					'<li><a rel="nofollow" title="' + Language.get('sharewidget_shareon') + ' Google" href="http://www.google.com/bookmarks/mark?op=add&hl=fr&title=&bkmk=%LINK%" class="ico_partage google skipgat popup standard 800 600 noicon">Google</a></li>' +
					'<li><a rel="nofollow" title="' + Language.get('sharewidget_shareon') + ' StumbleUpon" href="http://www.stumbleupon.com/submit?url=%LINK%&title=" class="ico_partage sharethis skipgat popup standard 800 600 noicon">StumbleUpon</a></li>' +
				'</ul>' +
				'<div class="form">' +
					'<div class="desc">' + Language.get('sharewidget_permalink') + '</div>' +
						'<div class="bloc_stf">' +
							'<input id="PK_sw_permalink" value="" type="text" class="text noevent" readonly="readonly" />' +
						'</div>' +
						'<div class="clearall"></div>' +
						'<div class="desc_long">' + Language.get('sharewidget_title') + ':</div>' +
						'<div class="clearall"></div>' +
						'<div class="block_desc">' +
							'<div class="desc_ipt fleft">' + Language.get('sharewidget_friend_email_label') + '</div>' +
							'<div class="desc_ipt second fleft">' + Language.get('sharewidget_friend_name_label') + ' </div>' +
						'</div>' +
						'<div class="bloc_stf">' +
							'<div id="PK_sw_fc" class="bloc_stf_carousel">' +
								'<div class="bloc_stf_carousel current friend initial">' +
									'<input name="fe_546273" value="' + Language.get('sharewidget_friend_email_value') + '" type="text" class="text courriel reset" />' +
									'<input name="fn_546273" value="' + Language.get('sharewidget_friend_name_value') + '" type="text" class="text name reset" />' +
								'</div>' +
								'<div id="carousel_end"></div>' +
							'</div>' +
						'</div>' +
						'<div class="clearall"></div>' +
						'<div class="block_desc">' +
							'<div class="desc_ipt fleft">' + Language.get('sharewidget_your_email_label') + '</div>' +
							'<div class="desc_ipt second fleft">' + Language.get('sharewidget_your_name_label') + '</div>' +
						'</div>' +
						'<div class="bloc_stf">' +
							'<input name="ye" value="' + Language.get('sharewidget_your_email_value') + '" type="text" class="text courriel reset" />' +
							'<input name="yn" value="' + Language.get('sharewidget_your_name_value') + '" type="text" class="text name reset" />' +
						'</div>' +
						'<div class="bloc_stf link_add">' +
							'<a class="btn interstate_regular cufon partage" href="javascript:void(0);" id="PK_sw_ap"><span>' + Language.get('sharewidget_btn_share') + ' ››</span></a>' +
						'</div>' +
					'</div>' +
				'</div>' +
				'<div class="foot">' +
			'</div>' +
		'</div>',

	/**
	 * Markup template used to generate the DOM structure for the jqModal confirmation dialog
	 *
	 * @property PK.SW_MSG_CONF
	 * @type String
	 * @static
	 */
	SW_MSG_CONF :
		'<div id="dialog_confirmation" class="PK_diag" style="display: none; cursor: default">' +
			'<div class="blockui-container">' +
				'<a href="javascript:void(0);" id="dialog_close" class="close dialogclose" title="' + Language.get('window_close_title') + '">' + Language.get('window_close_text') + '</a>' +
					'<div class="wait font_flama_medium cufon no_print">' + Language.get('sharewidget_confirmation_text1') + '</div>' +
					'<div class="processing font_flama_medium cufon no_print">' + Language.get('sharewidget_confirmation_text2') + '</div>' +
			'</div>' +
		'</div>',

	/**
	 * Markup template used to generate an error message for the share widget
	 *
	 * @property PK.SW_ERR_RECIPIENTS_EMPTY
	 * @type String
	 * @static
	 */
	SW_ERR_RECIPIENTS_EMPTY:
		'<div id="error_message" class="PK_diag" style="display: none; cursor: default">' +
			'<div class="blockui-container error">' +
				'<a href="javascript:void(0);" id="dialog_close" class="close dialogclose" title="' + Language.get('window_close_title') + '">' + Language.get('window_close_text') + '</a>' +
				'<div class="font_flama_medium cufon no_print"></div>' +
				'<div class="processing font_flama_medium cufon no_print">' + Language.get('sharewidget_error_empty') + '</div>' +
			'</div>' +
		'</div>',

	/**
	 * Markup template used to generate the DOM structure for the jqModal error message
	 *
	 * @property PK.ERROR_MESSAGE_TEMPLATE
	 * @type String
	 * @static
	 */
	ERR_MSG_GENERIC :
		'<div id="error_message" class="PK_diag" style="display: none; cursor: default">' +
			'<div class="blockui-container error">' +
				'<a href="javascript:void(0);" id="dialog_close" class="close dialogclose" title="' + Language.get('window_close_title') + '">' + Language.get('window_close_text') + '</a>' +
				'<div class="font_flama_medium cufon no_print"></div>' +
				'<div class="processing font_flama_medium cufon no_print">' + Language.get('error_generic') + '</div>' +
			'</div>' +
		'</div>',

	/**
	 * Markup template used to generate the DOM structure for the jqModal wait dialog
	 *
	 * @property PK.WAIT_MSG_GENERIC
	 * @type String
	 * @static
	 */
	WAIT_MSG_GENERIC :
		'<div id="wait_message" class="PK_diag" style="display: none; cursor: default">' +
			'<div class="blockui-container loader">' +
				'<div class="wait font_flama_medium cufon no_print">' + Language.get('error_generic_wait') + '</div>' +
				'<div class="processing font_flama_medium cufon no_print"></div>' +
			'</div>' +
		'</div>',

	/**
	 * Markup template used to generate the DOM structure for the jqModal newsletter confirmation dialog
	 *
	 * @property PK.NW_MSG_CONF
	 * @type String
	 * @static
	 */
	NW_MSG_CONF:
		'<div id="newsletter_confirmation_message" class="PK_diag" style="display: none; cursor: default">' +
			'<div class="blockui-container">' +
				'<a href="javascript:void(0);" id="dialog_close" class="close dialogclose" title="' + Language.get('window_close_title') + '">' + Language.get('window_close_text') + '</a>' +
				'<div class="wait interstate_regular cufon no_print">' + Language.get('newsletter_thanks') + '</div>' +
				'<div class="processing interstate_regular cufon no_print">' + Language.get('newsletter_next') + '</div>' +
			'</div>' +
		'</div>',

	/**
	 * Markup template used to generate the DOM structure for the share widget dialog
	 *
	 * @property PK.SW_DIALOG
	 * @type String
	 * @static
	 */
	I18N_DIALOG:
		'<div id="dialog_i18n" class="pu_main pu_equipe">' +
			'<a href="javascript:void(0);" class="close" title="' + Language.get('window_close_title') + '">' + Language.get('window_close_text') + '</a>' +
			'<div class="pu_scroll">' + '{text}' + '</div>' +
		'</div>',

	/**
	 * Markup template used to generate the DOM structure for the share widget dialog
	 *
	 * @property PK.SW_DIALOG
	 * @type String
	 * @static
	 */
	I18N_TEXTS: {

		"de":

		'<p>Guten Tag und Willkommen auf der Website des Cirque Éloize!</p>' + '<p>Auf der Suche nach immer neuen Wegen, die magischen Momente und die Kunst im Zirkus zu unvergesslich zu machen, schafft der Cirque Éloize seit 1993 seine inspirierenden und poetischen Produktionen. Durch seine hervorragenden, sich immer erneuernden artistischen Methoden, ist er eines der Aushängeschilder des Zirkus der Gegenwart. Der Cirque Éloize drückt seine innovativen Ideen durch eine beeindruckende Bühnenwirksamkeit und Menschlichkeit aus und verbindet auf moderne und originelle Art die Zirkuskunst mit der Musik, dem Tanz und dem Theater. Der Cirque Éloize hat sechs Originalproduktionen geschaffen und weltweit über 3000 Vorstellungen in mehr als 330 Städten und 30 Ländern gegeben.</p>' + '<p>Wir freuen uns, Ihnen unser Unternehmen vorstellen zu dürfen und hoffen, dass Sie auf unserer <a href="/en/home">englisch</a>- oder <a href="/">französischsprachigen</a> Website alle Informationen finden, die Sie suchen.</p>' + '<p>Vielleicht sind wir Ihnen schon durch unsere Produktionen Excentricus, Nomade, Rain oder Nebbia ein Begriff. Wir hoffen, Ihnen bald wieder einen Besuch abzustatten. Konsultieren Sie bitte zwischenzeitlich regelmäβig unseren Tourneekalender um herauszufinden, wann wir in Ihrer Gegend wieder mit einer unserer groβen Produktionen vorstellig werden.</p>' + '<p>Wir wünschen Ihnen viel Freude beim Besuch!</p>',

		"ar":


		'<p>أهلا ومرحبا بكم في موقع سيرك ايلواز!</p>' + '<p>في خضم حركة تجديد فنون السيرك، يعمل سيرك ايلواز منذ عام 1993 على تأليف عروض مؤثرة ذات طابع شعري. وهو في سعيه الفني الدءوب، يعد من كبار رواد السيرك المعاصر. ويستند سيرك ايلواز إلى المواهب المتعددة لفنانيه، حيث يعبر عن طابعه الابتكاري من خلال الدراما والإنسانية، جامعا بصورة فريدة ومبتكرة بين فنون السيرك والموسيقى، وبين الرقص والمسرح. ويضم تاريخ سيرك ايلواز الفني ستة أعمال إبداعية أصلية، حيث قدم أكثر من 3000 حفل في حوالي 330 مدينة و30 بلدا في شتى أنحاء العالم.</p>' + '<p>ربما سمعتم عنا خلال زياراتنا لمنطقة الشرق الأوسط حينما قدمنا عرض اكسنتريكوس وعرض نوماد، لا سيما في لبنان مع عرض نوماد أو المملكة الأردنية الهاشمية لدى تقديم أحد عروضنا لملك وملكة الأردن.</p>' + '<p>إذا كنتم لا تعرفونا بعد، قوموا بزيارة صفحتنا باللغتين <a href="/">الفرنسية</a> أو <a href="/en/home">الانجليزية</a> لاكتشاف عالمنا! ومن خلال التتبع المنتظم لبرنامج جولاتنا وأخبارنا، يمكنكم معرفة موعد جولتنا المقبلة في بلدكم.</p>' + '<p>مع تمنياتنا لكم بزيارة ممتعة لموقعنا!</p>',

		"ko":

		'<p>Cirque Éloize 사이트 방문을 환영합니다!</p>' + '<p>서커스 부흥의 중심지에 자리잡은 Cirque Éloize는 일찍이 1993년부터 놀라움으로 가득찬 역동적인 서커스 공연을 선사해 왔습니다. 끊임없이 예술적 완성을 추구하는 Cirque Éloize는 현대 서커스 기예의 대표주자입니다. 전속 기예인들의 다양한 재능을 바탕으로, Cirque Éloize는 연극성과 인간성을 통해 그 혁신적 성격을 표현하며, 개척적이고 독창적인 방식으로 서커스 기예를 음악, 춤 및 연극과 결합합니다. 여섯 개의 독창적 작품을 제작한 바 있는 Cirque Éloize는 세계 각지의 30개국 330개 도시에서 3,000회 이상의 공연을 선사했습니다.</p>' + '<p>이미 저희 이름을 잘 알고 있거나 얼마 전 서울에서 열린 ‘레인’ 및 ‘네비아’ 공연을 보신 분들도 있을 것입니다. 저희는 정기적으로 한국에서 공연 및 특별 이벤트를 열고 있습니다. <a href="/en/home">영어</a> 및 <a href="/">프랑스어</a>로 된 저희 공연 일정을 보십시오! 언제든지 두 손 들어 여러분을 환영합니다. 저희와 함께 즐거운 시간 보내십시오!</p>',

		"es":

		'<p>¡Buenos días y bienvenido al sitio del Cirque Éloize!</p>' + '<p>En el auge de la renovación de las artes circenses, el Cirque Éloize ha creado, desde 1993, espectáculos conmovedores e impregnados de poesía. Gracias a su investigación artística continua, forma parte de la vanguardia del circo contemporáneo. Con el apoyo de los talentos multidisciplinarios de sus artistas, el Cirque Éloize expresa su naturaleza innovadora a través de la teatralidad y la humanidad, y conjuga de manera inédita y original las artes circenses con la música, la danza y el teatro. Con seis producciones originales en su haber, el Cirque Éloize ha presentado más de 3000 representaciones en cerca de 330 ciudades y 30 países situados en los cuatro rincones del mundo.</p>' + '<p>Es posible que usted haya tenido la oportunidad de descubrir el Cirque Éloize en estos últimos años en España durante la presentación de Excentricus, Nomade o incluso Rain, en Colombia durante una gira mundial de los espectáculos Excentricus y Nebbia, o incluso en México con el espectáculo Rain. ¡No dude en consultar nuestro calendario de giras en <a href="/">francés</a> o en <a href="/en/home">inglés</a> para ver cuando pasaremos cerca de su región y compre sus boletos desde ahora!</p>',

		"it":

		'<p>Buon giorno e benvenuti sul sito del Cirque Éloize!</p>' + '<p>Nel cuore del rinnovo del circo, il Cirque Éloize crea, dal 1993, spettacoli commuoventi ed impressi di poesia. In perpetua ricerca artistica, conta tra i capo fila del circo contemporaneo. Forte dei talenti multidisciplinari dei suoi artisti, il Cirque Éloize esprime la sua natura novatrice tra teatralità ed umanità e coniuga in modo inedito arte circense con elementi e techniche musicali, coreografici e attoriali. Con sei produzioni originali al suo attivo, il Cirque Éloize vanta più di 3000 rappresentazioni in circa 330 città di 30 paesi di tutto il mondo.</p>' + '<p>Siamo lieti di accogliervi sul nostro sito Web. Forse ci conoscete già? La nostra compagnia conosce bene l’Italia e la Svizzera per esserci stata a più riprese. Infatti, quattro delle nostre creazioni – Excentricus, Nomade, Rain e Nebbia –hanno già girato l’Italia et la Svizzera durante le loro tournée mondiali.</p>' + '<p>Collaboriamo strettamente con l’autore e regista Daniele Finzi Pasca, di Lugano (Svizzera), dal 2002. D’altronde, i codirettori del Cirque Éloize, Julie Hamelin e Jeannot Painchaud, hanno avuto l’occasione di lavorare con lui nel gruppo di creazione della cerimonia di chiusura dei ventesimi Giochi Olimpionici d’inverno di Torino nel 2006… Forse avete assistito a quella grande serata?</p>' + '<p>Nell’attesa di rendervi visita entro breve:</p>' + '<p>Buona navigazione sul nostro sito in <a href="/">francese</a> o in <a href="/en/home">inglese</a>.</p>',

		"ja":

		'<p>こんにちは！シルク・エロワーズのサイトにようこそ!</p>' + '<p>1993年以来、サーカスアートの変革の中心で存在感を示すシルク・エロワーズは感動的で詩のようなショーをクリエートしてきました。アートを常に追求し、現代サーカスのリーダー格として活躍し脚光を浴びています。アーティストの多様な才能を生かしシルク・エロワーズは演劇性・人間性豊かな作品を通して、音楽、ダンス、シアターを今までにないユニークなタッチで革新的なサーカスアートとしてまとめています。６つのオリジナル作品でシルク・エロワーズは世界約30カ国約330都市において 3000以上のショーを行ってきました。</p>' + '<p>このサイトをご覧になって頂きありがとうございます。<a href="/">フランス語</a> または<a href="/en/home">英語</a>のページもどうぞ楽しんでください。私達の３つの作品は既に日本で紹介する機会を得ています。日本にはまたいつでも喜んで行きたいと思います。尚、2005年トヨタの依頼によりオーダーメード制作したショーを私達は愛知万博で何度も上演しました。また近いうちに皆様にお会いできることを楽しみにしています。私達のサイトをお楽しみ下さい!</p>',

		"pl":

		'<p>Witamy na stronie Cirque Éloize!</p>' + '<p>W centrum głębokich zmian i odrodzenia sztuki cyrkowej, Cirque Éloize od 1993 roku tworzy wzruszające wypełnione poezją i sprawiające ogromne wrażenie spektakle. W stałym poszukiwaniu nowych środków artystycznych plasuje się w ścisłej czołówce współczesnego cyrku. W oparciu o talenty swoich artystów z różnych dyscyplin Cirque Éloize pokazuje swoje oblicze twórcze poprzez teatralność i humanizm i łączy w sposób wybitny i oryginalny sztukę cyrkową z muzyką tańcem i teatrem. Cirque Éloize posiada na swoim koncie sześć oryginalnych przedstawień z którymi występował ponad 3000 razy w 330 miastach, 30 krajach na czterech krańcach świata.</p>' + '<p>Być może przyjdziecie zobaczyć spektakl Nomade w Warszawie?. Jeżeli nie to możecie zapoznać się ze światem Cirque Éloize zaglądając na nasze strony w języku <a href="/en/home">angielskim</a> lub <a href="/">francuskim</a>. Pracujemy z licznymi artystami pochodzenia polskiego i zawsze odczuwamy ogromną przyjemność, gdy możemy zaprezentować ich pracę w ich kraju. Będziemy zatem wkrótce w Waszym przepięknym kraju.....Możecie zawsze zapoznać się z programem naszego tournee zaglądając regularnie do naszego kalendarza występów.</p>' + '<p>Miłej wizyty na naszych stronach</p>',

		"ru":

		'<p>Добро пожаловать в цирк Элуаз!</p>' + '<p>Возрождая с 1993 года цирковое искусство, цирк Элуаз создает полные поэзии представления, которые не могут оставить зрителя равнодушным. Постоянные артистические поиски труппы опираются на лучшие образцы современного циркового искусства. Благодаря разносторонним талантам своих артистов цирк Элуаз стремится достичь новаторских высот сценического мастерства и гуманности, сочетая новую оригинальную манеру циркового исполнительства с музыкой, танцем и искусством театра. В репертуаре цирка Элуаз шесть оригинальных постановок, его артисты дали более 3000 представлений в 330 городах и 30 странах мира.</p>' + '<p>Впервые мы приехали в Россию в июле 2007 года для участия в престижном международном театральном фестивале имени А. П. Чехова. Нас глубоко взволновал ваш радушный прием, и мы надеемся вскоре к вам вернуться. Вы без труда можете узнать о нашем следующем визите на нашем сайте в интернете на <a href="/">французском</a> и <a href="/en/home">английском</a> языках.</p>' + '<p>Мы были счастливы видеть вас на наших представлениях, и хотим пожелать вам радости от нового общения с нами!</p>',

		"zh":

		'<p>您好，欢迎您浏览“幻光奇艺坊”网页！</p>' + '<p>自1993年以来，幻光奇艺坊(Cirque Éloize)处于杂技艺术革新的中心，创作了感人至深而富有诗意的戏剧。由于不断的艺术追求，它被列入现代艺术的排头兵。幻光奇艺坊依赖自己艺术家们多学科的才华，通过戏剧效果和人性，展现了它的创新性，它以前所未闻和独创的方式，把杂技艺术与音乐、舞蹈和戏剧结合为一体。幻光奇艺坊有六个创新的作品，已经在世界各地、30个国家、大约330座城市进行了3000多场演出。</p>' + '<p>感谢您浏览我们的网页，并希望，您能在我们的<a href="/">法文</a>或<a href="/en/home">英文</a>的网页上寻找到所需要的信息。迄今为止，我们尚未有幸到中国演出，但我们预料在最近几年，会在中国大地着陆，那么，请经常查阅我们的巡回演出日程，留意相关信息！希望很快见到您！浏览愉快！</p>'

	},

	/*
	* Initialize ze thing.
	*
	* @author		Frédéric Trudeau <ftrudeau@prospek.ca>
	* @copyright	Copyright (c) 2009 Prospek Inc. All rights reserved.
	*/
	steerItUp: function ()
	{
		
		// Check for method
		if (isU(Config.method))
		{
			alert("PK Class says: What do you want me to do? Method is undefined.\nUse Config.set('method', 'method_to_call') in your code.");
			return;
		}

		///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		// Configure jQuery's AJAX requests
		///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

		this.configureAjax();

		////////////////////////
		// INITIALIZE METHOD //
		//////////////////////

		if (!isF(this[Config.method]))
		{
			alert("PK Class says: I cannot initialize a method (" + Config.method + ") that does not exist");
		}

		// Figure short language (en|fr)
		Config.set('lang_short', Config.get('lang').split('_')[0]);

		// Run za thang.
		this[Config.method]();

	},

	/*
	* Home controller
	*
	* @author	Frédéric Trudeau <ftrudeau@prospek.ca>
	* @see		themes/cirqueeloize/index.php
	*/
	home: function ()
	{
		
		PK.cmActivate();
		PK.slideShowInit();
		PK.swActivate();

		// set default language for newsletter subscription
		$('#cm-language-' + Config.get('lang_short')).attr('checked', 'checked');

		// set mouse over on image sidebar
		$('.block_sidebar_single').mouseover(this.setSidebarLinkOver);
		$('.block_sidebar_single').mouseout(this.setSidebarLinkOut);

		this.last();

	},

	/*
	* News controller
	*
	* @author	Frédéric Trudeau <ftrudeau@prospek.ca>
	* @see		themes/cirqueeloize/news.php
	*/
	news: function ()
	{

		PK.swActivate();
		PK.last();

	},

	/*
	* 404 controller
	*
	* @author	Frédéric Trudeau <ftrudeau@prospek.ca>
	* @see		themes/cirqueeloize/404.php
	*/
	404: function () {
		PK.swActivate();
		PK.last();
	},
	
	/*
	* Special Events controller
	*
	* @author Frédéric Trudeau <ftrudeau@prospek.ca>
	* @see themes/cirqueeloize/special_event.php
	*/
	specialevents: function () {
		PK.last();
	},

	/*
	* Special Events Details controller
	*
	* @author Frédéric Trudeau <ftrudeau@prospek.ca>
	* @see themes/cirqueeloize/special_event_details.php
	*/
	specialeventsdetails: function () {
		jQuery('.js_specail_event_video').mouseenter(
			function () {
				yt_num = $(this).attr("rel");
				jQuery('.yt_' + yt_num).stop(true, true);
				jQuery('.yt_' + yt_num).fadeIn("fast");
			}
		);

		jQuery('.js_specail_event_video').mouseleave(
			function () {
				yt_num = jQuery(this).attr("rel");
				jQuery('.yt_' + yt_num).stop(true, true);
				jQuery('.yt_' + yt_num).fadeOut("fast");
			}
		);
		PK.lbActivate();
		PK.last();
	},

	/*
	* Contact controller
	*
	* @author		Frédéric Trudeau <ftrudeau@prospek.ca>
	* @see themes/cirqueeloize/contact.php
	*/
	contact: function ()
	{

		// jQuery.easing.def = "easeInOutExpo";

		PK.swActivate();

		var x = false;
		jQuery(".js_dropdownmenu").click(

		function () {
			if (x === false) {
				jQuery(".main").addClass("js_on");
				jQuery(".js_drop").fadeIn(300);
				x = true;
			}
			else {
				jQuery(".main").removeClass("js_on");
				jQuery(".js_drop").fadeOut(300);
				x = false;
			}
		});

		jQuery(".js_contact_link").click(
			function () {
				elm = $(this).attr('id').split('link');
				if ("block" != $("#contact" + elm[1]).css("display")) {
					jQuery(".js_contact_block").hide(10);
					jQuery("#contact" + elm[1]).show(300);
					jQuery("#js_contact_title").html($(this).html());
				}
			}
		);

		PK.last();

	},

	/*
	* Gallery controller
	*
	* @author		Frédéric Trudeau <ftrudeau@prospek.ca>
	* @see themes/cirqueeloize/gallery.php
	*/
	gallery: function ()
	{

		PK.lbActivate();
		PK.swActivate();
		PK.last();

	},

	/*
	* Shows controller
	*
	* @author		Frédéric Trudeau <ftrudeau@prospek.ca>
	* @see themes/cirqueeloize/shows.php
	*/
	shows: function ()
	{

		PK.last();

	},

	/*
	* Shows Details controller
	*
	* @author		Frédéric Trudeau <ftrudeau@prospek.ca>
	* @see themes/cirqueeloize/show_details.php
	*/
	showsdetails: function ()
	{

		PK.lbActivate();

		$("a.team_title").click
		(
			function ()
			{
				
				var href, parts, identifier, container;
				
				// Get indentifier and div container
				href = jQuery(this).attr('href');
				parts = href.split('#');
				identifier = parts[1];
				container = '#popup_team_' + identifier;
				
				// Show team member's popup, only if it was found
				if (jQuery(container).length) {
					jQuery(container).jqm({
						modal: true,
						toTop: true,
						onHide: function (H) {
							PK.setDialogFadeOut(H, false);
						}
					}).jqmShow();
				}
				
				// Listen for close
				jQuery(container).find('a.close').click(
					function () {
						jQuery(container).jqmHide();
					}
				);

				return false;

			}

		);

		PK.last();

	},

	/*
	* Shows Details List controller
	*
	* @author		Frédéric Trudeau <ftrudeau@prospek.ca>
	* @see themes/cirqueeloize/show_details_list.php
	*/
	showsdetailslist: function ()
	{
		PK.last();

	},

	/*
	* Who Are We controller
	*
	* @author		Frédéric Trudeau <ftrudeau@prospek.ca>
	* @see themes/cirqueeloize/whoarewe_details.php
	*/
	whoarewe: function ()
	{
		PK.lbActivate();
		
		$("a.team_title").click
		(
			function ()
			{
				var href, parts, identifier, container;
				
				// Get indentifier and div container
				href = jQuery(this).attr('href');
				parts = href.split('#');
				identifier = parts[1];
				container = '#popup_team_' + identifier;
				
				// Show team member's popup, only if it was found
				if (jQuery(container).length) {
					jQuery(container).jqm({
						modal: true,
						toTop: true,
						onHide: function (H) {
							PK.setDialogFadeOut(H, false);
						}
					}).jqmShow();
				}
				
				// Listen for close
				jQuery(container).find('a.close').click(
					function () {
						jQuery(container).jqmHide();
					}
				);

				return false;

			}

		);
		
		PK.swActivate();
		PK.last();
	},

	store: function ()
	{

		PK.last();

	},

	sitemap: function ()
	{

		PK.last();

	},

	///////////////////////////////////////
	// BEGIN COMMON AND PRIVATE METHODS //
	/////////////////////////////////////

	setSidebarLinkOver: function ()
	{

		$(this).find('a.js_sidebar_title').addClass('sidebar_selected');
		$(this).find('img.sidebar_arrow').attr('src', '/assets/images/arrow_white.gif');
		Cufon.refresh();

	},

	setSidebarLinkOut: function ()
	{

		$(this).find('a.js_sidebar_title').removeClass('sidebar_selected');
		$(this).find('img.sidebar_arrow').attr('src', '/assets/images/arrow_red.gif');
		Cufon.refresh();

	},

	/*
	* Stuff to do last
	*
	* @author		Frédéric Trudeau <ftrudeau@prospek.ca>
	* @copyright	Copyright (c) 2009 Prospek Inc. All rights reserved.
	*/

	last: function ()
	{

		// Create target blank
		jQuery(".extlink").attr("target", "_blank");

		// Bind click listerner on links having the "popup_i18n" class
		jQuery("#i18n a.popup_i18n").bind("click", function () {
			D = jQuery(PK.I18N_DIALOG).render({
				"text": PK.I18N_TEXTS[jQuery(this).attr("rel")]
			}, {
				"clone": true,
				"preserve_template": true
			});

			// Inject to DOM, just before the body end tag
			jQuery("body").append(D);

			$('#dialog_i18n a.close').click(

			function () {
				$('#dialog_i18n').jqmHide();
			});

			// DIAG.jqm
			D.jqm(

			{

				modal: true,
				toTop: true,
				onShow: function (H) {},
				onHide: function (H) {

					// Set default modal dialog fadeOut properties
					PK.setDialogFadeOut(H, true);

				}

			}

			).jqmShow();

		}

		);

	},

	/*
	* Campain monitor initialization
	*
	* @author		Frédéric Trudeau <ftrudeau@prospek.ca>
	* @copyright	Copyright (c) 2009 Prospek Inc. All rights reserved.
	*/
	cmActivate: function ()
	{

		PK.cm = {};
		PK.cm.nameValue = $("#cm-name").val();
		PK.cm.emailValue = $("#cm-email").val();

		$("#cm-email,#cm-name").click(

		function () {
			if (($(this).attr('id') == 'cm-email' && $(this).val() == PK.cm.emailValue) || ($(this).attr('id') == 'cm-name' && $(this).val() == PK.cm.nameValue)) {
				$(this).attr('value', '');
			}
		});

		$("#cm-email,#cm-name").blur(

		function () {
			if ($(this).attr('id') == 'cm-email' && $(this).val() == '') {
				$(this).attr('value', PK.cm.emailValue);
			}

			if ($(this).attr('id') == 'cm-name' && $(this).val() == '') {
				$(this).attr('value', PK.cm.nameValue);
			}
		});

		// Make sure form wont submit
		jQuery('form#cm-form').submit(

		function () {
			return false;
		});
		// doRegister if [ENTER] key is pressed
		jQuery(document).keypress(

		function (e) {
			if (e.keyCode === 13) {
				PK.cmPost('cm-form-error');
				return false;
			}
		});
		// doRegister on submit
		jQuery("input#cm-form-submit").click(

		function () {
			PK.cmPost('cm-form-error');
			return false;
		});

	},

	/*
	* Campain monitor POST
	*
	* @author	Frédéric Trudeau <ftrudeau@prospek.ca>
	* @param	string	Error container ID
	* @copyright	Copyright (c) 2009 Prospek Inc. All rights reserved.
	*/
	cmPost: function (ec) {

		// Grab data
		var root = jQuery('form#cm-form');
		var email = root.find("input#cm-email").val();
		var name = root.find("input#cm-name").val();
		var listid = root.find("input[name=language]:checked").val();

		// hide ec
		if (ec !== undefined) {
			jQuery('#' + ec).hide();
		}

		// Validate email
		if (!isValidEmail(email)) {
			// show error container
			if (ec !== undefined) {
				jQuery('#' + ec).fadeIn(300);
			}
			return;
		}

		// Validate listid
		if (typeof listid === 'undefined') {
			// show error container
			if (ec !== undefined) {
				jQuery('#' + ec).fadeIn(300);
			}
			return;
		}

		// Reset input text
		// Render and wait message dialog
		PK.DIALOG.active = PK.renderDialog(PK.WAIT_MSG_GENERIC);

		// Submit the form via ajax
		jQuery.ajax({
			url: "/proxies/campaignmonitor.php",
			type: "POST",
			data: {
				email: email,
				name: name,
				listid: listid,
				method: 'ajax'
			},
			success: function (html) {
				// show confirmation modal dialog
				PK.DIALOG.active = PK.renderDialog(PK.NW_MSG_CONF);
			},
			error: function (XMLHttpRequest, textStatus, errorThrown) {},
			complete: function () {}
		});

	},


	/*
	* Slideshow initialization
	*
	* @author		Frédéric Trudeau <ftrudeau@prospek.ca>
	* @copyright	Copyright (c) 2009 Prospek Inc. All rights reserved.
	*/
	slideShowInit: function ()
	{

		var slides, vignette, target, href, button;
		
		// Set current slide index
		PK.SLIDESHOW.index = 0;
		
		// Get available slides
		slides = jQuery('#slideshow div.slide');
		
		// Activate slideshow
		if (slides.length && slides.length > 1) {
			
			jQuery(slides).each(
					
				function (index, slide) {
					
					// Get vignette
					vignette = jQuery(slide).find('.nh_vignette');

					// Get link target
					target = jQuery(slide).find('a.btn_slider');
					
					// Remove link on vignette if no target was found
					if (!target.length) {
						
						jQuery(vignette).css('cursor', 'default');
						
					} else {
						
						// Get link href
						href = jQuery(target).attr('href');
						
						// Get button
						button = jQuery(vignette).find('a.btn_slider');
						
						jQuery(vignette).addClass('cursor_pointer');
						jQuery(vignette).click(
							function () {
								location.href = href;
							}
						);
						
					}
					
				}
				
			);

			jQuery('.btn_home_slideshow').click
			(
				function () {
					var slide = parseInt(jQuery(this).html(), 10);
					PK.slideShowGoTo(slide);
				}
			);

			// Hide non-current slides
			jQuery('#slideshow div.slide').not('#current').css
			(
				{
					display: 'none'
				}
			);

			// Run slideshow for the first time
			PK.SLIDESHOW.interval = setTimeout
			(
				function ()
				{
					PK.slideShowRun
					(
						'#slideshow div.slide',
						PK.SLIDESHOW.index + 1
					);
				},
				PK.SLIDESHOW.firstDelay
			);
			
		}
	},
	
	/*
	* @author		Stephane Taurand <staurand@prospek.ca>
	* @copyright	Copyright (c) 2009 Prospek Inc. All rights reserved.
	*/
	slideShowGoTo: function (index)
	{
		
		// Stop animation and complete it, and remove any queued animation on current slide
		jQuery(jQuery("#slideshow div.slide")[PK.SLIDESHOW.index]).stop(true, true);
		
		// Reset clock
		clearInterval(PK.SLIDESHOW.interval);
		
		// Run slideshow again
		PK.slideShowRun("#slideshow div.slide", index);

	},

	/*
	*
	* @author		Frédéric Trudeau <ftrudeau@prospek.ca>
	* @copyright	Copyright (c) 2009 Prospek Inc. All rights reserved.
	*/
	slideShowRun: function (to_fade, index)
	{
		
		var items = jQuery(to_fade);
		
		if (index === items.length) {
			index = 1;
		}
		
		PK.SLIDESHOW.index = index;

		var currentitem = items.filter(':visible');
		var new_item;
		var selector;

		items.css('visibility', 'visible');

		if (items.length > 1) {

			/*
			if (jQuery('#current').length > 0) {
				new_item = jQuery(items[index + 1]);
			} else {
				new_item = jQuery(items[index]);
			}
			*/
			
			new_item = jQuery(items[index]);
			
			// Remove active state on previous button, and add it to next one
			jQuery(jQuery("#slideshow .btn_home_slideshow.current_slide")).removeClass('current_slide');
			jQuery(jQuery("#slideshow .btn_home_slideshow")[PK.SLIDESHOW.index - 1]).addClass('current_slide');

			if (new_item.css('display') == 'none')
			{
			
				currentitem.css
				(
					{
						zIndex: 2
					}
				);

				new_item.css
				(
					{
						zIndex: 3
					}
				).fadeIn
				(
						
					1200,
					function ()
					{
						
						
						currentitem.css
						(
							{
								display: "none"
							}
						);
						
						PK.SLIDESHOW.interval = setTimeout
						(
							function ()
							{
								PK.slideShowRun("#slideshow div.slide", PK.SLIDESHOW.index + 1);
							},
							PK.SLIDESHOW.delay
						);
						
						
						
						// Delete 1st image :  mosaic play only one time
						// jQuery('#current').remove();
						
					}
					
				);
				
			}
			
		}

	},

	/*
	* Lightbox initialization
	*
	* @author		Alexandre Dumouchel <adumouchel@prospek.ca>
	* @author		Frédéric Trudeau <ftrudeau@prospek.ca>
	* @copyright	Copyright (c) 2009 Prospek Inc. All rights reserved.
	*/
	lbActivate: function ()
	{
		var c, cc;
		
		c = jQuery('div#container div[id^=photo_gallery]');
		
		if (c.length) {
			cc = c.length;
			for (i = 1; i <= cc; i++) {
				jQuery('.lightBox_' + i).lightBox();
				jQuery('.lightBox_' + i + ', img').bind("contextmenu", function (e) {
					return false;
				});
			}
		} else {
			jQuery('.lightBox').lightBox();
			jQuery('.lightBox, img').bind("contextmenu", function (e) {
				return false;
			});
		}
		
		$(".js_spect_ante").mouseover(

		function () {
			elm = $(this).attr('id').split('spect_ante');
			$('#spect_ante' + elm[1] + '_o').css('display', 'block');
		}).mouseout(

		function () {
			elm = $(this).attr('id').split('spect_ante');
			$('#spect_ante' + elm[1] + '_o').css('display', 'none');
		});

		$(".js_specail_event_video").click(

		function () {
			link = $(this).attr('href');
			$('.block_youtube').html('<object width="565" height="343" id="special_event_player"><param name="movie" value="' + link + '"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="' + link + '" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="565" height="343"></embed></object>');
			return false;
		});

	},

/*
	* Share widget dialog activation
	*
	* @author		Frederic Trudeau <ftrudeau@prospek.ca>
	* @copyright	Copyright (c) 2009 Prospek Inc. All rights reserved.
	*/
	swActivate: function ()
	{

		// Define SW object
		PK.SW = {};

		// Define values
		PK.SW.values = {};

		// Define properties
		PK.SW.cont = "div#PK_sw_fc";
		PK.SW.ac = "a#PK_sw_ac"; // Action close
		PK.SW.lo = "img#PK_sw_al"; // Loader
		PK.SW.ap = "a#PK_sw_ap"; // Action post
		// Bind click listerner on links having the "sharewidget" class
		jQuery("a.sharewidget").bind("click", function () {

			// Save item id
			PK.SW.id = jQuery(this).attr("id");
			if (PK.SW.id.substring(0, 2) == 'p_') {
				PK.SW.id = PK.SW.id.substring(2, PK.SW.id.length);
			}

			// Render share widget dialog
			PK.SW.instance = jQuery(PK.SW_DIALOG).render({}, {
				"clone": true,
				"preserve_template": true
			});

			// Inject to DOM, just before the body end tag
			jQuery("body").append(PK.SW.instance);

			// DIAG.jqm
			PK.SW.instance.jqm(

			{

				modal: true,
				toTop: true,
				onShow: function (H) {

					// Set default modal dialog fade-in properties
					PK.setDialogFadeIn(H);

					// Activate listeners
					PK.swListeners();

					// Reset input text on focus
					jQuery(H.w).find(":input").bind("focus", function () {
						if (!jQuery(this).hasClass("noevent")) {
							// Bind only once. We do not want to reset ze input text every time the user makes focus on it.
							jQuery(this).val("").unbind("focus").css({
								borderColor: "#a7a7a9",
								color: "#81807f"
							});
						}
					});

					// Post root container
					root = jQuery("div#post_" + PK.SW.id);

					// Fetch post properties
					PK.SW.values.http_host = root.find("input[name=PK_http_host]").val();
					PK.SW.values.date = root.find("input[name=PK_post_date]").val();
					PK.SW.values.title = root.find("input[name=PK_post_title]").val();
					PK.SW.values.title_clean = root.find("input[name=PK_post_title_clean]").val();
					PK.SW.values.link = root.find("input[name=PK_post_link]").val();
					PK.SW.values.link_clean = root.find("input[name=PK_post_link_clean]").val();
					PK.SW.values.excerpt = root.find("input[name=PK_post_excerpt]").val();

					// Assign permalink to input text
					jQuery("input#PK_sw_permalink").val(PK.SW.values.http_host + PK.SW.values.link);

					// Replace media links
					ml = ["facebook", "twitter", "linkedin", "delicious", "google", "sharethis"];
					jQuery(ml).each(

					function (z, cls) {
						el = jQuery("ul#social-media-popups ." + cls);
						el.attr("href", el.attr("href").replace("%LINK%", PK.SW.values.http_host + PK.SW.values.link_clean).replace("%EXCERPT%", PK.SW.values.excerpt));
					});

					// Add listerners in social-media-popups
					jQuery("ul#social-media-popups .popup").PK_popup(function () {}, {
						"t": "regular",
						"w": "300",
						"h": "300",
						"o": "noicon"
					});

				},

				onHide: function (H) {

					// Set default modal dialog fadeOut properties
					PK.setDialogFadeOut(H, true);

				}

			}

			).jqmShow();

		});

	},

/*
	* Share widget listeners activation
	*
	* @author		Frédéric Trudeau <ftrudeau@prospek.ca>
	* @copyright	Copyright (c) 2009-2010 Prospek Inc. All rights reserved.
	*/
	swListeners: function ()
	{

		////////////////////////////
		// Close button listener //
		//////////////////////////
		jQuery(PK.SW.ac).click(

		function () {
			// pageTracker._trackEvent("Share Widget", "Button", "Close");
			PK.SW.instance.jqmHide();
		});

		//////////////////
		// Post action //
		////////////////
		jQuery(PK.SW.ap).click(

		function () {

			// Initialize empty friends object
			PK.SW.friends = [];

			// Assign values
			v = PK.SW.values;

			// Check name and email
			sender_name = jQuery("input[name=yn]").val();
			sender_mail = jQuery("input[name=ye]").val();

			// Make sure sender email is valid
			if (!isValidEmail(sender_mail)) {
				jQuery("input[name=ye]").val(Language.get('error_generic_email')).css({
					borderColor: "#fa4800",
					color: "#fa4800"
				}).bind("focus", function () {
					jQuery(this).val("").unbind("focus").css({
						borderColor: "#a7a7a9",
						color: "#81807f"
					});
				});
				return;
			}

			// Make sure we got a non-empty string for sender name
			if (sender_name == "" || sender_name === "Votre nom") {
				jQuery("input[name=yn]").val(Language.get('error_generic_empty_name')).css({
					borderColor: "#fa4800",
					color: "#fa4800"
				}).bind("focus", function () {
					jQuery(this).val("").unbind("focus").css({
						borderColor: "#a7a7a9",
						color: "#81807f"
					});
				});
				return;
			}

			// Hide instance
			PK.SW.instance.jqmHide();

			// Show generic wait message
			PK.DIALOG.active = PK.renderDialog(PK.WAIT_MSG_GENERIC);

			// Populate friends object
			jQuery("input[name^=fe_]").each(

			function (k, v) {
				PK.SW.friends.push({
					"e": jQuery(v).val(),
					"n": jQuery("input[name^=fn_]").eq(k).val()
				});
			});

			// Submit the form via ajax
			jQuery.ajax({
				url: "/proxies/sendtofriend.php",
				type: "POST",
				data: {
					id: PK.SW.id,
					link: v.link,
					title: v.title,
					title_clean: v.title_clean,
					// excerpt: v.excerpt,
					sender_name: jQuery("input[name=yn]").val(),
					sender_email: jQuery("input[name=ye]").val(),
					friends: jQuery.json.encode(PK.SW.friends),
					method: 'ajax',
					lang: Config.get('lang')
				},
				success: function (data) {
					// Check response status
					if (data.status === 'ok') {
						PK.DIALOG.active = PK.renderDialog(
						PK.SW_MSG_CONF, {
							"happynumber": data.response.sent
						});
					}
					else {
						// Hide share widget
						PK.hideDialog(PK.DIALOG.active);
						if (data.response === "RECIPIENTS_EMPTY") {
							// Render and show error dialog
							PK.DIALOG.active = PK.renderDialog(PK.SW_ERR_RECIPIENTS_EMPTY);
						}
						else {
							// Render and show generic error dialog
							PK.DIALOG.active = PK.renderDialog(PK.ERR_MSG_GENERIC);
						}

					}

				},
				error: function (XMLHttpRequest, textStatus, errorThrown)
				{

					// Hide share widget
					PK.hideDialog(PK.DIALOG.active);

					// Render and show generic error dialog
					PK.DIALOG.active = PK.renderDialog(PK.ERR_MSG_GENERIC);

				},
				complete: function () {}

			}

			);

		}

		);

	},

	/*
	* Styles and animations to be applied on jqmDialog fade in
	*
	* @author		Frederic Trudeau <ftrudeau@prospek.ca>
	* @copyright	Copyright (c) 2009 Prospek Inc. All rights reserved.
	* @param		H	object	The jqm hash
	*/
	setDialogFadeIn: function (H)
	{

		H.o.css
		(
			{
				'display': 'none',
				'cursor': 'progress'
			}
		);

		// Dialog default style
		H.w.css("display", "none");

		// Fancy overlay fadein
		H.o.fadeIn
		(
			200,
			function ()
			{
				H.w.show();
			}
		);

	},

	/*
	* Styles and animations to be applied on jqmDialog fade out
	*
	* @author		Frederic Trudeau <ftrudeau@prospek.ca>
	* @copyright	Copyright (c) 2009 Prospek Inc. All rights reserved.
	* @param		H		object	The jqm hash
	* @param		killW	bool	If we should remove the dialog from the DOM once the fade out action is completed
	*/
	setDialogFadeOut: function (H, killW)
	{

		if (killW === 'undefined')
		{
			killW = false;
		}

		H.w.fadeOut
		(
			200,
			function ()
			{
				H.o.fadeOut
				(
					200,
					function ()
					{
						H.o.remove();
						if (killW === true)
						{
							H.w.remove();
						}
					}
				);
			}
		);

	},

/*
	* Configure jQuery's AJAX requests
	*
	* @author		Frédéric Trudeau <ftrudeau@prospek.ca>
	* @see			http://docs.jquery.com/Ajax/jQuery.ajax#options
	*/
	configureAjax: function () {
		jQuery.ajaxSetup(

		{
			async: true,
			// We want all requests to be asynchronously
			cache: true,
			// Allow caching, to avoid nasty
			global: false,
			// Prevent the global handlers like ajaxStart or ajaxStop from being triggered
			dataType: 'json',
			// Default data type expected back from server
			beforeSend: function (request) // Listener : Before the request is sent
			{},
			complete: function (request) // Listener : Once request is complete
			{}
		}

		);

	},

/*
	* Render a dialog
	*
	* @author		Frédéric Trudeau <ftrudeau@prospek.ca>
	* @copyright	Copyright (c) 2009 Prospek Inc. All rights reserved.
	* @param		T	string	Dialog template
	* @param		D	object	Data to replace into ze template
	* @param		C	object	Configuration options
	* @param		cb	object	Callbacks
	* @uses			jQuery jqModal cufon
*/

	renderDialog: function (T, D, C, cb) {
		// alert('renderDialog : '+T+','+ D +','+ C+','+ cb)
		// Check that jqModal plugin was loaded
		// @fixme Load jQuery Tools dynamically here
		if (jQuery.jqm === undefined) {
			alert("Les internets semblent être brisés. Nous travaillons régler la situation.");
			return false;
		}

		if (typeof D !== "object") {
			D = {};
		}

		if (typeof C !== "object") {
			C = {
				"addclose": PK.DIALOG.addclose,
				"autodisplay": PK.DIALOG.autodisplay,
				"cufon": PK.CUFON
			};
		}


		// Create DIV from template
		if (typeof T === "string") {
			T = jQuery(T);
		}

		DOM = jQuery(T).render(
		D, {
			"clone": true,
			"preserve_template": true
		});

		// Get div ID, which will be very usefull (??)
		ID = jQuery(DOM).attr("id");

		if (typeof DOM === "object") {
			// Insert template in DOM, before the body end tag
			jQuery("body").append(DOM);
		}
		else {
			return false;
		}

		// if (typeof C === "object")
		// {
		// SUPPORT FOR CLOSE BUTTON + APPROPRIATE LISTENER
/*
		if (typeof C.addclose === "boolean")
		{
			// TODO	Auto generate DOM for close button ? Heck, Why not !
			// Add close listener
			jQuery(DOM).bind
			(
				"click",
				function (e)
				{
					PK.hideDialog(DOM);
				}
			);
		}
		*/

		// SUPPORT FOR CUFON
		if (typeof C.cufon === "object") {
			if (typeof C.cufon.fonts === "object") {
				jQuery.each(C.cufon.fonts, function (k, v) {
					// alert (k + ':' + v);
					Cufon.replace("#" + ID + " ." + k, v);
				});
			}
			if (typeof C.cufon.fadeindelay === "number" || typeof C.cufon.fadeindelay === "string") {
				if (navigator.appName !== "Microsoft Internet Explorer") {
					jQuery("#" + ID + ' .cufon').animate({
						opacity: 1
					}, C.cufon.fadeindelay);
				}
				else {
					jQuery("#" + ID + ' .cufon').animate(1000).css({
						visibility: "visible"
					});
				}
			}
		}

		// SUPPORT FOR AUTO-DISPLAY
		if (typeof C.autodisplay === "boolean") {

			if (C.autodisplay === true) {

				// Hide previous dialog
				if (PK.DIALOG.active !== false) {
					PK.hideDialog(PK.DIALOG.active);
				}

				// Show ze new dialog
				// var myOpen=function(hash){ hash.w.css('opacity',0.88).show(); };
				// jQuery(d).jqm({modal: true, }).jqmHide();
				jQuery(DOM).jqm({
					overlay: 75,
					modal: true,
					toTop: true,
					closeClass: "dialogclose",
					onShow: function (hash) {
						jQuery(hash.w).css("zIndex", "9999");
						PK.setDialogFadeIn(hash);
						if (typeof cb === "object") {
							if (cb.onShow) {
								eval(cb.onShow);
							}
						}
					},
					onHide: function (hash) {
						PK.setDialogFadeOut(hash, true);
						if (typeof cb === "object") {
							if (cb.onHide) {
								eval(cb.onHide);
							}
						}
					}
				}).jqmShow();

			}
		}

		return ID;

	},

	hideDialog: function (d) {
		if (typeof d === "string") {
			d = jQuery("div#" + d);
		}
		jQuery(d).jqmHide();
	}

};

/*
* Returns the given URL's action-type if it is:
*
* a) a link to an external site	-> external
* b) a mailto link				-> mailto
* c) a downloadable file		-> download
*/

function decorateLink(u) {

	opts = {
		extensions: ['pdf', 'doc', 'docx', 'xls', 'csv', 'jpg', 'gif', 'mp3', 'swf', 'txt', 'ppt', 'zip', 'gz', 'dmg', 'xml', 'vcf']
	};

	if (u.indexOf('://') === -1 && u.indexOf('mailto:') !== 0) {
		// no protocol or mailto - internal link - check extension
		var ext = u.split('.')[u.split('.').length - 1];
		var exts = opts.extensions;

		for (i = 0; i < exts.length; i++) {
			if (ext === exts[i]) {
				return "download";
			}
		}
	}
	else {
		if (u.indexOf('mailto:') === 0) {
			return "mailto";
		}
		else {
			return "external";
		}
	}
}

/*
* Initialize PK Class on document ready
*/
jQuery
(
	function ()
	{
		PK.steerItUp();
	}
);

