
var isIE8 = ($.browser.msie && parseInt($.browser.version.substr(0,1)) >= 8);
var isIE7 = ($.browser.msie && parseInt($.browser.version.substr(0,1)) == 7);
var isIE6 = ($.browser.msie && parseInt($.browser.version.substr(0,1)) < 7);
var isIE = (isIE8 || isIE7 || isIE6) ;

function log(){
	if(window.console){
        for(var i=0; i <arguments.length; i++)
	    	console.log(arguments[i]);
	}
}

$(document).ready(function(){
	// ajoute les smoothScroll automatiquement
	constructSmoothScrollLink();
	constructExternalLink();
	constructEmptyField();
	constructDefaultAction();
	constructFancyBox();
	showInfoBox();
	disableAutoComplete();

	ajaxLoadScript(function(){
		constructSmoothScrollLink();
		constructExternalLink();
		constructEmptyField();
		constructDefaultAction();
		disableAutoComplete();
		constructFancyBox();
	});

});

/**
 * Function constructSmoothScrollLink 
 * 
 * @description : Construit les liens à défilement progressif 
 * @access : public
 * @return : void
 * @date : 2011-01-26
 * @author : emmanuel <e.gauthier@hegyd.com>
 */
function constructSmoothScrollLink(){

	$('a.jsSmoothScroll[href^=#]').each(function(){
		var linkEl = $(this);
		var destination = linkEl.attr('href');
		if( destination != '#' && $(destination).length >= 1){
			linkEl.unbind('click').click(function(){
				smoothScroll($(destination).offset().top ,function(){
					window.location.hash = destination;
				},700);
				return false;
			});
		}
	});
}

/**
 * Function constructExternalLink 
 * 
 * @description : target=_new workaround  
 * @access : public
 * @return : void
 * @date : 2011-01-26
 * @author : emmanuel <e.gauthier@hegyd.com>
 */
function constructExternalLink(){
	$('a[rel="external"]').attr('target','_new');
}

/**
 * Function constructEmptyField 
 * 
 * @description : Field with predefined text will hide and show this text  
 * @access : public
 * @return : void
 * @date : 2011-01-26
 * @author : emmanuel <e.gauthier@hegyd.com>
 */
function constructEmptyField(){
	$('.jsEmpty').each(function(){
		var inputEl = $(this);
		var defaultText = inputEl.val(); 

		inputEl.attr('rel',defaultText);

		inputEl.focus(function(){
			if(inputEl.val() == defaultText){
				inputEl.val('');
			}
		}).blur(function(){
			if(inputEl.val() == ''){
				inputEl.val(defaultText);
			}
		});
		inputEl.removeClass('jsEmpty').addClass('jsEmptyDone');
	});
}


/**
 * Function disableAutoComplete 
 * 
 * @description : Disable browser suggest box  
 * @access : public
 * @return : void
 * @date : 2011-01-26
 * @author : emmanuel <e.gauthier@hegyd.com>
 */
function disableAutoComplete(){
	$('.jsAutoCompleteOff').attr('autocomplete','off');	
}

/**
 * Function smoothScroll 
 * 
 * @description : smooth scroll to an y destination 
 * @param :  destinationY $destinationY 
 * @param :  callbackFunction $callbackFunction 
 * @param :  timing $timing 
 * @access : public
 * @return : void
 * @date : 2011-01-26
 * @author : emmanuel <e.gauthier@hegyd.com>
 */
function smoothScroll(destinationY,callbackFunction,timing){
	
	if(timing == undefined || timing == '') timing = 550 ;

	var MaxScroll = window.innerHeight || document.documentElement.clientHeight;
	MaxScroll = $('body').height() - MaxScroll;
	if(MaxScroll > 1 && destinationY > MaxScroll) destinationY = MaxScroll ;
	
	if(destinationY >= 0){
		$('html,body').animate({
			scrollTop: destinationY
		},timing,'easeOutExpo',function(){
			if( $.isFunction(callbackFunction) ) callbackFunction() ;
		});
	}else{
		if( $.isFunction(callbackFunction) ) callbackFunction() ;
	}
	return false;
}

