/**
 * Javascript for all metropolitain and international websites
 * 
 * @author        Mouhamed SEYE <mouhamed@seye.fr>
 * @copyright     Henner
 */

/**
 * jQuery Plugins 
 */
jQuery.expr[':'].exactcontains = function(obj, index, meta, stack) {
	return (obj.textContent || obj.innerText || $(obj).text() || "").toLowerCase() == meta[3].toLowerCase();
}

jQuery.fn.openInPopup = function(width, height, target, resizable, scrollbars) {
	if (!target) target = 'henner';
	if (!resizable) resizable = 1	;
	if (!scrollbars) scrollbars = 1;
	
	$(this).click(function() {
        var url = $(this).attr('href');
        if (!url) return false;
        window.open(url, target, 'resizable=' + resizable + ',scrollbars=' + scrollbars + ',width=' + width + ',height=' + height);
        return false;
    });
}

jQuery.fn.activeXOverlap = function() {
	$(this).each(function(i){
        var h   = $(this).outerHeight();
        var w   = $(this).outerWidth();
        var iframe  = '<!--[if IE 6]>' +
        	'<iframe src="javascript:false;" style="height: ' +
            h +
            'px; width: ' +
            w +
            'px" class="selectOverlap">' +
            '</iframe>' +
            '<![endif]-->'
        $(this).prepend(iframe);
    });
}

jQuery.fn.showInOverlay = function() {
    window.scroll(0,0) ;
    var maskHeight = $(document).height();
    var maskWidth = $(window).width();
    $('#mask')
        .css({'width':maskWidth,'height':maskHeight})
        .fadeIn("fast")
        .fadeTo("fast",0.5);
    var winH = $(window).height();
    var winW = $(window).width();
    $(this)
        .css('top',  winH/2-$(this).height()/2)
        .css('left', winW/2-$(this).width()/2)
        .fadeIn("fast");
}

jQuery.fn.activateOnly = function(flag) {
	$('#contentSearch p')
		.css('backgroundColor', '#F0F0F0')
		.children('input,select')
		.attr('disabled', true);
	$(this)
		.parent()
		.css('backgroundColor', '#FFF')
		.children('input,select')
		.attr('disabled', false);
}

jQuery.fn.allActivated = function() {
	var all = true;
	$(this).each(function(){
		if (!($(this).siblings('input:checkbox').attr('checked'))) {
			all = false;
		}
	})
	return all;
}

