jQuery.cookie=function(name,value,options){
    if(typeof value!='undefined'){
        options=options||{};

        if(value===null){
            value='';
            options.expires=-1;
        }
        var expires='';
        if(options.expires&&(typeof options.expires=='number'||options.expires.toUTCString)){
            var date;
            if(typeof options.expires=='number'){
                date=new Date();
                date.setTime(date.getTime()+(options.expires*24*60*60*1000));
            }else{
                date=options.expires;
            }
            expires='; expires='+date.toUTCString();
        }
        var path=options.path?'; path='+(options.path):'';
        var domain=options.domain?'; domain='+(options.domain):'';
        var secure=options.secure?'; secure':'';
        document.cookie=[name,'=',encodeURIComponent(value),expires,path,domain,secure].join('');
    }else{
        var cookieValue=null;
        if(document.cookie&&document.cookie!=''){
            var cookies=document.cookie.split(';');
            for(var i=0;i<cookies.length;i++){
                var cookie=jQuery.trim(cookies[i]);
                if(cookie.substring(0,name.length+1)==(name+'=')){
                    cookieValue=decodeURIComponent(cookie.substring(name.length+1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
(function($){
    $.dimensions={
        version:'1.2'
    };

    $.each(['Height','Width'],function(i,name){
        $.fn['inner'+name]=function(){
            if(!this[0])return;
            var torl=name=='Height'?'Top':'Left',borr=name=='Height'?'Bottom':'Right';
            return this.is(':visible')?this[0]['client'+name]:num(this,name.toLowerCase())+num(this,'padding'+torl)+num(this,'padding'+borr);
        };

        $.fn['outer'+name]=function(options){
            if(!this[0])return;
            var torl=name=='Height'?'Top':'Left',borr=name=='Height'?'Bottom':'Right';
            options=$.extend({
                margin:false
            },options||{});
            var val=this.is(':visible')?this[0]['offset'+name]:num(this,name.toLowerCase())+num(this,'border'+torl+'Width')+num(this,'border'+borr+'Width')+num(this,'padding'+torl)+num(this,'padding'+borr);
            return val+(options.margin?(num(this,'margin'+torl)+num(this,'margin'+borr)):0);
        };

    });
    $.each(['Left','Top'],function(i,name){
        $.fn['scroll'+name]=function(val){
            if(!this[0])return;
            return val!=undefined?this.each(function(){
                this==window||this==document?window.scrollTo(name=='Left'?val:$(window)['scrollLeft'](),name=='Top'?val:$(window)['scrollTop']()):this['scroll'+name]=val;
            }):this[0]==window||this[0]==document?self[(name=='Left'?'pageXOffset':'pageYOffset')]||$.boxModel&&document.documentElement['scroll'+name]||document.body['scroll'+name]:this[0]['scroll'+name];
        };

    });
    $.fn.extend({
        position:function(){
            var left=0,top=0,elem=this[0],offset,parentOffset,offsetParent,results;
            if(elem){
                offsetParent=this.offsetParent();
                offset=this.offset();
                parentOffset=offsetParent.offset();
                offset.top-=num(elem,'marginTop');
                offset.left-=num(elem,'marginLeft');
                parentOffset.top+=num(offsetParent,'borderTopWidth');
                parentOffset.left+=num(offsetParent,'borderLeftWidth');
                results={
                    top:offset.top-parentOffset.top,
                    left:offset.left-parentOffset.left
                };

            }
            return results;
        },
        offsetParent:function(){
            var offsetParent=this[0].offsetParent;
            while(offsetParent&&(!/^body|html$/i.test(offsetParent.tagName)&&$.css(offsetParent,'position')=='static'))offsetParent=offsetParent.offsetParent;
            return $(offsetParent);
        }
    });
    function num(el,prop){
        return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0;
    };

})(jQuery);
(function($){
    var isMouseDown=false;
    var currentElement=null;
    var dropCallbacks={};

    var dragCallbacks={};

    var bubblings={};

    var lastMouseX;
    var lastMouseY;
    var lastElemTop;
    var lastElemLeft;
    var dragStatus={};

    var holdingHandler=false;
    $.getMousePosition=function(e){
        var posx=0;
        var posy=0;
        if(!e)var e=window.event;
        if(e.pageX||e.pageY){
            posx=e.pageX;
            posy=e.pageY;
        }
        else if(e.clientX||e.clientY){
            posx=e.clientX+document.body.scrollLeft+document.documentElement.scrollLeft;
            posy=e.clientY+document.body.scrollTop+document.documentElement.scrollTop;
        }
        return{
            'x':posx,
            'y':posy
        };

    };

    $.updatePosition=function(e){
        var pos=$.getMousePosition(e);
        var spanX=(pos.x-lastMouseX);
        var spanY=(pos.y-lastMouseY);
        var newPos=$.setElementPosition(lastElemLeft+spanX,lastElemTop+spanY);
        return newPos;
    };

    $.setElementPosition=function(left,top)

    {
        if(currentElement.dragBounds)

        {
            var b=currentElement.dragBounds;
            left=Math.max(b.xMin,Math.min(b.xMax,left));
            top=Math.max(b.yMin,Math.min(b.yMax,top));
        }
        $(currentElement).css({
            top:top,
            left:left
        });
        return{
            left:left,
            top:top
        };

    }
    $(document).mousemove(function(e){
        if(isMouseDown&&dragStatus[currentElement.id]!='false'){
            var newPos=$.updatePosition(e);
            if(dragCallbacks[currentElement.id]!=undefined){
                dragCallbacks[currentElement.id](e,currentElement,newPos);
            }
            return false;
        }
    });
    $(document).mouseup(function(e){
        if(isMouseDown&&dragStatus[currentElement.id]!='false'){
            isMouseDown=false;
            if(dropCallbacks[currentElement.id]!=undefined){
                dropCallbacks[currentElement.id](e,currentElement);
            }
            return false;
        }
    });
    $.fn.ondrag=function(callback){
        return this.each(function(){
            dragCallbacks[this.id]=callback;
        });
    };

    $.fn.ondrop=function(callback){
        return this.each(function(){
            dropCallbacks[this.id]=callback;
        });
    };

    $.fn.dragOff=function(){
        return this.each(function(){
            dragStatus[this.id]='off';
        });
    };

    $.fn.dragOn=function(){
        return this.each(function(){
            dragStatus[this.id]='on';
        });
    };

    $.fn.setHandler=function(handlerId){
        return this.each(function(){
            var draggable=this;
            bubblings[this.id]=true;
            $(draggable).css("cursor","");
            dragStatus[draggable.id]="handler";
            $("#"+handlerId).css("cursor","move");
            $("#"+handlerId).mousedown(function(e){
                holdingHandler=true;
                $(draggable).trigger('mousedown',e);
            });
            $("#"+handlerId).mouseup(function(e){
                holdingHandler=false;
            });
        });
    }
    $.fn.easydrag=function(allowBubbling){
        return this.each(function(){
            if(undefined==this.id||!this.id.length)this.id="easydrag"+(new Date().getTime());
            bubblings[this.id]=allowBubbling?true:false;
            dragStatus[this.id]="on";
            $(this).css("cursor","move");
            $(this).mousedown(function(e){
                if((dragStatus[this.id]=="off")||(dragStatus[this.id]=="handler"&&!holdingHandler))
                    return bubblings[this.id];
                $(this).css("position","absolute");
                isMouseDown=true;
                currentElement=this;
                var pos=$.getMousePosition(e);
                lastMouseX=pos.x;
                lastMouseY=pos.y;
                lastElemTop=this.offsetTop;
                lastElemLeft=this.offsetLeft;
                $.updatePosition(e);
                return bubblings[this.id];
            });
        });
    };

})(jQuery);
(function($){
    var currentHash,previousNav,timer,hashTrim=/^.*#/;
    var msie={
        iframe:null,
        getDoc:function(){
            return msie.iframe.contentWindow.document;
        },
        getHash:function(){
            return msie.getDoc().location.hash;
        },
        setHash:function(hash){
            var d=msie.getDoc();
            d.open();
            d.close();
            d.location.hash=hash;
        }
    };

    var historycheck=function(){
        var hash=msie.iframe?msie.getHash():location.hash;
        if(hash!=currentHash){
            currentHash=hash;
            if(msie.iframe){
                location.hash=currentHash;
            }
            var current=$.history.getCurrent();
            $.event.trigger('history',[current,previousNav]);
            previousNav=current;
        }
    };

    $.history={
        add:function(hash){
            hash='#'+hash.replace(hashTrim,'');
            if(currentHash!=hash){
                var previous=$.history.getCurrent();
                location.hash=currentHash=hash;
                if(msie.iframe){
                    msie.setHash(currentHash);
                }
                $.event.trigger('historyadd',[$.history.getCurrent(),previous]);
            }
            if(!timer){
                timer=setInterval(historycheck,100);
            }
        },
        getCurrent:function(){
            return currentHash.replace(hashTrim,'');
        }
    };

    $.fn.history=function(fn){
        $(this).bind('history',fn);
    };

    $.fn.historyadd=function(fn){
        $(this).bind('historyadd',fn);
    };

    $(function(){
        currentHash=location.hash;
        if($.browser.msie){
            msie.iframe=$('<iframe style="display:none" src="javascript:false;"></iframe>').prependTo('body')[0];
            msie.setHash(currentHash);
            currentHash=msie.getHash();
        }
    });
})(jQuery);
﻿
(function($)
{
    var pwdDefault="****";
    function inputFocus()

    {
        var field=$(this);
        if($.trim(field.val())==$.trim(field.attr("title")))
            field.val("");
    }
    function inputBlur()
    {
        var field=$(this);
        if($.trim(field.val())=="")
            field.val(field.attr("title"));
    }
    function initField(ref)
    {
        var field=$(ref);
        field.focus(inputFocus).blur(inputBlur);
    }
    $.fn.inputDefault=function()
    {
        this.each(function(){
            initField(this);
        });
        return this;
    }
})(jQuery);
﻿
jQuery(function(){
    if(jQueue.length)
        for(var i in jQueue)jQueue[i](jQuery);
});
if(window.jQuery&&!window.jQuery.createTemplate){
    (function(jQuery){
        var Template=function(s,includes,settings){
            this._tree=[];
            this._param={};

            this._includes=null;
            this._templates={};

            this._templates_code={};

            this.settings=jQuery.extend({
                disallow_functions:false,
                filter_data:true,
                filter_params:false,
                runnable_functions:false,
                clone_data:true,
                clone_params:true
            },settings);
            this.f_cloneData=(this.settings.f_cloneData!==undefined)?(this.settings.f_cloneData):(TemplateUtils.cloneData);
            this.f_escapeString=(this.settings.f_escapeString!==undefined)?(this.settings.f_escapeString):(TemplateUtils.escapeHTML);
            this.splitTemplates(s,includes);
            if(s){
                this.setTemplate(this._templates_code['MAIN'],includes,this.settings);
            }
            this._templates_code=null;
        };

        Template.prototype.version='0.7.8';
        Template.DEBUG_MODE=true;
        Template.prototype.splitTemplates=function(s,includes){
            var reg=/\{#template *(\w*?)( .*)*\}/g;
            var iter,tname,se;
            var lastIndex=null;
            var _template_settings=[];
            while((iter=reg.exec(s))!=null){
                lastIndex=reg.lastIndex;
                tname=iter[1];
                se=s.indexOf('{#/template '+tname+'}',lastIndex);
                if(se==-1){
                    throw new Error('jTemplates: Template "'+tname+'" is not closed.');
                }
                this._templates_code[tname]=s.substring(lastIndex,se);
                _template_settings[tname]=TemplateUtils.optionToObject(iter[2]);
            }
            if(lastIndex===null){
                this._templates_code['MAIN']=s;
                return;
            }
            for(var i in this._templates_code){
                if(i!='MAIN'){
                    this._templates[i]=new Template();
                }
            }
            for(var i in this._templates_code){
                if(i!='MAIN'){
                    this._templates[i].setTemplate(this._templates_code[i],jQuery.extend({},includes||{},this._templates||{}),jQuery.extend({},this.settings,_template_settings[i]));
                    this._templates_code[i]=null;
                }
            }
        };

        Template.prototype.setTemplate=function(s,includes,settings){
            if(s==undefined){
                this._tree.push(new TextNode('',1,this));
                return;
            }
            s=s.replace(/[\n\r]/g,'');
            s=s.replace(/\{\*.*?\*\}/g,'');
            this._includes=jQuery.extend({},this._templates||{},includes||{});
            this.settings=new Object(settings);
            var node=this._tree;
            var op=s.match(/\{#.*?\}/g);
            var ss=0,se=0;
            var e;
            var literalMode=0;
            var elseif_level=0;
            for(var i=0,l=(op)?(op.length):(0);i<l;++i){
                var this_op=op[i];
                if(literalMode){
                    se=s.indexOf('{#/literal}');
                    if(se==-1){
                        throw new Error("jTemplates: No end of literal.");
                    }
                    if(se>ss){
                        node.push(new TextNode(s.substring(ss,se),1,this));
                    }
                    ss=se+11;
                    literalMode=0;
                    i=jQuery.inArray('{#/literal}',op);
                    continue;
                }
                se=s.indexOf(this_op,ss);
                if(se>ss){
                    node.push(new TextNode(s.substring(ss,se),literalMode,this));
                }
                var ppp=this_op.match(/\{#([\w\/]+).*?\}/);
                var op_=RegExp.$1;
                switch(op_){
                    case'elseif':
                        ++elseif_level;
                        node.switchToElse();
                    case'if':
                        e=new opIF(this_op,node);
                        node.push(e);
                        node=e;
                        break;
                    case'else':
                        node.switchToElse();
                        break;
                    case'/if':
                        while(elseif_level){
                            node=node.getParent();
                            --elseif_level;
                        }
                    case'/for':case'/foreach':
                        node=node.getParent();
                        break;
                    case'foreach':
                        e=new opFOREACH(this_op,node,this);
                        node.push(e);
                        node=e;
                        break;
                    case'for':
                        e=opFORFactory(this_op,node,this);
                        node.push(e);
                        node=e;
                        break;
                    case'continue':case'break':
                        node.push(new JTException(op_));
                        break;
                    case'include':
                        node.push(new Include(this_op,this._includes));
                        break;
                    case'param':
                        node.push(new UserParam(this_op));
                        break;
                    case'cycle':
                        node.push(new Cycle(this_op));
                        break;
                    case'ldelim':
                        node.push(new TextNode('{',1,this));
                        break;
                    case'rdelim':
                        node.push(new TextNode('}',1,this));
                        break;
                    case'literal':
                        literalMode=1;
                        break;
                    case'/literal':
                        if(Template.DEBUG_MODE){
                            throw new Error("jTemplates: Missing begin of literal.");
                        }
                        break;
                    default:
                        if(Template.DEBUG_MODE){
                            throw new Error('jTemplates: unknown tag: '+op_+'.');
                        }
                }
                ss=se+this_op.length;
            }
            if(s.length>ss){
                node.push(new TextNode(s.substr(ss),literalMode,this));
            }
        };

        Template.prototype.get=function(d,param,element,deep){
            ++deep;
            var $T=d,_param1,_param2;
            if(this.settings.clone_data){
                $T=this.f_cloneData(d,{
                    escapeData:(this.settings.filter_data&&deep==1),
                    noFunc:this.settings.disallow_functions
                },this.f_escapeString);
            }
            if(!this.settings.clone_params){
                _param1=this._param;
                _param2=param;
            }else{
                _param1=this.f_cloneData(this._param,{
                    escapeData:(this.settings.filter_params),
                    noFunc:false
                },this.f_escapeString);
                _param2=this.f_cloneData(param,{
                    escapeData:(this.settings.filter_params&&deep==1),
                    noFunc:false
                },this.f_escapeString);
            }
            var $P=jQuery.extend({},_param1,_param2);
            var $Q=(element!=undefined)?(element):({});
            $Q.version=this.version;
            var ret='';
            for(var i=0,l=this._tree.length;i<l;++i){
                ret+=this._tree[i].get($T,$P,$Q,deep);
            }
            --deep;
            return ret;
        };

        Template.prototype.setParam=function(name,value){
            this._param[name]=value;
        };

        TemplateUtils=function(){};

        TemplateUtils.escapeHTML=function(txt){
            return txt.replace(/&/g,'&amp;').replace(/>/g,'&gt;').replace(/</g,'&lt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;');
        };

        TemplateUtils.cloneData=function(d,filter,f_escapeString){
            if(d==null){
                return d;
            }
            switch(d.constructor){
                case Object:
                    var o={};

                    for(var i in d){
                        o[i]=TemplateUtils.cloneData(d[i],filter,f_escapeString);
                    }
                    if(!filter.noFunc){
                        if(d.hasOwnProperty("toString"))
                            o.toString=d.toString;
                    }
                    return o;
                case Array:
                    var o=[];
                    for(var i=0,l=d.length;i<l;++i){
                        o[i]=TemplateUtils.cloneData(d[i],filter,f_escapeString);
                    }
                    return o;
                case String:
                    return(filter.escapeData)?(f_escapeString(d)):(d);
                case Function:
                    if(filter.noFunc){
                        if(Template.DEBUG_MODE)
                            throw new Error("jTemplates: Functions are not allowed.");else
                            return undefined;
                    }
                default:
                    return d;
            }
        };

        TemplateUtils.optionToObject=function(optionText){
            if(optionText===null||optionText===undefined){
                return{};

            }
            var o=optionText.split(/[= ]/);
            if(o[0]===''){
                o.shift();
            }
            var obj={};

            for(var i=0,l=o.length;i<l;i+=2){
                obj[o[i]]=o[i+1];
            }
            return obj;
        };

        var TextNode=function(val,literalMode,template){
            this._value=val;
            this._literalMode=literalMode;
            this._template=template;
        };

        TextNode.prototype.get=function(d,param,element,deep){
            var __t=this._value;
            if(!this._literalMode){
                var __template=this._template;
                var $T=d;
                var $P=param;
                var $Q=element;
                __t=__t.replace(/\{(.*?)\}/g,function(__0,__1){
                    try{
                        var __tmp=eval(__1);
                        if(typeof __tmp=='function'){
                            if(__template.settings.disallow_functions||!__template.settings.runnable_functions){
                                return'';
                            }else{
                                __tmp=__tmp($T,$P,$Q);
                            }
                        }
                        return(__tmp===undefined)?(""):(String(__tmp));
                    }catch(e){
                        if(Template.DEBUG_MODE){
                            if(e instanceof JTException)
                                e.type="subtemplate";
                            throw e;
                        }
                        return"";
                    }
                });
            }
            return __t;
        };

        var opIF=function(oper,par){
            this._parent=par;
            oper.match(/\{#(?:else)*if (.*?)\}/);
            this._cond=RegExp.$1;
            this._onTrue=[];
            this._onFalse=[];
            this._currentState=this._onTrue;
        };

        opIF.prototype.push=function(e){
            this._currentState.push(e);
        };

        opIF.prototype.getParent=function(){
            return this._parent;
        };

        opIF.prototype.switchToElse=function(){
            this._currentState=this._onFalse;
        };

        opIF.prototype.get=function(d,param,element,deep){
            var $T=d;
            var $P=param;
            var $Q=element;
            var ret='';
            try{
                var tab=(eval(this._cond))?(this._onTrue):(this._onFalse);
                for(var i=0,l=tab.length;i<l;++i){
                    ret+=tab[i].get(d,param,element,deep);
                }
            }catch(e){
                if(Template.DEBUG_MODE||(e instanceof JTException))
                    throw e;
            }
            return ret;
        };

        opFORFactory=function(oper,par,template){
            if(oper.match(/\{#for (\w+?) *= *(\S+?) +to +(\S+?) *(?:step=(\S+?))*\}/)){
                oper='{#foreach opFORFactory.funcIterator as '+RegExp.$1+' begin='+(RegExp.$2||0)+' end='+(RegExp.$3||-1)+' step='+(RegExp.$4||1)+' extData=$T}';
                return new opFOREACH(oper,par,template);
            }else{
                throw new Error('jTemplates: Operator failed "find": '+oper);
            }
        };

        opFORFactory.funcIterator=function(i){
            return i;
        };

        var opFOREACH=function(oper,par,template){
            this._parent=par;
            this._template=template;
            oper.match(/\{#foreach (.+?) as (\w+?)( .+)*\}/);
            this._arg=RegExp.$1;
            this._name=RegExp.$2;
            this._option=RegExp.$3||null;
            this._option=TemplateUtils.optionToObject(this._option);
            this._onTrue=[];
            this._onFalse=[];
            this._currentState=this._onTrue;
        };

        opFOREACH.prototype.push=function(e){
            this._currentState.push(e);
        };

        opFOREACH.prototype.getParent=function(){
            return this._parent;
        };

        opFOREACH.prototype.switchToElse=function(){
            this._currentState=this._onFalse;
        };

        opFOREACH.prototype.get=function(d,param,element,deep){
            try{
                var $T=d;
                var $P=param;
                var $Q=element;
                var fcount=eval(this._arg);
                var key=[];
                var mode=typeof fcount;
                if(mode=='object'){
                    var arr=[];
                    jQuery.each(fcount,function(k,v){
                        key.push(k);
                        arr.push(v);
                    });
                    fcount=arr;
                }
                var extData=(this._option.extData!==undefined)?(eval(this._option.extData)):(($T!=null)?($T):({}));
                var s=Number(eval(this._option.begin)||0),e;
                var step=Number(eval(this._option.step)||1);
                if(mode!='function'){
                    e=fcount.length;
                }else{
                    if(this._option.end===undefined||this._option.end===null){
                        e=Number.MAX_VALUE;
                    }else{
                        e=Number(eval(this._option.end))+((step>0)?(1):(-1));
                    }
                }
                var ret='';
                var i,l;
                if(this._option.count){
                    var tmp=s+Number(eval(this._option.count));
                    e=(tmp>e)?(e):(tmp);
                }
                if((e>s&&step>0)||(e<s&&step<0)){
                    var iteration=0;
                    var _total=(mode!='function')?(Math.ceil((e-s)/step)):undefined;
                    var ckey,cval;
                    for(;((step>0)?(s<e):(s>e));s+=step,++iteration){
                        ckey=key[s];
                        if(mode!='function'){
                            cval=fcount[s];
                        }else{
                            cval=fcount(s);
                            if(cval===undefined||cval===null){
                                break;
                            }
                        }
                        if((typeof cval=='function')&&(this._template.settings.disallow_functions||!this._template.settings.runnable_functions)){
                            continue;
                        }
                        if((mode=='object')&&(ckey in Object)){
                            continue;
                        }
                        var prevValue=extData[this._name];
                        extData[this._name]=cval;
                        extData[this._name+'$index']=s;
                        extData[this._name+'$iteration']=iteration;
                        extData[this._name+'$first']=(iteration==0);
                        extData[this._name+'$last']=(s+step>=e);
                        extData[this._name+'$total']=_total;
                        extData[this._name+'$key']=(ckey!==undefined&&ckey.constructor==String)?(this._template.f_escapeString(ckey)):(ckey);
                        extData[this._name+'$typeof']=typeof cval;
                        for(i=0,l=this._onTrue.length;i<l;++i){
                            try{
                                ret+=this._onTrue[i].get(extData,param,element,deep);
                            }catch(ex){
                                if(ex instanceof JTException){
                                    switch(ex.type){
                                        case'continue':
                                            i=l;
                                            break;
                                        case'break':
                                            i=l;
                                            s=e;
                                            break;
                                        default:
                                            throw e;
                                    }
                                }else{
                                    throw e;
                                }
                            }
                        }
                        delete extData[this._name+'$index'];
                        delete extData[this._name+'$iteration'];
                        delete extData[this._name+'$first'];
                        delete extData[this._name+'$last'];
                        delete extData[this._name+'$total'];
                        delete extData[this._name+'$key'];
                        delete extData[this._name+'$typeof'];
                        delete extData[this._name];
                        extData[this._name]=prevValue;
                    }
                }else{
                    for(i=0,l=this._onFalse.length;i<l;++i){
                        ret+=this._onFalse[i].get($T,param,element,deep);
                    }
                }
                return ret;
            }catch(e){
                if(Template.DEBUG_MODE||(e instanceof JTException))
                    throw e;
                return"";
            }
        };

        var JTException=function(type){
            this.type=type;
        };

        JTException.prototype=Error;
        JTException.prototype.get=function(d){
            throw this;
        };

        var Include=function(oper,includes){
            oper.match(/\{#include (.*?)(?: root=(.*?))?\}/);
            this._template=includes[RegExp.$1];
            if(this._template==undefined){
                if(Template.DEBUG_MODE)
                    throw new Error('jTemplates: Cannot find include: '+RegExp.$1);
            }
            this._root=RegExp.$2;
        };

        Include.prototype.get=function(d,param,element,deep){
            var $T=d;
            var $P=param;
            try{
                return this._template.get(eval(this._root),param,element,deep);
            }catch(e){
                if(Template.DEBUG_MODE||(e instanceof JTException))
                    throw e;
            }
            return'';
        };

        var UserParam=function(oper){
            oper.match(/\{#param name=(\w*?) value=(.*?)\}/);
            this._name=RegExp.$1;
            this._value=RegExp.$2;
        };

        UserParam.prototype.get=function(d,param,element,deep){
            var $T=d;
            var $P=param;
            var $Q=element;
            try{
                param[this._name]=eval(this._value);
            }catch(e){
                if(Template.DEBUG_MODE||(e instanceof JTException))
                    throw e;
                param[this._name]=undefined;
            }
            return'';
        };

        var Cycle=function(oper){
            oper.match(/\{#cycle values=(.*?)\}/);
            this._values=eval(RegExp.$1);
            this._length=this._values.length;
            if(this._length<=0){
                throw new Error('jTemplates: cycle has no elements');
            }
            this._index=0;
            this._lastSessionID=-1;
        };

        Cycle.prototype.get=function(d,param,element,deep){
            var sid=jQuery.data(element,'jTemplateSID');
            if(sid!=this._lastSessionID){
                this._lastSessionID=sid;
                this._index=0;
            }
            var i=this._index++%this._length;
            return this._values[i];
        };

        jQuery.fn.setTemplate=function(s,includes,settings){
            if(s.constructor===Template){
                return jQuery(this).each(function(){
                    jQuery.data(this,'jTemplate',s);
                    jQuery.data(this,'jTemplateSID',0);
                });
            }else{
                return jQuery(this).each(function(){
                    jQuery.data(this,'jTemplate',new Template(s,includes,settings));
                    jQuery.data(this,'jTemplateSID',0);
                });
            }
        };

        jQuery.fn.setTemplateURL=function(url_,includes,settings){
            var s=jQuery.ajax({
                url:url_,
                async:false
            }).responseText;
            return jQuery(this).setTemplate(s,includes,settings);
        };

        jQuery.fn.setTemplateElement=function(elementName,includes,settings){
            var s=jQuery('#'+elementName).val();
            if(s==null){
                s=jQuery('#'+elementName).html();
                s=s.replace(/&lt;/g,"<").replace(/&gt;/g,">");
            }
            s=jQuery.trim(s);
            s=s.replace(/^<\!\[CDATA\[([\s\S]*)\]\]>$/im,'$1');
            s=s.replace(/^<\!--([\s\S]*)-->$/im,'$1');
            return jQuery(this).setTemplate(s,includes,settings);
        };

        jQuery.fn.hasTemplate=function(){
            var count=0;
            jQuery(this).each(function(){
                if(jQuery.getTemplate(this)){
                    ++count;
                }
            });
            return count;
        };

        jQuery.fn.removeTemplate=function(){
            jQuery(this).processTemplateStop();
            return jQuery(this).each(function(){
                jQuery.removeData(this,'jTemplate');
            });
        };

        jQuery.fn.setParam=function(name,value){
            return jQuery(this).each(function(){
                var t=jQuery.getTemplate(this);
                if(t===undefined){
                    if(Template.DEBUG_MODE)
                        throw new Error('jTemplates: Template is not defined.');else
                        return;
                }
                t.setParam(name,value);
            });
        };

        jQuery.fn.processTemplate=function(d,param){
            return jQuery(this).each(function(){
                var t=jQuery.getTemplate(this);
                if(t===undefined){
                    if(Template.DEBUG_MODE)
                        throw new Error('jTemplates: Template is not defined.');else
                        return;
                }
                jQuery.data(this,'jTemplateSID',jQuery.data(this,'jTemplateSID')+1);
                jQuery(this).html(t.get(d,param,this,0));
            });
        };

        jQuery.fn.processTemplateURL=function(url_,param,options){
            var that=this;
            options=jQuery.extend({
                type:'GET',
                async:true,
                cache:false
            },options);
            jQuery.ajax({
                url:url_,
                type:options.type,
                data:options.data,
                dataFilter:options.dataFilter,
                async:options.async,
                cache:options.cache,
                timeout:options.timeout,
                dataType:'json',
                success:function(d){
                    var r=jQuery(that).processTemplate(d,param);
                    if(options.on_success){
                        options.on_success(r);
                    }
                },
                error:options.on_error,
                complete:options.on_complete
            });
            return this;
        };

        var Updater=function(url,param,interval,args,objs,options){
            this._url=url;
            this._param=param;
            this._interval=interval;
            this._args=args;
            this.objs=objs;
            this.timer=null;
            this._options=options||{};

            var that=this;
            jQuery(objs).each(function(){
                jQuery.data(this,'jTemplateUpdater',that);
            });
            this.run();
        };

        Updater.prototype.run=function(){
            this.detectDeletedNodes();
            if(this.objs.length==0){
                return;
            }
            var that=this;
            jQuery.getJSON(this._url,this._args,function(d){
                var r=jQuery(that.objs).processTemplate(d,that._param);
                if(that._options.on_success){
                    that._options.on_success(r);
                }
            });
            this.timer=setTimeout(function(){
                that.run();
            },this._interval);
        };

        Updater.prototype.detectDeletedNodes=function(){
            this.objs=jQuery.grep(this.objs,function(o){
                if(jQuery.browser.msie){
                    var n=o.parentNode;
                    while(n&&n!=document){
                        n=n.parentNode;
                    }
                    return n!=null;
                }else{
                    return o.parentNode!=null;
                }
            });
        };

        jQuery.fn.processTemplateStart=function(url,param,interval,args,options){
            return new Updater(url,param,interval,args,this,options);
        };

        jQuery.fn.processTemplateStop=function(){
            return jQuery(this).each(function(){
                var updater=jQuery.data(this,'jTemplateUpdater');
                if(updater==null){
                    return;
                }
                var that=this;
                updater.objs=jQuery.grep(updater.objs,function(o){
                    return o!=that;
                });
                jQuery.removeData(this,'jTemplateUpdater');
            });
        };

        jQuery.extend({
            createTemplate:function(s,includes,settings){
                return new Template(s,includes,settings);
            },
            createTemplateURL:function(url_,includes,settings){
                var s=jQuery.ajax({
                    url:url_,
                    async:false
                }).responseText;
                return new Template(s,includes,settings);
            },
            getTemplate:function(element){
                return jQuery.data(element,'jTemplate');
            },
            processTemplateToText:function(template,data,parameter){
                return template.get(data,parameter,undefined,0);
            },
            jTemplatesDebugMode:function(value){
                Template.DEBUG_MODE=value;
            }
        });
    })(jQuery);
}
(function($){
    var types=['DOMMouseScroll','mousewheel'];
    $.event.special.mousewheel={
        setup:function(){
            if(this.addEventListener)
                for(var i=types.length;i;)
                    this.addEventListener(types[--i],handler,false);else
                this.onmousewheel=handler;
        },
        teardown:function(){
            if(this.removeEventListener)
                for(var i=types.length;i;)
                    this.removeEventListener(types[--i],handler,false);else
                this.onmousewheel=null;
        }
    };

    $.fn.extend({
        mousewheel:function(fn){
            return fn?this.bind("mousewheel",fn):this.trigger("mousewheel");
        },
        unmousewheel:function(fn){
            return this.unbind("mousewheel",fn);
        }
    });
    function handler(event){
        var args=[].slice.call(arguments,1),delta=0,returnValue=true;
        event=$.event.fix(event||window.event);
        event.type="mousewheel";
        if(event.wheelDelta)delta=event.wheelDelta/120;
        if(event.detail)delta=-event.detail/3;
        args.unshift(event,delta);
        return $.event.handle.apply(this,args);
    }
})(jQuery);
;
(function($){
    $.fn.simpletooltip=function(settings){
        var options=$.extend({
            hideOnLeave:true,
            margin:5,
            showEffect:false,
            hideEffect:false,
            click:false,
            hideDelay:1,
            showDelay:.1,
            showCallback:function(){},
            hideCallback:function(){},
            customTooltip:false,
            customTooltipCache:true,
            align:"top"
        },settings);
        this.each(function(){
            if(!$.isFunction(options.customTooltip)){
                $(this).data("$tooltip",getTooltip(this).hide());
            }
            if(options.click){
                $(this).bind("click",{
                    "options":options,
                    "target":this
                },openTooltip);
            }
            else{
                var tipTimeOut;
                $(this).bind("mouseenter",{
                    "options":options,
                    "target":this
                },function(e){
                    var mouseEvent=e;
                    tipTimeOut=window.setTimeout(function(){
                        openTooltip(mouseEvent);
                    },(options.showDelay*1000));
                }).bind("mouseleave",function(){
                    window.clearTimeout(tipTimeOut);
                });
            }
        });
        return this;
    };

    function getTooltip(target){
        var currentHrefMatch=$(target).attr("href").match(/#.+/);
        if(!!currentHrefMatch){
            var $tooltip=$(currentHrefMatch[0]);
        }
        return $tooltip;
    };

    function initTooltip($tooltip){
        $tooltip.appendTo(document.body).data("width",$tooltip.outerWidth()).data("height",$tooltip.outerHeight()).css({
            "position":"absolute",
            "zIndex":"9998",
            "display":"none"
        }).find("a[rel=close]").click(function(e){
            e.preventDefault();
            $tooltip.trigger("hide");
        }).end().data("init",true);
    };

    function openTooltip(e){
        if(e.type=="click"){
            e.preventDefault();
        }
        var opts=e.data.options;
        var $target=$(e.data.target);
        if(!opts.customTooltipCache&&$target.data("$tooltip")){
            $target.data("$tooltip").remove();
            $target.data("$tooltip",false);
        }
        if(!$target.data("$tooltip")){
            $target.data("$tooltip",$(opts.customTooltip($target.get(0))));
        }
        var $tooltip=$target.data("$tooltip");
        if(!$tooltip.data("init")){
            initTooltip($tooltip);
        }
        $tooltip.data("height",$tooltip.outerHeight());
        var winWidth=$(window).width();
        var winHeight=$(window).height();
        var winOffsetY=$(window).scrollTop();
        var winOffsetX=$(window).scrollLeft();
        $tooltip.unbind("show").unbind("hide");
        if(opts.showEffect&&(opts.showEffect.match(/^fadeIn|slideDown|show$/))){
            $tooltip.bind("show",function(){
                $tooltip[opts.showEffect](200);
                opts.showCallback($target[0],this);
            });
        }
        else{
            $tooltip.bind("show",function(){
                $tooltip.show();
                opts.showCallback($target[0],this);
            });
        }
        if(opts.hideEffect&&(opts.hideEffect.match(/^fadeOut|slideUp|hide$/))){
            $tooltip.bind("hide",function(){
                opts.hideCallback($target[0],this);
                $tooltip[opts.hideEffect](200);
            });
        }
        else{
            $tooltip.bind("hide",function(){
                opts.hideCallback($target[0],this);
                $tooltip.hide();
            });
        }
        var tooltipPosX=e.pageX-($tooltip.data("width")/2);
        var tooltipPosY=e.pageY+30;
        if(opts.align!="top"&&opts.hideDelay>0&&opts.hideOnLeave){
            var timer;
            $tooltip.unbind("mouseenter, mouseleave");
            $tooltip.hover(function(){
                window.clearTimeout(timer);
            },function(){
                timer=window.setTimeout(function(){
                    $tooltip.trigger("hide");
                    $tooltip.unbind("mouseenter, mouseleave");
                    if($.browser.msie&&parseInt($.browser.version)<7)$("select").css({
                        visibility:"visible"
                    });
                },opts.hideDelay*1000);
            });
        }
        else if(opts.hideOnLeave){
            var tipTarget=opts.align=="top"?$target:$tooltip;
            tipTarget.unbind("mouseleave");
            tipTarget.bind("mouseleave",function(){
                $tooltip.trigger("hide");
                tipTarget.unbind("mouseleave");
                if($.browser.msie&&parseInt($.browser.version)<7)$("select").css({
                    visibility:"visible"
                });
            });
        }
        $tooltip.css({
            "left":tooltipPosX+"px",
            "top":tooltipPosY+"px"
        }).trigger("show");
        if($.browser.msie&&parseInt($.browser.version)<7)$("select").css({
            visibility:"hidden"
        });
    };

})(jQuery);
(function($){
    var doc=document,object='object',win=window,x='';
    $.flashPlayerVersion=(function(){
        var flashVersion,activeX,errorA,errorB,fp6Crash=false,shockwaveFlash='ShockwaveFlash.ShockwaveFlash';
        if(!(flashVersion=navigator.plugins['Shockwave Flash'])){
            try{
                activeX=new ActiveXObject(shockwaveFlash+'.7');
            }
            catch(errorA){
                try{
                    activeX=new ActiveXObject(shockwaveFlash+'.6');
                    flashVersion=[6,0,21];
                    activeX.AllowScriptAccess='always';
                }
                catch(errorB){
                    if(flashVersion&&flashVersion[0]===6){
                        fp6Crash=true;
                    }
                }
                if(!fp6Crash){
                    try{
                        activeX=new ActiveXObject(shockwaveFlash);
                    }
                    catch(errorC){
                        flashVersion='X 0,0,0';
                    }
                }
            }
            if(!fp6Crash&&activeX){
                try{
                    flashVersion=activeX.GetVariable('$version');
                }catch(errorD){}
            }
        }
        else{
            flashVersion=flashVersion.description;
        }
        flashVersion=flashVersion.match(/^[A-Za-z\s]*?(\d+)(\.|,)(\d+)(\s+[rd]|,)(\d+)/);
        return flashVersion?[flashVersion[1]*1,flashVersion[3]*1,flashVersion[5]*1]:[0,0,0];
    }());
    $.flashExpressInstaller='/_swf/expressInstall.swf';
    $.hasFlashPlayer=($.flashPlayerVersion[0]!==0);
    $.hasFlashPlayerVersion=function(options){
        var flashVersion=$.flashPlayerVersion;
        options=(/string|number/.test(typeof options))?options.toString().split('.'):options;
        options=[options.major||options[0]||flashVersion[0],options.minor||options[1]||flashVersion[1],options.release||options[2]||flashVersion[2]];
        return($.hasFlashPlayer&&(options[0]>flashVersion[0]||(options[0]===flashVersion[0]&&(options[1]>flashVersion[1]||(options[1]===flashVersion[1]&&options[2]>=flashVersion[2])))));
    };

    $.flash=function(options){
        if(!$.hasFlashPlayer){
            return false;
        }
        var movieFilename=options.swf||x,paramAttributes=options.params||{},buildDOM=doc.createElement('body'),aArr,bArr,cArr,dArr,a,b,c,d;
        options.height=options.height||180;
        options.width=options.width||320;
        if(options.hasVersion&&!$.hasFlashPlayerVersion(options.hasVersion)){
            $.extend(options,{
                id:'SWFObjectExprInst',
                height:Math.max(options.height,137),
                width:Math.max(options.width,214)
            });
            movieFilename=options.expressInstaller||$.flashExpressInstaller;
            paramAttributes={
                flashvars:{
                    MMredirectURL:location.href,
                    MMplayerType:($.browser.msie&&$.browser.win)?'ActiveX':'PlugIn',
                    MMdoctitle:doc.title.slice(0,47)+' - Flash Player Installation'
                }
            };

        }
        if(typeof paramAttributes===object){
            if(options.flashvars){
                paramAttributes.flashvars=options.flashvars;
            }
            if(options.wmode){
                paramAttributes.wmode=options.wmode;
            }
        }
        for(a in(b=['expressInstall','flashvars','hasVersion','params','swf','wmode'])){
            delete options[b[a]];
        }
        aArr=[];
        for(a in options){
            if(typeof options[a]===object){
                bArr=[];
                for(b in options[a]){
                    bArr.push(b.replace(/([A-Z])/,'-$1').toLowerCase()+':'+options[a][b]+';');
                }
                options[a]=bArr.join(x);
            }
            aArr.push(a+'="'+options[a]+'"');
        }
        options=aArr.join(' ');
        if(typeof paramAttributes===object){
            aArr=[];
            for(a in paramAttributes){
                if(typeof paramAttributes[a]===object){
                    bArr=[];
                    for(b in paramAttributes[a]){
                        if(typeof paramAttributes[a][b]===object){
                            cArr=[];
                            for(c in paramAttributes[a][b]){
                                if(typeof paramAttributes[a][b][c]===object){
                                    dArr=[];
                                    for(d in paramAttributes[a][b][c]){
                                        dArr.push([d.replace(/([A-Z])/,'-$1').toLowerCase(),':',paramAttributes[a][b][c][d],';'].join(x));
                                    }
                                    paramAttributes[a][b][c]=dArr.join(x);
                                }
                                cArr.push([c,'{',paramAttributes[a][b][c],'}'].join(x));
                            }
                            paramAttributes[a][b]=cArr.join(x);
                        }
                        bArr.push([b,'=',paramAttributes[a][b]].join(x));
                    }
                    paramAttributes[a]=bArr.join('&amp;');
                }
                aArr.push(['<PARAM NAME="',a,'" VALUE="',paramAttributes[a],'">'].join(x));
            }
            paramAttributes=aArr.join(x);
        }
        if(!(/style=/.test(options))){
            options+=' style="vertical-align:text-top;"';
        }
        if(!(/style=(.*?)vertical-align/.test(options))){
            options=options.replace(/style="/,'style="vertical-align:text-top;');
        }
        if($.browser.msie){
            options+=' classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"';
            paramAttributes='<PARAM NAME="movie" VALUE="'+movieFilename+'">'+paramAttributes;
        }else{
            options+=' type="application/x-shockwave-flash" data="'+movieFilename+'"';
        }
        buildDOM.innerHTML=['<OBJECT ',options,'>',paramAttributes,'</OBJECT>'].join(x);
        return $(buildDOM.firstChild);
    };

    $.fn.flash=function(options){
        if(!$.hasFlashPlayer){
            return this;
        }
        var a=0,each;
        while((each=this.eq(a++))[0]){
            each.html($.flash($.extend({},options)));
            if(doc.getElementById('SWFObjectExprInst')){
                a=this.length;
            }
        }
        return this;
    };

    if(window.attachEvent){
        window.attachEvent("onbeforeunload",function(){
            __flash_unloadHandler=function(){};

            __flash_savedUnloadHandler=function(){};

        });
    }
}(jQuery));
(function($)

{
        var wsCache={};

        var wsMap={};

        var counter=0;
        $.abortWS=function(token)

        {
            if(wsMap[token])

            {
                try{
                    wsMap[token].abort();
                }
                catch(e){}
            }
        }
        $.callWS=function(service,method,data,callback,noCache)
        {
            var token=service+method+data;
            if(!noCache&&wsCache[token])

            {
                setTimeout(function(){
                    callback(wsCache[token])
                },10);
                return;
            }
            var basePath="/Webservices/";
            var uToken=token+(++counter);
            wsMap[uToken]=$.ajax({
                type:"POST",
                url:basePath+service+".asmx/"+method,
                data:data,
                contentType:"application/json; charset=utf-8",
                dataType:"json",
                success:function(json)

                {
                    delete wsMap[uToken];
                    if(!noCache)
                        wsCache[service+method+data]=json;
                    callback(json);
                },
                error:function(xhr)

                {
                    delete wsMap[uToken];
                    var json={
                        ExceptionType:"Unknown"
                    };

                    var response=xhr.responseText;
                    if(response)

                    {
                        if(response.indexOf("<html>")>=0)

                        {
                            var title=new RegExp("<(title)>(.*)</\\1>").exec(response);
                            if(title)title=title[2];
                            var p=response.lastIndexOf("<!--");
                            var trace="";
                            if(p>0)

                            {
                                trace=response.substr(p+4);
                                trace=trace.substring(trace.indexOf("["),trace.indexOf("-->"));
                            }
                            json.obj={
                                Message:title,
                                ExceptionType:"Unhandled Server Exception",
                                StackTrace:trace
                            };

                        }
                        else eval("json="+response);
                    }
                    callback(json);
                }
            });
            return uToken;
        }
    })(jQuery);
﻿
var ui={};

var viewHelper={};

var pageTracker;
ui._instances=[];
ui._checkTimer=0;
ui.addInstance=function(item)

{
        ui._instances.push(item);
        clearTimeout(ui._checkTimer);
        ui._checkTimer=setTimeout(ui.cleanup,100);
    }
ui.cleanup=function()
{
    clearTimeout(ui._checkTimer);
    function isAlive(e)

    {
        while(e&&e.nodeName!="BODY")e=e.parentNode;
        return e!=null;
    }
    var existing=[];
    jQuery.each(ui._instances,function()

    {
            if(isAlive(jQuery(this.domElement).get(0)))existing.push(this);else this.dispose();
        });
    ui._intances=existing;
}
ui.dispose=function()
{
    jQuery.each(ui._instances,function()

    {
            this.dispose();
        });
    ui._instances=[];
}
if(jQuery)jQuery(window).unload(ui.dispose);
ui.Scroller=function(direction,domElement,prevElement,nextElement,labelElement,callback)

{
        var self=this;
        var $=jQuery;
        var view=$(domElement);
        if(prevElement)var prevBtn=typeof(prevElement)=="string"?view.find(prevElement):$(prevElement);
        if(nextElement)var nextBtn=typeof(nextElement)=="string"?view.find(nextElement):$(nextElement);
        if(labelElement)var indexLabel=typeof(labelElement)=="string"?view.find(labelElement):$(labelElement);
        var isVert=(direction==ui.Scroller.VERTICAL);
        var scroll=0;
        var scrollProp=isVert?"top":"left";
        var pageSize=1;
        var maxScroll=0;
        var itemSize;
        this.domElement=domElement;
        this.prevElement=prevElement;
        this.nextElement=nextElement;
        this.makeImageFromAnchor=false;
        this.btEnabled={
            backgroundPosition:"left top",
            opacity:1,
            cursor:"pointer"
        };

        this.btDisabled={
            backgroundPosition:"left bottom",
            opacity:1,
            cursor:"default"
        };

        var container=view.find("ul");
        var viewWidth=container.width();
        var viewHeight=container.height();
        var viewFloat=container.css("float");
        container=container.wrap("<div></div>").parent();
        var items=container.find("li");
        container.css({
            position:"relative",
            overflow:"hidden",
            width:viewWidth,
            height:viewHeight,
            "float":viewFloat
        });
        container.find("ul").css({
            position:"absolute",
            overflow:"visible",
            width:"auto",
            height:"auto"
        });
        if(isVert)

        {
            itemSize=items.height();
            pageSize=Math.ceil((viewHeight-5)/itemSize);
        }
        else
        {
            itemSize=items.width();
            pageSize=Math.ceil((viewWidth-5)/itemSize);
        }
        maxScroll=items.length-pageSize;
        if(isVert)

        {
            items.css({
                position:"absolute"
            }).each(function(index){
                $(this).css({
                    top:itemSize*index
                });
            });
        }
        else
        {
            items.css({
                position:"absolute"
            }).each(function(index){
                $(this).css({
                    left:itemSize*index
                });
            });
        }
        if(prevBtn&&prevBtn.length)prevBtn.click(scrollPrev);
        if(nextBtn&&nextBtn.length)nextBtn.click(scrollNext);
        container.mousewheel(mousewheel);
        updateBtns();
        function mousewheel(e,delta)

        {
            if(delta>0)scrollPrev(e);
            else if(delta<0)scrollNext(e);
        }
        function updateBtns()
        {
            if(prevBtn)prevBtn.css(scroll>0?self.btEnabled:self.btDisabled);
            if(nextBtn)nextBtn.css(scroll<maxScroll?self.btEnabled:self.btDisabled);
        }
        function scrollPrev(e)
        {
            e.preventDefault();
            $(e.target).blur();
            if(scroll<=0)return;
            scroll--;
            smoothScroll();
        }
        function scrollNext(e)
        {
            e.preventDefault();
            $(e.target).blur();
            if(scroll>=maxScroll)return;
            scroll++;
            smoothScroll();
        }
        function smoothScroll()
        {
            if(indexLabel&&indexLabel.length)indexLabel.html(""+(scroll+1));
            var item=$(view.find("li").get(scroll+pageSize-1));
            if(item)

            {
                view.find("li:first").get(0).__current=item.get(0);
                item.css({
                    display:"block"
                });
                item.children().css({
                    display:""
                });
                if(self.makeImageFromAnchor)

                {
                    var anchor=item.children("a");
                    if(anchor.length)

                    {
                        var title=anchor.attr("title");
                        anchor.replaceWith('<img src="'+anchor.attr("href")+'" title="'+title+'" alt="'+title+'" />');
                    }
                }
            }
            var prop={};

            prop[scrollProp]=-(scroll*itemSize);
            view.find("ul").stop().animate(prop);
            updateBtns();
        }
        self.dispose=function()
        {
            if(self){
                self.domElement=null;
                self.prevElement=null;
                self.nextElement=null;
            }
            domElement=null;
            self=null;
            prevBtn=null;
            nextBtn=null;
            indexLabel=null;
            container=null;
            items=null;
            view=null;
            callback=null;
            $=null;
        }
        ui.addInstance(this);
    }
ui.Scroller.VERTICAL="v";
ui.Scroller.HORIZONTAL="h";
﻿
ui.Select=function(domElement,className){
    var self=this;
    var $=jQuery;
    var enabled=false;
    var items=[];
    this.domElement=domElement;
    this.onSelect=null;
    this.value=null;
    this.setItems=function(newItems)

    {
        items=newItems;
    }
    this.setEnabled=function(state)
    {
        enabled=state;
        if(view)view.css("opacity",enabled?1:0.5);
    }
    this.setState=function(label,data)
    {
        if(view)view.find("p").html(label);
        self.value=data;
    }
    this.setStateByValue=function(data)
    {
        $.each(items,function(){
            if(this.value==data)

            {
                self.setState(this.label,data);
                return false;
            }
        });
    }
    var select=$(domElement);
    if(!select.length)
        return;
    var width=select.width();
    select.wrap('<div class="ui-select"><div></div></div>').css({
        display:"none"
    });
    var view=select.parent();
    if(className)view.parent().addClass(className);
    if(select.get(0).nodeName=="SELECT")

    {
        var current=select.find("option:selected").get(0);
        self.value=$(current).val();
        $(select.get(0)).find("option").each(function(){
            items.push({
                label:$(this).text(),
                value:$(this).val()
            });
        });
    }
    else
    {
        var current=select.find("li.Active").get(0);
        self.value=$(current).text();
        $(select.get(0)).find("li").each(function(){
            items.push({
                label:$(this).text(),
                value:$(this).text()
            });
        });
    }
    view.append("<p></p>").find("p").html($(current).text());
    view.css({
        opacity:0.5
    });
    view.click(showList);
    var list=ui.Select.list;
    function showList()

    {
        if(!enabled)return;
        if(ui.Select.current==this)
            return;
        if(ui.Select.current)
            ui.Select.current.deselect();
        ui.Select.current=self;
        var target=$(this);
        target.addClass("ui-select-active");
        list.css({
            visibility:"hidden"
        });
        updateList();
        list.appendTo(target.parent());
        var top=target.hasClass("ui-select-up")?-list.outerHeight()+1:target.height()-1;
        list.css({
            top:top,
            visibility:"visible"
        }).show();
        $(document).unbind("mousedown",docMouseDown).bind("mousedown",docMouseDown);
    }
    function docMouseDown(e)
    {
        var climb=$(e.target).closest(".ui-select");
        if(climb.length==0)
            hideList();
    }
    function hideList()
    {
        $(document).unbind("mousedown",docMouseDown);
        view.removeClass("ui-select-active");
        list.hide();
    }
    function updateList()
    {
        list.empty();
        $.each(items,function(){
            if(this.label=="...")
                $('<li class="hr"></li>').appendTo(list);else
                $('<li><a href="#'+this.value+'">'+this.label+'</a></li>').click(selectItem).appendTo(list);
        });
    }
    function selectItem(e)
    {
        e.preventDefault();
        var value=$(this).find("a").attr("href");
        value=value.substr(value.indexOf("#")+1);
        self.setState($(this).text(),value);
        if(self.onSelect)
            self.onSelect(value);
        self.deselect();
    }
    this.deselect=function()
    {
        ui.Select.current=null;
        hideList();
    }
}
ui.Select.list=jQuery('<ul class="ui-select-list"></ul>');
ui.Select.current=null;
ui.Slider=function(domElement,callback)

{
        var self=this;
        var $=jQuery;
        var view=$(domElement).find(".slider");
        var notifyTimer=0;
        var hasChanged=false;
        var faded=false;
        this.ratio=0;
        this.ratioMin=0;
        this.domElement=domElement;
        this.onSelect=null;
        $('<div class="sliderInner"><div class="sliderBar"></div></div><div class="sliderCursor"></div>').appendTo(view);
        var xMin=-5;
        var xMax=parseInt(view.css("width"))-15;
        var bounds={
            xMin:xMin,
            yMin:-4,
            xMax:xMax,
            yMax:-4,
            slider:self
        };

        var boundsMin;
        var isDouble=view.hasClass("slider2");
        if(isDouble)

        {
            xMax-=2;
            bounds.xMax=xMax;
            boundsMin=bounds;
            bounds={
                xMin:xMin+14,
                yMin:-4,
                xMax:xMax+14,
                yMax:-4,
                slider:self
            };

            view.append($('<div class="sliderCursor sliderCursorMin">'));
        }
        var cursor="ew-resize";
        if($.browser.msie)cursor="w-resize";
        view.find(".sliderCursor").easydrag().ondrag(updateSlider).css("cursor",cursor).get(0).dragBounds=bounds;
        if(isDouble)
            view.find(".sliderCursorMin").easydrag().ondrag(updateSlider).css("cursor",cursor).get(0).dragBounds=boundsMin;
        function updateSlider(e,elem,newPos)

        {
            elem.dragBounds.slider.updateSlider(e,elem,newPos);
        }
        self.updateSlider=function(e,elem,newPos)
        {
            var b=elem.dragBounds;
            var newRatio;
            if(b==bounds)

            {
                if(isDouble)newPos.left-=14;
                newRatio=Math.round(1000*(newPos.left-xMin)/(xMax-xMin))/1000;
                if(newRatio==self.ratio)
                    return;
                self.ratio=newRatio;
                if(isDouble)
                    boundsMin.xMax=newPos.left;
            }
            else
            {
                newRatio=Math.round(1000*(newPos.left-xMin)/(xMax-xMin))/1000;
                if(newRatio==self.ratioMin)
                    return;
                self.ratioMin=newRatio;
                bounds.xMin=newPos.left+14;
            }
            updateBar();
            if(callback)

            {
                if(notifyTimer){
                    hasChanged=true;
                    return;
                }
                notifyTimer=setTimeout(notify,300);
            }
        }
        function updateBar()
        {
            var left=Math.round(xMin+self.ratioMin*(xMax-xMin))+9;
            var right=Math.round(xMin+self.ratio*(xMax-xMin))+5-left;
            $(domElement).find(".sliderBar").css({
                width:right+21,
                left:left
            });
        }
        view.hover(mouseOver,mouseOut).mousedown(select).find(".sliderCursor").mousedown(select);
        function select()

        {
            faded=false;
            if(self.onSelect)self.onSelect(this);
        }
        function mouseOver()
        {
            if(faded)view.stop().animate({
                opacity:1
            },"fast");
        }
        function mouseOut()
        {
            if(faded)view.stop().animate({
                opacity:0.5
            },"fast");
        }
        self.setFaded=function(state,animate)
        {
            if(faded==state)return;
            faded=state;
            if(animate)mouseOut();else view.stop().css({
                opacity:faded?0.5:1
            });
        }
        function notify()
        {
            callback(self.ratio,self.ratioMin);
            if(hasChanged)notifyTimer=setTimeout(notify,300);else notifyTimer=0;
            hasChanged=false;
        }
        self.setRatio=function(ratio,ratioMin)
        {
            self.ratio=ratio;
            var left=Math.round(xMin+ratio*(xMax-xMin));
            if(isDouble)left+=14;
            view.find(".sliderCursor").css("left",left);
            if(isDouble)

            {
                self.ratioMin=ratioMin;
                left=Math.round(xMin+ratioMin*(xMax-xMin));
                view.find(".sliderCursorMin").css("left",left);
            }
            updateBar();
            callback(ratio,ratioMin);
        }
        self.setMinMaxIndicators=function(min,max)
        {}
        self.dispose=function()
        {
            clearTimeout(notifyTimer);
            if(self)self.domElement=null;
            domElement=null;
            self=null;
            callback=null;
            view=null;
            $=null;
        }
        ui.addInstance(this);
    }
﻿
var ui=ui||{};

ui.Suggest=function(domElement,suggestMethod)

{
        var self=this;
        var $=jQuery;
        var view=$(domElement);
        var updateTimer;
        var loading;
        var updateToken=null;
        var lastSearch;
        var lastEmptySearch="*";
        var emptySearch={};

        var highIndex=-1;
        var currentList=null;
        var pressedEnter=false;
        var hasFocus=false;
        this.domElement=domElement;
        this.maxResults=30;
        this.delay=400;
        this.width=null;
        this.showOneResult=false;
        this.alwaysSubmitOnEnter=false;
        this.autoSelect=false;
        this.onQuery=null;
        this.onSelect=null;
        this.onSubmit=null;
        this.onData=null;
        function setFocus()

        {
            hasFocus=true;
        }
        function killFocus()
        {
            hasFocus=false;
        }
        function inputKeydown(e)
        {
            if(!hasFocus)return;
            if(currentList!=null)

            {
                if(e.keyCode==38)

                {
                    e.preventDefault();
                    return setHighlight(-1);
                }
                else if(e.keyCode==40)
                {
                    e.preventDefault();
                    return setHighlight(+1);
                }
            }
            if(e.keyCode==13)
            {
                e.preventDefault();
                if(currentList!=null)

                {
                    if(highIndex<0)highIndex=0;
                    currentList[highIndex].click();
                    if(self.onSubmit)self.onSubmit();
                }
                else
                {
                    pressedEnter=true;
                    if(!updateToken||(updateToken&&lastSearch!=$.trim(view.val())))

                    {
                        clearTimeout(updateTimer);
                        self.getSuggestions();
                    }
                }
            }
        }
        function inputKeyup(e)
        {
            if(currentList&&e.keyCode==27)
                return hideSuggestions();
            if(e.keyCode==38||e.keyCode==40||e.keyCode==13)
                return;
            if($.trim(view.val())==lastSearch)
                return;
            pressedEnter=false;
            currentList=null;
            hideSuggestions();
            clearTimeout(updateTimer);
            updateTimer=setTimeout(self.getSuggestions,self.delay);
        }
        function setHighlight(dir)
        {
            if(dir>0)newIndex=(highIndex+dir)%currentList.length;
            else if(dir<0){
                newIndex=highIndex+dir;
                if(newIndex<0)newIndex+=currentList.length;
            }
            if(highIndex>=0)currentList[highIndex].removeClass("highlight");
            highIndex=newIndex;
            currentList[highIndex].addClass("highlight");
            if(self.onSelect)self.onSelect(currentList[highIndex]);
        }
        self.getSuggestions=function(autoSelect)
        {
            if(updateToken)

            {
                $.abortWS(updateToken);
                updateToken=null;
            }
            var search=$.trim(view.val());
            if(lastSearch)
                if(lastSearch.length>search.length||search.substr(0,lastSearch.length)!=lastSearch)
                    hideSuggestions();
            lastSearch=search;
            if(search.length<2)
                return hideSuggestions();
            if(emptySearch[search])

            {
                lastEmptySearch=search;
                return;
            }
            if(lastEmptySearch.length<search.length&&search.substr(0,lastEmptySearch.length)==lastEmptySearch)
            {
                emptySearch[search]=true;
                lastEmptySearch=search;
                return;
            }
            self.autoSelect=autoSelect;
            if(self.onQuery)
                self.onQuery(search);
            updateToken=zapette.Webservices[suggestMethod](search,self.maxResults+1,function(data)

            {
                    updateToken=null;
                    if(self.onData)data=self.onData(data);
                    if(!data.d||data.d.length<1)

                    {
                        lastEmptySearch=search;
                        emptySearch[search]=true;
                        hideSuggestions();
                    }
                    else showSuggestions(data);
                });
        }
        function hideSuggestions(keepList)
        {
            if(updateToken)

            {
                $.abortWS(updateToken);
                updateToken=null;
            }
            ui.Suggest.panel.hide();
            $(document).unbind("mousedown",docMouseDown)
            if(!keepList)currentList=null;
        }
        function showSuggestions(data)
        {
            highIndex=-1;
            currentList=[];
            var content=$('<ul></ul>');
            $.each(data.d,function()

            {
                    if(!$.trim(this.Recherche).length)
                        return;
                    var item=$('<li><a href="'+(this.Url||"#")+'">'+this.Recherche+'</a></li>').click(setSearchText).appendTo(content);
                    currentList.push(item);
                    if(currentList.length>self.maxResults)

                    {
                        data.title="<p>"+self.maxResults+" premiers résultats :</p>";
                        return false;
                    }
                });
            if(self.autoSelect&&currentList.length==1)pressedEnter=true;
            if(pressedEnter&&self.onSubmit&&(self.alwaysSubmitOnEnter||currentList.length==1))
            {
                pressedEnter=false;
                if(self.onSelect)self.onSelect(currentList[0]);
                self.onSubmit();
                hideSuggestions();
                return;
            }
            if(!self.showOneResult&&currentList.length<2&&!(currentList.length==0&&data.title!=null))
            {
                hideSuggestions(true);
                return;
            }
            ui.Suggest.panel.css({
                width:"auto",
                height:"auto"
            });
            if(data.d.length>10)
                ui.Suggest.panel.css({
                    width:self.width||206,
                    height:220,
                    overflow:"auto"
                });
            else if(self.width)ui.Suggest.panel.css({
                width:self.width
            });
            ui.Suggest.panel.hide().empty().append(content).insertAfter(view).show();
            if(data.title)ui.Suggest.panel.prepend(data.title);
            $(document).unbind("mousedown",docMouseDown).bind("mousedown",docMouseDown);
        }
        function docMouseDown(e)
        {
            if($(e.target).parents(".suggestSite").length==0)
                hideSuggestions();
        }
        function setSearchText(e)
        {
            if(e)

            {
                var href=$(this).find("a").attr("href");
                if(href!="#"&&(e.shiftKey||e.ctrlKey))
                    return;
                e.preventDefault();
            }
            ui.Suggest.panel.hide();
            if(self.onSelect)self.onSelect(this);else view.val($(this).text());
            if(self.onSubmit)self.onSubmit();
        }
        if(!ui.Suggest.panel)
            ui.Suggest.panel=jQuery('<div id="SUGGEST"></div>').insertAfter(view);
        view.parent().addClass("suggestSite");
        view.focus(setFocus).blur(killFocus).keydown(inputKeydown).keyup(inputKeyup).focus(self.getSuggestions).attr("autocomplete","off");
    }
ui.Suggest.panel=null;
﻿
viewHelper.Comparator=function()
{
    var carac=[];
    var equip=[];
    var alone=[];
    function isCheckLine(tr)

    {
        var cname=tr.className;
        var end=cname.split(" ").pop();
        return(end=="tEven"||end=="tOdd"||end=="end"||end=="tLastEquip");
    }
    function isEquip(tr)
    {
        return tr.className.indexOf("Equip")>=0;
    }
    function setCaracClasses()
    {
        var isOdd=false;
        var count=carac.length;
        var tr;
        var last;
        for(var i=0;i<count;i++)

        {
                tr=carac[i];
                if(tr.__hidden)continue;
                tr.className=(isOdd)?"tOdd":"tEven";
                last=tr;
                isOdd=!isOdd;
            }
        if(!last)$("#COMPARE_TABLE .blank").hide();
        if(last&&!isOdd)last.className+=" end";
    }
    function setEquipClasses()
    {
        var isOdd=false;
        var count=equip.length;
        var tr;
        var last;
        for(var i=0;i<count;i++)

        {
                tr=equip[i];
                if(tr.__hidden)continue;
                tr.className=(isOdd)?"tEquipOdd tOdd":"tEquipEven tEven";
                last=tr;
                isOdd=!isOdd;
            }
        if(!last)$("#COMPARE_TABLE .tEquipStart,.tEquipEnd").hide();
        if(last)last.className+=" tLastEquip";
    }
    function hideLine(e)
    {
        e.preventDefault();
        if($(this).hasClass("supp"))
            return;
        var line=$(this).parents("tr");
        if(!line.length)return;
        line.hide();
        var tr=line[0];
        tr.__hidden=true;
        if(!tr.__alone)
            if(!isEquip(tr))setCaracClasses();else setEquipClasses();
    }
    function resetLines(e)
    {
        e.preventDefault();
        $("#COMPARE_TABLE .blank").show();
        $("#COMPARE_TABLE .tEquipStart,.tEquipEnd").show();
        var count,i;
        count=carac.length;
        for(i=0;i<count;i++)

        {
                carac[i].__hidden=false;
                $(carac[i]).show();
            }
        setCaracClasses();
        count=equip.length;
        for(i=0;i<count;i++)

        {
                equip[i].__hidden=false;
                $(equip[i]).show();
            }
        setEquipClasses();
        count=alone.length;
        for(i=0;i<count;i++)

        {
                alone[i].__hidden=false;
                $(alone[i]).show();
            }
    }
    $(".COMPARATOR .pictureScroller").each(function(){
        var scroller=new ui.Scroller("h",this,".previousPicture",".nextPicture",".multipleImage strong");
        scroller.makeImageFromAnchor=true;
    });
    $("#COMPARE_TABLE .checkbox").click(hideLine);
    var lines=$("#COMPARE_TABLE tr");
    var count=lines.length;
    for(var i=0;i<count;i++)

    {
            var tr=lines[i];
            if(isCheckLine(tr))

            {
                tr.__alone=false;
                if(isEquip(tr))equip.push(tr);
                else if(equip.length)

                {
                    alone.push(tr);
                    tr.__alone=true;
                }
                else carac.push(tr);
                tr.__hidden=false;
            }
        }
    var printPostForm;
    function printComparator(e)
    {
        e.preventDefault();
        var postUrl="/Comparateur-impression.aspx";
        var cssUrl="http://"+document.domain+"/_css/comparator-print.css?nocache="+Math.random();
        var rawSource="<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \
            \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\
             <html xmlns=\"http://www.w3.org/1999/xhtml\"><head>\
                <title>Comparateur - Occasions du Lion - Les occasions certifiées Peugeot</title>\
                <link rel=\"Stylesheet\" href=\""+cssUrl+"\" />\
            </head><body>\
            <center><h1><img src=\"http://"+document.domain+"/_img/Comparateur/logo-print.gif\" /></h1>"
        +$("#COMPARE_TABLE").parent().html()
        +"</center></body></html>";
        if(!printPostForm)printPostForm=$("<form id=\"printForm\" target=\"_blank\" method=\"post\" action=\""+postUrl+"\">\
                    <input type=\"hidden\" name=\"rawSource\" />\
                </form>").appendTo(document.body);
        printPostForm.find("input").val(rawSource.split("<").join("{["));
        printPostForm.submit();
    }
    $("#COMPARE_TABLE .ResetComparator a").click(resetLines);
    $("#COMPARE_TABLE .printVersion button").click(printComparator);
}
﻿﻿
function showDialogSupprimerCompte()
{
    var panel=$("#SUPPRIMER_COMPTE_PANEL");
    $(".smallMention").hide();
    panel.addClass("loginPanelSupprimer");
    if($.browser.msie)
        panel.show();else
        panel.fadeIn("fast");
}
function initSupprimerCompte()
{}
﻿
viewHelper.GoogleMap=function(domElement,containerClass,callback)
{
    var $=jQuery;
    var co=zapette.Common;
    var self=this;
    this.domElement=domElement;
    var view=$('<div class="'+containerClass+'">\
            <div id="GFRAME">\
                <div class="zone"><div id="GMAP"></div></div>\
            </div>\
         </div>').css({
        opacity:0.5
    });
    $(domElement).empty().append(view);
    var warning=null;
    var map=null;
    var mapReady=false;
    var mapData=null;
    var viewHeight=448;
    var layer=null;
    var mapX0=0;
    var mapY0=0;
    this.setMarkers=function(data)

    {
        mapData=data;
        if(!map)

        {
            viewHeight=view.find("#GFRAME").height();
            $("#GMAP").css({
                height:viewHeight
            })
            createMap();
            return;
        }
        if(!mapReady)return;
        updateMessages(mapData);
        createMarkers(mapData);
        view.css({
            opacity:1
        });
    }
    function updateMessages(data)
    {
        if(data.Warning)view.find(".warning").html(data.Warning).show();else view.find(".warning").hide();
    }
    function mapLoaded()
    {
        frameScope=this.contentWindow;
        if(mapData)self.setMarkers(mapData);
    }
    function createMap()
    {
        mapReady=false;
        initialize();
    }
    function initialize()
    {
        if(GBrowserIsCompatible())

        {
            map=new GMap2(document.getElementById("GMAP"))
            resetMap();
            map.setUIToDefault();
            $(window).unload(GUnload);
            var pos=$("#GMAP").offset();
            mapX0=pos.left;
            mapY0=pos.top;
            mapReady=true;
            if(mapData)self.setMarkers(mapData);
        }
    }
    function resetMap()
    {
        map.setCenter(new GLatLng(46.227638,2.213749),6);
        map.setZoom(6);
    }
    function createMarkers(data)
    {
        if(!map)

        {
            mapData=data;
            return;
        }
        map.clearOverlays();
        if(!data.d||!data.d.length)

        {
            resetMap();
            return;
        }
        var p0=data.d[0];
        var minLat=parseFloat(p0.GeoLat);
        var maxLat=parseFloat(p0.GeoLat);
        var minLng=parseFloat(p0.GeoLong);
        var maxLng=parseFloat(p0.GeoLong);
        var isIE6=false;
        var largeIcon=new GIcon(G_DEFAULT_ICON);
        if(isIE6)largeIcon.image="/_img/Maps/largeIcon.gif";else largeIcon.image="/_img/Maps/largeIcon.png";
        largeIcon.shadow=null;
        largeIcon.printImage="/_img/Maps/largeIcon.gif";
        if(isIE6)largeIcon.iconSize=new GSize(43,43);else largeIcon.iconSize=new GSize(44,48);
        largeIcon.iconAnchor=new GPoint(38,43);
        largeIcon.imageMap=null;
        var smallIcon=new GIcon(G_DEFAULT_ICON);
        if(isIE6)smallIcon.image="/_img/Maps/smallIcon.gif";else smallIcon.image="/_img/Maps/smallIcon.png";
        smallIcon.shadow=null;
        smallIcon.printImage="/_img/Maps/smallIcon.gif";
        if(isIE6)smallIcon.iconSize=new GSize(25,28);else smallIcon.iconSize=new GSize(32,32);
        smallIcon.iconAnchor=new GPoint(24,28);
        smallIcon.imageMap=[0,0,25,0,25,25,0,25];
        var count=data.d.length;
        for(var i=0;i<count;i++)

        {
                var p=data.d[i];
                if(!p.GeoLat.length||!p.GeoLong.length||isNaN(p.GeoLat)||isNaN(p.GeoLong))
                    continue;
                if(p.GeoLat<minLat)minLat=parseFloat(p.GeoLat);
                if(p.GeoLat>maxLat)maxLat=parseFloat(p.GeoLat);
                if(p.GeoLong<minLng)minLng=parseFloat(p.GeoLong);
                if(p.GeoLong>maxLng)maxLng=parseFloat(p.GeoLong);
                var iconSelected;
                if(p.Agent==true)iconSelected=smallIcon;else iconSelected=largeIcon;
                if(p.Icon)

                {
                    iconSelected=(p.Icon=="smallIcon.png")?smallIcon:largeIcon;
                }
                var op={
                    title:null,
                    icon:iconSelected
                }
                var m=new GMarker(new GLatLng(p.GeoLat,p.GeoLong),op);
                m.__data=p;
                GEvent.addListener(m,"click",selectMarker);
                GEvent.addListener(m,"mouseover",overMarker);
                GEvent.addListener(m,"mouseout",outMarker);
                map.addOverlay(m);
            }
        minLat-=0.05;
        maxLat+=0.05;
        minLng-=0.05;
        maxLng+=0.05;
        var ne=new GLatLng(minLat,maxLng);
        var sw=new GLatLng(maxLat,minLng);
        var zoom=map.getBoundsZoomLevel(new GLatLngBounds(sw,ne));
        map.setZoom(Math.max(6,Math.min(12,zoom)));
        map.setCenter(new GLatLng((minLat+maxLat)/2,(minLng+maxLng)/2));
    }
    function selectMarker(p)
    {
        top.location="/point-de-vente/"+this.__data.Nom.toLowerCase().replace(" & "," et ").replace(/ /g,"-")+"/"+this.__data.IdPdv;
    }
    function overMarker(p)
    {
        if(!layer)

        {
            layer=$('<div id="TIP"></div>')
            layer.appendTo($(document.body));
        }
        var d=this.__data;
        var c=map.fromLatLngToContainerPixel(p);
        var dy=(d.Agent?30:35);
        if(c.x+220>680)c.x-=(d.Agent?250:255);
        if(c.y<8)c.y=8;
        var fax=d.Fax?('Fax.: '+formatTel(d.Fax)+'<br/>'):'';
        var vehicles=(d.NumOfVehicle>1)?"véhicules":"véhicule";
        var title='<h1><strong>'+d.NumOfVehicle+'</strong> '+vehicles+'</h1>';
        layer.html(title
            +'<div>'
            +'<strong>'+d.Nom+'</strong><br/>'
            +d.Adresse+'<br/>'
            +d.CodePostal+' '+d.Ville+'<br/><br/>'
            +'Tel.: '+formatTel(d.Tel)+'<br/>'
            +fax
            +'</div>');
        layer.css({
            left:0,
            top:0
        }).show();
        var h=layer.height();
        if(c.y-dy+h>viewHeight-8)
            layer.css({
                left:c.x+10+mapX0,
                top:viewHeight-8-h+mapY0
            });else layer.css({
            left:c.x+10+mapX0,
            top:c.y-dy+mapY0
        });
    }
    function outMarker(p)
    {
        if(layer)layer.hide();
    }
    function formatTel(t)
    {
        var res="";
        var spaces=0;
        t=t.replace(/ -\./g,"");
        var len=t.length;
        for(var i=0;i<len;i++)

        {
                res=t.charAt(len-i-1)+res;
                if(i&&i%2&&spaces<4)

                {
                    spaces++;
                    res=" "+res;
                }
            }
        return res;
    }
}
function initHeader()
{
    var $=jQuery;
    var co=zapette.Common;
    var panel=document.getElementById("LOGIN_PANEL");
    if(!panel)
        return;
    panel=$("#LOGIN_PANEL");
    panel.addClass("loginPanel");
    panel.find(".login .panelBtn").click(loginClick);
    panel.find(".lostPassword .panelBtn").click(lostClick);
    $("form").submit(clearFields);
    function clearFields()

    {
        $("#LOGIN_PANEL input").val("");
    }
    panel.find(".closeBtn").click(hideLogin);
    panel.find(".lostPassword a.toggle").click(toggleLostPassword);
    $(".globalHeader .Menu_1 a.first").click(showLogin);
    $(".monCompte a.first").click(showLogin);
    var inviteLost=panel.find(".lostInput").attr("title");
    var inLogin;
    function showLogin(e)

    {
        e.preventDefault();
        var panel=$("#LOGIN_PANEL");
        panel.find(".lostPassword a.toggle").removeClass("active").next().hide();
        panel.find(".login").show();
        panel.find(".lostInput p").text(inviteLost);
        panel.find("input").blur();
        inLogin=true;
        if($.browser.msie)panel.show();else panel.fadeIn("fast");
    }
    function getValue(id)
    {
        var value=$.trim($(id).val());
        if($.trim(value)==$.trim($(id).attr("title")))
            return"";else return value;
    }
    function hideLogin(e)
    {
        e.preventDefault();
        if($.browser.msie)$("#LOGIN_PANEL").hide();else $("#LOGIN_PANEL").fadeOut("fast");
        $("#LOGIN_PANEL input").val("");
    }
    function toggleLostPassword(e)
    {
        e.preventDefault();
        inLogin=!inLogin;
        $(this).blur().toggleClass("active").next().slideToggle("normal");
        $(this).parents(".loginPanel").find(".login").slideToggle();
    }
    var hasFocus=false;
    var token=null;
    var restoreTimer=null;
    $("form").submit(formSubmit);
    $("#QUICK_EMAIL").focus(setFocus).blur(killFocus).keydown(keyDown);
    $("#QUICK_PASSWORD").focus(setFocus).blur(killFocus).keydown(keyDown);
    $("#QUICK_LOST").focus(setFocus).blur(killFocus).keydown(keyDown);
    function formSubmit(e)

    {
        if(token)e.preventDefault();
        else if(hasFocus)
            if(inLogin)loginClick(e);else lostClick(e);
    }
    function setFocus()
    {
        hasFocus=true;
    }
    function killFocus()
    {
        hasFocus=false;
    }
    function keyDown(e)
    {
        if(e.keyCode==13)

        {
            if(inLogin)loginClick(e);else lostClick(e);
        }
    }
    function loginClick(e)
    {
        e.preventDefault();
        if(token)return;
        var email=$.trim($("#QUICK_EMAIL").val());
        var pwd=$.trim($("#QUICK_PASSWORD").val());
        var selection=co.readCookieSafe(co.SELECTION_COOKIE);
        if(email.length&&email!=$.trim($(email).attr("title"))&&pwd.length&&pwd!=$.trim($(pwd).attr("title")))

        {
            token=zapette.Webservices.identifier(email,pwd,selection,loginResult);
            $("#LOGIN_PANEL .loginInner").css({
                opacity:0.5
            });
        }
    }
    function loginResult(data)
    {
        token=null;
        if(data.d)window.location.reload();
        else

        {
            var err=$('<p class="error">Ce compte est inconnu.<br/>Votre e-mail ou mot de passe est incorrect</p>');
            err.appendTo("#LOGIN_PANEL .login").click(restoreLogin);
            if($.browser.msie)

            {
                $("#LOGIN_PANEL .loginInner").css({
                    visibility:"hidden"
                });
                err.show();
            }
            else
            {
                $("#LOGIN_PANEL .loginInner").css({
                    opacity:0
                });
                err.hide().fadeIn("fast");
            }
            restoreTimer=setTimeout(restoreLogin,3000);
        }
    }
    function restoreLogin()
    {
        clearTimeout(restoreTimer);
        $("#LOGIN_PANEL .login p.error").remove();
        if($.browser.msie)$("#LOGIN_PANEL .loginInner").css({
            visibility:"visible"
        });else $("#LOGIN_PANEL .loginInner").animate({
            opacity:1
        },"fast");
    }
    function lostClick(e)
    {
        e.preventDefault();
        if(token)return;
        var email=$.trim($("#QUICK_LOST").val());
        if(email.length)
        {
            panel.find(".lostInput p").html("Envoi en cours...");
            token=zapette.Webservices.forgotPassword(email,lostResult);
            $("#LOGIN_PANEL .lostInput").css({
                opacity:0.5
            });
        }
    }
    function lostResult(data)
    {
        token=null;
        $("#LOGIN_PANEL .lostInput").css({
            opacity:1
        });
        if(data.d)

        {
            panel.find(".lostInput p").html('Un e-mail vient de vous être envoyé avec votre mot de passe.');
            $("#QUICK_LOST").val("");
        }
        else panel.find(".lostInput p").html('<span class="error">Cette adresse e-mail est inconnue.</span>');
    }
}
﻿function AfficheMensualiteSurLaPage(id,data)
{
    if(data.d.HasError){
        return;
    }
    else{
        var text=data.d.HtmlContent;
        if(id=="#Mensualite"){
            var callToUpdateMensualite="zapette.Webservices.getUpdatedMensualiteFromPagePerso(UpdateMensualiteFromPagePerso);";
            text=text.replace(";')",";'); "+callToUpdateMensualite);
            text=text.replace("8pt","");
            text=text.replace("size=\"2\"","");
            $(id).html(text);
        }
        else
        {
            $(id).append('<span class="sftMensualite">'+text+'</span>');
        }
        $(".sftMensualite a").attr("onclick","return false;");
        $(".sftMensualite a").click(function(event){
            event.preventDefault();
        });
    }
}
function UpdateMensualiteFromPagePerso(data){
    $("#Mensualite").html('');
    AfficheMensualiteSurLaPage("#Mensualite",data);
}
function AfficheMensualiteOnFicheVehicule(data)
{
    $("#Mensualite").html('');
    AfficheMensualiteSurLaPage("#Mensualite",data);
}
function AfficheMensualiteOnResultatRecherche(id,data)
{
    var objId="#PV_"+id+" .priceContent p";
    AfficheMensualiteSurLaPage(objId,data);
}
function AfficheMensualiteOnComparateur(id,data)
{
    var objId="#PV_"+id+" .infosPrice";
    AfficheMensualiteSurLaPage(objId,data);
}
function AfficheMensualiteOnEnvoyerAmi(id,data)
{
    var objId=".prixContent";
    AfficheMensualiteSurLaPage(objId,data);
}
﻿
viewHelper.Selection=function()
{
    var $=jQuery;
    var self=this;
    var co=zapette.Common;
    var maxIndex={
        selection:0,
        comparator:0
    };

    var selection=getCookieList(co.SELECTION_COOKIE);
    var comparator=getCookieList(co.COMPARATOR_COOKIE);
    this.getMySelectionLength=function()

    {
        return getMapLength(selection);
    }
    this.getComparatorLength=function()
    {
        return getMapLength(comparator);
    }
    this.isInMySelection=function(id)
    {
        return selection[id];
    }
    this.isInComparator=function(id)
    {
        return comparator[id];
    }
    this.removeFromMySelection=function(id)
    {
        selection[id]=false;
        setCookieList(co.SELECTION_COOKIE,selection);
    }
    this.removeFromComparator=function(id)
    {
        comparator[id]=false;
        setCookieList(co.COMPARATOR_COOKIE,comparator);
    }
    this.addToMySelection=function(id)
    {
        selection[id]=++(maxIndex.selection);
        setCookieList(co.SELECTION_COOKIE,selection);
    }
    this.addToComparator=function(id)
    {
        comparator[id]=++(maxIndex.comparator);
        setCookieList(co.COMPARATOR_COOKIE,comparator);
    }
    this.updateSelectionCount=function()
    {
        var count=self.getMySelectionLength();
        var text=count+(count<2?" véhicule":" véhicules");
        $(".globalHeader .maSelection a span").html(text);
        if(document.getElementById("MYSELECTION"))

        {
            $("#MYSELECTION h2 a span").html(text);
            $(".MYSELECTION .LinkMySelection").html("Ma sélection ("+count+")");
        }
    }
    this.updateComparatorCount=function()
    {
        var count=self.getComparatorLength();
        var text=count+(count<2?" véhicule":" véhicules");
        $(".centerColumn .btComparator em").html(text);
    }
    function getMapLength(o)
    {
        var count=0;
        for(var id in o)if(o[id])count++;return count;
    }
    function setCookieList(name,o)
    {
        var list=[];
        var id;
        for(id in o)if(o[id])
            list.push({
                id:id,
                index:o[id],
                toString:function(){
                    return this.id;
                }
            });list.sort(compareByIndex);
        if(name==co.COMPARATOR_COOKIE)
            while(list.length>4)list.shift();
        for(id in o)o[id]=false;for(var i in list)o[list[i].id]=list[i].index;var cookie=list.join(",");
        $.cookie(name,cookie,{
            expires:1,
            path:'/'
        });
    }
    function compareByIndex(a,b)
    {
        return a.index<b.index?-1:(a.index>b.index?1:0);
    }
    function getCookieList(name)
    {
        var cookie=co.readCookieSafe(name);
        if(!cookie.length)return{};

        list=cookie.split(",");
        var map={};

        $.each(list,function(index,value){
            map[value]=index+1;
        });
        maxIndex[name]=list.length+2;
        return map;
    }
}

viewHelper.VehicleDetail=function(){
    var $=jQuery;
    var self=this;
    var selection=new viewHelper.Selection();
    var lastClick=0;
    var selectionToken=null;
    var match=/IdVehicle=([0-9]+)/i.exec(document.location);
    if(!match)match=/fiche-vehicule\/[^\/]+\/[^\/]+\/([0-9]+)/i.exec(document.location);
    var id=match?match[1]:0;
    zapette.Webservices.getMensualiteFromVehicule(id,AfficheMensualiteOnFicheVehicule);
    function createBtns(){
        createMySelectionBtn($(".vehicleReference ul"),selection.isInMySelection(id));
    }
    function createMySelectionBtn(target,isSelected){
        target.empty();
        if(!isSelected)
            $('<li class="toggleBt"><img src="/_img/Vehicles/btnAjouterSelection.gif" alt="Ajouter à ma sélection" /></li>').click(toggleMySelection).appendTo(target);else
            $('<li class="toggleBt"><img src="/_img/Vehicles/btnRetirerSelection.gif" alt="Retirer de ma sélection" /></li>').click(toggleMySelection).appendTo(target);
    }
    function toggleMySelection(e){
        e.preventDefault();
        var t=new Date().getTime();
        if(t-lastClick<500)return;
        lastClick=t;
        var item=$(this).parents(".item");
        if(selection.isInMySelection(id)){
            //            zapette.Webservices.removeFromMySelection(id,selectionChanged);
            selection.removeFromMySelection(id);
            setTimeout(function(){
                animItem($(".globalHeader .maSelection a"),true)
            },100);
        }
        else{
            zapette.Webservices.addToMySelection(id,selectionChanged);
            selection.addToMySelection(id);
            setTimeout(function(){
                animItem($(".globalHeader .maSelection a"));
            },100);
        }
        selection.updateSelectionCount();
        createBtns();
    }
    function selectionChanged(data){
        selectionToken=null;
    }
    function animItem(target,reverse){
        var img=$(".vehiclePicture img");
        var parent=img.parent().get(0);
        var startPos=img.offset();
        var endPos=target.offset();
        var startCss={
            left:startPos.left,
            top:startPos.top,
            width:544,
            height:408,
            opacity:1
        };

        var endCss={
            left:endPos.left,
            top:endPos.top,
            width:177,
            height:16,
            opacity:0
        };

        if(reverse){
            var temp=endCss;
            endCss=startCss;
            startCss=temp;
        }
        var dup=$("<div></div>").css({
            position:"absolute",
            zIndex:10,
            width:544,
            height:408,
            overflow:"hidden",
            background:"url("+img.attr("src")+")",
            backgroundPosition:"50% 50%"            
        }).css(startCss).appendTo($(document.body)).animate(endCss,400+(startPos.top/3),removeDup);
    }
    function removeDup(){
        $(this).remove();
    }
    if(id)createBtns();
    $(".pictureNavigation").each(function(){
        new ui.Scroller("v",$(this),".pictureUp",".pictureDown",null);
    });
    $(".pictureViewer .pictureNavigation li a").click(function(e){
        e.preventDefault();
        $(this).blur();
        var src=$(this).find("img").attr("src").replace("_VD","_PD");
        $(".pictureViewer .vehiclePicture img").attr("src",src);
    });
}

var AA;
viewHelper.VehicleList=function(params,containerID){
    if(!containerID)containerID="#RESULTS";
    var self=this;
    var $=jQuery;
    var url="";
    var locked=true;
    var co=zapette.Common;
    if(!params)params={
        staticContent:true
    };

    var viewType=params.view||"liste";
    var mapView=null;
    var mapData=null;
    var lastClick=0;
    var configTimer=null;
    var selection=new viewHelper.Selection();
    selection.updateSelectionCount();
    selection.updateComparatorCount();
    this.onSortMode=null;
    this.onPageSize=null;
    this.onPageIndex=null;
    this.onViewType=null;
    this.fadeNotInSelection=false;
    this.updateList=function(data,context,orderBy){
        clearTimeout(configTimer);
        if(!orderBy)orderBy="prixttc_desc";
        $(".headerView .btAlert").css({
            display:context==""?"none":"block"
        }).attr("href","/Creer-alerte.aspx?"+context+"&orderby="+orderBy);
        var ref="/Recherche.aspx#"+context;
        if(orderBy!="prixttc_asc")ref+="&orderby="+orderBy;
        $(".headerView .btComparator").attr("href","/Comparateur.aspx?ref="+escape(ref));
        if(data.ExceptionType)

        {
            var err=$('<div class="serverException"></div>').setTemplateElement("ERROR_TEMPLATE").processTemplate(data);
            $(containerID+" .vehiclesContent").empty().append(err);
            return;
        }
        var count=data.d?data.d.length:0;
        if(count==0)

        {
            $(containerID+" .sortingType").addClass("jsHidden");
            $(containerID+" .vehiclesContent").empty().append('<div class="vehiclesInner"><p class="loading">Chargement en cours...</p></div>');
            $(containerID+" .vehiclesContent .vehiclesInner").load("/Aucun-resultat.aspx?"+context,null,noResultsLoaded);
            return;
        }
        else if(viewType!="carte")$(containerID+" .sortingType").removeClass("jsHidden");
        if(viewType=="carte")

        {
            createMapView();
            filterMapData(data);
            if(!locked)mapView.setMarkers(mapData);
            return;
        }
        if(viewType!="liste")context+="&view="+viewType;
        for(var i=0;i<count;i++){
            var item=data.d[i];
            if(viewType=="vignettes"){
                item._lineEnd=((i+1)%4==0);
                item._class=item._lineEnd?"last":"";
            }
            item._IdPlanetVo=item.IdPlanetVo;
            if(item.BonnesAffairesIdAndMentionegale&&item.BonnesAffairesIdAndMentionegale.length>0)
                item._idandmention=item.BonnesAffairesIdAndMentionegale.split("¥");else item._idandmention=[];
            item._PrixTtc=co.niceNumber(item.PrixTtc);
            item._IdNouvelleLicence=(item.IdNouvelleLicence!=-1)?item.IdNouvelleLicence:null;
            item._DescriptionNouvelleLicence=(item.IdNouvelleLicence!=-1)?item.DescriptionNouvelleLicence:null;
            item._Mensualites=(item.Mensualites>0)?co.niceNumber(item.Mensualites):null;
            item._km=item.Kilometrage?co.niceNumber(item.Kilometrage):"/";
            item._MiseCirculation=parseDate(item.MiseCirculation);
            var ctx="searchContext="+escape(context);
            item._url="/fiche-vehicule/"+item.Marque.toLowerCase()+"/"+item.Modele.toLowerCase()+"/"+item.IdPlanetVo+"?"+ctx+"&orderby="+orderBy+"&vehicleIndex="+i+"&useHash=1";
            if(item.NbPhotos==0){
                item._scrollable="";
                item._photo0="/_img/0000000_000000_01_VR.jpg";
                item._photos=[];
                item._alt="";
                continue;
            }
            item._alt=item.Marque+" "+item.Modele+" "+item.Silhouette+" "+item.Libelle+" chez "+item.NomPdv;
            item._scrollable="pictureScroller";
            item._photos=[];
            for(var j=0;j<item.NbPhotos;j++)
                item._photos.push(url+"/photos/"
                    +item.CodePostalPdv.substr(0,2)+"/"
                    +item.IdPdv+"/"
                    +item.ChronoXml+"/"
                    +item.PrefixPhoto
                    +item.ChronoXml+"_"
                    +co.padNumber(j+1,2)+"_VR.jpg");
            item._photo0=item._photos.shift();
        }
        if(viewType=="vignettes"&&data.d&&data.d.length)
            data.d[data.d.length-1]._lineEnd=true;
        var templateID="VEHICLELIST_TEMPLATE";
        switch(viewType){
            case"vignettes":
                templateID="VEHICLEVIGNETTES_TEMPLATE";
                break;
            case"galerie":
                templateID="VEHICLEGALLERY_TEMPLATE";
                break;
        }
        content=$('<div class="vehiclesInner"></div>').setTemplateElement(templateID).processTemplate(data);
        if(viewType=="galerie"){
            initGallery(data,content);
        }
        else{
            content.find("ul").find("li:first img").css({
                display:"block"
            });
            configTimer=setTimeout(function(){
                self.initItems(content);
                updateSFGMensualite();
            },200);
        }
    }
    function updateSFGMensualite(){}
    function parseDate(v){
        var m=/[0-9]+/.exec(v);
        if(!m)return"";
        var d=new Date();
        d.setTime(parseInt(m[0]));
        var y=d.getFullYear();
        if(y>1990)return Math.round(y);else return"";
    }
    function noResultsLoaded(responseText,textStatus){
        $(this).empty().append($.trim(responseText));
    }
    this.initItems=function(content,isCoverflowItem){
        clearTimeout(configTimer);
        var items=content.find(".item");
        items.find(".infosVehicles").css({
            cursor:"pointer"
        }).hover(overItem,outItem).click(clickItem);
        items.find(".pictureContent ul").css({
            cursor:"pointer"
        }).hover(overItem,outItem).click(clickItem);
        items.each(function(){
            var id=$(this).attr("id").split("_")[1];
            createBtns(this,id);
        });
        items.each(function(){
            var id=$(this).attr("id").split("_")[1];
            createBtns(this,id);
        });
        if(isCoverflowItem){
            items.find(".pictureContent").css({
                visibility:"hidden"
            });
            return;
        }
        if(params.staticContent)
            params.staticContent=false;else
            $(containerID+" .vehiclesContent").empty().append(content);
        configTimer=setTimeout(function(){
            items.find(".pictureScroller").each(function(){
                var scroller=new ui.Scroller("h",this,".previousPicture",".nextPicture",".multipleImage strong");
                scroller.makeImageFromAnchor=true;
            });
        },500);
    }
    function overItem(){
        $(this).parents(".item").addClass("hover");
    }
    function outItem(){
        $(this).parents(".item").removeClass("hover");
    }
    function clickItem(e){
        e.preventDefault();
        var url=$(this).parents(".item").find(".actionButton li.btMore a").attr("href");
        if(e.shiftKey||e.ctrlKey)window.open(url);else document.location=url;
    }
    var pageTitle="Occasions du Lion - Rechercher un véhicule";
    function setPageTitle(){
        window.document.title=pageTitle;
    }
    var coverflowIndex=-1;
    var coverflowTimer=0;
    function initGallery(data,content){
        var showTimer=0;
        AA=data;
        window.coverflow={};

        window.coverflow.getList=function(){
            var paging=0;
            if(currentPage>1&&currentPage<totalPages)paging=2;
            else if(currentPage>1)paging=1;
            else if(currentPage<totalPages)paging=3;
            var list=[{
                paging:paging
            }];
            $.each(data.d,function(index){
                list.push({
                    photos:[this._photo0].concat(this._photos),
                    id:index
                });
            });
            return list;
        }
        window.coverflow.setItem=function(index){
            setPageTitle();
            clearTimeout(showTimer);
            coverflowIndex=index;
            showTimer=setTimeout(showItemDetail,200);
        }
        window.coverflow.readMore=function(){
            var href=$(containerID+" .vehiclesContent .btMore a").attr("href");
            if(href&&href.length)
                document.location=href;
        }
        window.coverflow.prevPage=function(){
            prevPage();
        }
        window.coverflow.nextPage=function(){
            nextPage();
        }
        function showItemDetail(){
            clearTimeout(coverflowTimer);
            coverflowTimer=setTimeout(updateCoverflowItem,500);
        }
        function updateCoverflowItem(){
            var itemData={
                d:[data.d[coverflowIndex]]
            };

            var templateID="VEHICLELIST_TEMPLATE";
            var content=$(containerID+" .vehiclesContent .itemDetail");
            content.empty().setTemplateElement(templateID).processTemplate(itemData).show();
            self.initItems(content,true);
        }
        function scrollCoverflow(e,delta){
            setPageTitle();
            e.preventDefault();
            try{
                var flCoverflow=document.getElementById("flCoverflow");
                flCoverflow.mouseWheel(delta>0?1:-1);
            }
            catch(err){}
        }
        $(containerID+" .vehiclesContent").empty().append(content);
        $(containerID+" .vehiclesContent .flashCoverflow").empty().mousewheel(scrollCoverflow).append('<div id="flashCoverflow"></div>');
        var flashvars={};

        var params={
            menu:"false",
            scale:"noScale",
            allowFullscreen:"true",
            allowScriptAccess:"always",
            bgcolor:"#FFFFFF",
            wmode:"opaque"
        };

        var attributes={
            id:"flCoverflow",
            name:"flCoverflow"
        };

        swfobject.embedSWF("/_swf/ODLFlow.swf","flashCoverflow","727","420","9.0.0","expressInstall.swf",flashvars,params,attributes);
    }
    function createBtns(item,id){
        $(item).find(".actionsContent ul .toggleBt").remove();
        var isReserved=$(item).hasClass("item-reserved");
        createMySelectionBtn(item,selection.isInMySelection(id),isReserved);
        createComparatorBtn(item,selection.isInComparator(id),isReserved);
    }
    this.create_Btns=function(item,id){
        createBtns(item,id);
    }
    function createMySelectionBtn(item,isSelected,isReserved){
        if(!isSelected&&isReserved)return;
        var size=viewType=="vignettes"?"Small":"";
        if(!isSelected)
            $('<li class="toggleBt"><img src="http://localhost/akol/images/tpl/default/komisy/uzywanygwarantowany/img/Vehicles/btnAjouterSelection'+size+'.gif" alt="Ajouter à ma sélection" /></li>').click(toggleMySelection).appendTo($(item).find(".actionsContent ul.actionButton"));else
            $('<li class="toggleBt"><img src="http://localhost/akol/images/tpl/default/komisy/uzywanygwarantowany/img/Vehicles/btnRetirerSelection'+size+'.gif" alt="Retirer de ma sélection" /></li>').click(toggleMySelection).appendTo($(item).find(".actionsContent ul.actionButton"));
    }
    function createComparatorBtn(item,isSelected,isReserved){
        if(!isSelected&&isReserved)return;
        var size=viewType=="vignettes"?"Small":"";
        if(!isSelected)
            $('<li class="toggleBt"><img src="http://localhost/akol/images/tpl/default/komisy/uzywanygwarantowany/img/Vehicles/btnAjouterComparateur'+size+'.gif" alt="Ajouter au comparateur" /></li>').click(toggleComparator).appendTo($(item).find(".actionsContent ul.actionButton"));else
            $('<li class="toggleBt"><img src="http://localhost/akol/images/tpl/default/komisy/uzywanygwarantowany/img/Vehicles/btnRetirerComparateur'+size+'.gif" alt="Retirer du comparateur" /></li>').click(toggleComparator).appendTo($(item).find(".actionsContent ul.actionButton"));
    }
    function toggleMySelection(e){
        e.preventDefault();
        var t=new Date().getTime();
        if(t-lastClick<500)return;
        lastClick=t;
        var id=getVehicleID(this);
        var item=$(this).parents(".item");
        if(selection.isInMySelection(id)){
            if(self.fadeNotInSelection)item.css({
                opacity:0.5
            });
            //        zapette.Webservices.removeFromMySelection(id,selectionChanged);
            selection.removeFromMySelection(id);
            setTimeout(function(){
                animItem(item,$(".globalHeader .maSelection a"),true)
            },100);
        }
        else{
            if(self.fadeNotInSelection)item.css({
                opacity:1
            });
            //        zapette.Webservices.addToMySelection(id,selectionChanged);
            selection.addToMySelection(id);
            animItem(item,$(".globalHeader .maSelection a"));
        }
        selection.updateSelectionCount();
        createBtns(item,id);
    }
    function selectionChanged(data){
        selectionToken=null;
    }
    function toggleComparator(e){
        e.preventDefault();
        var t=new Date().getTime();
        if(t-lastClick<500)return;
        lastClick=t;
        var id=getVehicleID(this);
        var item=$(this).parents(".item");
        if(selection.isInComparator(id)){
            selection.removeFromComparator(id);
            setTimeout(function(){
                animItem(item,$(containerID+" .btComparator"),true)
            },100);
        }
        else if(!item.hasClass("item-reserved")){
            selection.addToComparator(id);
            animItem(item,$(containerID+" .btComparator"));
        }
        selection.updateComparatorCount();
        createBtns(item,id);
    }
    function getVehicleID(ref){
        return $(ref).parents(".item").attr("id").split("_")[1];
    }
    function animItem(item,target,reverse){
        var img=$(item).find(".pictureContent ul li img:first");
        var startPos;
        if(viewType!="galerie"){
            var parent=img.parent()[0];
            if(parent.__current)img=$(parent.__current).find("img");
            startPos=img.offset();
        }
        else if(!item.hasClass("item-reserved")){
            startPos=$(item).offset();
            startPos.left+=300;
            startPos.top+=15;
        }
        var endPos=target.offset();
        var startCss={
            left:startPos.left,
            top:startPos.top,
            height:116,
            opacity:1
        };

        var endCss={
            left:endPos.left,
            top:endPos.top,
            height:16,
            opacity:0
        };

        if(reverse){
            var temp=endCss;
            endCss=startCss;
            startCss=temp;
        }
        var dup=$('<div><img src="'+img.attr("src")+'" style="width: 100%;" /></div>').css({
            position:"absolute",
            zIndex:10,
            width:154,
            height:116,
            overflow:"hidden"
        }).css(startCss).appendTo($(document.body)).animate(endCss,600+(startPos.top/2),removeDup);
    }
    function removeDup(){
        $(this).remove();
    }
    var totalCount=0;
    var totalPages=0;
    var pageSize=params.pageSize||12;
    var currentPage=parseInt(params.page)||0;
    $(containerID+" select.orderBy").val(params.orderBy||"prixttc_asc");
    $(containerID+" select.pageSize").val(pageSize);
    $(containerID+" .viewType li a[rel="+viewType+"]").addClass("active");
    var paging=$(containerID+" .paging");
    if(paging.find("ul").length==0)
        $('<ul><li class="Active">'+(currentPage+1)+'</li></ul>').appendTo(paging);
    var selectByOrder=new ui.Select($(containerID+" select.orderBy"));
    var selectPageSize=new ui.Select($(containerID+" select.pageSize"),"select-size");
    var selectPageIndex=new ui.Select(paging.find("ul"),"select-index");
    selectByOrder.onSelect=changeSortMode;
    selectPageSize.onSelect=changePageSize;
    selectPageIndex.onSelect=changePageIndex;
    $(containerID+" .viewType li a").click(changeViewType);
    $('<div class="prevPage"></div>').click(prevPage).appendTo(paging);
    $('<div class="nextPage"></div>').click(nextPage).appendTo(paging);
    updateArrows();
    function prevPage(){
        if(locked)return;
        var page=parseInt(selectPageIndex.value);
        if(page>1&&self.onPageIndex)self.setPageIndex(page-1);
        autoScroll();
    }
    function nextPage(){
        if(locked)return;
        var page=parseInt(selectPageIndex.value);
        if(page<totalPages&&self.onPageIndex)self.setPageIndex(page+1);
        autoScroll();
    }
    function updateArrows(){
        paging.find(".prevPage").css({
            opacity:(!locked&&currentPage>1)?1:0.5,
            cursor:(!locked&&currentPage>1)?"pointer":"default"
        });
        paging.find(".nextPage").css({
            opacity:(!locked&&currentPage<totalPages)?1:0.5,
            cursor:(!locked&&currentPage<totalPages)?"pointer":"default"
        });
    }
    $(containerID+" .sortingTypeBottom .ui-select > div").addClass("ui-select-up");
    if(viewType!="carte")$(containerID+" .sortingType").removeClass("jsHidden");
    function changeViewType(e){
        e.preventDefault();
        $(this).blur();
        if(locked)return;
        $(containerID+" .viewType li a").removeClass("active");
        $(this).addClass("active");
        var newView=$(this).attr("rel");
        if(newView==viewType)return;
        if(viewType=="carte")GUnload();
        viewType=newView;
        if(viewType=="carte"){
            createMapView();
            $(containerID+" .sortingType").addClass("jsHidden");
        }
        else{
            mapView=null;
            $(containerID+" .sortingType").removeClass("jsHidden");
        }
        if(self.onViewType)
            self.onViewType(viewType);
        autoScroll();
    }
    function filterMapData(data){
        mapData={
            d:[]
        };

        if(!data.d)return;
        if(data.d.length>co.MAX_MAPPDV){
            mapData.Warning="Votre recherche a retourné trop de points de vente ("+data.d.length+").<br/>Merci d'ajouter des critères et/ou une localisation.";
            return;
        }
        $.each(data.d,function(){
            if(this.NumOfVehicle>0)mapData.d.push(this);
        });
    }
    function createMapView(){
        if(mapView==null)
            mapView=new viewHelper.GoogleMap($("#RESULTS .vehiclesContent"),"vehiclesInner");
    }
    function changeSortMode(value){
        if(self.onSortMode)
            self.onSortMode(value);
        autoScroll();
    }
    function changePageSize(value){
        pageSize=value;
        if(self.onPageSize)
            self.onPageSize(value);
        self.updatePaging(totalCount);
        if((parseInt(selectPageIndex.value)||1)>totalPages)
            self.setPageIndex(totalPages);
        autoScroll();
    }
    function changePageIndex(value){
        currentPage=parseInt(value);
        selectPageIndex.setState(currentPage+"/"+totalPages,currentPage);
        updateArrows();
        if(self.onPageIndex)
            self.onPageIndex(currentPage-1);
        autoScroll();
        updatePageSelect();
    }
    function autoScroll(){
        var viewTop=$("#RESULTS").offset().top;
        var doc=$("html,body");
        doc.animate({
            scrollTop:viewTop
        },doc.scrollTop()/2);
    }
    this.setEnabled=function(state){
        locked=!state;
        selectByOrder.setEnabled(state);
        selectPageIndex.setEnabled(state);
        selectPageSize.setEnabled(state);
        updateArrows();
        if(!locked&&mapData){
            if(viewType=="carte"&&mapView)mapView.setMarkers(mapData);
            mapData=null;
        }
    }
    this.setPageIndex=function(page,silent){
        currentPage=page;
        selectPageIndex.setState(currentPage+"/"+totalPages,currentPage);
        if(!silent)
            self.onPageIndex(currentPage-1);
        updateArrows();
        updatePageSelect();
    }
    this.updateState=function(view,orderBy,pageSize,pageIndex){
        viewType=view;
        $(containerID+" .viewType li a").removeClass("active");
        $(containerID+" .viewType li a[rel="+viewType+"]").addClass("active");
        currentPage=pageIndex;
        totalPages=Math.ceil(totalCount/pageSize);
        selectByOrder.setStateByValue(orderBy);
        selectPageSize.setState(pageSize,pageSize);
        selectPageIndex.setState(pageIndex+"/"+totalPages,pageIndex);
        updateArrows();
    }
    this.updatePaging=function(count){
        totalCount=count;
        totalPages=Math.ceil(count/(selectPageSize.value||10));
        currentPage=parseInt(selectPageIndex.value)||1;
        selectPageIndex.setState(currentPage+"/"+totalPages,currentPage);
        updateArrows();
        updatePageSelect();
    }
    function updatePageSelect(){
        var min=Math.max(1,currentPage-4);
        var max=Math.min(totalPages,Math.max(min+8,currentPage+4));
        min=Math.max(1,Math.min(max-8,min));
        var list=[];
        if(min>1)list.push({
            label:1,
            value:1
        },{
            label:"..."
        });
        for(var i=min;i<=max;i++)list.push({
            label:i,
            value:i
        });
        if(max<totalPages)list.push({
            label:"..."
        },{
            label:totalPages,
            value:totalPages
        });
        selectPageIndex.setItems(list);
    }
    if(params.staticContent)
        configTimer=setTimeout(function(){
            var list=$("#MYSELECTION .vehicleList");
            var listTop=list.offset().top;
            list.find(".reserved").each(function(){
                var top=$(this).parent().offset().top-listTop;
                $(this).parent().css({
                    opacity:0.5
                }).addClass("item-reserved");
                $(this).css({
                    top:top
                }).appendTo(list);
            });
            self.initItems($(containerID+" .vehiclesContent .vehiclesInner"));
            self.updatePaging(parseInt($(containerID+" h2 em").text().split(" ").join("")));
        },500);
}

var zapette={};

var context;
function initCommon()
{
    var wsRunning;
    var wsCallback;
    zapette.Common={
        NOFINANCING:true,
        NOPARAM:"indifferent",
        SELECTION_COOKIE:"ODLV3.MySelection",
        COMPARATOR_COOKIE:"ODLV3.Comparator",
        MAX_MAPPDV:100,
        DISTANCE_MIN:3,
        DISTANCE_DEFAULT:10,
        DISTANCE_MAX:200,
        KM_MIN:0,
        KM_MAX:150000,
        AGE_MIN:0,
        AGE_MAX:6,
        PRICE_MIN:4000,
        PRICE_MAX:75000,
        MONTHLY_MIN:60,
        MONTHLY_MAX:700,
        CO2_MAX:250,
        SILENT:function(e){
            if(e)e.preventDefault();
        },
        roundNumber:function(num,step)

        {
            if(!step)step=1;
            return Math.round(num/step)*step;
        },
        niceNumber:function(p)

        {
            p=Math.round(p).toString();
            if(p.length>3)return p.substr(0,p.length-3)+" "+p.substr(p.length-3);else return p;
        },
        padNumber:function(num,length)

        {
            var s=String(num);
            while(s.length<length)s="0"+s;
            return s;
        },
        selectionChanged:function(a,b)

        {
            len=a.length;
            if(len!=b.length)return true;
            for(var i=0;i<len;i++)
                if(b[i]!=a[i])return true;return false;
        },
        loadWS:function(method,data,callback)

        {
            if(wsRunning)
                return false;
            wsRunning=true;
            wsCallback=callback;
            zapette.Webservices[method](data,wsResponse);
            return true;
        },
        serializeParams:function(o)

        {
            if(typeof(o)!="object")return o.toString();
            var result=[];
            for(var p in o)

            {
                    var s=p+"="+jQuery.trim(""+o[p]);
                    result.push(s);
                }
            return result.join("&");
        },
        serializeJSON:function(o)

        {
            if(o===undefined)return undefined;
            else if(o===null)return"null";
            var type=typeof(o);
            if(type=="string")return'"'+o+'"';
            else if(type=="number")return o.toString();
            else if(type=="function")return indefined;
            var result=[];
            var v;
            if(o.push!=undefined&&typeof(o.push)=="function")

            {
                var n=o.length;
                for(var i=0;i<n;i++)

                {
                        v=this.serializeJSON(o[p]);
                        if(v!==undefined)result.push(v);
                    }
                return"["+result.join(",")+"]";
            }
            else
            {
                for(var p in o)

                {
                        v=this.serializeJSON(o[p]);
                        if(v!==undefined)result.push(p+":"+v);
                    }
                return"{"+result.join(",")+"}";
            }
        },
        getMinMaxContext:function()

        {
            if(context==undefined)return;
            this.PRICE_MIN=PrixMin;
            this.PRICE_MAX=PrixMax;
            this.MONTHLY_MIN=MensualiteMin;
            this.MONTHLY_MAX=MensualiteMax;
            this.KM_MIN=KilometrageMin;
            this.KM_MAX=KilometrageMax;
            var year=new Date().getFullYear();
            this.AGE_MIN=Math.max(1,year-AnneeMax);
            this.AGE_MAX=year-AnneeMin;
        },
        parseParams:function(q)

        {
            var o={};

            if(!q)return o;
            var parts=q.split("&");
            jQuery.each(parts,function(index,p)

            {
                    var param=p.split("=");
                    if(param.length>1&&param[0].length)
                        o[param[0]]=param[1];
                });
            return o;
        },
        compareObjects:function(a,b)

        {
            var diff={};

            var p;
            for(p in a)if(a[p]!=b[p])diff[p]=true;for(p in b)if(a[p]!=b[p])diff[p]=true;var list=[];
            for(p in diff)list.push(p);return list;
        },
        postQuery:function(q)

        {
            if(!q)return;
            q=q.split("?");
            var url=q[0];
            var params=this.parseParams(q[1]);
            var $=jQuery;
            var form=$('<form></form>').css({
                width:0,
                height:0,
                overflow:"hidden",
                position:"absolute",
                top:0
            }).attr("method","POST").attr("action","/Resultats.aspx");
            for(var name in params)

            {
                    $('<input type="hidden" />').attr("name",name).val(params[name]).appendTo(form);
                }
            $(document.body).append(form);
            form.submit();
        },
        readCookieSafe:function(name)

        {
            var cookie=unescape($.cookie(name));
            if(!cookie||cookie==""||cookie=="null")return"";else return cookie;
        }
    }
    function wsResponse(data)
    {
        wsRunning=false;
        var callback=wsCallback;
        wsCallback=null;
        callback(data);
    }
}
initCommon();
zapette.DropDown=function(domElement,callback,disabled){
    var self=this;
    var view=jQuery(domElement);
    var initText=view.find("span").html();
    var activeClass=view.attr("className")+"-active";
    this.domElement=domElement;
    this.currentText=initText;
    view.click(click);
    function click(e){
        e.preventDefault();
        if(!disabled)callback(self);
    }
    this.select=function(){
        if(zapette.DropDown.current)
            zapette.DropDown.current.deselect();
        zapette.DropDown.current=self;
        view.addClass(activeClass).find("span").html("Sélection en cours...");
    }
    this.deselect=function(){
        zapette.DropDown.current=null;
        view.removeClass(activeClass).find("span").html(self.currentText);
    }
    this.reset=function(newText){
        self.currentText=(newText)?newText:initText;
        self.deselect();
    }
    if(disabled)view.css({
        opacity:0.3
    });
    this.setEnabled=function(state){
        disabled=!state;
        view.stop().animate({
            opacity:disabled?0.3:1
        });
    }
}
zapette.DropDown.current=null;
﻿
zapette.FreeText=function(domElement,callback,openNewWin){
    var $=jQuery;
    var co=zapette.Common;
    var reSmallTag=new RegExp("<[/]?small>","gi");
    var reSmallContent=new RegExp("\\s*<small>[^<]*</small>","gi");
    var query;
    var loadingAnim=$("<div class='loading'><div></div></div>");
    var lastSend=0;
    var self=this;
    this.pdvID=null;
    var suggest=new ui.Suggest($("#FREETEXT .searchTextBox"),"getCriteres");
    suggest.onQuery=onSuggestQuery;
    suggest.onSelect=onSuggestSelect;
    suggest.onData=onSuggestData;
    suggest.onSubmit=onSuggestSubmit;
    suggest.delay=60000;
    function onSuggestQuery(){
        loadingAnim.appendTo($("#FREETEXT")).show();
        query=null;
        pressedEnter=false;
    }
    function onSuggestSelect(item){
        if(item==null){
            query=null;
            return;
        }
        if(new Date().getTime()-lastSend<500)return;
        query="/Recherche.aspx#"+$(item).find("a").attr("href").split(/[?#]/)[1];
        if(self.pdvID)query+="&pdvid="+self.pdvID;
        $("#FREETEXT .searchTextBox").val($(item).text());
    }
    function onSuggestSubmit(){
        if(query&&query.length)sendQuery();
    }
    function onSuggestData(data){
        loadingAnim.hide();
        if(!data.d||data.d==""){
            return{
                d:[{
                    Recherche:""
                }],
                title:"<p>Recherche non reconnue</p>"
            };

        }
        var params={};

        var ambi=[];
        var inco=[];
        var parts=data.d.split("&");
        var map=["marque","modele","silhouette","energie","couleur","equipement","localisation","codepostal","annee",null,"prix",null,null,null,null,"num_departement","lib_departement","motorisation","boite","version","licence"];
        for(var i in parts){
            var param=parts[i].split("=");
            var name=param[0];
            var ai,parName,conf;
            if(name.substr(0,10)=="ambiguity_"){
                conf=name.split("_");
                ai=parseInt(conf[1]);
                parName=map[parseInt(conf[3])-1];
                if(!name)
                    return;
                if(!ambi[ai])ambi[ai]=[];
                ambi[ai].push({
                    name:parName,
                    value:formatAmbiguity(param[1],parName)
                });
            }
            else if(name.substr(0,14)=="inconsistency_"){
                conf=name.split("_");
                parName=map[parseInt(conf[1])-1];
                if(!name)
                    return;
                inco.push({
                    name:parName,
                    value:formatAmbiguity(param[1],parName)
                });
            }
            else params[param[0]]=param[1];
        }
        var results=[params];
        if(ambi.length)results=expandAmbiguities(results,ambi);
        if(inco.length)results=expandInconsistencies(results,inco);
        var lines=[];
        var maxLen=0;
        for(var i in results){
            var item=formatResponse(results[i]);
            var txt=item.Recherche.replace(reSmallTag,"");
            if(txt.length>maxLen)maxLen=txt.length;
            lines.push(item);
        }
        if(maxLen<30)suggest.width=225;else suggest.width=225+Math.round(225*(maxLen-30)/30);
        query=lines[0].Url;
        if(lines.length>1)pressedEnter=false;
        else if(pressedEnter&&query&&query.length>0)sendQuery();
        return{
            d:lines,
            title:"<p>Votre recherche est ambigüe :</p>"
        };

    }
    function expandInconsistencies(results,inco){
        var newRes=[];
        for(var i in inco){
            for(var j in results){
                var temp=cloneParams(results[j]);
                temp[inco[i].name]=inco[i].value;
                newRes.push(temp);
            }
        }
        return newRes;
    }
    function expandAmbiguities(results,ambi){
        for(var i in ambi){
            var list=ambi[i];
            var newRes=[];
            for(var j in list){
                var param=list[j];
                for(var k in results){
                    var temp=cloneParams(results[k]);
                    if(temp[param.name])temp[param.name]+=","+param.value;else temp[param.name]=param.value;
                    newRes.push(temp);
                }
            }
            results=newRes;
        }
        return results;
    }
    function formatAmbiguity(value,name){
        switch(name){
            case"marque":
                return value+formatHint("marque");
            case"modele":
                return value+formatHint("modèle");
            case"silhouette":
                return value+formatHint("silhouette");
            case"energie":
                return value+formatHint("énergie");
            case"couleur":
                return value+formatHint("couleur");
            case"equipement":
                return value+formatHint("équipement");
            case"localisation":
                return value+formatHint("ville");
            case"codepostal":
                return value+formatHint("code postal");
            case"annee":
                return value+formatHint("année");
            case"prix":
                return value+formatHint("prix");
            case"num_departement":
                return value+formatHint("département");
            case"lib_departement":
                return value+formatHint("département");
            case"motorisation":
                return value+formatHint("motorisation");
            case"boite":
                return value+formatHint("boite de vitèsse");
            case"version":
                return value+formatHint("version simple");
            case"licence":
                return value+formatHint("nouvelle licence");
        }
        return value;
    }
    function formatHint(name){
        return' <small>('+name+')</small>';
    }
    function cloneParams(o){
        var c={};

        for(var p in o)c[p]=o[p];return c;
    }
    function formatResponse(o){
        var res="";
        if(o.marque)res+=formatOptions(o.marque);
        if(o.modele)res+=formatOptions(o.modele);
        if(o.silhouette)res+=formatOptions(o.silhouette);
        if(o.energie)res+=formatOptions(o.energie);
        if(o.couleur)res+=formatOptions(o.couleur);
        if(o.prix){
            res+=""+o.prix;
            var prix=o.prix.replace(reSmallContent,"");
            o.prixmin=Math.round(parseInt(prix)*0.9);
            o.prixmax=Math.round(parseInt(prix)*1.1);
            delete o.prix;
        }
        if(o.equipement)res+="avec "+formatOptions(o.equipement);
        if(o.annee){
            var years=new Date().getFullYear()-o.annee;
            if(years>1)res+="de moins de "+years+" ans ";else res+="de moins de "+years+" an ";
        }
        if(o.kilometrage){
            if(!o.annee)res+="de ";else res+="et ";
            res+="moins de "+o.kilometrage+"km ";
        }
        if(o.num_departement){
            res+="dans le "+o.num_departement+" ";
            if(o.radius&&o.radius!=co.DISTANCE_MIN&&o.radius!=co.DISTANCE_DEFAULT)
                res+="à moins de "+o.radius+"km ";
            o.codepostal=o.num_departement;
            delete o.num_departement;
        }
        else if(o.lib_departement){
            res+="dans "+o.lib_departement+" ";
            if(o.radius&&o.radius!=co.DISTANCE_MIN&&o.radius!=co.DISTANCE_DEFAULT)
                res+="à moins de "+o.radius+"km ";
            o.localisation=o.lib_departement;
            delete o.lib_departement;
        }
        else if(o.localisation||o.codepostal){
            res+="à ";
            if(o.radius&&o.radius!=co.DISTANCE_MIN&&o.radius!=co.DISTANCE_DEFAULT)
                res+="moins de "+o.radius+"km de ";
            if(o.localisation)res+=formatOptions(o.localisation)+" ";
            if(o.codepostal)res+=formatOptions(o.codepostal)+" ";
        }
        if(o.motorisation)res+=formatOptions(o.motorisation);
        if(o.boite)res+=formatOptions(o.boite);
        if(o.version)res+=formatOptions(o.version);
        if(o.licence)res+=formatOptions(o.licence);
        return{
            Recherche:res,
            Url:formatQuery(o)
        };

    }
    function formatQuery(o){
        return"/Recherche.aspx#"+co.serializeParams(o).replace(reSmallContent,"");
    }
    function formatOptions(p){
        return p.split(",").join(", ")+" ";
    }
    var hasFocus=false;
    $("form").submit(formSubmit);
    $("#FREETEXT .btnOk").click(btnClick);
    function btnClick(e){
        e.preventDefault();
        var current=$.trim($("#FREETEXT .searchTextBox").val());
        if(!current.length||(query&&query.length))sendQuery();else suggest.getSuggestions(true);
    }
    function formSubmit(e){
        e.preventDefault();
        if(hasFocus)sendQuery();
    }
    function sendQuery(e){
        if(e)e.preventDefault();
        pressedEnter=false;
        $("#FREETEXT .searchTextBox").val("");
        if(new Date().getTime()-lastSend<500)return;
        lastSend=new Date().getTime();
        if(pageTracker)
            pageTracker._trackEvent("FreeText","Click",query);
        var url=query||"";
        if(url.length>1)url=url.substr(url.indexOf('#')+1);
        if(callback){
            if(!url.length)url="pdvid="+self.pdvID;
            callback("#"+url);
            return;
        }
        if(self.pdvID){
            if(!url.length)url="pdvid="+self.pdvID;
            url="/Votre-point-de-vente-page.aspx?"+url;
        }
        else{
            if(!url.length)url=co.NOPARAM;
            url="/Recherche.aspx#"+url;
        }
        if(openNewWin||(e&&(e.shiftKey||e.ctrlKey)))window.open("http://www.occasionsdulion.com"+url);else window.location=url;
        query=null;
    }
}
﻿
function initHome($,panelTop,openNewWin)
{
    var co=zapette.Common;
    var suggest=new zapette.FreeText(true,null,openNewWin);
    if(!panelTop)panelTop=-27;
    if(openNewWin)panelTop=5;
    var panel=new zapette.Panel($("#PANEL"));
    panel.loadingAnim=$("<div class='loading'></div>");
    function getMenuTop()

    {
        $("#PANEL.PANEL_BUDGET").css("height","");
        $("#PANEL.PANEL_BUDGET .buttons").css("top","");
        if(openNewWin)return panelTop;
        else if(zapette.DropDown.current)
            return zapette.DropDown.current.domElement.position().top+panelTop;else return 0;
    }
    var pdvID=0;
    var mPDV=/pdvid=([0-9]+)/i.exec(document.location);
    if(mPDV)

    {
        pdvID=mPDV[1];
        suggest.pdvID=pdvID;
    }
    var brandData;
    var brandSelection=[];
    var modelData;
    var modelSelection=[];
    var variantData;
    var variantSelection=[];
    var budgetData={
        priceMin:co.PRICE_MIN,
        priceMax:co.PRICE_MAX
    };
    var wsCallInProgress=null;
    $("#LOCATION").focus(locaFocus).blur(locaBlur);
    function locaFocus()


    {
        if($(this).val()=="Localisation")$(this).val("");
    }
    function locaBlur()
    {
        if($.trim($(this).val())=="")$(this).val("Localisation");
    }
    var suggestLoca=new zapette.SuggestLocation($("#LOCATION"),"propositionsLocalisation",219);
    suggestLoca.onChanged=onLocationChange;
    function onLocationChange(location)

    {
        if(location!=null&&location.length>0)
            $("#LOCATION").val(location);
    }
    var brandMenu=new zapette.DropDown($("#BRAND"),showBrands);
    var modelMenu=new zapette.DropDown($("#MODEL"),showModels,true);
    var variantMenu=new zapette.DropDown($("#VARIANT"),showVariants);
    var budgetMenu=new zapette.DropDown($("#BUDGET"),showBudget);
    var brandTitle="<strong>Marques :</strong> Veuillez sélectionner une ou plusieurs marques";
    var modelTitle="<strong>Modèles :</strong> Veuillez sélectionner un ou plusieurs modèles";
    var variantTitle="<strong>Silhouettes :</strong> Veuillez sélectionner une ou plusieurs silhouettes";
    var budgetTitle;
    if(co.NOFINANCING)budgetTitle="<strong>Budget :</strong> Veuillez sélectionner un budget";else budgetTitle="<strong>Budget :</strong> Veuillez sélectionner un budget et/ou une mensualité";
    var currentFocus=null;
    var onListChanged=null;
    function showError(data)

    {
        panel.showTemplate(getMenuTop(),"<strong>Erreur serveur :</strong>","ERROR_TEMPLATE",data.obj);
        panel.domElement.find(".validateBtn").hide();
    }
    function showListSelector(data)
    {
        if(data.ExceptionType)return showError(data);
        eval(currentFocus+"Data = data");
        panel.showList(getMenuTop(),eval(currentFocus+"Title"),data,eval(currentFocus+"Selection"));
        panel.onValidate=validateListCriteria;
        if(currentFocus=="variant")
            panel.domElement.find("ul").addClass("twoColumns");
    }
    function validateListCriteria(result)
    {
        if(co.selectionChanged(result.list,eval(currentFocus+"Selection")))

        {
            eval(currentFocus+"Selection = result.list");
            if(onListChanged)onListChanged(result);
        }
        eval(currentFocus+"Menu").reset(result.text);
    }
    function showBrands()
    {
        currentFocus="brand";
        onListChanged=brandsChanged;
        var params="";
        if(pdvID)params+="&pdvid="+pdvID;
        if(co.loadWS("getMarque",params,showListSelector))
            panel.select(brandMenu);
    }
    function brandsChanged(result)
    {
        modelData=null;
        variantData=null;
        modelSelection=[];
        variantSelection=[];
        modelMenu.reset();
        variantMenu.reset();
        modelMenu.setEnabled(result.list.length>0);
    }
    function showModels()
    {
        if(!brandSelection.length)
            return;
        currentFocus="model";
        onListChanged=modelsChanged;
        var params="marque="+brandSelection.join(",");
        if(pdvID)params+="&pdvid="+pdvID;
        if(co.loadWS("getModele",params,showListSelector))
            panel.select(modelMenu);
    }
    function modelsChanged(result)
    {
        variantData=null;
        variantSelection=[];
        variantMenu.reset();
    }
    function showVariants()
    {
        currentFocus="variant";
        onListChanged=null;
        var params="marque="+brandSelection.join(",")+"&modele="+modelSelection.join(",");
        if(pdvID)params+="&pdvid="+pdvID;
        if(co.loadWS("getSilhouette",params,showListSelector))
            panel.select(variantMenu);
    }
    function showBudget()
    {
        panel.select(budgetMenu);
        if(wsCallInProgress)$.abortWS(wsCallInProgress);
        wsCallInProgress=zapette.Webservices.getOffreDetails(updateSFGDetails);
    }
    var SFG_Details={};
    function updateSFGDetails(data){
        wsCallInProgress=null;
        panel.loadingAnim.hide();
        var customTop=getMenuTop();
        if(!openNewWin){
            customTop=150;
            if(data.d.HasError){
                customTop=255;
            }
        }
        panel.showTemplate(customTop,budgetTitle,"BUDGET_TEMPLATE",null,"PANEL_BUDGET");
        panel.domElement.find(".pictoTip").simpletooltip().click(co.SILENT);
        var monthly=panel.domElement.find("#SLIDER_MONTHLY");
        SFG_Details=data.d;
        if(data.d.HasError){
            $("#SLIDER_MONTHLY").hide();
            $("#PANEL.PANEL_BUDGET").css("height","160px");
            $("#PANEL.PANEL_BUDGET .buttons").css("top","121px");
        }
        else{
            $("#SLIDER_MONTHLY").show();
            monthly.find(".SimulateurFinancement_TitreOffre").each(function(){
                $(this).html(SFG_Details.Titre)
            });
            monthly.find(".SimulateurFinancement_DescriptionOffre").each(function(){
                $(this).html(SFG_Details.Description)
            });
            for(var i=0;i<SFG_Details.Fields.length;i++){
                var calculerLink=$("#CALCULER_SFG");
                var titleHtml='<label class="SimulateurFinancement_TitreControl" title="'+SFG_Details.Fields[i].Title+'" id="TITRECONTROL_'+i.toString()+'">'+SFG_Details.Fields[i].Title+'</label><br />'
                var unitHtml=''
                if(SFG_Details.Fields[i].Unit!=null)
                    unitHtml='<label class="SimulateurFinancement_UnitControl" title="'+SFG_Details.Fields[i].Unit+'" id="UNITCONTROL'+i.toString()+'">'+SFG_Details.Fields[i].Unit+'</label><br />'
                var inputControl;
                if(SFG_Details.Fields[i].SelectableValues){
                    inputControl=$(document.createElement('select')).addClass("SimulateurFinancement_Control").attr("id","CONTROL_"+i.toString());
                    $.each(SFG_Details.Fields[i].SelectableValues,function(key,value){
                        if(SFG_Details.Fields[i].DefaultValue==value)

                        {
                            inputControl.append($("<option></option>").attr("value",value).attr('selected','selected').text(value));
                        }
                        else
                        {
                            inputControl.append($("<option></option>").attr("value",value).text(value));
                        }
                    });
                }
                else{
                    inputControl=$(document.createElement('input')).attr("type","text").attr("id","CONTROL_"+i.toString()).val(SFG_Details.Fields[i].DefaultValue);
                    if((SFG_Details.Fields[i].MinValue!=0)&&(SFG_Details.Fields[i].MaxValue!=0)){
                        if(!SFG_Details.Fields[i].Mandatory)
                            inputControl.attr("title","saisir un chiffre entre "+SFG_Details.Fields[i].MinValue+" et "+SFG_Details.Fields[i].MaxValue);else
                            inputControl.attr("title","important de saisir un chiffre entre "+SFG_Details.Fields[i].MinValue+" et "+SFG_Details.Fields[i].MaxValue);
                    }
                }
                calculerLink.before(titleHtml).before(inputControl).before(unitHtml);
            }
            $("#CALCULER_SFG").click(function(event){
                event.preventDefault();
                var isValid=true;
                var firstError=false;
                for(var j=0;j<SFG_Details.Fields.length;j++){
                    if($("#CONTROL_"+j.toString()).val().length==0){
                        if(SFG_Details.Fields[j].Mandatory){
                            isValid=false;
                            if(!firstError){
                                firstError=true;
                                $("#CONTROL_"+j.toString()).focus();
                            }
                            SetupUpErrorHere(j);
                        }
                    }
                    else{
                        if(!SFG_Details.Fields[j].SelectableValues){
                            var valeur=parseInt($("#CONTROL_"+j.toString()).val());
                            var min=parseInt(SFG_Details.Fields[j].MinValue);
                            var max=parseInt(SFG_Details.Fields[j].MaxValue);
                            if((valeur<min)||(valeur>max)){
                                isValid=false;
                                if(!firstError){
                                    firstError=true;
                                    $("#CONTROL_"+j.toString()).focus();
                                }
                                SetupUpErrorHere(j);
                            }
                        }
                    }
                }
                if(!isValid)return;
                var code=[];
                var value=[];
                for(var i=0;i<SFG_Details.Fields.length;i++){
                    code[i]=SFG_Details.Fields[i].ShortDescription;
                    value[i]=$("#CONTROL_"+i.toString()).val();
                }
                if(wsCallInProgress)$.abortWS(wsCallInProgress);
                $("#CHARGEUR_SFG").html("Calcul en cours...");
                $("#CHARGEUR_SFG").show();
                wsCallInProgress=zapette.Webservices.getBudgetMinMax(code,value,UpdateSliderMinMaxFromSFG);
            });
            function SetupUpErrorHere(index){
                $("#CONTROL_"+index.toString()).addClass("SimulateurFinancement_ErreurValidation");
            }
            function UpdateSliderMinMaxFromSFG(data){
                wsCallInProgress=null;
                if(data.d.HasError){
                    return;
                }
                $("#CHARGEUR_SFG").fadeOut();
                priceMin=data.d.PrixMin;
                priceMax=data.d.PrixMax;
                if(priceMin>co.PRICE_MAX)
                    priceMin=co.PRICE_MAX;
                if(priceMax>co.PRICE_MAX)
                    priceMax=co.PRICE_MAX;
                priceSlider.setRatio((priceMax-co.PRICE_MIN)/(co.PRICE_MAX-co.PRICE_MIN),(priceMin-co.PRICE_MIN)/(co.PRICE_MAX-co.PRICE_MIN));
            }
        }
        var budgetByPrice=budgetData.byPrice;
        var priceMin=budgetData.priceMin;
        var priceMax=budgetData.priceMax;
        var price=panel.domElement.find("#SLIDER_PRICE");
        var priceSlider=new ui.Slider("#SLIDER_PRICE",priceChanged);
        priceSlider.setRatio((priceMax-co.PRICE_MIN)/(co.PRICE_MAX-co.PRICE_MIN),(priceMin-co.PRICE_MIN)/(co.PRICE_MAX-co.PRICE_MIN));
        function priceChanged(ratio,ratioMin)
        {
            priceMin=co.roundNumber(co.PRICE_MIN+ratioMin*(co.PRICE_MAX-co.PRICE_MIN),100);
            priceMax=co.roundNumber(co.PRICE_MIN+ratio*(co.PRICE_MAX-co.PRICE_MIN),100);
            if(priceMin==co.PRICE_MIN&&priceMax==co.PRICE_MAX)
                price.find("label").html('Prix : indifférent');
            else if(priceMin==co.PRICE_MIN)
                price.find("label").html('Prix : jusqu\'à <strong class="max">'+co.niceNumber(priceMax)+" €</strong>");
            else if(priceMax==co.PRICE_MAX)
                price.find("label").html('Prix : à partir de <strong class="min">'+co.niceNumber(priceMin)+" €</strong>");else
                price.find("label").html('Prix : entre <strong class="min">'+co.niceNumber(priceMin)
                    +' €</strong> et <strong class="max">'+co.niceNumber(priceMax)+" €</strong>");
        }
        panel.onValidate=function()
        {
            budgetData.priceMin=priceMin;
            budgetData.priceMax=priceMax;
            if(priceMin==co.PRICE_MIN)priceMin=0;
            if(priceMax==co.PRICE_MAX)priceMax=0;
            validateBudget(priceMin,priceMax);
        }
        priceSlider.setFaded(true);
    }
    function validateBudget(priceFrom,priceTo){
        var msg;
        if(priceFrom&&priceTo)msg="Prix entre "+co.niceNumber(priceFrom)+" € et "+co.niceNumber(priceTo)+" €";
        else if(priceFrom)msg="Prix à partir de "+co.niceNumber(priceFrom)+" €";
        else if(priceTo)msg="Prix jusqu'à "+co.niceNumber(priceTo)+" €";
        budgetMenu.reset(msg);
    }
    $(".searchCriteria").css({
        visibility:"visible",
        opacity:0
    }).animate({
        opacity:1
    }).find(".btnTrouverMonVehicule").click(searchResults);
    $("form").submit(searchResults);
    function searchResults(e)
    {
        e.preventDefault();
        var url="";
        var loca=suggestLoca.query;
        if(loca!=null&&loca.length&&loca!="Localisation")
            url+="&"+loca;
        if(brandSelection.length)url+="&marque="+brandSelection.join(",");
        if(modelSelection.length)url+="&modele="+modelSelection.join(",");
        if(variantSelection.length)url+="&silhouette="+variantSelection.join(",");
        if(budgetData.priceMin>co.PRICE_MIN)url+="&prixmin="+budgetData.priceMin;
        if(budgetData.priceMax<co.PRICE_MAX)url+="&prixmax="+budgetData.priceMax;
        if(url.length>1)url=url.substr(1);
        if(pageTracker)
            pageTracker._trackEvent("FindForm","Click",url);
        if(pdvID)

        {
            if(url.length)url="&"+url;
            url="/Votre-point-de-vente-page.aspx?pdvid="+pdvID+url;
        }
        else
        {
            if(!url.length)url=co.NOPARAM;
            url="/Recherche.aspx#"+url;
        }
        if(openNewWin)window.open("http://www.occasionsdulion.com"+url);else window.location=url;
    }
    $(function(){
        $(".globalFooter .listVehicle a").click(function(e)

        {
                var url=$(this).attr("href");
                url=url.split("marque/")[1];
                if(url)

                {
                    e.preventDefault();
                    if(pageTracker)
                        pageTracker._trackEvent("Footer","Click",$(this).text());
                    url="marque="+url.split("/").join("&modele=");
                    if(pdvID)

                    {
                        if(url.length)url="&"+url;
                        url="/Votre-point-de-vente-page.aspx?pdvid="+pdvID+url;
                    }
                    else
                    {
                        if(!url.length)url=co.NOPARAM;
                        url="/Recherche.aspx#"+url;
                    }
                    if(openNewWin)window.open("http://www.occasionsdulion.com"+url);else window.location=url;
                }
            });
    });
}
﻿
zapette.SuggestLocation=function(domElement,method,suggestWidth)
{
    var $=jQuery;
    var view=$(domElement);
    var self=this;
    var animLoading=null;
    this.domElement=domElement;
    this.onChanged=null;
    this.onSubmit=null;
    this.location=null;
    this.query=null;
    view.change(checkEmpty);
    function checkEmpty(e)

    {
        if($.trim(view.val())=="")

        {
            self.location="";
            self.query="";
        }
    }
    var suggest=new ui.Suggest(view,method);
    suggest.showOneResult=true;
    suggest.alwaysSubmitOnEnter=true;
    suggest.width=suggestWidth;
    suggest.onQuery=function()

    {
        self.selection=null;
        self.query=null;
        if(!animLoading)animLoading=$('<div class="loading"></div>');
        animLoading.show().appendTo(view.parent());
    }
    suggest.onSubmit=function()
    {
        view.blur();
        if(self.onSubmit)self.onSubmit();
    }
    suggest.onData=function(data)
    {
        animLoading.hide();
        if(!data||!data.d)return data;
        var count=0;
        var list={
            d:[]
        };

        var query;
        for(var i in data.d)

        {
                var item=data.d[i];
                if(!item.Libelle)
                    item.Libelle=item.LibCommune+" ("+item.CodePostal+")";
                if(item.PdvId)query="pdvid="+item.PdvId;
                else if(item.CodePostal)query="localisation="+item.Localisation+"&codepostal="+item.CodePostal;else query="localisation="+item.Localisation;
                list.d.push({
                    Recherche:item.Libelle,
                    Url:"#"+query
                });
            }
        if(list.d.length)
        {
            self.location=list.d[0].Recherche;
            self.query=list.d[0].Url.split("#")[1];
        }
        else self.location=self.query=null;
        return list;
    }
    suggest.onSelect=function(choice)
    {
        if(choice==null)

        {
            self.location="";
            self.query="";
            if(self.onChanged)
                self.onChanged(self.location,self.query);
            return;
        }
        var item=$(choice).find("a");
        self.location=$.trim(item.text());
        self.query=item.attr("href").split("#")[1];
        if(self.onChanged)
            self.onChanged(self.location,self.query);
    }
}
zapette.Panel=function(domElement){
    var self=this;
    var $=jQuery;
    var view=$(domElement);
    var isOpen=false;
    var hideTimer=null;
    var currentValidation=null;
    var isList=null;
    this.domElement=domElement;
    this.loadingAnim=null;
    this.onGetTop=null;
    this.onShow=null;
    this.onValidate=null;
    this.onClose=null;
    this.close=function(e){
        clearTimeout(hideTimer);
        $(document).unbind("mousedown",docMouseDown);
        if(e){
            e.preventDefault();
            $(e.target).blur();
            hide();
        }
        else hideTimer=setTimeout(hide,100);
        if(!isOpen)return;
        isOpen=false;
        if(zapette.DropDown.current)
            zapette.DropDown.current.deselect();
        if(self.onClose)
            self.onClose(self);
    }
    function hide(){
        if(view.css("display")!="none")
            view.stop().show().fadeOut("fast");
    }
    this.select=function(menu){
        self.close();
        menu.select();
        menu.domElement.blur();
        if(self.loadingAnim)
            self.loadingAnim.appendTo(menu.domElement).show();
    }
    this.show=function(top,title){
        clearTimeout(hideTimer);
        self.loadingAnim.hide();
        isOpen=true;
        isList=null;
        view.find(".title").html(title);
        if(view.css("display")=="none"||parseInt(view.css("top"))<-100)view.css({
            top:top,
            opacity:0
        });
        view.show().stop().animate({
            opacity:1,
            top:top
        },"fast");
        $(document).unbind("mousedown",docMouseDown).bind("mousedown",docMouseDown);
        if(self.onShow)
            self.onShow(self);
    }
    function docMouseDown(e){
        if($(e.target).closest("#PANEL").length==0)
            self.close();
    }
    this.showTemplate=function(top,title,templateID,data,panelCSSClassName){
        view.find(".inner").empty().setTemplateElement(templateID).processTemplate(data);
        self.show(top,title);
        self.show(top,title);
        if(panelCSSClassName&&panelCSSClassName.toString().length>0)
            $("#PANEL").attr("class",panelCSSClassName);else
            $("#PANEL").removeClass();
    }
    this.showList=function(top,title,data,selection){
        self.showTemplate(top,title,"LIST_TEMPLATE",data);
        view.find("#CLEAR_SELECTION").bind("click",toggleClear).end().find("ul a.checkbox").bind("click",toggleCheck);
        if(!selection.length)
            view.find("#CLEAR_SELECTION").addClass("checkbox-checked");else
            $.each(selection,function(i,id){
                view.find("[id="+id+"]").addClass("checkbox-checked");
            });
        isList=data;
    }
    function toggleClear(e){
        e.preventDefault();
        $(this).blur().toggleClass("checkbox-checked");
        ;
        if($(this).hasClass("checkbox-checked"))
            view.find("ul a").removeClass("checkbox-checked");
        $("#PANEL .inner").focus();
    }
    function toggleCheck(e){
        e.preventDefault();
        $(this).blur().toggleClass("checkbox-checked");
        if($(this).hasClass("checkbox-checked"))
            view.find("#CLEAR_SELECTION").removeClass("checkbox-checked");
        $("#PANEL .inner").focus();
    }
    function validate(e){
        if(e)e.preventDefault();
        var result=null;
        if(isList)result=getNewSelection();
        if(self.onValidate)
            self.onValidate(result);
        self.close();
    }
    function getNewSelection(){
        var text=null;
        var list=[];
        var detail=[];
        view.find("ul a").each(function(){
            if($(this).hasClass("checkbox-checked")){
                var id=$(this).attr("id");
                list.push(id);
                detail.push(getItemDetail(id));
                if(text==null)text="";else text+=", ";
                text+=id;
            }
        });
        return{
            text:text,
            list:list,
            detail:detail
        };

    }
    function getItemDetail(id){
        var found=null;
        $.each(isList.d,function(){
            if(this.Value==id){
                found=this;
                found.Selected=true;
                return false;
            }
        });
        return found;
    }
    function inputKeydown(e){
        if(e.keyCode==13){
            validate(e);
        }
    }
    function setFocus(e){
        e.target.focus();
    }
    function removeFocus(e){
        e.target.blur();
    }
    view.css({
        top:-10000,
        opacity:0
    }).find("a.closeBtn").click(this.close).end().find("a.cancelBtn").click(this.close).end().find("a.validateBtn").click(validate);
    $("#PANEL .inner").mouseover(setFocus).keydown(inputKeydown);
    if($.browser.msie)
        view.addClass("ie6");
}
﻿
function initPdvMap($)
{
    var searchToken=null;
    var currentSearch=null;
    var loadingAnim=$('<div class="loading"><div></div></div>');
    var mapView=new viewHelper.GoogleMap($("#MAP_VIEW"),"googleMap");
    mapView.setMarkers({
        d:[]
    });
    var suggestLoca=new zapette.SuggestLocation($("#LOCATION"),"getPropositions",229);
    suggestLoca.onChanged=onLocationChange;
    suggestLoca.onSubmit=setLocation;
    function onLocationChange(location)


    {
        if(location!="")
            $("#LOCATION").val(location);
    }
    $("form").submit(setLocation);
    $("#SETLOCATION").click(setLocation);
    function setLocation(e)

    {
        if(e)e.preventDefault();
        $(this).blur();
        if(currentSearch==suggestLoca.location)
            return;
        currentSearch=suggestLoca.location;
        if(searchToken)$.abortWS(searchToken);
        if(suggestLoca.query==null)
            return;
        onLocationChange(suggestLoca.location);
        if(suggestLoca.location=="")
            return;
        loadingAnim.appendTo($("#LOCATION").parent()).show();
        var query=suggestLoca.query;
        searchToken=zapette.Webservices.getPointVenteListBySearchContext(query,0,updateMap);
    }
    function updateMap(data)
    {
        loadingAnim.hide();
        mapView.setMarkers(data);
    }
    var mDep=/\/votre-point-de-vente\/([^\/]+)\/([0-9]+)/i.exec(document.location.href);
    if(mDep)

    {
        suggestLoca.location=mDep[2];
        suggestLoca.query="codepostal="+mDep[2];
        setLocation();
    }
}
﻿
zapette.Promotions=function(domElement)
{
    var $=jQuery;
    var list=[];
    $(domElement).find("li").each(function(){
        var a=$(this).find("a");
        list.push({
            image:$(this).find("img").attr("src"),
            url:a.attr("href"),
            target:a.attr("target")
        });
    });
    $(domElement).find("ul").attr("id","PROMOBOX");
    var params={
        menu:"false",
        scale:"noScale",
        allowScriptAccess:"always",
        bgcolor:"#FFFFFF",
        wmode:"opaque"
    };
    var attributes={
        id:"flPromoBox",
        name:"flPromoBox"
    };
    swfobject.embedSWF("/_swf/promotions.swf","PROMOBOX","235","170","9.0.0","expressInstall.swf",null,params,attributes);
    window.promotions={
        getList:function(){
            return list;
        }
    }
}
function initSearch($)
{
    $=jQuery;
    var view=$("#CRITERIAS");
    var locked=true;
    var injectContext=null;
    var initialContext=null;
    var firstRunParams={};
    var pageTitle="Occasions du Lion - Rechercher un véhicule";
    var defaultTitle=window.document.title;
    //    var co=zapette.Common;
    co.getMinMaxContext();
    var suggest=new zapette.FreeText(false,sendFreeSearch);
    function sendFreeSearch(query)

    {
        var hash=query.split("#")[1];
        if(hash=="")hash=co.NOPARAM;
        $.history.add(hash||"");
        setPageTitle(hash);
        context=(hash!=co.NOPARAM)?hash:"";
        locked=true;
        filterChanged=true;
        getSliderValues(context);
        setSlidersRatios();
        injectContext=context;
        reloadResults();
    }
    view.find(".box a.title").addClass("active").click(clickBlock);
    view.find(".endContainBox").click(clearZapette);
    function clickBlock(e)

    {
        e.preventDefault();
        $(e.target).blur();
        $(this).parents(".box").zapetteToggleBlock();
    }
    $.fn.zapetteToggleBlock=function(forceOpen){
        if(locked)
            return this;
        $.each(this,function(){
            if(forceOpen)
                $(this).find("a.title").addClass("active").end().find(".boxContent").slideDown();
            else{
                $(this).find("a.title").toggleClass("active");
                if($(this).find("a").attr("title")!='Equipements'){
                    $(this).find(".boxContent").slideToggle();
                }
                else{
                    if(!$(this).find("a.title").hasClass("active")){
                        loadZapetteEquipement();
                    }
                    else{
                        $("ul#ulEquipementList li").remove();
                        $(this).find(".boxContent").slideToggle();
                    }
                }
            }
        });
        return this;
    }
    var panel=new zapette.Panel($("#PANEL"));
    panel.loadingAnim=$("<div class='loading'></div>");
    //    zapette.Panel.PANEL_OFFSET_TOP=-5;
    function getMenuTop()
    {
        if(zapette.DropDown.current)
            return zapette.DropDown.current.domElement.parents(".box").position().top+zapette.Panel.PANEL_OFFSET_TOP;else return 0;
    }
    var viewType="liste";
    var orderBy="prixttc_asc";
    var pageSize=12;
    var pageIndex=0;
    var filterChanged=true;
    var pdvID=0;
    var promoSelection=[];
    var brandData;
    var brandSelection=[];
    var modelData;
    var modelSelection=[];
    var motorData;
    var motorSelection=[];
    var versionData;
    var versionSelection=[];
    var licenceData;
    var licenceSelection=[];
    var reservablesData;
    var reservablesSelection=[];
    var variantData;
    var variantSelection=[];
    var gearboxData;
    var gearboxSelection=[];
    var energyData;
    var energySelection=[];
    var colorData;
    var colorSelection=[];
    var equipData;
    var equipSelection=[];
    var warrantyData;
    var warrantySelection=[];
    var budgetData={
        byPrice:true,
        priceMin:co.PRICE_MIN,
        priceMax:co.PRICE_MAX,
        monthly:co.MONTHLY_MAX
    };

    var locaData={
        radius:co.DISTANCE_MAX,
        value:"",
        codepostal:""
    };

    var kmData={
        value:co.KM_MAX
    };

    var ageData={
        value:co.AGE_MAX
    };

    var co2Data={
        value:0
    };

    var timerRefresh;
    var updateToken=null;
    var resultsToken=null;
    var statsToken=null;
    var lastSearchSummary="";
    function initZapette()
    {
        $(window).history(historyChange);
        var hash=unescape($.history.getCurrent());
        if(hash.length>0||!context||context.length<2)

        {
            if(hash==co.NOPARAM)hash="";
            getSliderValues(hash);
            filterChanged=true;
            hash=co.serializeParams(firstRunParams);
            injectContext=hash;
            reloadResults();
            firstRunParams.staticContent=false;
        }
        else
        {
            context=context.substr(context.indexOf("?")+1);
            filterChanged=false;
            getSliderValues(context);
            injectContext=co.serializeParams(firstRunParams);
            reloadZapette();
            firstRunParams.staticContent=true;
        }
        initialContext=getContext();
        setPageTitle(initialContext);
    }
    function historyChange(e)
    {
        if($.browser.safari)return;
        var hash=unescape($.history.getCurrent());
        if(hash=="")hash=initialContext;
        if(hash==co.NOPARAM)hash="";
        locked=true;
        filterChanged=false;
        getSliderValues(hash);
        setSlidersRatios();
        injectContext=hash;
        clearTimeout(timerRefresh);
        timerRefresh=setTimeout(reloadResults,500);
    }
    function getSliderValues(s)
    {
        viewType="liste";
        orderBy="prixttc_asc";
        pageSize=12;
        pageIndex=0;
        budgetData.byPrice=true;
        budgetData.priceMin=co.PRICE_MIN;
        budgetData.priceMax=co.PRICE_MAX;
        budgetData.monthly=co.MONTHLY_MAX
        ageData.value=co.AGE_MAX;
        kmData.value=co.KM_MAX;
        co2Data.value=0;
        locaData.value="";
        locaData.codepostal="";
        locaData.radius=co.DISTANCE_DEFAULT;
        firstRunParams=co.parseParams(s);
        for(var name in firstRunParams)

        {
                var value=parseInt(firstRunParams[name]);
                switch(name)

                {
                    case"pdvid":
                        pdvID=value;
                        setFixedLocation();
                        break;
                    case"view":
                        viewType=firstRunParams[name]||"liste";
                        break;
                    case"page":
                        pageIndex=value||0;
                        break;
                    case"pageSize":
                        pageSize=value||12;
                        break;
                    case"orderBy":
                        orderBy=firstRunParams[name]||"prixttc_asc";
                        break;
                    case"prixmin":
                        budgetData.priceMin=value||co.PRICE_MIN;
                        break;
                    case"prixmax":
                        budgetData.priceMax=value||co.PRICE_MAX;
                        break;
                    case"mensualite":
                        budgetData.monthly=value||co.MONTHLY_MAX;
                        budgetData.byPrice=false;
                        break;
                    case"localisation":
                        locaData.value=firstRunParams[name]||"";
                        break;
                    case"codepostal":
                        locaData.codepostal=firstRunParams[name]||"";
                        break;
                    case"radius":
                        locaData.radius=value||co.DISTANCE_DEFAULT;
                        break;
                    case"annee":
                        ageData.value=value?new Date().getFullYear()-value:co.AGE_MAX;
                        break;
                    case"kilometrage":
                        kmData.value=value||co.KM_MAX;
                        break;
                    case"co2max":
                        co2Data.value=value||co.CO2_MAX;
                        break;
                }
            }
        var propChanged=co.compareObjects(co.parseParams(getContext()),firstRunParams);
        for(var i in propChanged)
            if(!isPagingProp(propChanged[i]))filterChanged=true;
    }
    function getContext()
    {
        if(injectContext!=null)

        {
            if(injectContext.indexOf("&view=")>=0)
                return injectContext.substr(0,injectContext.indexOf("&view="));
            else if(injectContext.indexOf("view=")>=0)
                return injectContext.substr(0,injectContext.indexOf("view="));else return injectContext;
        }
        var o={};

        if(pdvID)o.pdvid=pdvID;
        if(brandSelection.length)o.marque=brandSelection;
        if(modelSelection.length)o.modele=modelSelection;
        if(motorSelection.length)o.motorisation=motorSelection;
        if(gearboxSelection.length)o.boite=gearboxSelection;
        if(variantSelection.length)o.silhouette=variantSelection;
        if(versionSelection.length)o.version=versionSelection;
        if(licenceSelection.length)o.licence=licenceSelection;
        if(energySelection.length)o.energie=energySelection;
        if(equipSelection.length)o.equipement=equipSelection;
        if(promoSelection.length)o.promotion=promoSelection;
        if(colorSelection.length)o.couleur=colorSelection;
        if(ageData.value<co.AGE_MAX)o.annee=new Date().getFullYear()-ageData.value;
        if(kmData.value<co.KM_MAX)o.kilometrage=kmData.value;
        if(locaData.value.length){
            o.localisation=locaData.value;
            if(locaData.radius>co.DISTANCE_MIN)o.radius=locaData.radius;
        }
        if(locaData.codepostal.length)o.codepostal=locaData.codepostal;
        if(budgetData.byPrice){
            if(budgetData.priceMin>co.PRICE_MIN)o.prixmin=budgetData.priceMin;
            if(budgetData.priceMax<co.PRICE_MAX)o.prixmax=budgetData.priceMax;
        }
        else if(budgetData.monthly<co.MONTHLY_MAX)o.mensualite=budgetData.monthly;
        if(co2Data.value!=0)o.co2max=co2Data.value;
        if(pageIndex!=0)o.page=pageIndex;
        if(orderBy!="prixttc_asc")o.orderBy=orderBy;
        if(pageSize!=12)o.pageSize=pageSize;
        if(reservablesSelection.length)o.reservable=reservablesSelection;
        return co.serializeParams(o);
    }

    function buildBrandContext(brandName)
    {
        var o={};

        if(brandName)o.marque=brandName;
        return co.serializeParams(o);
    }
    function loadZapetteEquipement(){
        if(updateToken)$.abortWS(updateToken);
        updateToken=zapette.Webservices.getZapetteEquipement(getContext(),updateZapetteEquipement);
        $("#EQUIP").parents(".box").find("div.loading:first").toggle();
    }
    function updateZapetteEquipement(data){
        $("#EQUIP").parents(".box").find("div.loading:first").toggle();
        updateToken=null;
        var map=["brand","model","variant","energy","color","equip",null,null,"promo",null,null,null,null,null,null,null,null,"motor","gearbox","version",null];
        var lists=[];
        var details=[];
        $.each(data.d.ArrayOfCritereArgus,function(){
            var i=this.CritereId-1;
            if(!map[i]||this.Value==null)return;
            if(!lists[i])lists[i]=[];
            if(!details[i])details[i]=[];
            if(this.Selected)lists[i].push(this.Value);
            this.Id=this.Value;
            details[i].push(this);
        });
        rebuildSelection("equip",lists[5],details[5]);
        $("#EQUIP").parents(".box").find(".boxContent").slideToggle();
    }
    function reloadZapette()
    {
        if(updateToken)$.abortWS(updateToken);
        if(equipSelection.length)
            updateToken=zapette.Webservices.updateZapette(getContext(),updateZapette);else
            updateToken=zapette.Webservices.updateZapetteLite(getContext(),updateZapette);
        closeEquipementBox();
        view.find(".firstLoading").show();
        view.find(".endContainBox").hide();
    }
    function closeEquipementBox(){
        if(!equipSelection.length){
            $("ul#ulEquipementList li").remove();
            $("#EQUIP").parents(".box").find(".boxContent").slideUp();
            $("#EQUIP").parents(".box").find("a.title").removeClass("active").addClass("active");
        }
    }
    function updateZapette(data)
    {
        $(".leftColumn .box-first .firstLoading").hide();
        updateToken=null;
        if(data.ExceptionType)
            return;
        if(data==null||data.d==null)return;
        var map=["brand","model","variant","energy","color","equip",null,null,"promo",null,null,null,null,null,null,null,null,"motor","gearbox","version","licence","reservables"];
        var lists=[];
        var details=[];
        $.each(data.d.ArrayOfPromotionCritere,function(){
            var i=8;
            if(!map[i]||this.Value==null)return;
            if(!lists[i])lists[i]=[];
            if(!details[i])details[i]=[];
            if(this.Selected)lists[i].push(this.Id);
            details[i].push(this);
        });
        $.each(data.d.ArrayOfCritereArgus,function(){
            var i=this.CritereId-1;
            if(!map[i]||this.Value==null)return;
            if(!lists[i])lists[i]=[];
            if(!details[i])details[i]=[];
            if(this.Selected)lists[i].push(this.Value);
            this.Id=this.Value;
            details[i].push(this);
        });
        $.each(map,function(i,name){
            rebuildSelection(name,lists[i],details[i]);
        });
        map=["age",null,"price",null,"km"];
        $.each(data.d.ArrayOfSliders,function(){
            var i=this.CritereId-9;
            if(!map[i])return;
            setSliderMinMaxIndicators(map[i],this);
        });
        if(locked)

        {
            locked=false;
            injectContext=null;
            view.find(".box-expand").zapetteToggleBlock(true);
            resultsHelper.setEnabled(true);
        }
        view.find(".firstLoading").hide();
        view.find(".endContainBox").show();
        var hasBrand=brandSelection.length;
        var params=buildBrandContext("Peugeot");
        $("#versionCritereBox").attr("style","display: none;");
        co.loadWS("getModele",params,function(data){
            var hasBrandPeugeot=false;
            var hasModelPeugeot=false;
            $.each(brandSelection,function(){
                if(this=="Peugeot")hasBrandPeugeot=true;
            });
            if(hasBrandPeugeot){
                $.each(modelSelection,function(){
                    var model=this;
                    $.each(data.d,function(){
                        if(this.Value==model)hasModelPeugeot=true;
                    });
                    if(hasBrandPeugeot&&hasModelPeugeot){
                        $("#versionCritereBox").attr("style","display: block;");
                    }
                });
            }
        });
        modelMenu.setEnabled(hasBrand);
        motorMenu.setEnabled(hasBrand);
        versionMenu.setEnabled(hasBrand);
    }
    function clearZapette(e)
    {
        e.preventDefault();
        $(this).blur();
        getSliderValues("");
        filterChanged=true;
        setSlidersRatios();
        rebuildSelection("promo");
        rebuildSelection("brand");
        rebuildSelection("reservables");
        rebuildSelection("model");
        rebuildSelection("motor");
        rebuildSelection("version");
        rebuildSelection("licence");
        rebuildSelection("variant");
        rebuildSelection("gearbox");
        rebuildSelection("energy");
        rebuildSelection("color");
        rebuildSelection("equip");
        reloadResults();
    }
    function reloadStats()
    {
        if(statsToken)$.abortWS(statsToken);
        statsToken=zapette.Webservices.getMaRechercheEtSuggestions(getContext(),updateStats);
    }
    function updateStats(data)
    {
        if(data.ExceptionType||!data.d)return;
        var msg=(data.d.Nombre>1)?"véhicules correspondants":"véhicule correspondant";
        lastSearchSummary=data.d.MaRecherche;
        $(".recordsInfos").find("h2").html("<em>"+co.niceNumber(data.d.Nombre)+"</em> "+msg).end().find("p").removeClass("loading").html(lastSearchSummary);
        var list="<ul>";
        if(!data.d.Suggestions||!data.d.Suggestions.length)
            list+="<li class='empty'>Aucune suggestion</li>";else
            $.each(data.d.Suggestions,function(index,value){
                list+="<li>"+value+"</li>";
            });
        list+="</ul>";
        $("#Suggestions ul").remove();
        $("#Suggestions .inner ").append($(list));
        resultsHelper.updatePaging(data.d.Nombre);
    }
    function uiDataChanged(name)
    {
        if(locked)return;
        if(!isPageSafeProp(name))

        {
            pageIndex=0;
            resultsHelper.setPageIndex(1,true);
        }
        var delay=600;
        if(!isFilteringProp(name))

        {
            if(isPagingProp(name))delay=200;
            filterChanged=false;
        }
        else filterChanged=true;
        clearTimeout(timerRefresh);
        timerRefresh=setTimeout(reloadResults,delay);
    }
    function isPageSafeProp(name)
    {
        return name=="page"||name=="view";
    }
    function isFilteringProp(name)
    {
        return(name!="view"&&name!="orderBy"&&name!="pageSize"&&name!="page"&&name!="localisation");
    }
    function isPagingProp(name)
    {
        return!(name!="view"&&name!="orderBy"&&name!="pageSize"&&name!="page");
    }
    function reloadResults()
    {
        if(updateToken)$.abortWS(updateToken);
        if(resultsToken)$.abortWS(resultsToken);
        if(statsToken)$.abortWS(statsToken);
        updateToken=resultsToken=statsToken=null;
        $(".recordsInfos").find("p").addClass("loading").html("Chargement en cours...");
        var context=getContext();
        var hash=context;
        if(hash=="")hash=co.NOPARAM;
        if(viewType!="liste")hash+="&view="+viewType;
        if(hash!=$.history.getCurrent())

        {
            $.history.add(hash||"");
            setPageTitle(hash);
        }
        $(".SEARCH .vehiclesContent .vehiclesInner").css({
            opacity:0.5
        });
        if(viewType=="carte")

        {
            resultsToken=zapette.Webservices.getPointVenteListBySearchContext(context,1,updateResults);
            $(".headerView").css("height","auto");
            $(".sortingType").hide();
        }
        else{
            resultsToken=zapette.Webservices.searchVehicle(context,orderBy,pageIndex,pageSize,updateResults);
            $(".headerView").css("height","115px");
            $(".sortingType").show();
        }
        clearTimeout(timerRefresh);
        if(filterChanged)timerRefresh=setTimeout(reloadStats,100);
    }
    function updateResults(data)
    {
        resultsToken=null;
        resultsHelper.updateList(data,getContext(),orderBy);
        if(!filterChanged)
            $(".recordsInfos").find("p").removeClass("loading").html(lastSearchSummary);
        if(filterChanged)reloadZapette();
        setTimeout("zapette.FloodlightSearch()",200);
        setTimeout(setPageTitle,1000);
        setTimeout(setPageTitle,2000);
    }

    var brandMenu=new zapette.DropDown($("#BRAND"),showBrands);
    var modelMenu=new zapette.DropDown($("#MODEL"),showModels);
    var motorMenu=new zapette.DropDown($("#MOTOR"),showMotors);
    var versionMenu=new zapette.DropDown($("#VERSION"),showVersions);
    var licenceMenu=new zapette.DropDown($("#LICENCE"),showLicences);
    var reservablesMenu=new zapette.DropDown($("#RESERVABLES"),showReservables);
    var variantMenu=new zapette.DropDown($("#VARIANT"),showVariants);
    var gearboxMenu=new zapette.DropDown($("#GEARBOX"),showGearboxes);
    var energyMenu=new zapette.DropDown($("#ENERGY"),showEnergies);
    var colorMenu=new zapette.DropDown($("#COLOR"),showColors);
    var equipMenu=new zapette.DropDown($("#EQUIP"),showEquipments);
    var warrantyMenu=new zapette.DropDown($("#WARRANTY"),showWarranties);
    var brandTitle="<strong>Marques :</strong> Veuillez sélectionner une ou plusieurs marques";
    var modelTitle="<strong>Modèles :</strong> Veuillez sélectionner un ou plusieurs modèles";
    var motorTitle="<strong>Motorisation :</strong> Veuillez sélectionner une ou plusieurs motorisations";
    var gearboxTitle="<strong>Boite de vitesses :</strong> Veuillez choisir une ou plusieurs boites de vitesses";
    var variantTitle="<strong>Silhouettes :</strong> Veuillez sélectionner une ou plusieurs silhouettes";
    var versionTitle="<strong>Versions :</strong> Veuillez sélectionner un ou plusieurs type d'offre";
    var licenceTitle="<strong>Type offre :</strong> Veuillez sélectionner une ou plusieurs versions";
    var energyTitle="<strong>Energie :</strong> Veuillez sélectionner une ou plusieurs énergies";
    var colorTitle="<strong>Couleur :</strong> Veuillez sélectionner une ou plusieurs couleurs";
    var equipTitle="<strong>Equipement :</strong> Veuillez sélectionner un ou plusieurs équipement";
    var warrantyTitle="<strong>Garantie :</strong> Veuillez sélectionner une ou plusieurs option de garantie";
    var currentFocus=null;
    var suggestLoca;
    var distSlider;
    var priceSlider;
    var monthlySlider;
    var kmSlider;
    var ageSlider;
    var co2Select;
    function showError(data)
    {
        panel.showTemplate(getMenuTop(),"<strong>Erreur serveur :</strong>","ERROR_TEMPLATE",data.obj);
        panel.domElement.find(".validateBtn").hide();
    }
    function showListSelector(data)
    {
        if(data.ExceptionType)
            return showError(data);
        eval(currentFocus+"Data = data");
        panel.showList(getMenuTop(),eval(currentFocus+"Title"),data,eval(currentFocus+"Selection"));
        panel.onValidate=validateListCriteria;
        if(currentFocus=="variant"||currentFocus=="energy"||currentFocus=="equip")
            panel.domElement.find("ul").addClass("twoColumns");
    }
    function validateListCriteria(result)
    {
        var menu=eval(currentFocus+"Menu");
        menu.reset();
        if(co.selectionChanged(result.list,eval(currentFocus+"Selection")))

        {
            rebuildSelection(currentFocus,result.list,result.detail);
            uiDataChanged("distance");
        }
    }
    function rebuildSelection(name,list,detail)
    {
        if(!name)return;
        if(!list)list=[];
        if(!detail)detail=[];
        eval(name+"Selection = list");
        var data={
            group:name,
            list:list,
            detail:detail
        }
        var ul;
        if(name=="promo")ul=$("#PROMOTION");else ul=eval(name+"Menu").domElement.parents(".box").find("ul");
        ul.empty().setTemplateElement("SELECTION_TEMPLATE").processTemplate(data).find("a").bind("click",toggleCriteria);
    }
    function toggleCriteria(e)
    {
        e.preventDefault();
        var item=$(this);
        var name=item.attr("name");
        var selection=eval(name+"Selection");
        var id=item.attr("id");
        id=id.substr(id.indexOf("-")+1);
        if(item.hasClass("checkbox-checked"))

        {
            $.each(selection,function(index,value){
                if(value==id)

                {
                    selection.splice(index,1);
                    return false;
                }
            });
            if(name=="promo")

            {
                item.removeClass("checkbox-checked");
                item.attr("title","Ajouter ce critère");
            }
            else
            {
                if(selection.length==0)
                    item.parents("li").html("<p>(Indifférent)</p>");else item.parents("li").slideUp("fast");
            }
        }
        else
        {
            item.addClass("checkbox-checked");
            item.attr("title","Supprimer ce critère");
            selection.push(id);
        }
        uiDataChanged(name);
    }
    function setSliderMinMaxIndicators(name,params)
    {
        var slider=eval(name+"Slider");
        if(!slider)return;
        slider.setMinMaxIndicators(params.Min,params.Max);
    }
    function initOptions()
    {
        view.find(".promotionBoxContent a").click(toggleOption);
    }
    function toggleOption(e)
    {
        e.preventDefault();
        $(e.target).blur();
        $(this).toggleClass("checkbox-checked");
        promoSelection=[];
        view.find(".promotionBoxContent a.checkbox-checked").each(function(){
            promoSelection.push($(this).find("span").html());
        });
        uiDataChanged("promo");
    }
    function showBrands()
    {
        currentFocus="brand";
        var params=getContext();
        if(co.loadWS("getMarque",params,showListSelector))
            panel.select(brandMenu);
    }
    function showModels()
    {
        if(!brandSelection.length)
            return;
        currentFocus="model";
        var params=getContext();
        if(co.loadWS("getModele",params,showListSelector))
            panel.select(modelMenu);
    }
    function showMotors()
    {
        if(!brandSelection.length)
            return;
        currentFocus="motor";
        onListChanged=null;
        var params=getContext();
        if(co.loadWS("getMotorisation",params,showListSelector))
            panel.select(motorMenu);
    }
    function showGearboxes()
    {
        currentFocus="gearbox";
        onListChanged=null;
        var params=getContext();
        if(co.loadWS("getBoite",params,showListSelector))
            panel.select(gearboxMenu);
    }
    function showVariants()
    {
        currentFocus="variant";
        onListChanged=null;
        var params=getContext();
        if(co.loadWS("getSilhouette",params,showListSelector))
            panel.select(variantMenu);
    }
    function showVersions()
    {
        if(!brandSelection.length)
            return;
        currentFocus="version";
        onListChanged=null;
        var params=getContext();
        if(co.loadWS("getVersion",params,showListSelector))
            panel.select(versionMenu);
    }
    function showLicences()
    {
        if(!brandSelection.length)
            return;
        currentFocus="licence";
        onListChanged=null;
        var params=getContext();
        if(co.loadWS("getLicence",params,showListSelector))
            panel.select(licenceMenu);
    }
    function showReservables()
    {}
    function initLocalization()
    {
        if(pdvID)
            return;
        var field=$("#LOCATION");
        field.attr("autocomplete","off").parents(".box").css({
            zIndex:1
        });
        suggestLoca=new zapette.SuggestLocation(field,"propositionsLocalisation",206);
        suggestLoca.onChanged=onLocationChange;
        suggestLoca.onSubmit=setLocation;
        function onLocationChange(location)

        {
            if(location!=null&&location.length>0)
                $("#LOCATION").val(location);
        }
        field.parent().find("a.checkbox").click(clearLocation);
        function clearLocation(e)

        {
            e.preventDefault();
            if(locaData.value!="")

            {
                $("#LOCATION").val("");
                suggestLoca.location="";
                suggestLoca.query="";
                setLocation();
            }
        }
        $("#SETLOCATION").click(setLocation);
        function setLocation(e)
        {
            if(e)e.preventDefault();
            $(this).blur();
            if(suggestLoca.query!=null&&suggestLoca.query.length>0)

            {
                var obj=co.parseParams(suggestLoca.query);
                locaData.value=obj.localisation||"";
                locaData.codepostal=obj.codepostal||"";
                onLocationChange(suggestLoca.location);
                $("#LOCATION").parents(".searchBoxSmall").addClass("locationFilled");
            }
            else
            {
                locaData.value=locaData.codepostal="";
                $("#LOCATION").parents(".searchBoxSmall").removeClass("locationFilled");
            }
            uiDataChanged("localization");
            return false;
        }
        var dist=$("#SLIDER_DISTANCE");
        distSlider=new ui.Slider("#SLIDER_DISTANCE",distChanged);
        function distChanged(ratio)
        {
            var value=co.roundNumber(co.DISTANCE_MIN+(co.DISTANCE_MAX-co.DISTANCE_MIN)*ratio);
            if(ratio==0)dist.find("p").html("Annonces à proximité");else dist.find("p").html("Annonces à moins de <strong>"+co.niceNumber(value)+" km</strong>");
            locaData.radius=value;
            if(locaData.value.length>0)uiDataChanged("radius");
        }
    }
    function setFixedLocation()
    {
        suggest.pdvID=pdvID;
        var container=$("#SLIDER_DISTANCE").parent();
        var name=$(".dealerName h2").html();
        var address=$(".dealerLocation p").html();
        container.empty().html('<div class="address">\
             <p><strong>'+name+'</strong></p>\
             <p>'+address+'</p>\
             <p><a href="/Votre-point-de-vente.aspx">Changer de point de vente</a></p>\
             </div>');
    }
    function initBudget()
    {
        $("#SLIDER_PRICE .pictoTip").simpletooltip().click(co.SILENT);
        var monthly=$("#SLIDER_MONTHLY");
        monthlySlider=new ui.Slider("#SLIDER_MONTHLY",monthlyChanged);
        monthlySlider.onSelect=monthlySwitch;
        function monthlySwitch()

        {
            budgetData.byPrice=false;
            priceSlider.setFaded(true,true);
            uiDataChanged("budget");
        }
        function monthlyChanged(ratio)
        {
            monthlyValue=co.roundNumber(co.MONTHLY_MIN+ratio*(co.MONTHLY_MAX-co.MONTHLY_MIN),10);
            if(ratio==1)
                monthly.find("p").html("<em>Mensualité</em>* : indifférent");else
                monthly.find("p").html("<em>Mensualité</em>* : jusqu'à <strong>"+co.niceNumber(monthlyValue)+" €</strong>");
            budgetData.monthly=monthlyValue;
            uiDataChanged("budget");
        }
        var price=$("#SLIDER_PRICE");
        priceSlider=new ui.Slider("#SLIDER_PRICE",priceChanged);
        priceSlider.onSelect=priceSwitch;
        function priceSwitch()

        {
            budgetData.byPrice=true;
            monthlySlider.setFaded(true,true);
            uiDataChanged("budget");
        }
        function priceChanged(ratio,ratioMin)
        {
            priceMin=co.roundNumber(co.PRICE_MIN+ratioMin*(co.PRICE_MAX-co.PRICE_MIN),100);
            priceMax=co.roundNumber(co.PRICE_MIN+ratio*(co.PRICE_MAX-co.PRICE_MIN),100);
            if(priceMin==co.PRICE_MIN&&priceMax==co.PRICE_MAX)
                price.find("p").html('Prix : indifférent');
            else if(priceMin==co.PRICE_MIN)
                price.find("p").html('Prix : jusqu\'à <strong class="max">'+co.niceNumber(priceMax)+" €</strong>");
            else if(priceMax==co.PRICE_MAX)
                price.find("p").html('Prix : à partir de <strong class="min">'+co.niceNumber(priceMin)+" €</strong>");else
                price.find("p").html('Prix : entre <strong class="min">'+co.niceNumber(priceMin)
                    +' €</strong> et <strong class="max">'+co.niceNumber(priceMax)+" €</strong>");
            budgetData.priceMin=priceMin;
            budgetData.priceMax=priceMax;
            uiDataChanged("budget");
        }
        if(budgetData.byPrice)monthlySlider.setFaded(true);else priceSlider.setFaded(true);
    }
    function initKm()
    {
        var km=$("#SLIDER_KM");
        kmSlider=new ui.Slider("#SLIDER_KM",kmChanged);
        kmSlider.setFaded();
        function kmChanged(ratio)

        {
            var value=co.roundNumber(co.KM_MIN+ratio*(co.KM_MAX-co.KM_MIN),1000);
            if(ratio==1)km.find("p").html("Indifférent");else km.find("p").html("Inférieur à : <strong>"+co.niceNumber(value)+" km</strong>");
            kmData.value=value;
            uiDataChanged("km");
        }
    }
    function initAge()
    {
        var age=$("#SLIDER_AGE");
        ageSlider=new ui.Slider("#SLIDER_AGE",ageChanged);
        ageSlider.setFaded(true);
        function ageChanged(ratio)

        {
            var value=co.roundNumber(co.AGE_MIN+ratio*(co.AGE_MAX-co.AGE_MIN));
            if(ratio==1)age.find("p").html("Indifférent");else age.find("p").html("Inférieur à : <strong>"+co.niceNumber(1+ratio*7)+" ans</strong>");
            ageData.value=value;
            uiDataChanged("age");
        }
    }
    function initCO2()
    {
        co2Select=new zapette.SelectCO2(view.find(".co2Selector"));
        co2Select.onChanged=function(value)

        {
            co2Data.value=value;
            uiDataChanged("co2");
        }
    }
    function initEnergy()
    {
        if(firstRunParams["energie"])
            $("#ENERGY").parents(".box").addClass("box-expand");
    }
    function showEnergies()
    {
        currentFocus="energy";
        var params=getContext();
        if(co.loadWS("getEnergie",params,showListSelector))
            panel.select(energyMenu);
    }
    function initColor()
    {
        if(firstRunParams["couleur"])
            $("#COLOR").parents(".box").addClass("box-expand");
    }
    function showColors()
    {
        currentFocus="color";
        var params=getContext();
        if(co.loadWS("getCouleur",params,showListSelector))
            panel.select(colorMenu);
    }
    function initEquip()
    {
        if(firstRunParams["equipement"])
            $("#EQUIP").parents(".box").addClass("box-expand");
    }
    function showEquipments()
    {
        currentFocus="equip";
        var params=getContext();
        if(co.loadWS("getEquipement",params,showListSelector))
            panel.select(equipMenu);
    }
    function showWarranties()
    {
        currentFocus="warranty";
        var params=getContext();
        if(co.loadWS("getGarantie",params,showListSelector))
            panel.select(warrantyMenu);
    }
    function setSlidersRatios()
    {
        monthlySlider.setRatio((budgetData.monthly-co.MONTHLY_MIN)/(co.MONTHLY_MAX-co.MONTHLY_MIN));
        priceSlider.setRatio((budgetData.priceMax-co.PRICE_MIN)/(co.PRICE_MAX-co.PRICE_MIN),(budgetData.priceMin-co.PRICE_MIN)/(co.PRICE_MAX-co.PRICE_MIN));
        if(distSlider)

        {
            if(locaData.value.length>0)
                distSlider.setRatio((co.DISTANCE_DEFAULT-co.DISTANCE_MIN)/(co.DISTANCE_MAX-co.DISTANCE_MIN));else
                distSlider.setRatio((locaData.radius-co.DISTANCE_MIN)/(co.DISTANCE_MAX-co.DISTANCE_MIN));
        }
        kmSlider.setRatio((kmData.value-co.KM_MIN)/(co.KM_MAX-co.KM_MIN));
        ageSlider.setRatio((ageData.value-co.AGE_MIN)/(co.AGE_MAX-co.AGE_MIN));
        co2Select.setValue(co2Data.value);
        if(locaData.codepostal.length)
            $("#LOCATION").val(locaData.value+" ("+locaData.codepostal+")");else
            $("#LOCATION").val(locaData.value);
        if(locaData.value.length)
            $("#LOCATION").parents(".searchBoxSmall").addClass("locationFilled");else
            $("#LOCATION").parents(".searchBoxSmall").removeClass("locationFilled");
        if(ageData.value!=co.AGE_MAX)
            $("#SLIDER_AGE").parents(".box").addClass("box-expand");
        if(kmData.value!=co.KM_MAX)
            $("#SLIDER_KM").parents(".box").addClass("box-expand");
        if(co2Data.value!=0)
            $(co2Select.domElement).parents(".box").addClass("box-expand");
        if(resultsHelper)
            resultsHelper.updateState(viewType,orderBy,pageSize,pageIndex+1);
    }
    var currentTitle;
    function setPageTitle(hash)
    {
        if(hash)

        {
            if(hash==co.NOPARAM||pdvID)currentTitle=defaultTitle;else currentTitle=pageTitle;
        }
        if(currentTitle)window.document.title=currentTitle;
    }
    var resultsHelper;
    $(function()

    {
            initZapette();
            initOptions();
            initLocalization();
            initBudget();
            initKm();
            initAge();
            initCO2();
            initEnergy();
            initColor();
            initEquip();
            setSlidersRatios();

            resultsHelper=new viewHelper.VehicleList(firstRunParams);
            resultsHelper.onViewType=function(view)

            {
                viewType=view;
                uiDataChanged("view");
            }
            resultsHelper.onSortMode=function(mode)
            {
                orderBy=mode;
                uiDataChanged("orderBy");
            }
            resultsHelper.onPageSize=function(size)
            {
                pageSize=size;
                uiDataChanged("pageSize");
            }
            resultsHelper.onPageIndex=function(index)
            {
                pageIndex=index;
                uiDataChanged("page");
            }
        });
}
﻿
zapette.SelectCO2=function(domElement)
{
    var self=this;
    var $=jQuery;
    var view=$(domElement);
    var currentIndex=-1;
    var values=[100,120,140,160,200,250];
    this.domElement=domElement;
    this.onChanged=null;
    this.setValue=function(value)

    {
        currentIndex=-1;
        for(var i=0;i<values.length;i++)
            if(values[i]==value)
            {
                currentIndex=i;
                break;
            }
        setState(currentIndex);
    }
    view.find("ul li").hover(overItem,outItem).click(setIndex).each(function(index){
        this._index=index;
    });
    function setIndex()

    {
        currentIndex=this._index<6?this._index:-1;
        setState(currentIndex);
        var value=currentIndex<0?0:values[currentIndex];
        if(self.onChanged)
            self.onChanged(value||0);
    }
    function overItem()
    {
        setState(this._index);
    }
    function outItem()
    {
        if(currentIndex<6)setState(currentIndex);else setState(-1);
    }
    function setState(index)
    {
        view.find("ul").css({
            backgroundPosition:"0 "+(-33*(6-index))+"px"
        });
        var tip=view.find(".co2tip");
        if(index<0)

        {
            tip.css({
                left:63
            }).find(".arrow").css({
                left:54
            }).end().find("p").html("Indifférent")
        }
        else
        {
            tip.css({
                left:110*index/6+8
            }).find(".arrow").css({
                left:22+64*index/6
            }).end().find("p").html($(view.find("ul li").get(index)).html())
        }
    }
}
﻿
zapette.FloodlightSearch=function()
{
    var axel=Math.random()+"";
    var a=axel*10000000000000;
    var src='<ifr'+'ame src="https://fls.doubleclick.net/activityi;src=1620812;type=minsit09;cat=ptvol09;u5=occasions_du_lion;u8='+SessionID+';ord='+a+'" %>?" width="1" height="1" frameborder="0"></ifr'+'ame>';
    if(!zapette.__tracking)
        zapette.__tracking=$('<div style="position:absolute; top:0; left;0; width:1px; height:1px; overflow:hidden; visibility:hidden"></div>').appendTo(document.body);
    zapette.__tracking.html(src);
}
zapette.__tracking=null;
zapette.Webservices={
    forgotPassword:function(email,callback){
        var data=zapette.Common.serializeJSON({
            email:email
        });
        return jQuery.callWS("User","ForgotPassword",data,callback);
    },
    identifier:function(email,password,currentSelection,callback){
        var data=zapette.Common.serializeJSON({
            email:email,
            password:password,
            currentSelection:currentSelection
        });
        return jQuery.callWS("User","Identifier",data,callback);
    },
    getCriteres:function(input,maxNumberOfRecords,callback){
        var data=zapette.Common.serializeJSON({
            freeTextInput:input
        });
        return jQuery.callWS("SearchEngine","GetCriteres",data,callback);
    },
    getCouleur:function(searchContext,callback){
        var data=zapette.Common.serializeJSON({
            searchContext:searchContext
        });
        return jQuery.callWS("Zapette","GetCouleurByQueryString",data,callback);
    },
    getEnergie:function(searchContext,callback){
        var data=zapette.Common.serializeJSON({
            searchContext:searchContext
        });
        return jQuery.callWS("Zapette","GetEnergieByQueryString",data,callback);
    },
    getEquipement:function(searchContext,callback){
        var data=zapette.Common.serializeJSON({
            searchContext:searchContext
        });
        return jQuery.callWS("Zapette","GetEquipementByQueryString",data,callback);
    },
    getMarque:function(searchContext,callback){
        var data=zapette.Common.serializeJSON({
            searchContext:searchContext
        });
        return jQuery.callWS("Zapette","GetMarqueByQueryString",data,callback);
    },
    getModele:function(searchContext,callback){
        var data=zapette.Common.serializeJSON({
            searchContext:searchContext
        });
        return jQuery.callWS("Zapette","GetModeleByQueryString",data,callback);
    },
    getMotorisation:function(searchContext,callback){
        var data=zapette.Common.serializeJSON({
            searchContext:searchContext
        });
        return jQuery.callWS("Zapette","GetMotorisationByQueryString",data,callback);
    },
    getBoite:function(searchContext,callback){
        var data=zapette.Common.serializeJSON({
            searchContext:searchContext
        });
        return jQuery.callWS("Zapette","GetBoiteByQueryString",data,callback);
    },
    getSilhouette:function(searchContext,callback){
        var data=zapette.Common.serializeJSON({
            searchContext:searchContext
        });
        return jQuery.callWS("Zapette","GetSilhoutteByQueryString",data,callback);
    },
    getVersion:function(searchContext,callback){
        var data=zapette.Common.serializeJSON({
            searchContext:searchContext
        });
        return jQuery.callWS("Zapette","GetVersionByQueryString",data,callback);
    },
    getLicence:function(searchContext,callback){
        var data=zapette.Common.serializeJSON({
            searchContext:searchContext
        });
        return jQuery.callWS("Zapette","GetLicenceByQueryString",data,callback);
    },
    getModeles:function(searchContext,callback){
        var data=zapette.Common.serializeJSON({
            searchContext:searchContext
        });
        return jQuery.callWS("Zapette","GetModeleByQueryString",data,callback);
    },
    getGarantie:function(searchContext,callback){
        var data=zapette.Common.serializeJSON({
            searchContext:searchContext
        });
        return jQuery.callWS("Zapette","GetGarantieByQueryString",data,callback);
    },
    getLocalisation:function(localisation,maxNumberOfRecords,callback){
        var data=zapette.Common.serializeJSON({
            localisation:localisation,
            maxNumberOfRecords:maxNumberOfRecords
        });
        return jQuery.callWS("Zapette","GetLocalisation",data,callback);
    },
    propositionsLocalisation:function(input,maxNumberOfRecords,callback){
        var data=zapette.Common.serializeJSON({
            input:input,
            maxNumberOfRecords:maxNumberOfRecords
        });
        return jQuery.callWS("Zapette","PropositionsLocalisation",data,callback);
    },
    updateZapette:function(searchContext,callback){
        var data=zapette.Common.serializeJSON({
            searchContext:searchContext
        });
        return jQuery.callWS("Zapette","UpdateZapetteByQueryString",data,callback);
    },
    updateZapetteLite:function(searchContext,callback){
        var data=zapette.Common.serializeJSON({
            searchContext:searchContext
        });
        return jQuery.callWS("Zapette","UpdateZapetteLiteByQueryString",data,callback);
    },
    getZapetteEquipement:function(searchContext,callback){
        var data=zapette.Common.serializeJSON({
            searchContext:searchContext
        });
        return jQuery.callWS("Zapette","GetZapetteEquipementByQueryString",data,callback);
    },
    searchVehicle:function(searchContext,orderBy,pageIndex,pageSize,callback){
        var data=zapette.Common.serializeJSON({
            searchContext:searchContext,
            orderBy:orderBy,
            pageIndex:pageIndex,
            pageSize:pageSize
        });
        return jQuery.callWS("Vehicle","SearchVehicle",data,callback);
    },
    getMaRechercheEtSuggestions:function(searchContext,callback){
        var data=zapette.Common.serializeJSON({
            searchContext:searchContext
        });
        return jQuery.callWS("Vehicle","GetMaRechercheEtSuggestions",data,callback);
    },
    addToMySelection:function(vehicleId,callback){
        var data=zapette.Common.serializeJSON({
            vehicleId:vehicleId
        });
        return jQuery.callWS("MySelection","AddToMySelection",data,callback);
    },
    removeFromMySelection:function(vehicleId,callback){
        var data=zapette.Common.serializeJSON({
            vehicleId:vehicleId
        });
        return jQuery.callWS("MySelection","RemoveFromMySelection",data,callback);
    },
    getPointVenteListBySearchContext:function(searchContext,havingVehicles,callback){
        var data=zapette.Common.serializeJSON({
            searchContext:searchContext,
            havingVehicles:havingVehicles
        });
        return jQuery.callWS("GoogleMaps","GetPointVenteListBySearchContext",data,callback);
    },
    getPropositions:function(input,maxNumberOfRecords,callback){
        var data=zapette.Common.serializeJSON({
            input:input,
            maxNumberOfRecords:maxNumberOfRecords
        });
        return jQuery.callWS("GoogleMaps","GetPropositions",data,callback);
    },
    getOffreDetails:function(callback){
        var data=zapette.Common.serializeJSON({});
        return jQuery.callWS("SimulateurFinancement","GetOffreDetails",data,callback);
    },
    getBudgetMinMax:function(code,value,callback){
        var data=zapette.Common.serializeJSON({
            code:code.toString(),
            value:value.toString()
        });
        return jQuery.callWS("SimulateurFinancement","GetBudgetMinMax",data,callback);
    },
    getMensualiteFromVehicule:function(idVehicule,callback){
        var data=zapette.Common.serializeJSON({
            idVehicule:idVehicule
        });
        return jQuery.callWS("SimulateurFinancement","GetMensualiteFromVehicule",data,callback);
    },
    getMensualiteFromVehiculeCleanUpString:function(idVehicule,callback){
        var data=zapette.Common.serializeJSON({
            idVehicule:idVehicule
        });
        return jQuery.callWS("SimulateurFinancement","GetMensualiteFromVehiculeCleanUpString",data,callback);
    },
    getUpdatedMensualiteFromPagePerso:function(callback){
        var data=zapette.Common.serializeJSON({});
        return jQuery.callWS("SimulateurFinancement","GetUpdatedMensualiteFromPersoPage",data,callback,true);
    }
}