/**
 * Function constructDefaultAction 
 * 
 * @description : if you want an element to have a default action on dblclicking 
 * @access : public
 * @return : void
 * @date : 2011-01-26
 * @author : emmanuel <e.gauthier@hegyd.com>
 */
function constructDefaultAction(){
	$('.jsDefaultAction').each(function(){
		var blockEl = $(this);
		var defaultLink = blockEl.find('jsDefaultLink');
		if(defaultLink.length != 1){
			defaultLink = blockEl.find('a:first');
		}

		if(defaultLink.length == 1){
			blockEl.dblclick(function(e){
				window.location = defaultLink.attr('href');
			}).hover(function(){
				blockEl.css('cursor','pointer');
			},function(){
				blockEl.css('cursor','');
			});
		}
	});
}


/**
 * Function showInfoBox 
 * 
 * @description : Show information box on top of the design  
 * @param :  text $text 
 * @param :  b $b 
 * @param :  s $s 
 * @param :  a $a 
 * @param :  h $h 
 * @access : public
 * @return : void
 * @date : 2011-01-26
 * @author : emmanuel <e.gauthier@hegyd.com>
 */

var beforeShowDuration = 500;
var showDuration = 500;
var aliveDuration = 4000;
var hideDuration = 500;

var infoBoxTimeout = null;

function showInfoBox(text,b,s,a,h){

	if(b == 0 || b == undefined ) b=beforeShowDuration;
	if(s == 0 || s == undefined ) s=showDuration;
	if(a == 0 || a == undefined ) a=aliveDuration;
	if(h == 0 || h == undefined ) h=hideDuration;
	
	var infoBox = $('#infoBox');

	if(infoBox.length){
		if(infoBoxTimeout) window.clearTimeout(infoBoxTimeout);
		
		infoBox.css({ display: 'none'}).stop();

		if(text || (text = infoBox.find('.callbackText').html()) ){
			infoBox.find('.message').html(text);
			var infoBoxHeight = infoBox.height();
			infoBox.css({
					'top': -(infoBoxHeight)
			});

			infoBoxTimeout = window.setTimeout(function(){
				infoBox.css({display:'block'});
				infoBox.animate({
					top: 0 
				},s,function(){					
					infoBoxTimeout = window.setTimeout(function(){
						infoBox.animate({top: -(infoBoxHeight+10)}, h);
					},a);
				});
			},b);

		}

	}
}


/**
 * Function constructFancyBox 
 * 
 * @description : Construit les fancybox de la page 
 * @access : public
 * @return : void
 * @date : 2011-01-27
 * @author : emmanuel <e.gauthier@hegyd.com>
 */

var fancyBoxGalleryCount = 1;

function constructFancyBox(){

	$('a.jsFancyBox').each(function(){ $(this).fancybox() });
	
	$('.jsFancyBoxGallery').each(function(){
		var galleryEl = $(this);
		galleryEl.find('a.jsFancyBoxGalleryLink').attr('rel','FancyBoxGallery-'+ fancyBoxGalleryCount++ ).fancybox() ;
	});
}



(function( $ ){
    $.fn.serializeJSON=function() {
        var json = {};
        jQuery.map($(this).serializeArray(), function(n, i){
            json[n['name']] = n['value'];
        });
        return json;
    };

    $.fn.textNodes = function() {
      var ret = [];
      $.each(this[0].childNodes, function() {
          if ( this.nodeType == 3 || $.nodeName(this, "br") ) 
            ret.push( this );
          else $.each(this.childNodes, arguments.callee);
      });
      return $(ret);
    };

})( jQuery );

function ucFirst(string) {
    return string.substring(0, 1).toUpperCase() + string.substring(1).toLowerCase();
}

/**
 * Function colorToHex 
 * 
 * @description : 
 * @param :  color $color 
 * @access : public
 * @return : void
 * @date : 2011-06-29
 * @source : http://haacked.com/archive/2009/12/29/convert-rgb-to-hex.aspx
 */
