/**

 *  Script by Johan Bergström (http://devexe.com).

**/



var Sabina = {



    /*

    Flower configuration

    The format is:

    'collection-name': [

    {flower: 'path-to-flower', text: 'path-to-flower-text'},

    {flower: 'path-to-flower2', text: 'path-to-flower-text2'}

    ... separate flower blocks with a comma ...

    ],

		

		'second-collection': [

    ...

    ]

    */

    flowers: {

    /*'neon': [

    {flower: 'F1.gif', text: 'blackmarket.png', closeAfter: 10000},

    { flower: 'F2.gif', text: 'onpedder.png', closeAfter: 10000 },

    { flower: 'F3.gif', text: 'edition.png', closeAfter: 10000 }

    ],

    'velour': [

    { flower: 'F1.gif', text: 'blackmarket.png', closeAfter: 10000 },

    { flower: 'F2.gif', text: 'colette.png', closeAfter: 10000 },

    { flower: 'F3.gif', text: 'kabiri.png', closeAfter: 10000 }

    ],

    'paint': [

    { flower: 'F1.gif', text: 'edition.png', closeAfter: 10000 }

    ],

    'bloom': [

    { flower: 'F1.gif', text: 'onpedder.png', closeAfter: 10000 }

    ],

    'graffiti': [

    {flower: 'F1.gif', text: 'edition.png', closeAfter: 10000}

    ]*/



},



// The pdf link flower configuration

dover: {

    flower: '',

    text: 'dsmhut.gif',

    closeAfter: 10000,



    title: 'Velour available at Dover Street Market - London',

    click: function() {

        //Sabina.setPNGSource(this.textImage, 'surprise-text-purple.png');

        window.location.href = 'http://www.doverstreetmarket.com/';

    }

},



ostetantoire: {

    flower: '',

    text: 'OstentatoireLogo.gif',

    closeAfter: 10000,



    title: 'Velour, punk pearls and neon pearls available at Ostentatoire - Paris',

    click: function() {

        //Sabina.setPNGSource(this.textImage, 'surprise-text-purple.png');

        window.location.href = 'http://www.Ostentatoire-Paris.com/';

    }

},



octium: {

    flower: '',

    text: 'octium.gif',

    closeAfter: 10000,



    title: 'Velour and diamond breeze available at Octium - Kuwait',

    click: function() {

        //Sabina.setPNGSource(this.textImage, 'surprise-text-purple.png');

        window.location.href = 'http://www.octiumjewelry.com/';

    }

},



initialized: false,



initialize: function() {

    if (Sabina.initialized) {

        return;

    }



    var i;

    var wrapper = document.getElementById('wrapper');



    // Show initial PDF-link flower

    

	/*if(wrapper != null)

	{

		return;

	}*/

    wrapper.onmouseover = function() {

/*        if (!arguments.callee.opened) {

            var dover = new Sabina.Flower(Sabina.dover);

			dover.open();

	

			var ostetantoire = new Sabina.Flower(Sabina.ostetantoire);

			ostetantoire.open();

			

			var octium = new Sabina.Flower(Sabina.octium);

			octium.open();

            arguments.callee.opened = true;

        }*/

    };

	

    // The function that applies the fading events to a link.

    var add = function(link, img) {

        var opacity = new Sabina.Opacity(img);



        Sabina.setOpacity(img, 0);

        img.style.display = 'block';



        link.onmouseover = function() {

            opacity.start(parseFloat(img.style.opacity) || 0, 1);

        };



        link.onmouseout = function() {

            opacity.start(parseFloat(img.style.opacity) || 1, 0);

        };



        link.onclick = function() {

            Sabina.openCollection(this.parentNode, this);

            return false;

        };

    };



    var parent = null;

    var collection = window.location.href;

    collection = collection.substr(collection.indexOf('#') + 1);



    // Walk through the documents links

    var links = document.getElementsByTagName('a');

    for (i = 0, l = links.length; i < l; i++) {

        var link = links[i];

        var img = new Image();

        img = link.getElementsByTagName('img');



        if (img && img.length > 0) {

            img = img[0];



            var filename = img.src;

            filename = filename.substr(filename.lastIndexOf('/') + 1);

            var tmpImage = new Image();

            tmpImage.src = name + '/' + filename;



            // Remove the focus outline

            link.onfocus = function() {

                this.blur();

            };



            add(link, img);



            // If we have a collection name after the #-sign we should go to that collection

            if (link.parentNode.id === collection) {

                parent = link.parentNode;

            }

        }

    }



    if (parent) {

        Sabina.openCollection(parent);

    }



    Sabina.initialized = true;

},



openCollection: function(container, focus) {

    var self = this;

    var name = container.id;



    // This modifies the url, so that a user can go directly to a collection.

    window.location.href = '#' + name;



    // Prepare for the new 'window'

    window.scrollTo(0, 0);

    Sabina.Flower.hideAll();



    // Hide the wrapper.

    var wrapper = document.getElementById('wrapper');

    if (wrapper) {

        wrapper.style.display = 'none';

    }



    // Show the flowers associated with this collection

    var flowers = Sabina.flowers[name];

    if (flowers) {

        for (var i = 0, l = flowers.length; i < l; i++) {

            var flower = new Sabina.Flower(flowers[i]);

            flower.open();

        }

    }



    // Create the neccessary elements.

    var collection = document.createElement('div');

    collection.id = 'collection';



    var navigation = collection.appendChild(document.createElement('div'));

    navigation.id = 'navigation';



    var spinner = collection.appendChild(document.createElement('div'));

    spinner.id = 'spinner';



    var left = spinner.appendChild(document.createElement('img'));

    left.src = 'navigation-left.gif';

    var current = spinner.appendChild(document.createElement('span'));

    current.id = 'current_spin';

    var right = spinner.appendChild(document.createElement('img'));

    right.src = 'navigation-right.gif';



    var headline = navigation.appendChild(document.createElement('h1'));



    // Close on click

    headline.onclick = function() {

        Sabina.closeCollection();

    };



    var add = function(thumb, i) {

        thumb.onclick = function() {

            self.setCollectionImage(container, i);

        };

    };



    var index = 0;

    var list = navigation.appendChild(document.createElement('ul'));

    var links = container.getElementsByTagName('a');

    for (var i = 0, l = links.length; i < l; i++) {

        var link = links[i];

        var image = link.getElementsByTagName('img');

        if ((image = image[0])) {

            if (link === focus) {

                index = i;

            }



            var item = list.appendChild(document.createElement('li'));

            var filename = image.src;

            filename = filename.substr(filename.lastIndexOf('/') + 1);



            var thumb = item.appendChild(document.createElement('img'));

            thumb.src = name + '_thumbs2/' + filename;



            add(thumb, i);

        }

    }



    // Spin left (previous image)

    left.onclick = function() {

        if (index <= 0) {

            index = links.length;

        }



        if (self.setCollectionImage(container, index - 1)) {

            index--;

        }

    };



    // Spin right (next image)

    right.onclick = function() {

        if (index >= links.length - 1) {

            index = -1;

        }



        if (self.setCollectionImage(container, index + 1)) {

            index++;

        }

    };





    var title = collection.insertBefore(document.createElement('h2'), spinner);

    title.style.backgroundImage = 'url(text/' + name + '.jpg)';



    var view = collection.insertBefore(document.createElement('img'), spinner);

    view.id = 'viewpic';



    document.body.appendChild(collection);



    // Set the current image

    self.setCollectionImage(container, index);

},



closeCollection: function() {

    Sabina.Flower.hideAll();



    var collection = document.getElementById('collection');

    var navigation = document.getElementById('navigation');



    collection.parentNode.removeChild(collection);



    var wrapper = document.getElementById('wrapper');

    if (wrapper) {

        wrapper.style.display = 'block';

    }



    window.location.href = '#';

},



setCollectionImage: function(container, index) {

    var links = container.getElementsByTagName('a');

    var image = document.getElementById('viewpic');





    if (links && image && index >= 0 && index < links.length) {

        if (Sabina.collectionTimer) {

            clearInterval(Sabina.collectionTimer);

        }



        var tmpFilename = links[index].href;



        tmpFilename = tmpFilename.substr(tmpFilename.lastIndexOf('/') + 1);

        var tmpImage = new Image();

        tmpImage.src = container.id + '/' + tmpFilename;





        var complete = function() {

            var filename = links[index].href;



            filename = filename.substr(filename.lastIndexOf('/') + 1);

            image.src = container.id + '/' + filename;

        };



        if (image.src) {

            Sabina.collectionTimer = new Sabina.Opacity(image, null, function() {

                complete();

                Sabina.collectionTimer = this.start(0, 1);

            }).start(parseFloat(image.style.opacity) || 1, 0);

        } else {

            complete();

        }



        var current = document.getElementById('current_spin');

        if (current) {

            current.innerHTML = (index + 1) + '/' + links.length;

        }



        return true;

    }



    return false;

},



setOpacity: function(element, opacity) {

    element.style.opacity = opacity;

    if (window.ActiveXObject) {

        if (opacity === 0) {

            element.style.visibility = 'hidden';

        } else if (opacity === 1) {

            element.style.filter = '';

            element.style.visibility = 'visible';

        } else {

            element.style.filter = 'Alpha(opacity=' + Math.round(opacity * 100) + ')';

            element.style.visibility = 'visible';

        }

    }

},



setPNGSource: function(element, source) {

    if (window.ActiveXObject && !window.XMLHttpRequest) {

        element.style.background = 'transparent';

        element.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + source + "', sizingMethod='crop')";

    } else {

        element.style.background = 'transparent url(' + source + ') left top no-repeat';

    }

}



};



