;
(function($) {
    $.fn.extend( {
        adqwbutton : function(style) {
            return this.each(function() {
                new $.AdqwButton(this, style);
            });
        },
        ajaxLink: function(options) {
            return this.each(function() {
                new $.AjaxLink(this,options);
            });
        }
    });

    $.AjaxHistory={
        detectInterval : false,
        latestHash : false,
        hitso : false,
        current: false
    };
	
    $.AjaxHistory.start=function () {
        $.AjaxHistory.histo=[];
        $.AjaxHistory.detectInterval=setInterval('$.AjaxHistory.checkLocation()',100);
        current=window.location.href;
    }
	
    $.AjaxHistory.checkLocation=function () {
        var currentLocation=window.location.href;
        if (currentLocation!=current) {
            var hrefArr=currentLocation.split('#');
            if (hrefArr.length>1) {
                if (hrefArr[1].length>3 && hrefArr[1].substring(0,4)=='ajax') {
                    var newHash=parseInt(hrefArr[1].substring(4));
                    if ($.AjaxHistory.latestHash && newHash!=$.AjaxHistory.latestHash) {
                        $.AjaxHistory.goTo(newHash);
                    }
                }
            } else if($.AjaxHistory.latestHash) {
                //went back to base url
                $.AjaxHistory.goTo(0);
            }
        }
    }
	
    $.AjaxHistory.add=function(url) {
        $.AjaxHistory.histo.push(url);
        //now change the location
        var currentLocation=window.location.href;
        var hrefArr=currentLocation.split('#');
        currentLocation=hrefArr[0];
        currentLocation=currentLocation+'#ajax'+($.AjaxHistory.histo.length);
        $.AjaxHistory.latestHash=$.AjaxHistory.histo.length;
        window.location.href=currentLocation;
        current=currentLocation;
    };
	
    $.AjaxHistory.goTo=function(num) {
        if (num==-1) {
            if ($.AjaxHistory.latestHash) {
                num=$.AjaxHistory.latestHash;
            } else {
                num=0;
            }
        }
        $.AjaxHistory.latestHash=num;
        $.fn.colorbox({
            transition: "none",
            html: "<div class=\"loader loaderMessage\"><h1>Rechargement de la page en cours...</h1>"
        });
        if (num>0) {
            var url=$.AjaxHistory.histo[num-1];
            if (url) {
                window.location.href=url;
            }
        } else {
            window.location.reload();
        }
		
    };
	
    $.AdqwButton = function(button, style) {
        var $button = $(button);
        var init = function() {
            $button.addClass('btApplied');
            $button.mouseover(function() {
                $(this).addClass(style);
            });
            $button.mouseout(function() {
                $(this).removeClass(style);
            });
        }
        if (!$button.hasClass('btApplied')) {
            init();
        }
    };
	
	
	
    $.AjaxLink = function(element, options) {
        var $link = $(element);
        var opts=$.extend({},$.AjaxLink.defaults,options);
        var init = function() {
            $link.addClass('alApplied');
            $link.click(function() {
                $this=$(this);
                var doSend=true;
                if (opts.beforeSend) {
                    doSend=opts.beforeSend();
                }
                if (doSend) {
                    var url=$(this).attr('href');
                    if (!url) {
                        url=opts.url;
                    }
                    if (url) {
                        $.AjaxLink.ajaxLoad(url,opts);
                    }
                }
                return false;
            });
			
        }
        if (!$link.hasClass('alApplied')) {
            init();
        }
    }
	
    $.AjaxLink.ajaxLoad=function (url,opts) {
        opts=$.extend({},$.AjaxLink.defaults,opts);
        var aUrl=ajaxUrl(url);
        var $theContainer = false;
        if (opts.target) {
            $theContainer=$(opts.target);
        }
        var aOptions= {
            url : aUrl,
            dataType: 'html',
            success: function(data,statusText,xhr) {
                if ($theContainer) {
                    $theContainer.replaceWith(data);
                    $.fn.colorbox.resize({
                        doNotScroll: true
                    });
                    if (opts.doHistory) {
                        $.AjaxHistory.add(url);
                    }
                }
            }
        };
        if (opts.complete) {
            aOptions.complete=opts.complete;
        }
        if (opts.confirm) {
            jConfirm(opts.confirm, 'Confirmation', function(r){
                if (r) {
                    if ($theContainer) {
                        opts.showWaiter($theContainer,opts.waiterClass);
                    }
                    $.ajax(aOptions);
                }
            });
        } else {
            if ($theContainer) {
                opts.showWaiter($theContainer,opts.waiterClass);
            }
            $.ajax(aOptions);
        }
    }
	
    $.AjaxLink.showWaiter= function($theContainer,waiterClass,inner) {
        var $waiter=$('<div id="waiter" class="loader"></div>');
        if (!inner) {
            inner=false;
        }
        if (waiterClass) {
            $waiter.addClass(waiterClass);
        }
        if (inner) {
            $waiter.css('width',$theContainer.width());
            $waiter.css('height',$theContainer.height());
        } else {
            $waiter.css('width',$theContainer.outerWidth());
            $waiter.css('height',$theContainer.outerHeight());
        }
        $waiter.css('position','absolute');
        if ($.fn.bgiframe) {
            $waiter.bgiframe();
        }
        $theContainer.prepend($waiter);
    }
	
    $.AjaxLink.removeWaiter= function($theContainer) {
        var $waiter=$('#waiter',$theContainer);
        $waiter.remove();
    }
	
    $.AjaxLink.showWaiterUpload= function($theContainer,waiterClass,message) {
        if (!message) {
            message='Envoi en cours... <br />L\'envoi de fichiers peut prendre un certain temps, merci de bien vouloir patienter';
        }
        var $waiter=$('<div id="waiter" class="loader"><h3>'+message+'</h3></div>');
        if (waiterClass) {
            $waiter.addClass(waiterClass);
        }
        $waiter.css('width',$theContainer.outerWidth());
        var height=$theContainer.outerHeight();
        if (height<220) {
            height=220;
        }
        $waiter.css('height',height+'px');
        $waiter.css('position','absolute');
        $waiter.css('background-position','center bottom');
        $theContainer.prepend($waiter);
        if ($.fn.bgiframe) {
            $waiter.bgiframe();
        }
    }
	
    $.AjaxLink.defaults = {
        target: false,
        beforeSend: false,
        complete: false,
        confirm: false,
        showWaiter: $.AjaxLink.showWaiter,
        doHistory: true,
        url: false,
        waiterClass: false
    }
})(jQuery)