jQuery.fn.htmlentities = function(texte) {
	//texte = texte.replace(/"/g,'&quot;'); // 34 22
	texte = texte.replace(/&/g,'&amp;'); // 38 26
	//texte = texte.replace(/\'/g,'&#39;'); // 39 27
	texte = texte.replace(/</g,'&lt;'); // 60 3C
	texte = texte.replace(/>/g,'&gt;'); // 62 3E
	texte = texte.replace(/\^/g,'&circ;'); // 94 5E
	texte = texte.replace(/‘/g,'&lsquo;'); // 145 91
	texte = texte.replace(/’/g,'&rsquo;'); // 146 92
	texte = texte.replace(/“/g,'&ldquo;'); // 147 93
	texte = texte.replace(/”/g,'&rdquo;'); // 148 94
	texte = texte.replace(/•/g,'&bull;'); // 149 95
	texte = texte.replace(/–/g,'&ndash;'); // 150 96
	texte = texte.replace(/—/g,'&mdash;'); // 151 97
	texte = texte.replace(/˜/g,'&tilde;'); // 152 98
	texte = texte.replace(/™/g,'&trade;'); // 153 99
	texte = texte.replace(/š/g,'&scaron;'); // 154 9A
	texte = texte.replace(/›/g,'&rsaquo;'); // 155 9B
	texte = texte.replace(/œ/g,'&oelig;'); // 156 9C
	texte = texte.replace(//g,'&#357;'); // 157 9D
	texte = texte.replace(/ž/g,'&#382;'); // 158 9E
	texte = texte.replace(/Ÿ/g,'&Yuml;'); // 159 9F
	// texte = texte.replace(/ /g,'&nbsp;'); // 160 A0
	texte = texte.replace(/¡/g,'&iexcl;'); // 161 A1
	texte = texte.replace(/¢/g,'&cent;'); // 162 A2
	texte = texte.replace(/£/g,'&pound;'); // 163 A3
	//texte = texte.replace(/ /g,'&curren;'); // 164 A4
	texte = texte.replace(/¥/g,'&yen;'); // 165 A5
	texte = texte.replace(/¦/g,'&brvbar;'); // 166 A6
	texte = texte.replace(/§/g,'&sect;'); // 167 A7
	texte = texte.replace(/¨/g,'&uml;'); // 168 A8
	texte = texte.replace(/©/g,'&copy;'); // 169 A9
	texte = texte.replace(/ª/g,'&ordf;'); // 170 AA
	texte = texte.replace(/«/g,'&laquo;'); // 171 AB
	texte = texte.replace(/¬/g,'&not;'); // 172 AC
	texte = texte.replace(/­/g,'&shy;'); // 173 AD
	texte = texte.replace(/®/g,'&reg;'); // 174 AE
	texte = texte.replace(/¯/g,'&macr;'); // 175 AF
	texte = texte.replace(/°/g,'&deg;'); // 176 B0
	texte = texte.replace(/±/g,'&plusmn;'); // 177 B1
	texte = texte.replace(/²/g,'&sup2;'); // 178 B2
	texte = texte.replace(/³/g,'&sup3;'); // 179 B3
	texte = texte.replace(/´/g,'&acute;'); // 180 B4
	texte = texte.replace(/µ/g,'&micro;'); // 181 B5
	texte = texte.replace(/¶/g,'&para'); // 182 B6
	texte = texte.replace(/·/g,'&middot;'); // 183 B7
	texte = texte.replace(/¸/g,'&cedil;'); // 184 B8
	texte = texte.replace(/¹/g,'&sup1;'); // 185 B9
	texte = texte.replace(/º/g,'&ordm;'); // 186 BA
	texte = texte.replace(/»/g,'&raquo;'); // 187 BB
	texte = texte.replace(/¼/g,'&frac14;'); // 188 BC
	texte = texte.replace(/½/g,'&frac12;'); // 189 BD
	texte = texte.replace(/¾/g,'&frac34;'); // 190 BE
	texte = texte.replace(/¿/g,'&iquest;'); // 191 BF
	texte = texte.replace(/À/g,'&Agrave;'); // 192 C0
	texte = texte.replace(/Á/g,'&Aacute;'); // 193 C1
	texte = texte.replace(/Â/g,'&Acirc;'); // 194 C2
	texte = texte.replace(/Ã/g,'&Atilde;'); // 195 C3
	texte = texte.replace(/Ä/g,'&Auml;'); // 196 C4
	texte = texte.replace(/Å/g,'&Aring;'); // 197 C5
	texte = texte.replace(/Æ/g,'&AElig;'); // 198 C6
	texte = texte.replace(/Ç/g,'&Ccedil;'); // 199 C7
	texte = texte.replace(/È/g,'&Egrave;'); // 200 C8
	texte = texte.replace(/É/g,'&Eacute;'); // 201 C9
	texte = texte.replace(/Ê/g,'&Ecirc;'); // 202 CA
	texte = texte.replace(/Ë/g,'&Euml;'); // 203 CB
	texte = texte.replace(/Ì/g,'&Igrave;'); // 204 CC
	texte = texte.replace(/Í/g,'&Iacute;'); // 205 CD
	texte = texte.replace(/Î/g,'&Icirc;'); // 206 CE
	texte = texte.replace(/Ï/g,'&Iuml;'); // 207 CF
	texte = texte.replace(/Ð/g,'&ETH;'); // 208 D0
	texte = texte.replace(/Ñ/g,'&Ntilde;'); // 209 D1
	texte = texte.replace(/Ò/g,'&Ograve;'); // 210 D2
	texte = texte.replace(/Ó/g,'&Oacute;'); // 211 D3
	texte = texte.replace(/Ô/g,'&Ocirc;'); // 212 D4
	texte = texte.replace(/Õ/g,'&Otilde;'); // 213 D5
	texte = texte.replace(/Ö/g,'&Ouml;'); // 214 D6
	texte = texte.replace(/×/g,'&times;'); // 215 D7
	texte = texte.replace(/Ø/g,'&Oslash;'); // 216 D8
	texte = texte.replace(/Ù/g,'&Ugrave;'); // 217 D9
	texte = texte.replace(/Ú/g,'&Uacute;'); // 218 DA
	texte = texte.replace(/Û/g,'&Ucirc;'); // 219 DB
	texte = texte.replace(/Ü/g,'&Uuml;'); // 220 DC
	texte = texte.replace(/Ý/g,'&Yacute;'); // 221 DD
	texte = texte.replace(/Þ/g,'&THORN;'); // 222 DE
	texte = texte.replace(/ß/g,'&szlig;'); // 223 DF
	texte = texte.replace(/à/g,'&aacute;'); // 224 E0
	texte = texte.replace(/á/g,'&aacute;'); // 225 E1
	texte = texte.replace(/â/g,'&acirc;'); // 226 E2
	texte = texte.replace(/ã/g,'&atilde;'); // 227 E3
	texte = texte.replace(/ä/g,'&auml;'); // 228 E4
	texte = texte.replace(/å/g,'&aring;'); // 229 E5
	texte = texte.replace(/æ/g,'&aelig;'); // 230 E6
	texte = texte.replace(/ç/g,'&ccedil;'); // 231 E7
	texte = texte.replace(/è/g,'&egrave;'); // 232 E8
	texte = texte.replace(/é/g,'&eacute;'); // 233 E9
	texte = texte.replace(/ê/g,'&ecirc;'); // 234 EA
	texte = texte.replace(/ë/g,'&euml;'); // 235 EB
	texte = texte.replace(/ì/g,'&igrave;'); // 236 EC
	texte = texte.replace(/í/g,'&iacute;'); // 237 ED
	texte = texte.replace(/î/g,'&icirc;'); // 238 EE
	texte = texte.replace(/ï/g,'&iuml;'); // 239 EF
	texte = texte.replace(/ð/g,'&eth;'); // 240 F0
	texte = texte.replace(/ñ/g,'&ntilde;'); // 241 F1
	texte = texte.replace(/ò/g,'&ograve;'); // 242 F2
	texte = texte.replace(/ó/g,'&oacute;'); // 243 F3
	texte = texte.replace(/ô/g,'&ocirc;'); // 244 F4
	texte = texte.replace(/õ/g,'&otilde;'); // 245 F5
	texte = texte.replace(/ö/g,'&ouml;'); // 246 F6
	texte = texte.replace(/÷/g,'&divide;'); // 247 F7
	texte = texte.replace(/ø/g,'&oslash;'); // 248 F8
	texte = texte.replace(/ù/g,'&ugrave;'); // 249 F9
	texte = texte.replace(/ú/g,'&uacute;'); // 250 FA
	texte = texte.replace(/û/g,'&ucirc;'); // 251 FB
	texte = texte.replace(/ü/g,'&uuml;'); // 252 FC
	texte = texte.replace(/ý/g,'&yacute;'); // 253 FD
	texte = texte.replace(/þ/g,'&thorn;'); // 254 FE
	texte = texte.replace(/ÿ/g,'&yuml;'); // 255 FF
	return texte;
}

jQuery.fn.getInputName = function() {
	return $(this).siblings('select, input').eq(0).attr('name');
}

jQuery.fn.toggleWithName = function() {
	$(this).each(function() {
		url = $(this).attr('src');
		$(this)
			.attr('src', $(this).attr('name'))
			.attr('name', url)
	})
}

jQuery.fn.togglePDF = function() {
	url = $(this).parents('tr').prev('tr').children('td').eq(0).find('input[name=pdf]').val();
	$(this).each(function() {
		if ($(this).toggle().is(':visible')) {
			$(this).html(
				'<iframe width="100%" height="100%" scrolling="auto" frameborder="no" src="'
			  + url
			  /*+ $('base').attr('href') 
			  + '/reimbursement/pdf/id/' 
			  + $(this).parents('tr').prev().children('td').eq(1).text()*/ 
			  + '" ></iframe>'
			)
		}
	})
}

jQuery.fn.dateField = function() {
	$(document.createElement('script'))
		.attr({
			type: 'text/javascript', 
			src: $('base').attr('href') + '/js/jquery-ui-1.8.1.custom.min.js', 
			language: 'Javascript'
		})
		.appendTo('head');
	$(document.createElement('link'))
		.attr({
			type: 'text/css', 
			href: $('base').attr('href') + '/css/jquery-ui-1.7.2.custom.css', 
			rel: 'stylesheet'})
		.appendTo('head');

	if ($('html').attr('lang') == 'fr' || $('html').attr('lang') == 'es') {
		$(document.createElement('script'))
		.attr({
			type: 'text/javascript', 
			src: $('base').attr('href') + '/js/ui.datepicker-' + $('html').attr('lang') + '.js', 
			language: 'Javascript'
		})
		.appendTo('head');
	}
	else {
		$(document.createElement('script'))
		.attr({
			type: 'text/javascript', 
			src: $('base').attr('href') + '/js/ui.datepicker-en.js', 
			language: 'Javascript'
		})
		.appendTo('head');
	}
	$(this).each(function() {
		if ($(this).hasClass('dob')) {
			$(this)
				.css('margin-right', '5px')
				.removeClass('hasDatepicker')
				.datepicker({
			        changeMonth: true,
			        buttonImageOnly: true,
			        changeYear: true,
			        dateFormat: "dd/mm/yy",
			        showOn: "both",
			        buttonImage: $('base').attr('href') + '/images/calendar.gif',
			        constrainInput: true,
			        maxDate:0,
			        yearRange: ((new Date().getFullYear())-100) + ':' + (new Date().getFullYear()) 
			    });
		}
		else {
			$(this)
				.attr('autocomplete', 'off')
				.attr('readonly', 'readonly')
				.css('margin-right', '5px')
				.removeClass('hasDatepicker')
				.blur(function() {
			
				})
				.datepicker({
			        changeMonth: true,
			        buttonImageOnly: true,
			        changeYear: true, 
			        dateFormat: "dd/mm/yy",
			        showOn: "both",
			        buttonImage: $('base').attr('href') + '/images/calendar.gif',
			        constrainInput: true,
			        maxDate:0
			    });
		}
	})
	return true;
}

jQuery.fn.uploadButton = function(url) {
	var interval, uploadedSize = 0;
	var that = $(this);
	$(document.createElement('script'))
	.attr({
		type: 'text/javascript', 
		src: $('base').attr('href') + '/js/ajaxupload.js', 
		language: 'Javascript'
	})
	.appendTo('head');
	new AjaxUpload(that, {
    action: url,
    name: 'Filedata',
    data: {},
    autoSubmit: true,
    responseType: 'text',
    onChange: function(file, extension){},
    onSubmit: function(file, ext) {
    	$('.dynamicerror').hide();
    	
    	if (! (ext && /^(jpg|jpeg|tif|tiff|gif|png|bmp|pdf)$/i.test(ext))) {
			$('#errorMessage')
				.text($('#translation label:nth(2)').text())
				.css('display','block');
			return false;
		}
    	
    	$('#errorMessage').css('display','none');
		
		$('#itemClone')
			.clone()
			.append('<input type="hidden" value="' + file + '" name="hfiles[]">')
			.css('display','block')
			.removeAttr('id')
			.appendTo($('#fileInputQueue'))
			.find('.fileName')
			.text(file);
		
		that.val($('#translation label:nth(1)').text());
		
		that.attr('disabled', true);
		that.css('cursor', 'default');
				
		var percent = 0;
		interval = window.setInterval(function() {
			percent += 2;
			if(percent>=200) {
				percent = 0;
				$('.uploadifyProgressBar:last').css('width',percent + '%');
				$('.uploadifyProgressBar:last').css('margin-left','0%');
			}else if(percent>=100) {
				var padding = percent - 100;
				var newPercent = 100 - padding;
				$('.uploadifyProgressBar:last').css('margin-left',padding + '%');
				$('.uploadifyProgressBar:last').css('width',newPercent + '%');
			}else {
				$('.uploadifyProgressBar:last').css('width',percent + '%');
			}
		}, 5);
  	  },
  	  
  	  onComplete: function(file, response) {
  		
  		var error = (response.substring(0,1) == '/');

  		window.clearInterval(interval);	
		$('.uploadifyProgressBar:last').css('width','100%');
		$('.uploadifyProgressBar:last').css('margin-left','0%');
		$('.labelProgress:last').text($('#translation label:nth(0)').text() + " :");
		that.attr('disabled', false);
		that.css('cursor', 'default');
		that.val($('#translation label:nth(4)').text());

  		if (error) {
  			$('#errorMessage')
  				.text($('#translation label:nth(5)').text())
  				.css('display','block');
  			$('.uploadifyQueueItem:last').remove();
  		}
  		else {
  			var pos = response.indexOf('_');
  	  		var size = response.substring(0, pos);
  	  		var filename = response.substring(pos+1);
  			
  			$('.uploadifyQueueItem:last .fileName').html(file + ' (<span class="size">' + size + '</span> Ko)');
			if(uploadedSize + eval(size)>10000) {
				$('#errorMessage')
					.text($('#translation label:nth(3)').text())
					.css('display','block');
				$('div.cancel:last a').parent().parent().remove();
			} else {
				uploadedSize += eval(size);
				$('div.uploadifyQueueItem:last input[type=hidden]').val(filename);
				$('div.uploadifyQueueItem:last input[type=hidden]').after('<input type="hidden" value="' + size + '" name="hsizes[]">');
				//$('div.uploadifyQueueItem:last').after('<input type="hidden" value="' + file + '" name="hfiles[]">');
				//$('div.uploadifyQueueItem:last').after('<input type="hidden" value="' + response + '" name="hsizes[]">');
				if(uploadedSize<10000){
					$('#errorMessage').css('display','none');
				}
				$('div.cancel:last a').click(function(){
					uploadedSize -= eval($(this).parents('.uploadifyQueueItem').find('span:first span.size').text());
					$(this).parent().parent().remove();
					if(uploadedSize<10000){
						$('#errorMessage').css('display','none');
					}
			    	return false;
			    });
			}
  		}
  		}
  	});
}

jQuery.fn.createAct = function(that) {
	if (!document.getElementById('act_sample'))
		return;
	var actcode = $('td:eq(0)', that).text();

	var act_idx = 0;
	if ($('input[name=hact_idx]:last').length) 
		act_idx = $('input[name=hact_idx]:last').val() + 1;

	$('fieldset#act_sample')
	    .clone()
	    .removeAttr('id')
	    .appendTo($('div',this))
	    .show()
	    .find('input:first')
	    	.val(actcode + ' - ' + $('td:eq(1)', that).text())
	    .siblings('input[name=hcode]')
	    	.attr('name', 'hact[' + act_idx + '][code]')
	    	.val(actcode)
	    .siblings('input[name=hact_idx]')
	    	.val(act_idx+1)
	    .siblings('select[name=hrecipient]')
	    	.attr('name', 'hact[' + act_idx + '][recipient]' )
	    .siblings('input[name=hquantity]')
	    	.attr('name', 'hact[' + act_idx + '][quantity]' )
	    .siblings('input[name=hcost]')
	    	.attr('name', 'hact[' + act_idx + '][cost]' )
	    .siblings('input[name=hdiagnosis]')
	    	.attr('name', 'hact[' + act_idx + '][diagnosis]' )
	    .siblings('input[name=hdate]')
	    	.attr('name', 'hact[' + act_idx + '][date]' )
	    	.dateField();
}

$(function() {
    /**
     * Add to favorite
     */
    $('a#addtofavorite').click(function(e) {
        var url  = $(this).attr('href');
        var name = $(this).attr('target');
        if(navigator.appName != 'Microsoft Internet Explorer') {
            window.sidebar.addPanel(name, url, "");
        }
        else {
            window.external.AddFavorite(url, name);
        }
        return false;
    });
    
    /**
     * Link for details in a popup
     */
    $('a[target=popup]').openInPopup(760, 610);
    $('a[target=demo]').openInPopup(790, 600, 'demo', 0, 0);
        
    $('.myHoverClass').activeXOverlap();
    
    /**
     * Dialog box in an overlay
     */
    $('button[name=modal]').click(function() {
        $($(this).attr('value')).showInOverlay();
        return false;
    })
    
    $('a[name=modal]').click(function() {
        $($(this).attr('href')).showInOverlay();
        return false;
    })

    $('#mask, .window .close').click(function (e) {
        $('#mask, .window').hide();
        return false;
    });
    
    if (document.getElementById('confirmmessage')) {
        $('#confirm').showInOverlay();
        $('#mask, .window .close').unbind('click');
    }
    
    /**
     * Date picker
     */
    if ($('input.date').size() > 0) {
    	$('input.date').dateField()
    }
    
    /**
     * Accordion
     */
    if ($('.accordion').size() > 0) {
    	$('.accordion').accordion();
    }

    /**
     * Connexion form
     */
    if (document.getElementById('connexion')) {
        var form = $('form#connexion');
        var defaultlogin = $('input[name=husername]', form).val();
        var defaultpasss = '............'
        
        form
        	.submit(function() {
	            var pass = $('input[name=hpassword]', this);
	            pass.val(hex_md5($.trim(pass.val())));
	        })
	        .find('input[name=husername]')
            .focus(function() {
                if(this.value == defaultlogin) {
                	this.value = '';
                    this.maxLength = 50;
                }
            })
            .blur(function() {
                if(this.value == '') {
                    this.maxLength = 20;
                    this.value = defaultlogin;
                }
            })
            .siblings('input[name=hpassword]')
            .focus(function() {
                if (this.value == defaultpasss) {
                    this.value = '';
                }
            })
            .blur(function() {
                if (this.value == '') {
                    this.value = defaultpasss;
                }
            })
    }
    
    /**
     * Change password form
     */
    if (document.getElementById('changepass')) {
        var form = $('form#changepass');
        form.submit(function(e){
        	var pass_new = $('input[name=hpasswordnew]', this);
        	var pass_confirm = $('input[name=hpasswordconfirm]', this);
        	var pass_old = $('input[name=hpasswordold]', this);

            if (pass_new.val() != "") {
            	pass_new.val(hex_md5(pass_new.val()));
            }
            
            if (pass_confirm.val() != "") {
            	pass_confirm.val(hex_md5(pass_confirm.val()));
            }
            
            if (document.getElementById('passwordold') && $('input[name=hpasswordold]', this).val != "") {
            	pass_old.val(hex_md5(pass_old.val()));
            }
        });
    }
    
    /**
     * Change bank details form
     */
    if (document.getElementById('changebban')) {
        var formBankDetails = $('form#changebban');
        formBankDetails
	        .submit(function() {
	            $('input[name*=accountnumber]:hidden', this)
	            	.remove()
	        })
        
        $('select[name*=bankcountry]', formBankDetails)
        	.change(function() {
        		var cCode = $(this).val();
	        	$.post(
	            	$('base').attr('href') + '/ajax/affiliate/country/',
	                {"hcountry" : cCode}, 
	                function (data) {

	                	if ($('input[name*=accountnumber]:visible', formBankDetails).length > 0)
	                		$('input[name*=accountnumber]:hidden', formBankDetails)
		                    	.val(
		                   			$('input[name*=accountnumber]:visible', formBankDetails).val()
		                    	);

	                    if (data.frenchtype == 1) {
	                        $('.international, .custom2').hide();
	                        $('.france, .custom1').show();
	                        if ($('.custom1 input[type=hidden]').val() == '')
	                        	$('.custom1').hide();
	                    }
	                    else {
	                        $('.france').hide();
	                        $('.international').show();
	                        
	                        switch (cCode) {
	                            case '' :
	                                $('.custom1, .custom2').hide();
	                                break;
	                            case 'CA' :
	                            case 'GB' :
	                            case 'US' :
	                                $('.custom1, .custom2').show();
	                                if ($('.custom1 input[type=hidden]').val() == '')
	    	                        	$('.custom1').hide();
	                                if ($('.custom1 input[type=hidden]').val() == '')
	    	                        	$('.custom2').hide();
	                                break;
	                            default:
	                                $('.custom1').show();
	                            	if ($('.custom1 input[type=hidden]').val() == '')
	                            		$('.custom1').hide();
	                                $('.custom2').hide();
	                        }
	                    }
	                    
	                    i = 0;
	                    $.each(data.bankTransferSystems, function(key, value) {
	                    	$('label[for=hadditionnal] strong', formBankDetails)
	                    		.eq(i).text(value.title);
	                        $('div:has([for=hadditionnal]) input[type=hidden]', formBankDetails)
	                        	.eq(i++).val(value.code);
	                    })
	                    
	                    $('select[name*=currency]').val(data.currency);
	                },
	                'json'
	            );
        	})
        	.trigger('change');
    }
    
    /**
     * Hospitalization
     */
    if (document.getElementById('hospitalization')) {
    	$('#hospitalization input[name=hdate]').datepicker('option', 'minDate', '0');
    	$('#hospitalization input[name=hdate]').datepicker('option', 'maxDate', '+15d');
    	$('#hospitalization select').change(function() {
    		var benef = $(this).val();
            $.post(
            	$('base').attr('href') + '/ajax/hospitalization/beneficiarydetails/', 
                {"hbeneficiary" : benef}, 
                function (data) {
                	$.each(data, function(key, value) {
                    	$('label[for=h' + key + '] + span').text(value);
                    })
                },
                'json'
            );
    	})
    	.trigger('change');
    }
    
    /**
     * Reimbursements
     */
    if (document.getElementById('content2')) {
    	$('#content2').tabs();
    	$('#content2 li.selected a').click();
    	$('#onglet-2').click(function () {
    		$("#tab-2 #searchResult div")
    			.html('<center><img src="../images/ajax-loader.gif" /></center>');
	    });
    	
    	/**
    	 * Hightlight rows
    	 */
    	$('#content2 fieldset#searchResult tbody tr:not(.click):not(:has(.pdf))')
	    	.hover(function() {
				$(this).toggleClass('on');
			})
    		.click(function() {
    			$(this)
					.siblings()
					.find('iframe')
					.remove()
    			$(this)
    				.toggleClass('click')
    				.find('img')
    				.toggleWithName()
    			$(this)
    				.next()
    				.find('div.pdf')
    				.togglePDF()
    		})
    		.find('img:last')
    		.click(function() {
	    		window.open(
	    			$(this).parents('tr').children('td').eq(0).find('input[name=pdf]').val(),
	    			/*$('base').attr('href') 
	    			+ '/reimbursement/pdf/id/' 
	    			+ $(this).parents('tr').children('td').eq(1).text(),*/
	    			'','width=900,height=700');
	    		return false;
    		})
    		
		$('#onglet-2').click(function () {
			/*
			$.ajax({
			      url: 'http://liweb02/www.gmcnet.recette.fr/Reimbursement/distribution/',
			      global: false,
			      type: "POST",
			      data: ({
				      	dico : '<?php echo $_GET['dico'] ?>', 
				      	format_date_php : '<?php echo $format_date_php ?>'
					    <?php foreach($_POST as $key => $value): ?>
					    	,<?php echo $key ?> : '<?php echo $value ?>'
					    <?php endforeach; ?>
				  }),
			      dataType: "html",
			      success: function(html){
					$("#tab-2").html(html);
			      }
			});*/
	    });    
    	
    	/**
    	 * Triggers
    	 */
    	$('#contentSearch select').change(function() {
    		$(this)
    			.siblings('input:checkbox')
    			.attr('checked', true)
    			.trigger('click')
    			.attr('checked', true)
    	})
    	$('#contentSearch input:text').click(function() {
    		$(this)
    			.siblings('input:checkbox')
    			.attr('checked', true)
    			.trigger('click')
    			.attr('checked', true)
    	})
    	
    	/**
    	 * Check which options are available
    	 */
    	$('#contentSearch input:checkbox')
	    	.click(function(){
	    		if (this.checked) {
	    			$(this).parent().css({
	        			backgroundColor : '#FFF',
	        			borderColor     : '#F08122'
	        		});
	    		}
		    	else {
		    		$(this).parent().css({
		    			backgroundColor : '#FFF',
		    			borderColor     : '#F0F0F0'
		    		});
		    	}
	    		if($('#contentSearch').find('[name^=hdatecare], [name=hbeneficiary]').allActivated()) {
	    			$('[name^=hdatecare], [name=hbeneficiary]').activateOnly();
	    		}
	    		else if ($('#contentSearch').find('[name^=hdatecare], [name=hactcode]').allActivated()) {
	    			$('[name^=hdatecare], [name=hactcode]').activateOnly();
	    		}
	    		else if ($('#contentSearch').find('[name^=hdateemission], [name=hbeneficiary]').allActivated()) {
	    			$('[name^=hdateemission], [name=hbeneficiary]').activateOnly();
	    		}
	    		else if ($('#contentSearch').find('[name=hbeneficiary], [name=hactcode]').allActivated()) {
	    			$('[name=hbeneficiary], [name=hactcode]').activateOnly();
	    		}
	    		else if ($('#contentSearch [name=hnumber]').allActivated()) {
	    			$('[name=hnumber]').activateOnly();
	    		}
	    		/*
	    		else if ($('[name^=hdateemission], [name=hactcode]').allActivated()) {
	    			$('[name^=hdateemission], [name=hactcode]').activateOnly();
	    		}
	    		*/
	    		else if ($('#contentSearch [name^=hdatecare]').allActivated()) {
	    			$('[name=hactcode], [name=hbeneficiary], [name^=hdatecare]').activateOnly();
	    		}
	    		else if ($('#contentSearch [name^=hdateemission]').allActivated()) {
	    			$('[name^=hdateemission], [name=hbeneficiary]').activateOnly();
	    		}
	    		else if ($('#contentSearch [name=hbeneficiary]').allActivated()) {
	    			$('[name=hbeneficiary], [name=hactcode], [name^=hdateemission], [name^=hdatecare]').activateOnly();
	    		}
	    		else if ($('#contentSearch [name=hactcode]').allActivated()) {
	    			$('[name=hbeneficiary], [name=hactcode], [name^=hdatecare]').activateOnly();
	    		}	    		
	    		else {
	    			$('[name=hbeneficiary], [name=hactcode], [name=hnumber], [name^=hdateemission], [name^=hdatecare]').activateOnly();
	    		}
	    	})
    }
    
    /**
     * E-claiming
     */
    if (document.getElementById('general')) {
        $('select[name=hcountry]')
	        .change(function() {
	            var cCode = $(this).val();
	            $.post(
	            	$('base').attr('href') + '/ajax/affiliate/country/',
	                {"hcountry" : cCode}, 
	                function (data) {
	                    $('select[name=hcurrency]').val(data.currency);
	                },
	                'json'
	            );
	        })
	        .trigger('change');
        
        $('input[name=hok]')
	        .click(function() {
	        	javascript:window.close();
	        	return false;
	        });
    }
    
    if (document.getElementById('complement')) {
    	$('fieldset#complement div.comp div input:radio')
	    	.click(function(){
	    		$(this).val() == 1
	    			? $(this).siblings('textarea, input:text').removeAttr('disabled')
	    			: $(this).siblings('textarea, input:text').attr('disabled', true);
	    		return true;
	    	})
    }
    
    if (document.getElementById('act')) {
        var act = $('fieldset#act');
        var soin = $('fieldset#soin');
        var numAct = 0;
        var total = 0;

        $('fieldset#soin fieldset:not(:first) input[readonly]:not(.date)')
	        .each (function() {
	        	var code = $(this).siblings('input[name*=code]').val();
	        	var val = $(this).siblings('input[name*=cost]').val();
	        	total += parseFloat(val == '' ? 0 : val);
	        	$(this).val(
	        		code + ' - ' + $("td:exactcontains('" + code + "')", act).nextAll('td').eq(0).text()
	        	);
	        })
	        
        $('fieldset div#total span')
        	.text(total);
        
        $('form#claim_create')
	        .submit(function() {
	        	$('fieldset#act_sample').remove();
	        });

        $('button[name=haddact]', act)
            .click(function(e) {
                e.preventDefault();
                $('div', act).animate({
                    'height':'toggle'
                },'fast');
                $('#soin select').toggle();
            });

        $('tr:has(td)', act)
            .hover(function() {
                $(this).children('td').toggleClass('orange');
            })
            .click(function() {
            	$('div', act)
            		.animate({'height':'toggle'}, 'fast');
                $('#soin select')
                	.toggle();
                //if (++numAct > 10) return;
                if ($('select[name^=hact]').length >= 10) return;
                soin.createAct(this);
                return false;
            });
        
        $('fieldset#soin img.trash')
	        .live('click', function(e){
	            $(this).parent().parent().remove();
	            return false;
	        });
        
        //$('fieldset#soin input[name^=hamount]')
        $('fieldset#soin input[name*=cost]')
	        .live('blur', function(e) {
	            var total = 0;
	        	$('fieldset#soin fieldset:not(:first) input[name*=cost]').each(function() {
	        		total += parseFloat($(this).val() == '' ? 0 : $(this).val());
	            })
	        	$('fieldset div#total span').text(total.toFixed(2));
	        });
    }
    
    if (document.getElementById('uploadButton')) {
    	$('#uploadButton').uploadButton($('base').attr('href') + '/ajax/eclaiming/upload/');
    	
    	var uploadedSize = 0;
    	$('#fileInputQueue :not(#itemClone) div.cancel a')
	    	.each(function(){
	    		uploadedSize += eval($(this).parents('.uploadifyQueueItem').find('span:first span.size').text());
	    		$(this).click(function(){
	    			uploadedSize -= eval($(this).parents('.uploadifyQueueItem').find('span:first span.size').text());
	    			$(this).parent().parent().remove();
	    			if(uploadedSize<10000){
	    				$('#errorMessage').css('display','none');
	    			}
	    	    	return false;
	    	    });
	    	});
    }
    
    $(':button[name=hprev]')
	    .click(function() {
	    	$(':button[name=hnext], :button.boutonLong').attr('disabled', true);
	    })
    $(':button[name=hnext]')
	    .click(function() {
	    	$(':button[name=hprev]').attr('disabled', true);
	    })
})