// The flower class

Sabina.Flower = function (options) {

	this.textFadeDuration = 2000;

	for (var property in options) {

		this[property] = options[property];

	}

	this.timers = [];

};



Sabina.Flower.list = [];



Sabina.Flower.hideAll = function () {

	var flowers = Sabina.Flower.list;

	for (var i = flowers.length; i--;) {

		var flower = flowers.splice(i, 1);

		if ((flower = flower[0])) {

			flower.remove();

		}

	}

};



Sabina.Flower.prototype = {



	open: function () {

		this.clear();

	

		Sabina.Flower.list.push(this);

		

		if (!this.container) {

			var container = document.createElement('div');

			container.className = 'flower-surprise';

			

			container.style.background = 'transparent url(' + this.flower + ') left top no-repeat';

			container.style.zIndex = 10 * Sabina.Flower.list.length;

			container.style.width = 200 + 'px';

			container.style.height = 200 + 'px';

			

			if (this.title) {

				container.title = this.title;

			}

			

			var self = this;

			if (this.click) {

				container.onclick = function () {

					self.click.call(self);

				};

			}

			

			var height = window.innerHeight || document.documentElement.clientHeight;

			height -= 50;

			

			var x = Math.floor(Math.random() * (document.body.clientWidth - 200));

			var y = Math.floor(Math.random() * (height - 200));

			

			container.style.left = x + 'px';

			container.style.top = y + 'px';

			

			if (this.text) {

				var opaque = container.appendChild(document.createElement('div'));

				opaque.className = 'flower-surprise-text';

				opaque.style.zIndex = 11 * Sabina.Flower.list.length;

				Sabina.setOpacity(opaque, 0);

				

				var text = this.textImage = opaque.appendChild(document.createElement('div'));

				Sabina.setPNGSource(text, this.text);

				

				if (this.link) {

					text.onclick = function () {

						self.click.call(self);

					};

				}

				

				var temp = document.body.appendChild(document.createElement('img'));

				Sabina.setOpacity(temp, .01);

				temp.src = this.text;

				temp.onload = function () {

					text.style.width = this.offsetWidth + 'px';

					text.style.height = this.offsetHeight + 'px';

				

					opaque.style.left = (200 - this.offsetWidth) / 2 + 'px';

					opaque.style.top = (200 - this.offsetHeight) / 2 + 'px';

					

					this.parentNode.removeChild(this);

				};

			}

			

			Sabina.setOpacity(container, 0);

			this.container = document.body.appendChild(container);

			

			if (this.closeAfter) {

				setTimeout(function () {

					self.close();

				}, this.closeAfter);

			} else {			

				container.onmouseover = function () {

					self.open();

				};

				container.onmouseout = function () {

					self.close();

				};

			}

		}

		

		this.timers.push(new Sabina.Opacity(this.container, null, function () {

			if (self.text) {

				self.timers.push(setTimeout(function () {

					self.timers.push(new Sabina.Opacity(opaque).start(0, 1));

				}, self.textFadeDuration));

			}

		}).start(parseFloat(this.container.style.opacity) || 0, 1));

	},

	

	close: function () {

		this.clear();

		

		if (this.container) {	

			var self = this;

			this.timers.push(new Sabina.Opacity(this.container, null, function () {

				self.remove();

			}).start(parseFloat(this.container.style.opacity) || 1, 0));

		}

	},

	

	remove: function () {

		if (this.container) {

			this.container.parentNode.removeChild(this.container);

			this.container = null;

		}

		

		var flowers = Sabina.Flower.list;

		for (var i = flowers.length; i--;) {

			if (flowers[i] === this) {

				flowers.splice(i, 1);

				break;

			}

		}

	},

	

	clear: function () {

		for (var i = this.timers.length; i--;) {

			var timer = this.timers.splice(i, 1)[0];

			clearInterval(timer);

			clearTimeout(timer);

		}

	}

	

};