function loginStatus() {
    $.fn.colorbox( {
        href : '#loginStatus',
        inline : true,
        width : '400',
        initialWidth : '400',
        initialHeight : '300',
        innerHeight: '150',
        close : 'Fermer'
    });
}

function initOnglets() {
    $('#onglets a').each(function() {
        if (!$(this).hasClass('ongletsApplied')) {
            $(this).addClass('ongletsApplied');
            $(this).click(function() {
                var url = $(this).attr('href');
                if (url) {
                    var aUrl = ajaxUrl(url) + 'doSubOnglets/1/';
                    // remove the active and move it to this one
                    $('#onglets li.active').removeClass('active');
                    $(this).parent('li').addClass('active');
                    var $theContainer = $('#ongletsContent .ongletTarget');
                    if (!$theContainer.hasClass('contentWrapper')) {
                        $theContainer.addClass('contentWrapper');
                    }
                    $.AjaxLink.showWaiter($theContainer,'noborder',true);
                    var options = {
                        url : aUrl,
                        dataType : 'html',
                        success : function(data, statusText, xhr) {
                            $theContainer.empty();
                            $theContainer.append(data);
                            initPage();
                            $.AjaxHistory.add(url);
                        }
                    };
                    $.ajax(options);
                }
                return false;
            });
        }
    });

    $('#sousOnglets a').each(function() {
        if (!$(this).hasClass('sousOngletsApplied')) {
            $(this).addClass('sousOngletsApplied');
            $(this).click(function() {
                var url = $(this).attr('href');
                if (url) {
                    var aUrl = ajaxUrl(url);
                    // remove the active and move it to this one
                    $('#sousOnglets div.buttonCur').removeClass('buttonCur');
                    $(this).parent('div').addClass('buttonCur');
                    var $theContainer = $('#sousOngletsContent');
                    $.AjaxLink.showWaiter($theContainer,'noborder',true);
                    var options = {
                        url : aUrl,
                        dataType : 'html',
                        success : function(data, statusText, xhr) {
                            $theContainer.empty();
                            $theContainer.append(data);
                            initPage();
                            $.AjaxHistory.add(url);
                        }
                    };
                    $.ajax(options);
					
                }
                return false;
            });
        }
    });

}

