$(document).ready(function(){ 
  page_init();
});


// hash change : http://benalman.com/projects/jquery-hashchange-plugin/
(function($,e,b) {
    var c="hashchange",h=document,f,g=$.event.special,i=h.documentMode,d="on"+c in e&&(i===b||i>7);
    function a(j) {
        j=j||location.href;
        return"#"+j.replace(/^[^#]*#?(.*)$/,"$1")
    }

    $.fn[c]= function(j) {
        return j?this.bind(c,j):this.trigger(c)
    };
    $.fn[c].delay=50;
    g[c]=$.extend(g[c],{setup: function() {
            if(d) {
                return false
            }
            $(f.start)
        },teardown: function() {
            if(d) {
                return false
            }
            $(f.stop)
        }});
    f=(function() {
        var j={},p,m=a(),k= function(q) {
            return q
        },l=k,o=k;
        j.start= function() {
            p||n()
        };
        j.stop= function() {
            p&&clearTimeout(p);
            p=b
        };
        function n() {
            var r=a(),q=o(m);
            if(r!==m) {
                l(m=r,q);
                $(e).trigger(c)
            } else {
                if(q!==m) {
                    location.href=location.href.replace(/#.*/,"")+q
                }
            }
            p=setTimeout(n,$.fn[c].delay)
        }

        $.browser.msie&&!d&&(function() {
            var q,r;
            j.start= function() {
                if(!q) {
                    r=$.fn[c].src;
                    r=r&&r+a();
                    q=$('<iframe tabindex="-1" title="empty"/>').hide().one("load", function() {
                        r||l(a());
                        n()
                    }).attr("src",r||"javascript:0").insertAfter("body")[0].contentWindow;
                    h.onpropertychange= function() {
                        try {
                            if(event.propertyName==="title") {
                                q.document.title=h.title
                            }
                        } catch(s) {
                        }
                    }
                }
            };
            j.stop=k;
            o= function() {
                return a(q.location.href)
            };
            l= function(v,s) {
                var u=q.document,t=$.fn[c].domain;
                if(v!==s) {
                    u.title=h.title;
                    u.open();
                    t&&u.write('<script>document.domain="'+t+'"<\/script>');
                    u.close();
                    q.location.hash=v
                }
            }
        })();
        return j
    })()
})(jQuery,this);




function page_init() {
  init_fluxoulou();
  

$('.tweet').append('<div class="scene" /><nav><a class="prev button"><</a><a class="next button">></a></nav>');

        var options = {
          username: "ezoulou",
          page: 1,
          avatar_size: 40,
          count: 1,
          loading_text: "loading ..."
        };

        var widget = $(".tweet .scene"),
          next = $(".tweet .next"),
          prev = $(".tweet .prev");

        var enable = function(el, yes) {
          yes ? $(el).removeAttr('disabled') :
                $(el).attr('disabled', true);
        };

        var stepClick = function(incr) {
          return function() {
            options.page = options.page + incr;
            enable(this, false);
            widget.tweet(options);
          };
        };

        next.bind("checkstate", function() {
          enable(this, widget.find("li").length == options.count)
        }).click(stepClick(1));

        prev.bind("checkstate", function() {
          enable(this, options.page > 1)
        }).click(stepClick(-1));

        widget.tweet(options).bind("loaded", function() { next.add(prev).trigger("checkstate"); });


    // home
/*    $('#pageid-home .type_blog .items').wrap('<div class="type_cycle">');
    $('#pageid-home .type_blog .items').after('<div id="navigation-blog" class="navigation"><a class="previous" href="#previous"><</a><span class="pager" /><a class="next" href="#next">></a></div>');
    $('#pageid-home .type_blog .items').cycle({
        fx: 'scrollDown',
        sync : true,
        timeout: 5000,
        random: false,
        pager: '#navigation-blog .pager',
        prev: '#navigation-blog .previous',
        next: '#navigation-blog .next',
        pause: true
    });
*/
    /* lexique */
    if ($('#pageid-lexique').length>0) {
        $(window).hashchange( function() {
            // Alerts every time the hash changes!
            $('#content .box').removeClass('success');
            var lh = window.location.hash.toLowerCase();
            if (lh !='#header') $(lh).parent().addClass('success').remove('.contentnav').append('<nav class="contentnav clearfix"><div class="documentnav"><a title="To top of page" class="totop" href="#header"><span class="picto">⇑</span><span class="title">Haut de page</span></a></div></nav>');
        })
        $(window).hashchange();
    }
    
    // sitemap : css3 fix/hack
	var ccc= '2';
	var cg = 20;
    $('#pageid-plan-du-site #content ul ul ul').css({
        '-webkit-column-count':   ccc,
        '-webkit-column-gap':   cg,
        '-moz-column-count':      ccc,
        '-moz-column-gap':      cg,
        'column-count': ccc,
        'column-gap': cg
    });
  
  
  
  /* blog */
  
  
  
	    /* blog sidebar */
    
  for(var i=1; i< $('.sidebar > div').length-1; i++) {  
    
    var box = $('.sidebar > div:eq('+i+')');
    box.wrapInner('<div class="wrapper jquery"></div>');
    box.find('.wrapper.jquery').hide();

    box.find('.wrapper.jquery > h3').prependTo(box);

    
    box.append('<a href="javascript:void(0)" class="button jquery">+</a>');
    box.find('a.button.jquery').click(function() {
      $(this).prevAll('.wrapper.jquery').toggle();
      if ($(this).text()=='-') $(this).text('+');      
      else $(this).text('-');
    });
        

    box.find('h3').css({'cursor':'pointer'}).click(function() {
      $(this).nextAll('.wrapper.jquery').toggle();
      if ($(this).nextAll('.button.jquery').text()=='-') $(this).nextAll('.button.jquery').text('+');      
      else $(this).nextAll('.button.jquery').text('-');
    });
  }


  $('.sidebar .button.jquery:first').trigger('click');
  
  
  
  
	DD_roundies.addRule('.box', '10px 0 10px 0', true);
	DD_roundies.addRule('#topnav ul li .container.box', '0 0 10px 10px', true);
	DD_roundies.addRule('input,aside li.selected a, aside a.selected', '3px', true);
	DD_roundies.addRule('button, a.button, a.readmore, input.title', '5px', true);
  

  // search template
  $('form.search input[type=text]').each(function() {
    if($(this).attr('value')=='') $(this).attr('value', searchFieldDefault);
    $(this).focus(function() {
      if($(this).attr('value')==searchFieldDefault) $(this).attr('value', '');
    });      
  });
    
  /* search plugin */
  $('body.search3Plugin #content ol li').hover(function(){
      $(this).addClass('selected');
  }, function(){
      $(this).removeClass('selected');
  });

  /* blog plugin */
  $('body.blogPlugin .comments_new .checkbox label').click(function() {
    if ($(this).parent().find('input:checked').length>0) {
      $(this).parent().find('input').attr('checked','');      
    } else {
      $(this).parent().find('input').attr('checked','checked');
    }
  });

	$('body.blogPlugin .comments h4 img').each(function() {
		 if ($(this).width()<10) $(this).attr('src','/weblocal/fluxoulou/images/user.png');
	});
}

function initLightbox() {
    // default case : images 
    $(".lightbox:not(.video):not(.external):not(.iframe)").fancybox({
      "titlePosition"   : "inside", 
      "overlayColor"    : "black", 
      "overlayOpacity"  : 0.2, 
      "showNavArrows"   : false, 
      "titleFormat"   : lightBoxTitle
    });
    // case : videos 
    for (var i =0; i<$('.lightbox.video').length; i++) {
        // first we change the original link (to the flv video) to the player (flowplayer)
      if ($('.lightbox.video').eq(i).attr('href').indexOf('flowplayer/flowplayer-3.1.5.swf')<0) $('.lightbox.video').eq(i).attr('href',"/weblocal/flowplayer/flowplayer-3.1.5.swf?&config={'canvas': {'backgroundColor': '#000'},'clip':{'scaling': 'fit', 'url':'"+webroot.substring(0,webroot.length-1)+$('.lightbox.video').eq(i).attr('href')+"'},'plugins':{'controls':{'url':'/weblocal/flowplayer/flowplayer.controls-3.1.5.swf'}}}");

        // then we call lightbox on these
      $('.lightbox.video').eq(i).fancybox({
          "titlePosition"   : "inside",
          "overlayColor"    : "black", 
          "overlayOpacity"  : 0.2, 
          "titleFormat"   : lightBoxTitle, 
          "type"        : "swf",
          "swf"       : {
            "wmode"       : "window", // pour ie :-( 
           "allowfullscreen"  : true
          }
        });
    } 
    //external links
    $(".lightbox.external").fancybox({
      "titlePosition"   : "inside", 
      "overlayColor"    : "black", 
      "overlayOpacity"  : 0.2, 
      "showNavArrows"   : false,
      "titleFormat"   : lightBoxTitle,      
      'width'       : '75%',
      'height'      : '75%',
      'autoScale'     : false,
      'type'        : 'iframe' 
    });

    $(".lightbox.iframe").fancybox({
      "titlePosition"   : "inside", 
      "overlayColor"    : "black", 
      "overlayOpacity"  : 0.2, 
      "showNavArrows"   : false,
      "titleFormat"     : lightBoxTitle,
      'autoScale'       : true,
      'type'            : 'iframe' 
    });

/*   // try catch needed for ie6
   try {
      // create a teaser node used then in css.
      $('.lightbox > .image img').after('<span class="teaser" />'); // fixme : ne pas créer de teaser sio il en existe déjà un!!. essayer $('.lightbox').each(), plus stable?  
      $('.lightbox:not(:has(> .image img))').append('<span class="teaser" />');
      // fixme : we set the css top position here. fix needed by ie.
      for (var i = 0; i < $('.lightbox > .image .teaser').length; i++) {
        var ih = $('.lightbox > .image .teaser').eq(i).prev().attr('height');
        if (ih>0) {
          $('.lightbox > .image .teaser').eq(i).css({
            'top':ih
          });
        }
      }
    } catch(e) {}
    
    */
    
    $('a.lightbox').each(function() {
      if ($(this).find('.teaser').length==0) {
        try {
          if ($(this).find('> .image img').length>0) {
            $(this).find('> .image img').after('<span class="teaser" />');
            var ih = $(this).find('img').attr('height');
            if (ih>0) {
              $(this).find('.teaser').css({
                'top':ih
              });
            }
          } else {
            $(this).append('<span class="teaser" />');          
          }
        } catch(e) {}
      }      
    });
     
}



/**
 * FLUXOULOU V.4
 * 
 * @author florent global variables
 */
 
var timeoutTopnav;

function init_fluxoulou() {
  // we declare the javascript activated!! party on! :-)
  $("html").addClass("js");
  // languages buttons
  $('#languages.compact li a').hide();
  $('#languages.compact').hover(function() {
    $('#languages.compact li a').stop().slideDown('fast', function() { 
        $('#languages').addClass('active');
      });
  }, function() {
    $('#languages.compact li a').stop().slideUp('fast', function() { 
        $('#languages.compact').removeClass('active');
      });
  });
  /* XHTML video (not gallery ones) intro screen */    
  $('.video.splash a').append('<span class="marker" />');
  $('.video .notice').hide();
  // cycle for galleries list
  // fixme : dirty fix for ie6
  if(!$.browser.msie || $.browser.version>6) {
    for (var i =0; i<$('.item:not(.flickr) .cycle').length; i++) {      

      $('.item:not(.flickr) .cycle span').show();
      $('.item:not(.flickr) .cycle').eq(i).cycle({
        'fit':        1,
       'delay':       (i+1)*1000,
        'timeout':    3000
      });
    }
  }
  // text effects. try catch needed for ie6 I think... 
  try {
    $(".text-effect.typewriter").typewriter();
/*    $(".text-effect.unscramble").each(function() {
      $(this).unscramble();
    });*/
    $(".text-effect.scrambledWriter").scrambledWriter();
  } catch(e) {} 
  // INIT LIGHTBOX : fancybox.net
  // we must change the href of the images of the gallery (mode display gallery) because they lead to the pages for non javascript users.  
  for (var i =0; i<$('.singlegallery:not(.flickr) .lightbox').length; i++) {
    var lightboxHref = pathGalleryFiles+$('.singlegallery:not(.flickr) .lightbox').eq(i).attr('href');
    $('.singlegallery:not(.flickr) .lightbox').eq(i).attr('href', lightboxHref);
  }
  initLightbox();

  // single gallery
//  if ($('.images.singlegallery.galleria').length>0) $('.images.singlegallery.galleria').galleria();    
  
  // images legend rollover
  $('.singlegallery .image').hover(function(){
    $(this).addClass('selected');
    $(this).find('.legend').stop().fadeIn();
  }, function() {
    $(this).removeClass('selected');      
    $(this).find('.legend').stop().fadeOut();
  }).css({
      'cursor': 'pointer'
  }).click(function(){
    $(this).find('.lightbox').trigger('click');
  });
  
  // topnavrollover    
  if ($('#topnav.rollover').length>0) {
    clearTopnav();      
    $('#topnav>ul>li>a').mouseenter(function() {
      var topnavBoxDelay = 500;
      if ($('#topnav>ul>li>a.active').length>0) topnavBoxDelay = 100; 
      clearTopnav();
      $(this).addClass('active');
      // fixme : dirty ie detection 
      if ($.browser.msie) {
        timeoutTopnav = setTimeout(activateTopnav,topnavBoxDelay);        
      } else {
        timeoutTopnav = setTimeout('activateTopnav()',topnavBoxDelay);
      }
    });
    $('#topnav').mouseleave(function() {
      clearTopnav();
    }); 
  }
}

function activateTopnav() {
  $('#topnav>ul>li>a.active').nextAll('.container').addClass('active').stop().slideDown('fast');
}

function clearTopnav() {
    try {
      clearTimeout(timeoutTopnav);
    } catch(e) {}
    $('#topnav>ul>li>.container').removeClass('active').hide();
    $('#topnav>ul>li>a').removeClass('active');    
}


function lightBoxTitle(title, currentArray, currentIndex, currentOpts) {
  var titleStr = '';
  if (currentIndex > 0) titleStr += '<a class="previous" href="javascript:;" onclick="$.fancybox.prev();"><img src="/weblocal/fancybox/fancy_nav_left.png" /></a>'; 
  if (title && title.length) titleStr += '<span class="title">'+title+'</span>';
  if (currentIndex < currentArray.length-1) titleStr += '<a class="next" href="javascript:;" onclick="$.fancybox.next();"><img src="/weblocal/fancybox/fancy_nav_right.png" /></a>';  
    return titleStr; 
}
/*
  // fix : stop play/pause timeout at the last image
  if (currentIndex == currentArray.length-1) {
    clearInterval(lpi);
  }

  if (currentArray.length>1) {
   if (lm == 'play') {
     titleStr += '<a class="play pause" href="javascript:;" onclick="lightboxPlay($(this));">pause</a>';
    } else {
      titleStr += '<a class="play" href="javascript:;" onclick="lightboxPlay($(this));">play</a>';
    }
  }
  

function lightboxPlay(node) {
  if (lm == 'play') {
    lm = 'pause';  
    clearInterval(lpi);
    node.addClass('pause').html('play');
  } else {
    lm = 'play';
    $.fancybox.next();
    lpi = setInterval('$.fancybox.next()', 3000);
    node.removeClass('pause').html('pause');
  }
}
*/



/*
 * FORMS
 * @author florent@ezoulou.be 20092010 - feel free to use
 */
$(document).ready(function(){
    /*
     *  actions happening on fields focus
     */
    $('.form_field').change(function(){
        // remove error style
        $(this).parent().removeClass('error');
    });

  /*
   *  store original value in @alt
   */
    for (var i = 0; i < $('.form_item').length; i++) {
    var node = $('.form_item:eq(' + i + ')').find('.form_field');
    var origVal = node.val();
    node.attr('alt', origVal);
  } 
    
    /* 
     * Country and state fields
     */
  // hide state field
  $('.field input[id*=state]').parent().parent().hide();
  $('select[id*=country]').each(activateStateField);
  // activate state field for United States and Canada
  $('select[id*=country]').change(activateStateField);  
    
    /*
     * form validation
     */
    $('form.form').submit(function(){
        // we check the current step
        if (formItemsCheck($(this), true)) {
            // we submit
            return true;
        }
        else {
            // form is not validated 
            return false;
        }
    });
});



/*
 * forms functions
 */

function activateStateField () {
  if ($(this).find('option:selected').val() == 'us' || $(this).find('option:selected').val() == 'ca') {
    $(this).parent().parent().next().slideDown();
  } else {
    $(this).parent().parent().next().slideUp();
    $(this).parent().parent().next().find('input').attr('value', '');
  }
}

function formItemsCheck(node, showMessage){
    var checkedOk = true;
    /*
     * checking the active substep fields
     */
    if (node.find('.form_item').length > 0) {       
        for (var i = 0; i < node.find('.form_item.required').length; i++) {
            // current form item (one form item = one field) 
            var formItem = node.find('.form_item.required:eq(' + i + ')');
            if (!formItemCheck(formItem, showMessage)) checkedOk = false;
        }
        
        // dirty : check email based on field name!
        if(node.find('.form_field[name=email]').length>0 && node.find('.form_field[name=email]').attr('value')!='' && !isValidEmailAddress(node.find('.form_field[name=email]').val())) {
          checkedOk = false;
          if (showMessage) {
            node.find('.form_field[name=email]').parent().addClass('error');
          }
        }

        
    }
    return checkedOk;
}

function formItemCheck(formItem, showMessage){
    var checkedOk = true;
    // text or textarea
    if (formItem.hasClass('text') || formItem.hasClass('textarea')) {      
        if (formItem.find('.form_field').val() == '' || formItem.find('.form_field').val() == formItem.find('.form_field').attr('alt')) {        
            checkedOk = false;
            if (showMessage) {
                formItem.find('.form_field').parent().addClass('error');
            }
        }
    }
    
    
    else {
        // select
        if (formItem.hasClass('select')) {
            if (formItem.find('.form_field option:selected').length == 0) {
                checkedOk = false;
                if (showMessage) {
                    formItem.addClass('error');
//                    formItem.find('.formAlert:first').remove();
//                    formItem.prepend('<div class="formAlert">required</div>');
                }
            }
        }
    }
    
  /*
    else 
        // email
        if (formItem.hasClass('email')) {
            if (formItem.find('.form_field').val() == '' ||
            formItem.find('.form_field').val() == origEmailStr ||
            formItem.find('.form_field').val() == 'required' ||
            !isValidEmailAddress(formItem.find('.form_field').val())) {
                checkedOk = false;
                if (showMessage) {
                    formItem.find('.form_field').parent().addClass('error');
                }
            }
        }
        else 
            // file
            if (formItem.hasClass('file')) {
                if (formItem.find('.form_field').val() == '') {
                    checkedOk = false;
                    if (showMessage) {
                        formItem.find('.form_field').parent().addClass('error');
                        formItem.find('.form_field').parent().find('.formAlert').remove();
                        formItem.find('.form_field').parent().prepend('<div class="formAlert">required</div>');
                    }
                }
            }
            else 
                // substep checkbox 
                if (formItem.hasClass('checkbox') && formItem.hasClass('hasSubstep')) {
                    if (formItem.find('.substepKicker .form_field:checked').length == 0) {
                        checkedOk = false;
                        if (showMessage) {
                            formItem.addClass('error');
                            formItem.find('.formAlert:first').remove();
                            formItem.prepend('<div class="formAlert">required</div>');
                        }
                    }
                }
                else 
                    // default checkbox
                    if (formItem.hasClass('checkbox')) {
                        if (formItem.find('.form_field:checked').length == 0) {
                            checkedOk = false;
                            if (showMessage) {
                                formItem.addClass('error');
                                formItem.find('.formAlert:first').remove();
                                formItem.prepend('<div class="formAlert">required</div>');
                            }
                        }
                    }
                    */
    return checkedOk;
}

function isValidEmailAddress(emailAddress){
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
}


