//Scripts for handlig ad bucket functions
//Author Asgaut Mjølne

//This is meant to be used on all verticals, all licencees


        var Bucket = {

            //Array for content
			anImage : {},
			currentimage : {},
            content : [],
            cookieBucketName : "",
            bucketName: "",
            maxLength : 0,
            maxLengthDesc : "",
            alreadyInBucketMessage : "",
            arrayAdIds : [],
            cookie_string : "",
        	moveFactor : 0.1,
        	moveDistanceStop : 20,
        	moveDelay : 20,
            steps : 20,
            cachePrefix : "",


            //Extracting the cookie content into the content array
            fill : function (cookieContent) {
                if (cookieContent!="") {
                    var pairs = cookieContent.split("_|_");
                    for (var x=0; x<pairs.length; x++) {
                        var singles = pairs[x].split("$@");
                        this.content.push([singles[0],singles[1],singles[2]]);
                    }
                }
            },

            //Function that extracts the content array, creates html for the bucket, appends it, then setting it into the cookie
            display : function () {

                var d = document.getElementById(this.getBucketName());

				if (d) {
					d.innerHTML = "";

					var cookie_string = "";

                    if(this.content.length == 0) {
                        var container = document.createElement("div");
                        container.style.position="relative";
                        container.style.padding="8px";
                        container.innerHTML = '<div>Din lista är tom. Klicka på <img src="' + this.getCachePrefix() + 'img/add-to-bucket.gif"/> för att lägga till annonser</div>';
                        d.appendChild(container);
                    }

                    for (var x=0; x<this.content.length; x++) {
						cookie_string += this.content[x][0]+"$@"+this.content[x][1]+"$@"+this.content[x][2];

						if (x<this.content.length-1)
							cookie_string += "_|_";

						var container = document.createElement("div");
							container.style.position="relative";
							//container.style.border="1px solid #999";
							container.style.padding="8px";
							container.id=x;

						//Adid
						var element1 = document.createElement("div");
							element1.innerHTML=this.content[x][0];
							//element1.style.border="1px dotted #999";
							container.appendChild(element1);

						//logo
						var element2 = document.createElement("div");
							element2.innerHTML = '<img src="'+ this.content[x][1] +'" />';
							//element2.style.border="1px dotted #999";
							container.appendChild(element2);

						//heading
						var element3 = document.createElement("div");
							element3.innerHTML=unescape(String(this.content[x][2]).replace(/\+/g," "));
							//element3.style.border="1px dotted #999";
							container.appendChild(element3);

						var deleteicon = document.createElement("img");
							deleteicon.src = this.getCachePrefix() + "styles/delete.gif";
							deleteicon.style.position="absolute";
							deleteicon.style.top="8px";
							deleteicon.style.right="8px";
							deleteicon.style.cursor="pointer";
							deleteicon.onclick=function(){
								Bucket.remove(this.parentNode.id);
							}
							container.appendChild(deleteicon);

						d.appendChild(container);

					}
				}

                createCookie(this.getCookieBucketName(),cookie_string);
            },

            //Function for adding the ads into the content. Running display which does most of the job
            add : function (inAdId,heading) {

                if(this.content.length > this.getMaxLength()){
                   alert(this.getMaxLengthDesc());
                } else {
                    var imageSrc = document.getElementById(inAdId).src;

                    if(heading=='')
                    {
                        heading = document.getElementById("headingId_"+ inAdId).innerHTML;
                        heading = heading.replace(/\n/g,"");
                    }

                    if (!this.contains(inAdId))
                    {
                        this.doMagic(inAdId);
                        this.content.push([[inAdId],[imageSrc],[heading]]);
                    }
                    else
                        alert(this.getAlreadyInBucketMessage());
                }

                return false;

            },
            //Function for adding the ads into the content. Running display which does most of the job
            addFromObjectSite : function (inAdId,heading,imageSrc) {

                if(this.content.length > this.getMaxLength()){
                   alert(this.getMaxLengthDesc());
                } else {
                    if (!this.contains(inAdId)){

                        if(imageSrc=="carObjectSite")
                            imageSrc = this.getImageSourceFromElement();
                        else
                        {
                            if(imageSrc.substring(imageSrc.length-1)=="/")
                                imageSrc = this.getCachePrefix() + "img/icon_job.gif";
                        }

                        this.content.push([[inAdId],[imageSrc],[heading]]);
                        this.display();
                    }
                    else
                        alert(this.getAlreadyInBucketMessage());
                }

                return false;

            },
            //The implementation of this function can be different in other licensees due to design of the object site
            getImageSourceFromElement : function(){

                var _span = document.getElementById('content').getElementsByTagName('SPAN');

                    var _images = [];
                    for (var x=0; x<_span.length; x++) {
                        if (_span[x].className == "mmo") {
                            _images = _span[x].getElementsByTagName("IMG");
                            break;
                        }
                    }

                    var _image = "";
                    if (_images.length > 0) {
                        _image = (!_images[0].src.match(/.gif/)) ? _images[0].src.replace(/hoved/,'thumb') : this.getCachePrefix() + "styles/default_car.jpg";
                    } else {
                        _image = this.getCachePrefix() + "styles/default_car.jpg";
                    }


                return _image;
            },

            //Function to remove. Works in the same way as add
            remove : function (id) {
                this.content.splice(id,1);
                this.display();
                return false;
            },

            //Funciton for checking if the ad is in the content array
            contains : function (inAdId) {
                for (var x=0; x<this.content.length; x++) {
                    if (this.content[x][0]==inAdId) return true;
                }
                return false;
            },

            //Function that returns a semicolon seperated array with adids
            getArrayAdIds : function () {
                cookie_string = readCookie(this.getCookieBucketName());
                //alert("kake i getArrayIds: " + cookie_string);
                if (cookie_string!="") {
                    var pairs = cookie_string.split("_|_");
                    for (var x=0; x<pairs.length; x++) {
                        var singles = pairs[x].split("$@");
                        this.arrayAdIds.push([singles[0]]);
                    }
                }
                //alert("kake i getArrayIds: " + cookie_string);

                if(this.arrayAdIds.length >0)
                    return this.arrayAdIds.join(';');
            },

            //Getters and setters for maxlength,maxlengthDesc, cookie and bucket name. These are set in leftpanel_search.jsp to detrmine which type
            //of bucket (vertical) to use. This is the magic that makes it non-vertical specific

            setCookieBucketName : function (cookieName){
                this.coockieBucketName = cookieName;
            },

            getCookieBucketName : function (){
                return this.coockieBucketName;
            },

            setBucketName : function (bucketName){
                this.bucketName = bucketName;
            },

            getBucketName : function(){
                return this.bucketName;
            },

            setMaxLength : function (maxLength){
                this.maxLength = maxLength;
            },

            getMaxLength : function(){
                return this.maxLength;
            },

            setMaxLengthDesc : function (maxLengthDesc){
                this.maxLengthDesc = maxLengthDesc;
            },

            getMaxLengthDesc : function(){
                return this.maxLengthDesc;
            },

            setAlreadyInBucketMessage : function(inAlreadyInBucketMessage){
                this.alreadyInBucketMessage = inAlreadyInBucketMessage;
            },

            getAlreadyInBucketMessage : function(){
                return this.alreadyInBucketMessage;
            },

            getCachePrefix : function(){
                return this.cachePrefix;
            },

            setCachePrefix : function(inCachePrefix){
                this.cachePrefix = inCachePrefix;
            },

            //Function that sets the semicolon seperated list of ads to the form which is posted
            putAdIds : function (targetForm, targetField) {
                var adIds = Bucket.getArrayAdIds();
                var result = document.forms[targetForm].elements[targetField].value = adIds;
            },


               moveableImage : function (inAdId) {



                this.move = function() {


					var deltaX = this.posX - this.destX;
					var deltaY = this.posY - this.destY;

					var dist = Math.sqrt((deltaX*deltaX) + (deltaY*deltaY));
					var moveX = Bucket.steps * (deltaX / dist);
					var moveY = Bucket.steps * (deltaY / dist);

					var tempThis = this;

					if (Bucket.steps >= dist) {
						this.posX = this.destX;
						this.posY = this.destY;
						tempThis.remove();
                        Bucket.display();
					} else {
						this.posX -= moveX;
						this.posY -= moveY;
						window.setTimeout(function(){tempThis.move();},Bucket.moveDelay,40);
					}

					this.newDiv.style.left = this.posX + "px";
					this.newDiv.style.top = this.posY + "px";

                    /*if(this.posX > this.destX) {
                        this.posX = this.posX - (Math.abs(this.posX - this.destX) * Bucket.moveFactor);
                    } else {
                        this.posX = this.posX + (Math.abs(this.posX - this.destX) * Bucket.moveFactor);
                    }
                    this.newDiv.style.left = this.posX + "px";

                    if(this.posY > this.destY) {
                        this.posY = this.posY - (Math.abs(this.posY - this.destY) * Bucket.moveFactor);
                    } else {
                        this.posY = this.posY + (Math.abs(this.posY - this.destY) * Bucket.moveFactor);
                    }
                    this.newDiv.style.top = this.posY + "px";
                    var tempThis = this;


                    if (Math.abs(this.posX-this.destX) > Bucket.moveDistanceStop) {
                        window.setTimeout(function(){tempThis.move();},Bucket.moveDelay);
                    } else {
                        tempThis.remove();
                        Bucket.display();
                    }*/
                }

				this.remove = function() {
					document.body.removeChild(this.newDiv);
				}


				this.adId = inAdId;

				//Lookup chosen image on adid
				var myImage = document.getElementById(inAdId);
				var newImage = new Image();
				newImage.src = myImage.src;

				this.destX = getRealPosition(document.getElementById("bucketBottom"),"x");
				this.destY = getRealPosition(document.getElementById("bucketBottom"),"y");

				this.newDiv = document.createElement("div");
				document.body.appendChild(this.newDiv);
				this.newDiv.appendChild(newImage);
				this.posX = getRealPosition(myImage,"x");
				this.posY = getRealPosition(myImage,"y");
				this.newDiv.style.left = this.posX + "px";
				this.newDiv.style.top = this.posY + "px";
				this.newDiv.style.position = "absolute";

			},

			doMagic : function (inAdId) {
				this.anImage = new this.moveableImage(inAdId);
				this.anImage.move();
			},

            //Fills cookie and dispays content on page load.
            init : function() {
                  var cookie = readCookie(Bucket.getCookieBucketName());
                  Bucket.cookie_string = cookie ? cookie : "";
                  Bucket.fill(Bucket.cookie_string);
                  Bucket.display();
              }


        };


        //Functions for move magic
        getRealPosition = function () {

                var pos = (arguments[1] == 'x') ? arguments[0].offsetLeft : arguments[0].offsetTop;
                var tmp = arguments[0].offsetParent;
                while(tmp != null)
                {
                    pos += (arguments[1] == 'x') ? tmp.offsetLeft : tmp.offsetTop;
                    tmp = tmp.offsetParent;
                }
                return pos;
            }