function initPopupForm($scope) {
	
    $('form', $scope).each(function() {
        var url = $(this).attr('action');
        $(this).attr('action', ajaxUrl(url));
        $(this).ajaxForm( {
            success : function() {
                // when browser is ie, make sure loaded scripts are executed
				
                $('#cboxLoadingOverlay').hide();
                $('#cboxLoadingOverlay').empty();
                $('#cboxLoadingGraphic').hide();
                $.fn.colorbox.resize();
            },
            target : '#cboxLoadedContent',
            beforeSubmit : function(arr, $form, options) {
                if ($('input[type=file]',$form).length) {
                    //we need to warn about file upload...
                    $('<div><h3>Envoi en cours... L\'envoi de fichiers peut prendre beaucoup de temps, merci de bien vouloir patienter</h3></div>').css('padding','20px').css('margin-top','30px').appendTo($('#cboxLoadingOverlay'));
                }
                $('#cboxLoadingOverlay').show();
                $('#cboxLoadingGraphic').show();
            }
        });
    });
}

var lastPopup;

function reloadLastPopup() {
    if (lastPopup) {
        $('#cboxLoadingOverlay').show();
        $('#cboxLoadingGraphic').show();
        $theContainer=$('#cboxLoadedContent');
        var aUrl=ajaxUrl(lastPopup)+'popup/1/';
        var aOptions= {
            url : aUrl,
            dataType: 'html',
            success: function(data,statusText,xhr) {
                $theContainer.html(data).each(function() {
                    if ($.browser.msie && parseInt($.browser.version) <= 6 ) {
                        $('script',$theContainer).each(function() {
                            var code = $(this).innerHtml();
                            eval(code);
                        });
                    }
                    $('#cboxLoadingOverlay').hide();
                    $('#cboxLoadingOverlay').empty();
                    $('#cboxLoadingGraphic').hide();
                    $.fn.colorbox.resize();
                });
            }
        };
        alert('reload last popup is '+aUrl);
        $.ajax(aOptions);
    } else {
        $.fn.colorbox.close();
    }
}

