var ltie7 = (jQuery.browser.msie && jQuery.browser.version < 7);
var ltie9 = (jQuery.browser.msie && jQuery.browser.version < 9);
jQuery(document).ready(function() {
	jQuery.ifixpng('/wp-content/themes/linedata-FR/images/pixel.gif');
	jQuery('img[src$=.png], input[src$=.png]').ifixpng();
	create_content_tabs.init();
	content_tabs.init();
	//menu_left.init();
	if(jQuery('#sidebar').is('div')){
		jQuery('#sidebar,#content').adjustSize();
	}
	//jQuery('.item_link_module h2').adjustSize({periode:'4'});
	jQuery('.bloc_push_related').adjustSize({periode:'2'});
	jQuery("#find_solution").fancybox({
		'width'				: 800,
		'height'			: 500,
		'autoScale'			: false,
		'transitionIn'		: 'elastic',
		'transitionOut'		: 'elastic',
		'type'				: 'iframe'
	});
	jQuery(".find_contacts").fancybox({
		'titleShow'			: false,
		'width'				: 800,
		'height'			: 430,
		'autoDimensions'	: false,
		'autoScale'			: false,
		'transitionIn'		: 'elastic',
		'transitionOut'		: 'elastic',
		'type'				: 'iframe'
	});	
	jQuery('#menu_left li ul li:first-child').addClass('first');

	// carousel home
	if(jQuery('#carousel_home').size()){
		jQuery('#carousel_home').jcarousel({scroll: 1});
	}
	
	// affichage bloc sous_menu
	jQuery('#menu_top .sous_menu ul li:last-child').css('border-bottom','1px dotted #cfd1d1');
	jQuery('#menu_top ul > li').hover(function(){
		jQuery(this).addClass('hover');
	},function(){
		jQuery(this).removeClass('hover');
	});
	
	jQuery("#menu_top li.level-0").each(function(i) {
		var menu_id = jQuery(this).attr("id");
	  	if( jQuery('#'+menu_id+' .bloc_chairman').is('div') ) {
	  		jQuery('#'+menu_id+' .bloc_chairman').clone().appendTo(jQuery('#'+menu_id+' .sous_menu'));
	  		jQuery('#'+menu_id+' .sous_menu .bloc_chairman').show();
	  		var parent_width = jQuery('#'+menu_id+' .sous_menu .bloc_chairman').width() + jQuery('#'+menu_id+' .sous_menu ul:eq(0)').width() + 20 ;
	  		jQuery('#'+menu_id+' .sous_menu').width(parent_width);
		}
	});
	
	// ajout lien link_spec au menu top li.special
	jQuery('#menu_top li.special > a').addClass('link_spec');
	//jQuery('#Section_nav ul li:last-child').css('border-right','0px none');
	// Contact Form
	jQuery('.world_map_activer a').click(function(){
		jQuery(this).hide();
		return false;
	});
	jQuery('#world_map_1 area').hover(function(){
		jQuery("#"+jQuery(this).attr('rel')).show();
	},function(){
		jQuery("#"+jQuery(this).attr('rel')).hide();
	});
	// Switch image
	jQuery('.switch').each(function(){jQuery(this).switchImage("","> img");});
	jQuery('#Bookmark').jFav();
	jQuery('#globalContainer .wp-table-reloaded  .row-hover tr').hover(function(){
		jQuery(this).find("td").addClass('tr_hover');
	},function(){
		jQuery(this).find("td").removeClass('tr_hover');
	});
	jQuery(".search_texte").autocomplete('/auto_complete.php');	
	
	
	/**
	 *  force links to open in popup 
	 */
	/*var authentificate_user = jQuery.cookie("linedata_documents");  
    jQuery("a:regex(href, ^.*\.(doc|DOC|pdf|PDF)$)").each(function(){
    	if ( !authentificate_user ||  authentificate_user != "authentificate_user") {
			jQuery(this).click(function() {
			  popup("/download_document.php?url_document="+jQuery(this).attr("href"), 500, 400);
			  return false;			  			  
			});
    	} else {
	    	jQuery(this).attr("target", "_blank");
	    	}
	});*/
	

});

function popup(url, width, height) {
	 var left   = (screen.width  - width)/2;
	 var top    = (screen.height - height)/2;
	 var params = 'width='+width+', height='+height;
	 params += ', top='+top+', left='+left;
	 params += ', directories=no';
	 params += ', location=no';
	 params += ', menubar=no';
	 params += ', resizable=no';
	 params += ', scrollbars=no';
	 params += ', status=no';
	 params += ', toolbar=no';
	 newwin=window.open(url,'windowname5', params);
	 if (window.focus) {newwin.focus()}
	 return false;
}