function colorToHex(color) {
	if (color.substr(0, 1) === '#') {
		return color;
	}
	var digits = /(.*?)rgb\((\d+), (\d+), (\d+)\)/.exec(color);

	var red = parseInt(digits[2]);
	var green = parseInt(digits[3]);
	var blue = parseInt(digits[4]);

	//var rgb = blue | (green << 8) | (red << 16);
    var hex = 1 << 24 | red << 16 | green << 8 | blue

	//return digits[1] + '#' + rgb.toString(16);
	return digits[1] + '#' + hex.toString(16).substr(1);
};

// XPath
// source http://code.google.com/p/fbug/source/browse/branches/firebug1.6/content/firebug/lib.js#1332
/**
 * Gets an XPath for an element which describes its hierarchical location.
 */
function getElementXPath(element)
{
    if (element && element.id)
        return '//*[@id="' + element.id + '"]';
    else
        return this.getElementTreeXPath(element);
};

function getElementTreeXPath(element)
{
    var paths = [];

    // Use nodeName (instead of localName) so namespace prefix is included (if any).
    for (; element && element.nodeType == 1; element = element.parentNode)
    {
        var index = 0;
        for (var sibling = element.previousSibling; sibling; sibling = sibling.previousSibling)
        {
            // Ignore document type declaration.
            //if (sibling.nodeType == Node.DOCUMENT_TYPE_NODE)
            if (sibling.nodeType == 10)
                continue;

            if (sibling.nodeName == element.nodeName)
                ++index;
        }

        var tagName = element.nodeName.toLowerCase();
        var pathIndex = (index ? "[" + (index+1) + "]" : "");
        paths.splice(0, 0, tagName + pathIndex);
    }

    return paths.length ? "/" + paths.join("/") : null;
};

function getElementsByXPath(doc, xpath)
{
    var nodes = [];

    try {
        var result = doc.evaluate(xpath, doc, null, XPathResult.ANY_TYPE, null);
        for (var item = result.iterateNext(); item; item = result.iterateNext())
            nodes.push(item);
    }
    catch (exc)
    {
        // Invalid xpath expressions make their way here sometimes.  If that happens,
        // we still want to return an empty set without an exception.
    }

    return nodes;
};

Array.prototype.compare = function(testArr) {
    if (this.length != testArr.length) return false;
    for (var i = 0; i < testArr.length; i++) {
        if (this[i].compare) { 
            if (!this[i].compare(testArr[i])) return false;
        }
        if (this[i] !== testArr[i]) return false;
    }
    return true;
}

function strip_tags (input, allowed) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Luke Godfrey
    // +      input by: Pul
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +      input by: Alex
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Marc Palau
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Eric Nagel
    // +      input by: Bobby Drake
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Tomasz Wesolowski
    // +      input by: Evertjan Garretsen
    // +    revised by: Rafał Kukawski (http://blog.kukawski.pl/)
    // *     example 1: strip_tags('<p>Kevin</p> <br /><b>van</b> <i>Zonneveld</i>', '<i><b>');
    // *     returns 1: 'Kevin <b>van</b> <i>Zonneveld</i>'
    // *     example 2: strip_tags('<p>Kevin <img src="someimage.png" onmouseover="someFunction()">van <i>Zonneveld</i></p>', '<p>');
    // *     returns 2: '<p>Kevin van Zonneveld</p>'
    // *     example 3: strip_tags("<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>", "<a>");
    // *     returns 3: '<a href='http://kevin.vanzonneveld.net'>Kevin van Zonneveld</a>'
    // *     example 4: strip_tags('1 < 5 5 > 1');
    // *     returns 4: '1 < 5 5 > 1'
    // *     example 5: strip_tags('1 <br/> 1');
    // *     returns 5: '1  1'
    // *     example 6: strip_tags('1 <br/> 1', '<br>');
    // *     returns 6: '1  1'
    // *     example 7: strip_tags('1 <br/> 1', '<br><br/>');
    // *     returns 7: '1 <br/> 1'
    allowed = (((allowed || "") + "").toLowerCase().match(/<[a-z][a-z0-9]*>/g) || []).join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
    var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
        commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
    return input.replace(commentsAndPhpTags, '').replace(tags, function ($0, $1) {
        return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
    });
}