function initPopupLinks($scope,repop) {
    if (!$scope) {
        $scope = $('body');
    }
    $('a.popup', $scope).each(function() {
        if (!$(this).hasClass('pApplied')) {
            $(this).addClass('pApplied');
            var url=$(this).attr('href');
            var imgPat=/\.jpg$|\.gif$|\.jpeg$/
            if (!url.match(imgPat)) {
                var ajHref = ajaxUrl(url)+'popup/1/';
                if (repop) {
                    ajHref = ajHref+'repop/1/';
                }
            }
            $(this).colorbox( {
                href : ajHref,
                title : ' ',
                initialWidth : '400',
                initialHeight : '300',
                close : 'Fermer',
                transition : 'elastic',
                scrolling: false,
                onComplete : function() {
                    if (!repop) {
                        lastPopup=url;
                    }
                }
            });
        }
    });
    $('a.popupConfirm', $scope).each(function() {
        if (!$(this).hasClass('pApplied')) {
            $(this).addClass('pApplied');
            var url=$(this).attr('href');
            ajHref = ajaxUrl(url)+'popup/1/';
            var invite=$(this).attr('rel');
            $(this).click(function (){
                var r=jConfirm(invite,'Attention',function(r) {
                    if (r) {
                        $.fn.colorbox({
                            href : ajHref,
                            title : ' ',
                            initialWidth : '400',
                            initialHeight : '300',
                            close : 'Fermer',
                            transition : 'elastic',
                            scrolling: false,
                            onComplete : function() {
                                if (!repop) {
                                    lastPopup=url;
                                }
                            }
                        });
                    }
                });
                return false;
            });
        }
    });
}

function initButtons($scope) {
    if (!$scope) {
        $scope = $('body');
    }
    $('.roundButton',$scope).adqwbutton('roundButtonOver');
    $('.button',$scope).adqwbutton('buttonOver');
    $('input.submit',$scope).adqwbutton('submitOver');
	
}

function initTooltip($scope) {
    if (!$scope) {
        $scope = $('body');
    }
    $('.tooltip', $scope).each(function() {
        if (!$(this).hasClass('tpApplied')) {
            $(this).addClass('tpApplied');
            var rel = $(this).attr('rel');
            var relSplit = rel.split('|');
            var size = 300;
            if (relSplit.length <= 2) {
                if (relSplit.length>1) {
                    $(this).attr('rel', relSplit[0]);
                    size = relSplit[1];
                }
                $(this).cluetip( {
                    cluezIndex: 10001,
                    local : true,
                    hideLocal : true,
                    dropShadow: true,
                    width : size,
                    cluetipClass : 'jtip',
                    clickThrough: true
                });
            } else {
                $(this).cluetip( {
                    cluezIndex: 10001,
                    titleAttribute: 'rel',
                    local : false,
                    splitTitle : '|',
                    dropShadow: true,
                    width : size,
                    cluetipClass : 'jtip',
                    clickThrough: true
                });
            }
			
        }
    });
}

function ajaxUrl(url) {
    var now = new Date();
    var nowTs = now.getTime();
    var urlArr=url.split('?');
    if (urlArr.length>1) {
        return urlArr[0] + 'ajax/1/rand/' + nowTs + '/?'+urlArr[1];
    } else {
        return url + 'ajax/1/rand/' + nowTs + '/';
    }
}

