$(function(){
	var annCookieName = 'crij_announces';	// cookie var name
	var currAnnCookieArr = $.cookie(annCookieName);
	if ((currentController != 'job')&&(currentController != 'special')&&(currentController != 'logement')){
		currentController = 'job';			
	}
	
	//	Update announce cart
	function updateCart () {
		if(($.cookie(annCookieName) != null)&&($.cookie(annCookieName).length>0)) {
			var arrCookie = $.cookie(annCookieName).split(',');
		} else {
			var arrCookie = new Array();
		}
		$('.amount').html(' '+arrCookie.length+' ');
	}

	//	Remove current announce from cart
	function removeCurrAnnounce ( cId ) {
		var arrCookie = $.cookie(annCookieName).split(',');
		for (i in arrCookie){
			if(arrCookie[i] == cId ){
				arrCookie.splice(i,1);
				$.cookie(annCookieName, arrCookie.toString(), { path: "/" });
			}
		}
		updateCart();
	}

	function notify(flash_message, x, y){
		var flash_div = $(".flashmessage");
  		if (x && y)
		{
			flash_div.css({top: y-50});
			flash_div.css({left: x-10});
		}
		flash_div.html(flash_message);
		flash_div.fadeIn(400);
		setTimeout(function(){
			flash_div.fadeOut(500,function(){
				flash_div.html("");
				flash_div.hide()
			})
		}, 3000);
	}

	function announceModalMenu () {
		// bind submit action to send-invite form
	 	$('#send_invite', h.w.filter('#cart')).submit(function(){
	 		if($(this).valid()){
	 			$('#send_invite').ajaxSubmit({ 
					dataType: 'json',
					success: function (data) {
						var url = baseUrl+'/ads/'+currentController+'/cart/format/html';
						$.ajax({
							url: url,
							success: function ( resp ) {
								h.w.html( resp );
								announceModalMenu(h);
							}
						});
			 		}
				});
	 		}
	 		return false;
	 	});
	 	
		//	sending recommended announces from cart window

	
		h.w.jqmAddClose('.close', h.w);
	}

	// print in received-from-friend window 
	function Tooltip(){
		$('.form li.tooltip label').cluetip({
			cluetipClass: 'jtip', 
			sticky: true,
	      	mouseOutClose: true,
	  		local: true, 
	  		hideLocal: true,
			closePosition: 'title',
	  		closeText: 'X'
		});
	}
	Tooltip();

	$('body').append('<div class="flashmessage" id="flash"></div>');
	$('.flashmessage').hide();

	function onShowCart(){
		$('.jqmcontent a.subject').nyroModal({
			closeButton:null, 
			width: 600, 
			height: 400,
			url: this.href,
			endShowContent: function(elts, settings){
				onShowDetails();
			}    
		});
		$('.print a').click( function(event) {
			event.preventDefault();
			var allIds = new Array();
			var url = baseUrl+'/ads/'+currentController+'/print-cart';
			$('tbody input:checked').each( function () {
				var type = $(this).parents('tr').children('td.cat').children('div.sub').text();
				allIds.push($(this).val()+':'+type.toLowerCase());
			});
			window.open(url+'?recommend='+allIds.join(','), 'print', 'width=700,height=700,location=0,menubar=0,resizable=0,scrollbar=1,status=0,toolbar=0');			
		});
		$('.remove a').click( function(event) {
			event.preventDefault();
			$('tbody input:checked').each(function(){
				var type = $(this).parents('tr').children('td.cat').children('div.sub').text();
				removeCurrAnnounce ($(this).val()+':'+type.toLowerCase());
				$(this).parents('tr').remove();
				
			});
			updateCart();
		});		
		$('thead input[type="checkbox"]').click( function() {
			var allInps = $('tbody input[type="checkbox"]');
			$(this).is(':checked') 
			? allInps.each( function () { this.checked = true; })
			: allInps.each( function () { this.checked = false; });
		});
		$('.nyroModal').nyroModal();
		$('.invite a').click( function(event) {
			event.preventDefault();
			var allIds = new Array();
			var url = baseUrl+'/ads/'+currentController+'/invite-cart/format/html';
			$('tbody input:checked').each( function () {
				var type = $(this).parents('tr').children('td.cat').children('div.sub').text();
				allIds.push($(this).val()+':'+type.toLowerCase());
			});
			$.nyroModalManual({
				closeButton:null, 
				width: 600, 
				height: 430,
				url: url,
				type: "POST",
				data: { recommend: allIds.join(',') },
				endShowContent: function(elts, settings){
				 	$('#send_invite').submit(function(){
				 		if($(this).valid()){
				 			$('#send_invite').ajaxSubmit({ 
								dataType: 'json',
								success: function (data) {
								 	$.nyroModalManual({
										closeButton:null, 
										width: 600, 
										height: 400, 
										url: baseUrl+'/ads/'+currentController+'/cart/format/html',
										endShowContent: function(elts, settings){
											onShowCart();
										}
									});
						 		}
							});
				 		}
				 		return false;
				 	});
				}    
			});
		});
	}
	
	function onShowDetails(){
		$('.addtocart a').click( function(event) {
			event.preventDefault();
			var currAnnVal = $('#announce_id').val()+':'+currentController;
			if (currAnnVal !== 'undefined') {
				var arrCookie;
				currAnnCookieArr = $.cookie(annCookieName);
				if (currAnnCookieArr) {
					arrCookie = currAnnCookieArr.split(',');
					for (i in arrCookie) 
						if(currAnnVal == arrCookie[i]) return $(this);
					currAnnCookieArr += ',' + currAnnVal;
				} else {
					currAnnCookieArr = currAnnVal;
				}
			}
			$.cookie(annCookieName, currAnnCookieArr, { path: "/" });
			notify('Votre annonce a bien été ajoutée au panier', event.pageX, event.pageY);
			updateCart();
		});
		$('.backtocart a').nyroModal({
			closeButton:null, 
			width: 600, 
			height: 400,
			url: this.href,
			endShowContent: function(elts, settings){
				onShowCart();
			}    
		});
		$('.invite a').nyroModal({
			closeButton:null, 
			width: 600, 
			height: 430,
			endShowContent: function(elts, settings){
			 	$('#send_invite').submit(function(){
			 		if($(this).valid()){
			 			$('#send_invite').ajaxSubmit({ 
							dataType: 'json',
							success: function (data) {
								if(data.url.length>0){
								 	$.nyroModalManual({
										closeButton:null, 
										width: 600, 
										height: 400, 
										url: data.url,
										endShowContent: function(elts, settings){
											onShowDetails();
										}
									});
								}
					 		}
						});
			 		}
			 		return false;
			 	});
				$('button#add_recipient').click(function(){
					$new_recipient = $(
					'<tr id="recipient">'+
					'	<td>'+
					'		Prénom de votre ami <input id="to_name" class="required" type="text" value="" name="bcc_name[]"/>'+
					'	</td>'+
					'	<td class="inp" colspan="2">'+
					'		Email de votre ami <input id="to_email" class="required" type="text" value="" name="bcc_email[]"/>'+
					'	</td>'+
					'</tr>');
					$('tr#recipient:last').after($new_recipient);
					return false;	
				});
				
			},    
			ajax:{
				url: this.href,
				data: { id : $('#announce_id').val(), type : currentController }
			}
		});
		$('.print a').click( function(event) {
			event.preventDefault();
			var url = baseUrl+'/ads/'+currentController+'/print/id/'+$('#announce_id').val();
			window.open(url, 'print', 'width=700,height=700,location=0,menubar=0,resizable=0,scrollbar=1,status=0,toolbar=0');			
		});
	}
        

	function bindModal(){
		$('.cart a').nyroModal({
			closeButton:null, 
			width: 600, 
			height: 400,
			endShowContent: function(elts, settings){
				onShowCart();
			}
		});
		$('table.announcelist .details a').nyroModal({
			closeButton:null, 
			width: 600, 
			height: 400, 
			endShowContent: function(elts, settings){
				onShowDetails();
			}
		});				
	};

	bindModal();

	// print in received-from-friend window 
	$('.detailsfooter .print a').click( function(event) {
		event.preventDefault();
		var url = baseUrl+'/ads/'+currentController+'/print/id/'+$('#announce_id').val();
		window.open(url, 'print', 'width=700,height=700,location=0,menubar=0,resizable=0,scrollbar=1,status=0,toolbar=0');			
	});
	// add to cart in received-from-friend window 
	$('.detailsfooter .addtocart a' ).click( function(event) {
			event.preventDefault();
			
			var currAnnVal = $('#announce_id').val()+':'+currentController;
//			var currAnnVal = $('#announce_id').val();
			if (currAnnVal !== 'undefined') {
				var arrCookie;
				currAnnCookieArr = $.cookie(annCookieName);
				if (currAnnCookieArr) {
					arrCookie = currAnnCookieArr.split(',');
					for (i in arrCookie) 
						if(currAnnVal == arrCookie[i]) return $(this);
					currAnnCookieArr += ',' + currAnnVal;
					}
				else {
					currAnnCookieArr = currAnnVal;
					}
			}
			$.cookie(annCookieName, currAnnCookieArr, { path: "/" });
			updateCart();
			
	});

	options = {
		success: function(data){
			$('#list-container').html(data).hide().slideDown();
			bindModal();
		}
	};
	
	$('#filter-ads-form').ajaxForm(options);
	updateCart();

	// Add check all checkboxes
	(function() {
		var checkAllId = 0;
		var curDiv;
		var checkID;
		$('#announce_sector, #announce_geozone').each(function() {
			curDiv = $(this);
			checkAllId++;
			checkID = "check-all-" + checkAllId;
	
			// create check
			curDiv
				.children('h4')
				.after('<input type="checkbox" class="ads-filter-check-all" id="' + checkID + '" /><label for="' + checkID + '" class="ads-filter-check-all">Tout cocher</label>');
			$('.ads-filter-check-all', curDiv).click(function() {
				$('li input[type=checkbox]', $(this).parent()).attr('checked', $(this).attr('checked'));
			});
		});
	})();

})
