﻿SlideFlow = function(elmt) {
    this.containerElement = document.getElementById(elmt);
    this.PosImgC = 241;
    this.ImgName = new Array();
    this.ImgVeh = new Array();
    this.ImgPath = '/vomini/PhotoSlide.aspx?name=';
    this.ImgPathVc = '/vomini/PhotoSlide.aspx?name=';

    this.Is_Collab = false;

    this.imgLeft = new Array();
    this.imgCenter = new Array();
    this.imgRight = new Array();

    this.ImgS = 0;
    this.imgIndex = 0;
    this.imgHeight = 215;
    this.imgWidthNormal = 267;
    this.imgWidthTilted = 245;


    this.LoadImgs = function() {
        // on load le fichier XML
        var xmlDoc;
        var httpReq;

        if (window.XMLHttpRequest && !(window.ActiveXObject)) {
            try {
                httpReq = new XMLHttpRequest();
            } catch (e) {
            }
        }

        if (window.ActiveXObject) { // IE 
            try {
                httpReq = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try {
                    httpReq = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {
                }
            }
        }

        var type = 0;
        var now = new Date();
        var qs = location.search.toQueryParams();
        if (qs.type) type = qs.type;

        // on construit les criteres
        critere = new Array();

        if (qs.concess) critere['concess'] = qs.concess;

        critere['type'] = type;
        critere['carrosserie'] = $('modele_select').value;

        if ($('km_max').value != '150000') critere['kmax'] = $('km_max').value;
        if ($('km_min').value != '0') critere['kmin'] = $('km_min').value;
        if ($('year_max').value != now.getFullYear().toString()) critere['ymax'] = $('year_max').value;
        if ($('year_min').value != '2001') critere['ymin'] = $('year_min').value;
        if ($('price_max').value != '50000') critere['pmax'] = $('price_max').value;
        if ($('price_min').value != '2000') critere['pmin'] = $('price_min').value;

        if (!$('search_enegie_essence').checked || !$('search_enegie_diesel').checked) {
            if ($('search_enegie_essence').checked) critere['energie'] = 1;
            if ($('search_enegie_diesel').checked) critere['energie'] = 2;
        }

        if (!$('transmission_ma').checked || !$('transmission_au').checked) {
            if ($('transmission_ma').checked) critere['transmission'] = 1;
            if ($('transmission_au').checked) critere['transmission'] = 2;
        }

        if ($('search_motorisation').value != 'Type de motorisation') critere['motorisation'] = $('search_motorisation').value;
        /*if ($('search_finition').value != '') critere['finition'] = $('search_finition').value;*/

        optselect = '';
        for (i = 1; i <= 6; ++i) {
            if ($('search_opt_' + i).checked) {
                if (optselect != '') optselect += ',';
                optselect += $('search_opt_' + i).value;
            }
        }
        if (optselect != '') critere['opt'] = optselect;

        var searchLocation = $('search_loc').getAttribute('data-value');
        if (searchLocation != '') critere['loc'] = searchLocation;

        critere['order'] = Search_List_Order;
        critere['orderdir'] = Search_List_Order_Dir;

        url = '/vomini/ajax/Load_Slide.aspx';

        first = true;

        for (key in critere) {
            if (typeof (critere[key]) != 'function') {
                if (first) {
                    url += '?';
                    first = false;
                } else {
                    url += '&';
                }
                url += key + '=' + critere[key];
            }
        }


        httpReq.open("GET", url, false /* sync */);
        httpReq.send(null);
        xmlDoc = httpReq.responseXML;
        if (httpReq.status == 404 || httpReq.status == 403) return '';

        //var photos = xmlDoc.getElementsByTagName("photo");
        //        for (var i=0; i < photos.length; i++) {
        //			this.ImgName[i] = photos.item(i).getElementsByTagName("src")[0].childNodes[0].nodeValue;
        //			this.ImgVeh[i] = photos.item(i).getElementsByTagName("id")[0].childNodes[0].nodeValue;			
        //		}
        //		
        if (this.Is_Collab) this.ImgPath = this.ImgPathVc;
    };
    this.PrepareImgs = function() {
        for (var i = 0; i < this.ImgName.length; ++i) {
            var imgL = new Image;
            imgL.src = this.ImgPath + this.ImgName[i].replace('.jpg', '-l.jpg');
            this.imgLeft.push(imgL);

            var imgC = new Image;
            imgC.src = this.ImgPath + this.ImgName[i].replace('.jpg', '-c.jpg');
            this.imgCenter.push(imgC);

            var imgR = new Image;
            imgR.src = this.ImgPath + this.ImgName[i].replace('.jpg', '-r.jpg');
            this.imgRight.push(imgR);
        }
    };
    this.CreateDiv = function() {
        for (var i = 0; i < this.ImgName.length; ++i) {
            if (!$('divslide' + i)) {
                var newDiv = document.createElement('div');
                newDiv.id = 'divslide' + i;
                newDiv.className = 'preloadImage';
                newDiv.style.display = 'none';
                this.containerElement.appendChild(newDiv);
            } else {
                var newDiv = $('divslide' + i);
                newDiv.className = 'preloadImage';
                newDiv.style.display = 'none';
            }

            if (!$('imgslide' + i)) {
                var newImage = document.createElement('img');
                newImage.id = 'imgslide' + i;
                newImage.style.display = 'none';
                newImage.src = '/vomini/commun/img/slide/transparent.gif';
                newDiv.appendChild(newImage);
            } else {
                var newImage = $('imgslide' + i);
                newImage.style.display = 'none';
                newImage.src = '/vomini/commun/img/slide/transparent.gif';
            }
        }
    };
    this.MoveTo = function(Nb_Mov) {

        if ((this.ImgS + Nb_Mov) < 0) return;
        if ((this.ImgS + Nb_Mov) >= this.ImgName.length) return;

        this.ImgS += Nb_Mov;
        this.imgIndex = this.ImgName.length;

        // on cache les images    
        for (var i = 0; i < this.ImgName.length; ++i) {
            var elmtdiv = document.getElementById('divslide' + i);
            elmtdiv.style.display = 'none';
        }

        for (var i = -3; i <= 3; ++i) {
            if ((this.ImgS + i) >= 0 && (this.ImgS + i) < this.ImgName.length) {

                var elmtimg = document.getElementById('imgslide' + (this.ImgS + i));
                elmtimg.height = this.imgHeight;

                var elmtdiv = document.getElementById('divslide' + (this.ImgS + i));
                elmtdiv.style.display = '';
                elmtdiv.style.position = 'absolute';
                elmtdiv.style.top = '0px';

                switch (i) {
                    case -3:
                        elmtdiv.style.left = (this.PosImgC - 132) + 'px';
                        elmtdiv.style.zIndex = (this.imgIndex + i);
                        elmtimg.width = this.imgWidthTilted;
                        elmtimg.src = this.imgLeft[(this.ImgS + i)].src;
                        elmtimg.onclick = function() { return CurrentSlideFlow.MoveTo(-3); }
                        break;
                    case -2:
                        elmtdiv.style.left = (this.PosImgC - 112) + 'px';
                        elmtdiv.style.zIndex = (this.imgIndex + i);
                        elmtimg.width = this.imgWidthTilted;
                        elmtimg.src = this.imgLeft[(this.ImgS + i)].src;
                        elmtimg.onclick = function() { return CurrentSlideFlow.MoveTo(-2); }
                        break;
                    case -1:
                        elmtdiv.style.left = (this.PosImgC - 71) + 'px';
                        elmtdiv.style.zIndex = (this.imgIndex + i);
                        elmtimg.width = this.imgWidthTilted;
                        elmtimg.src = this.imgLeft[(this.ImgS + i)].src;
                        elmtimg.onclick = function() { return CurrentSlideFlow.MoveTo(-1); }
                        break;
                    case 0:
                        elmtdiv.style.left = this.PosImgC + 'px';
                        elmtdiv.style.zIndex = (this.imgIndex + i);
                        elmtimg.width = this.imgWidthNormal;
                        elmtimg.src = this.imgCenter[(this.ImgS + i)].src;
                        elmtimg.onclick = this.HandleCenterClick;

                        // on load les info de la voiture
                        if ($('info_id').value != this.ImgVeh[(this.ImgS + i)]) {
                            Load_Info(this.ImgVeh[(this.ImgS + i)]);
                        }
                        break;
                    case 1:
                        elmtdiv.style.left = (this.PosImgC + 71) + 'px';
                        elmtdiv.style.zIndex = (this.imgIndex - i);
                        elmtimg.width = this.imgWidthTilted;
                        elmtimg.src = this.imgRight[(this.ImgS + i)].src;
                        elmtimg.onclick = function() { return CurrentSlideFlow.MoveTo(1); }
                        break;
                    case 2:
                        elmtdiv.style.left = (this.PosImgC + 112) + 'px';
                        elmtdiv.style.zIndex = (this.imgIndex - i);
                        elmtimg.width = this.imgWidthTilted;
                        elmtimg.src = this.imgRight[(this.ImgS + i)].src;
                        elmtimg.onclick = function() { return CurrentSlideFlow.MoveTo(2); }
                        break;
                    case 3:
                        elmtdiv.style.left = (this.PosImgC + 132) + 'px';
                        elmtdiv.style.zIndex = (this.imgIndex - i);
                        elmtimg.width = this.imgWidthTilted;
                        elmtimg.src = this.imgRight[(this.ImgS + i)].src;
                        elmtimg.onclick = function() { return CurrentSlideFlow.MoveTo(3); }
                        break;
                }
            }
        }

        // on regarde si -4 +4 si oui on enleve l'index
        var elmtdiv = document.getElementById('divslide' + (this.ImgS - 4));
        if (elmtdiv) elmtdiv.style.zIndex = '0';
        var elmtdiv = document.getElementById('divslide' + (this.ImgS + 4));
        if (elmtdiv) elmtdiv.style.zIndex = '0';

        // on fait bouger le slide
        if (window.CurrentSlide) window.CurrentSlide.f_setValue(this.ImgS, false, true, true);

        // on lance le prelod des images
        var p = new Preloader();

        $$('.preloadImage img')._forEach(
            function(img) {
                p.addEventOnLoad(img.src, function() {
                    img.up().setStyle({ background: 'none' });
                    img.setStyle({ opacity: 0 });
                    img.style.display = '';
                    new Effect.Opacity(img, { from: 0, to: 1, duration: 0.3 });
                    img.up().removeClassName('preloadImage');
                });
                p.addToQueue(img.src);
            });
    };
    this.InitWheel = function() {

        document.onkeydown = this.handleKeys;

        if (window.addEventListener)
        /** DOMMouseScroll is for mozilla. */
            window.addEventListener('DOMMouseScroll', this.wheelHandler, false);

        /** IE/Opera. */
        window.onmousewheel = document.onmousewheel = this.wheelHandler;

        // on insert dans le doc la class
        window.CurrentSlideFlow = document.CurrentSlideFlow = this;
    };
    this.DestroyWheel = function() {
        if (window.addEventListener)
        /** DOMMouseScroll is for mozilla. */
            window.removeEventListener('DOMMouseScroll', this.wheelHandler, false);

        /** IE/Opera. */
        window.onmousewheel = document.onmousewheel = null;
    };
    this.wheelHandler = function(event) {
        var delta = 0;

        /* For IE. */
        if (!event) event = window.event;

        if (event.wheelDelta) {
            /* IE/Opera. */
            delta = event.wheelDelta / 120;
        } else if (event.detail) {
            /** Mozilla case. */
            delta = -event.detail / 3;
        }
        if (delta != 0) this.CurrentSlideFlow.MoveTo(delta > 0 ? 1 : -1);

        if (event.preventDefault) event.preventDefault();
        event.returnValue = false;
    };
    this.handleKeys = function(evt) {
        evt = (evt) ? evt : ((window.event) ? event : null);
        if (evt) {
            //debugLog("key " + evt.keyCode);
            switch (evt.keyCode) {
                case 40: /* down */
                case 39: /* right */
                    this.CurrentSlideFlow.MoveTo(1);
                    return false;
                    break;
                case 38: /* up */
                case 37: /* left */
                    this.CurrentSlideFlow.MoveTo(-1);
                    return false;
                    break;
            }
        }
    };
    this.HandleCenterClick = function() {
        if (window.CurrentSlideFlow) View_Present(window.CurrentSlideFlow.ImgVeh[window.CurrentSlideFlow.ImgS]);
    }
}


var Preloader = new Class.create({

	initialize: function() {
		this._currentlyLoading = '';
		this._loading = false;
		this._imgQueue = [];
		this._loadEvents = {};
		this._loadedImages = {};
	},
	
	addToQueue: function(src) {
		if (this.isLoaded(src) || this.isInQueue(src)) return;
		this._imgQueue.push(src);
		if (!this._loading) this._loadNext();
		return this;
	},

	addToFrontOfQueue: function(src) {
		if (this.isLoaded(src)) return false;
		if (this._currentlyLoading == src) return true;
		this.removeFromQueue(src);
		this._imgQueue.unshift(src);
		if (!this._loading) this._loadNext();
		return true;
	},

	removeFromQueue: function(src) {
		this._imgQueue.remove(src)
		return this;
	},
	
	addEventOnLoad: function(src, fn) {
		this._loadEvents[src] = fn;
		return this;
	},
	
	flushQueue: function() {
		this._imgQueue = [];
		return this;
	},
	
	stopAllEvents: function() {
		this._loadEvents = {};
		return this;
	},
	
	isLoaded: function(src) {
		return !!this._loadedImages[src];
	},
	
	isInQueue: function(src) {
		return (this._currentlyLoading == src || this._imgQueue.contains(src));
		//return (this._currentlyLoading == src || this._imgQueue.find(src));
	},
	
	priorityLoadWithCallback: function(src, fn) {
		this.addEventOnLoad(src, fn);
		if (!this.addToFrontOfQueue(src)){
			this._fireLoadEvent(src); // Already loaded
			return true;
		}
		return false;
	},
	
	_fireLoadEvent: function(src) {
		if (this._loadEvents[src]) this._loadEvents[src].call(this._loadedImages[src]);
		this._loadEvents[src] = null;
	},
	
	_loadNext: function() {
		if (this._imgQueue.length == 0) {
			this._currentlyLoading = '';
			return this._loading = false;
		}
		this._loading = true;
		this._currentlyLoading = this._imgQueue.shift();
		var img = new Element('img');
		var preloader = this;
		img.observe('load', function() {
			preloader._loadedImages[this.src] = this;
			preloader._currentlyLoading = '';
			preloader._fireLoadEvent(this.src);
			setTimeout(function() {
				preloader._loadNext();
			}, 0); //setTimeout for Opera; stops this hogging the javascript thread.
			this.stopObserving('load', arguments.callee);
		});
		img.src = this._currentlyLoading;
	}

});