// The opacity class

Sabina.Opacity = function (element, duration, onComplete) {

	this.element = element;

	this.duration = duration || 1250;

	this.onComplete = onComplete;

};



Sabina.Opacity.prototype = {



	start: function (start, end) {	

		this.stop();

		var time = new Date().getTime();

		var self = this;

		this.timer = setInterval(function () {

			var change = (new Date().getTime() - time) / self.duration;

			if (change < 1) {

				Sabina.setOpacity(self.element, start + (end - start) * change);

			} else {

				self.stop();

				Sabina.setOpacity(self.element, end);

				if (self.onComplete) {

					self.onComplete.call(self);

					self.onComplete = null;

				}

			}

		}, 20);

		return this.timer;

	},

	

	stop: function () {

		clearInterval(this.timer);

	}

	

};



// Initialize the javascript when the DOM is ready

(function () {



	var fn = Sabina.initialize;



	if (document.readyState && (/safari/i).test(navigator.appVersion)) { // Safari

		setTimeout(function() {

			if (document.readyState === 'loaded' || document.readyState === 'complete') {

				fn();

			} else {

				setTimeout(arguments.callee, 50);

			}

		}, 50);

	} else if (window.ActiveXObject) { // IE

		document.attachEvent('onreadystatechange', function () {

			if (document.readyState === 'complete') {

				document.detachEvent('onreadystatechange', arguments.callee);

				fn();

			}

		});

	} else if (window.addEventListener) { // Fx, Opera ...

		window.addEventListener('DOMContentLoaded', fn, false);

	}

	

	// For older browsers and as a last resort if all else fails

	if (window.addEventListener) {

		window.addEventListener('load', fn, false);

	} else if (window.attachEvent) {

		window.attachEvent('onload', fn);

	}



})();