function initCommentForm(discussionId,commentId) {
    var $theDiscussion=$('#BmDiscussion_'+discussionId);
    var $theForm=$('#BmDiscussion_'+discussionId+' #BmCommentEditForm_'+commentId);
    var $photoRemoveLink=$('#BmDiscussion_'+discussionId+' #BmCommentEditForm_'+commentId+' #removePhoto');
    var $theContainer=$('#BmDiscussion_'+discussionId+' #BmCommentEditFormContainer_'+commentId);
    var $title=$('.title',$theContainer);
    //hide the link control
    var $theLink=$('.inputLine.link',$theForm);
    var linkValue=$('.inputLine.link input',$theForm).val();
    if (!$theLink.hasClass('error') && (!linkValue || linkValue=='http://')) {
        $theLink.hide();
        $('.inputLine.link input',$theForm).val("http://");
        //activate the link toggle button
        $('.toggleLink',$theForm).click(function() {
            $theLink.slideToggle('fast',function() {
                $.fn.colorbox.resize({
                    doNotScroll: true
                });
            });
        });
    } else {
        //hide the link toggle button
        $('.toggleLink',$theForm).hide();
    }
    //hide the photo control
    var $thePhoto=$('.inputLine.fileNames',$theForm);
    var already=$('input#files',$theForm).val() || ($('input.photo_uid',$theForm).val()>0);
    if (!$thePhoto.hasClass('error') && !already) {
        $thePhoto.hide();
        //activate the link toggle button
        $('.togglePhoto',$theForm).click(function () {
            $thePhoto.slideToggle('fast',function() {
                $.fn.colorbox.resize({
                    doNotScroll: true
                });
            });
        });
    } else {
        //hide the link toggle button
        $('.togglePhoto',$theForm).hide();
    }
    //make the photo stuff a file
    $('#fileNames',$theForm).adqwFileInput({
        nbMax: 1
    });
    if (!$title.hasClass('fixed')) {
        $title.click(function(){
            $theForm.toggleClass('collapsed');
        });
    }
    if ($photoRemoveLink.length) {
        $photoRemoveLink.click(function() {
            $('input.photo_uid',$theForm).val('');
            $('#currentPhoto',$theForm).hide();
            $(this).hide();
            return false;
        });
    }
    initButtons();
    initTooltip($theForm);
    var target=$theForm.attr('rel');
    if (target=='self') {
        target='#BmDiscussion_'+discussionId+' #BmCommentEditFormContainer_'+commentId;
    } else {
        target='#BmDiscussion_'+discussionId;
    }
    var $theTarget=$(target);
    var action=$theForm.attr('action');
    $theForm.attr('action',ajaxUrl(action));
    $theForm.ajaxForm({
        target : target,
        replaceTarget: true,
        beforeSubmit : function(arr, $form, options) {
            if ($form.hasClass('uploading')) {
                jAlert('Transfert de fichier en cours, merci de patienter...');
                return false;
            } else {
                if ($('input[type=file]',$form).length) {
                    $.AjaxLink.showWaiterUpload($theTarget,'noborder','Envoi en cours... <br />L\'envoi de fichiers et la vérification d\'adresse web peut prendre un certain temps, merci de bien vouloir patienter');
                } else {
                    $.AjaxLink.showWaiter($theTarget,'noborder');
                }
            }
            return true;
        },
        success: function(data) {
            var $images=$('img',data);
            var nbImages=$images.length;
            if (nbImages) {
                $images.load(function() {
                    nbImages=nbImages-1;
                    if (!nbImages) {
                        $.fn.colorbox.resize({
                            doNotScroll: true
                        });
                    }
                    $(this).unbind('load');
                });
            } else {
                $.fn.colorbox.resize({
                    doNotScroll: true
                });
            }
        }
    });
}

function ShowWaiter(containerId) {
    var $theContainer=$(containerId);
    var $waiter=$('<div id="waiter" class="loader"></div>');
    $waiter.css('width',$theContainer.outerWidth());
    $waiter.css('height',$theContainer.outerHeight());
    $waiter.css('position','absolute');
    $theContainer.prepend($waiter);
}

function loadInTarget(url,target,replace) {
    if (replace==null) {
        replace=true;
    }
    var $theContainer=$(target);
    $.AjaxLink.showWaiter($theContainer,'noborder');
    var options={
        url : ajaxUrl(url),
        dataType: 'html',
        success: function(data,statusText,xhr) {
            if (replace) {
                $theContainer.replaceWith(data);
            } else {
                $theContainer.empty();
                $theContainer.append(data);
            }
        }
    };
    $.ajax(options);
}


function initPage() {
    initPopupLinks();
    initOnglets();
    initButtons();
    initTooltip();
}

var deferPopupReady=[];
var popupReady=false;

$(document).ready(function() {
    initPage();
    $.AjaxHistory.start();
    $(document).bind('cbox_complete',function() {
        popupReady=true;
        while (deferPopupReady.length) {
            var deferredFunc=deferPopupReady.shift();
            deferredFunc();
        }
    //when all functions are executes, hide the loader
    });
    $(document).bind('cbox_closed',function() {
        popupReady=false;
        //if we were asked to do stuff, too late !
        deferPopupReady=[];
    });
});