/**
 * Create a cookie with the given key and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String key The key of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given key.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String key The key of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function (key, value, options) {

    // key and value given, set cookie...
    if (arguments.length > 1 && (value === null || typeof value !== "object")) {
        options = jQuery.extend({}, options);

        if (value === null) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? String(value) : encodeURIComponent(String(value)),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};


/**
 * Jquery patch to enable regular expression filter
 *
 */

jQuery.expr[':'].regex = function(elem, index, match) {
   var matchParams = match[3].split(','),
       validLabels = /^(data|css):/,
       attr = {
           method: matchParams[0].match(validLabels) ?
                       matchParams[0].split(':')[0] : 'attr',
           property: matchParams.shift().replace(validLabels,'')
       },
       regexFlags = 'ig',
       regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
   return regex.test(jQuery(elem)[attr.method](attr.property));
}

/* =CREATE CONTENT TABS */ // Transformation des fieldset en DIV pour la génération de la tabulation
var create_content_tabs = function() {
	function init() {
		if(jQuery('fieldset').size()){
			var content_tabulation = '<div class="tabbed">';
			var ul_tabulation = '<ul class="tabs">';
			var text_tabulation = '';
			jQuery("#content fieldset").each(function(i) {
		        var fieldsetTitle = jQuery(this).find("legend").html();
		        ul_tabulation += '<li class="t'+ i +'"><a class="t'+ i +' tab" title="'+ fieldsetTitle +'">'+ fieldsetTitle +'</a></li>';
		        jQuery(this).find("legend").remove();
		        var fieldsetContent = jQuery(this).html();
		        text_tabulation += '<div class="t'+ i +' t">'+ fieldsetContent +'</div>';
		    });
		    ul_tabulation += '</ul>';
		    //alert(ul_tabulation);
			jQuery("fieldset:first").replaceWith('<div class="tabbed">' + ul_tabulation + ' ' + text_tabulation + "</div>");
			jQuery("fieldset").remove();
			return false;
		}
	}
	return {init:init};
}();
/* =CONTENT_TABS */
var content_tabs = function() {
	function init() {
		if(jQuery('.tabbed').size()){
			// setting the tabs in the sidebar hide and show, setting the current tab
			jQuery('div.tabbed .t').hide();
			jQuery('div.t0').show();
			jQuery('div.tabbed ul.tabs li.t0 a').addClass('tab-current');

			// SIDEBAR TABS
			jQuery('div.tabbed ul li a').click(function(){
				var thisClass = this.className.slice(0,2);
				jQuery('div.tabbed .t').hide();
				jQuery('div.' + thisClass).show();
				jQuery('div.tabbed ul.tabs li a').removeClass('tab-current');
				jQuery(this).addClass('tab-current');
				});
			
			return false;
		}
	}
	return {init:init};
}();
/* =CONTENT_TABS */
var menu_left = function() {
	function init() {
		jQuery('#menu_left li').not('.active').find('ul').hide();
		jQuery('#menu_left li').not('.active').hover(function(){
			jQuery(this).find('> ul').toggle();
		},function(){
			jQuery(this).find('> ul').toggle();
		});
	}
	return {init:init};
}();
// Nouvelle fonction jquery de retaillage de blocks
jQuery.fn.adjustSize=function(options) {
	var settings = {
		periode: 2,
		mode: 'height',
		minHeight: 0,
		minWidth: 0
	};
	var ltie7 = jQuery.browser.msie && /MSIE\s(5\.5|6\.)/.test(navigator.userAgent);
	if (options) {
		jQuery.extend(settings, options);
	}
	var totalSize = jQuery(this).size();
	var nbPeriodes = Math.ceil(totalSize/settings.periode);
	var index = 0;
	if (settings.mode == 'height' || settings.mode == 'both') {
		var maxTotalHeightArray = new Array();
		jQuery(this).each(function(){
			var blockId = Math.floor(index/settings.periode);
			if (!maxTotalHeightArray[blockId]) maxTotalHeightArray[blockId]=0;
			var blockTotalHeight = jQuery(this).height();
			if (blockTotalHeight > maxTotalHeightArray[blockId]) {
				if (settings.minHeight && settings.minHeight > blockTotalHeight) blockTotalHeight = settings.minHeight;
				maxTotalHeightArray[blockId] = blockTotalHeight;
			}
			index++;
		});
		var index = 0;
		jQuery(this).each(function(){
			var blockId = Math.floor(index/settings.periode);
			var blockComputedHeight = maxTotalHeightArray[blockId];
			if (ltie7) jQuery(this).height(blockComputedHeight+'px');
			else jQuery(this).css('minHeight',blockComputedHeight+'px');
			index++;
		});
	}
	if (settings.mode == 'width' || settings.mode == 'both') {
		var maxTotalWidthArray = new Array();
		jQuery(this).each(function(){
			var blockId = Math.floor(index/settings.periode);
			if (!maxTotalWidthArray[blockId]) maxTotalWidthArray[blockId]=0;
			var blockTotalWidth = jQuery(this).width() ? jQuery(this).width() : jQuery(this).attr('offsetWidth') ;
			if (blockTotalWidth > maxTotalWidthArray[blockId]) {
				if (settings.minWidth && settings.minWidth > blockTotalHeight) blockTotalWidth = settings.minWidth;
				maxTotalWidthArray[blockId] = blockTotalWidth;
			}
			index++;
		});
		var index = 0;
		jQuery(this).each(function(){
			var blockId = Math.floor(index/settings.periode);
			var blockComputedWidth = maxTotalWidthArray[blockId];
			if (ltie7) jQuery(this).width(blockComputedWidth+'px');
			else jQuery(this).css('minWidth',blockComputedWidth+'px');
			index++;
		});
	}
	return this;
}
// Ex : jQuery('#menu > li').each(function(){jQuery(this).switchImage("","> a > img");});
jQuery.fn.switchImage=function(eventTargetSelector, changeTargetSelector, options) {
	var eventTargetSelector, changeTargetSelector, eventTarget, changeTarget;
	if (!eventTargetSelector) eventTargetSelector = '?myself';
	if (!changeTargetSelector) changeTargetSelector = '?myself';
	var settings = {
		stringDefault: '_off',
		stringHover: '_on'
	};
	if (options) {
		jQuery.extend(settings, options);
	}
	if (eventTargetSelector == '?myself') eventTarget=jQuery(this);
	else eventTarget = jQuery(this).find(eventTargetSelector);
	if (changeTargetSelector == '?myself') changeTarget=jQuery(this);
	else changeTarget = jQuery(this).find(changeTargetSelector);
	eventTarget.filter(function(index){
		return (changeTarget.is("input[type=image][src]") || changeTarget.is("img[src]"));
	}).mouseover(function() {switchToHover(changeTarget)}).focus(function() {switchToHover(changeTarget)}).mouseout(function() {switchToDefault(changeTarget)}).blur(function() {switchToDefault(changeTarget)});
	function switchToHover(e) {
		e.each(function(){
			getSrcElmts.init(jQuery(this));
			if (getSrcElmts.fileName().indexOf(settings.stringDefault) != -1) {
				jQuery(this).attr('src', getSrcElmts.filePath()+'/'+getSrcElmts.replaceFileName(settings.stringDefault, settings.stringHover));
				if (jQuery.ifixpng && ltie7) jQuery(this).ifixpng();
			}
		});
	}
	function switchToDefault(e) {
		e.each(function(){
			getSrcElmts.init(jQuery(this));
			if (getSrcElmts.fileName().indexOf(settings.stringHover) != -1) {
				jQuery(this).attr('src', getSrcElmts.filePath()+'/'+getSrcElmts.replaceFileName(settings.stringHover, settings.stringDefault));
				if (jQuery.ifixpng && ltie7) jQuery(this).ifixpng();
			}
		});
	}
	var getSrcElmts = function() {
		var src,srcPathSplit, srcPathSplitLength;
		function init(e){
			if (jQuery.ifixpng && ltie7) e.iunfixpng();
			src = e.attr('src');
			srcPathSplit = src.split('/');
			srcPathSplitLength = srcPathSplit.length;
		}
		function filePath(){
			if (srcPathSplitLength)	return srcPathSplit.slice(0,-1).join('/');
		}
		function fileName(){
			if (srcPathSplitLength)	return srcPathSplit[srcPathSplitLength-1];
		}
		function replaceFileName(stFrom,stTo){
			elemts=fileName().split(stFrom);
			end=elemts.pop();
			begin=elemts.join(stFrom);
			return begin+stTo+end;
		}
		return {init:init,filePath:filePath,fileName:fileName,replaceFileName:replaceFileName}
	}()
	changeTarget.each(function(){
		// preload
		getSrcElmts.init(jQuery(this));
		var preload = new Image;
		preload.src=getSrcElmts.filePath()+'/'+getSrcElmts.replaceFileName(settings.stringDefault, settings.stringHover);
		if (jQuery.ifixpng && ltie7) jQuery(this).ifixpng();
	});
	return this;
};