/**
 * jQuery extensions
 */
$.extend({
	_enc_div: null,
	htmlenc: function(val) {
		if (this._enc_div == null) this._enc_div = $("<div>");
		this._enc_div.text(val);
		return this._enc_div.html().replace(/\n/g, "<br />");
	},
	htmldec: function(val) {
		if (this._enc_div == null) this._enc_div = $("<div>");
		this._enc_div.html(val);
		return this._enc_div.text();
	},
	intValue: function(val, min, max) {
		var v = $.trim(val);
		if (v == "") {
			return null;
		}
		v = parseInt(v, 10);
		if (isNaN(v)) {
			return null;
		}
		return Math.min(max, Math.max(min, v));
	},
	floatValue: function(val, min, max, precision) {
		if (precision === undefined) {
			precision = 2;
		}
		var v = $.trim(val);
		if (v == "") {
			return null;
		}
		v = parseFloat(v.replace(/,/, "."));
		if (isNaN(v)) {
			return null;
		}
		var multiplier = Math.round(Math.pow(10, precision));
		return Math.min(max, Math.max(min, Math.round(v * multiplier) / multiplier));  
	}
});

// fixes the problem of assigning a null value to the controls in IE
(function (oldVal) {
	$.fn.val = function(value) {
		if (arguments.length) {
			return oldVal.call(this, (value === undefined || value === null) ? "" : value);
		} else {
			return oldVal.call(this);
		}
	};
})($.fn.val);

// usage: log('inside coolFunc',this,arguments);
// http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
	log.history = log.history || [];   // store logs to an array for reference
	log.history.push(arguments);
	if (this.console) {
		console.log(Array.prototype.slice.call(arguments));
	}
};




/*******************************************************
 * FingerSwipe class
 * implements the finger swipe emulation on touch devices
 * 
 *******************************************************/
function FingerSwipe(client, parameters) {
	this.downX = null;
	this.upX = null;
	this.downY = null;
	this.upY = null;
	this.client = client;
	this.parameters = parameters || {};

	$(client)
		.bind('touchstart', $.proxy(this.onTouchStart, this))
		.bind('touchmove', $.proxy(this.onTouchMove, this))
		.bind('touchend', $.proxy(this.handleSwipe, this))
	;
	
	// emulate the swipe with mouse moves?
	if ((this.parameters.emulateMouse === undefined) || this.parameters.emulateMouse) {
		$(client)
			.mousedown($.proxy(this.onMouseDown, this))
			.mouseup($.proxy(this.onMouseUp, this))
		;
	}

	return this;
}

FingerSwipe.prototype = {
	'onMouseDown': function(event) {
		event.preventDefault();
		this.downX = event.pageX;
		this.downY = event.pageY;
	},
	'onMouseUp': function(event) {
		this.upX = event.pageX;
	    this.upY = event.pageY;
	    this.handleSwipe(event);
	},
	'onTouchStart': function(event) {
		var touch = event.originalEvent.touches[0];
		this.upX = this.downX = touch.pageX;
		this.upY = this.downY = touch.pageY;
		this.parameters.onStart && this.parameters.onStart(this.upX, this.upY, event); 
	},
	'onTouchMove': function(event) {
		var touch = event.originalEvent.touches[0];
		this.upX = touch.pageX;
		this.upY = touch.pageY;
		this.parameters.onMove && this.parameters.onMove(this.downX - this.upX, this.downY - this.upY, event); 
	},
	'handleSwipe': function(event) {
		var xDiff = this.downX - this.upX;
		var yDiff = this.downY - this.upY;
		if (!(this.parameters.onEnd && this.parameters.onEnd(xDiff, yDiff))) {
			if (xDiff > 50) {
				event.preventDefault();
				this.parameters.onSwipeLeft && this.parameters.onSwipeLeft(-xDiff); 
			} else if (xDiff < -50) {
				event.preventDefault();
				this.parameters.onSwipeRight && this.parameters.onSwipeRight(xDiff); 
			}
		} 
	}
};

var timo = {
		mobile: false,
		tools: {
			preloadImages: function(images, callback, pointer) {
				if (pointer === undefined) pointer = 0;
				if (images.length > pointer) {
					$('<img />').load(function() {
						timo.tools.preloadImages(images, callback, pointer + 1);
					}).attr('src', images[pointer]);
				} else {
					callback();
				}
			},
			setCookie: function (c_name,value,exdays)
			{
				var exdate=new Date();
				exdate.setDate(exdate.getDate() + exdays);
				var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString())+"; path=/";
				document.cookie=c_name + "=" + c_value;
			},
			preloadImagesList: function(list, itemCallback) {
				$('>li.loading', list).each(function (i, item) {
					$("<img>").load(function () {
						$(item).removeClass("loading");
						if (itemCallback) itemCallback(item);
					}).attr("src", $("img", item).attr("src"));
				});
			},
			
			parseQueryParameters: function (serialized_params) {
				var result = {};
				$.each(("" + serialized_params).split("&"), function (i, item) {
					var parts = item.split("=");
					if (parts.length < 2) parts[1] = "";
					result[decodeURI(parts[0])] = decodeURI(parts[1]);
				});
				return result;
			},
			
			isMobileBrowser: function () {
				var ua = navigator.userAgent;
				if (ua.indexOf('iPod') != -1) {
					return 'ipod';
				} else if (ua.indexOf('iPhone') != -1) {
					return 'iphone';
				} else if (ua.indexOf('iPad') != -1) {
					return 'ipad';
				} else if (ua.indexOf('Android') != -1 && ua.indexOf('mobile') != -1) {
					return 'android phone';
				} else if (ua.indexOf('Android') != -1) {
					return 'android tablet';
				} else if (ua.indexOf('webOS') != -1) {
					return 'webos';
				} else if (ua.indexOf('BlackBerry') != -1) {
					return 'blackberry phone';
				} else if (ua.indexOf('RIM Tablet') != -1) {
					return 'rim tablet';
				} else {
					return false;
				}
			}
		},
		add_content: function(){
			var status = 1;
			$(window).bind('scroll',function(){
				pt = parseInt(($(window).scrollTop()/$(window).height())*100);
				if (((pt > 40) && (status == 1)) || (timo.tools.isMobileBrowser() && pt >14)){
					$(window).unbind('scroll');
					var sid = $("div.news_block").length;
					var mod = $("div.news_wrapper").attr("id");
					if ((typeof(sid) !== 'undefined' && sid >=3)&& (typeof(mod) !== 'undefined')){
						$.ajax({
							url: './',
							data: {action:'get_article', 
								pos: sid,
								module: mod},
							dataType: 'json',
							type: 'POST',
							success: function(r){
									if (r.status == 1) {
											$("div.news_wrapper").append(r.html);
									}else { status = 0;}						
							}
						});
					}
				}

			});
			
		},
		init: function(){
			
			this.mobile = this.tools.isMobileBrowser();
				
				var module = $('#conteiner>div');
				switch (module.attr("id")) {
					case "lookbook":
					case "lovestory":
						this.Lookbook.init(module);
						break;
					case "news":
						this.News.init(module);
						break;
					case "about":
						this.About.init(module);
						break;
					case "collection":
						this.Collection.init(module);
						break;
					case "search":
						this.Search.init(module);
						break;
					case "facebook":
						this.Facebook.init(module);
					default:
						break;
				}
		},
		search: function(){
			var el = $('input.search');
			el.data('value',el.val())
			.bind("focus", function(){
				if ($(this).val() == $(this).data('value')){
					$(this).val("");
				};
			}).bind("focusout", function(){
				if ($(this).val() == ''){
					$(this).val($(this).data('value'));
				}
			});
			$('.search_button').click(function(){
				if (el.data('value') != el.val() && el.val() != '') {
					$(this).parent().submit();
				} else {
					el.focus();
				}
			});
		},
		hideEmail: function(){
			
		    $('a.email_url').each(function(i) {
		        var text = $(this).siblings("span").text();
		        var address = text.replace(" at ", "@").split(" dot ").join(".");
		        $(this).attr('href', 'mailto:' + address);
		        $(this).siblings("span").detach();
		        });
		},
		menuImg: function(){
			var menu_img = $("#menu>img");
				var w_h = $(window).height();
				var i_h = menu_img.height();
				if (w_h > i_h) {
					menu_img.css({'bottom':'0px', 'visibility': 'visible'});
				} else {
					menu_img.css({'top':(w_h-125)*-1+'px', 'visibility': 'visible'});
				}	
		}
};
/////////////////////////////////////// NEWS ///////////////////////////////////////////
timo.News = {
		container: undefined,
		init: function(container){
			this.container = container;
			timo.add_content();
			timo.search();
			$(">.news_wrapper",container).hide().fadeIn("1500");
			timo.menuImg();
			

		}
};
timo.Facebook = {
		container: undefined,
		init: function(container){
			this.container = container;
			$('body').css('overflow','hidden');
			$('html').css('overflow','visible');
			timo.hideEmail();
		}
		
};
/////////////////////////////////////// SEARCH ///////////////////////////////////////////
timo.Search = {
		container: undefined,
		init: function(container){
			this.container = container;
			timo.search();
			$(">.news_wrapper",container).hide().fadeIn("1500");
			timo.menuImg();
		}
};
/////////////////////////////////////// NEWS ///////////////////////////////////////////
timo.Collection = {
		container: undefined,
		init: function(container){
			this.container = container;
			timo.search();
			$(">.news_wrapper",container).hide().fadeIn("1500");
			timo.menuImg();
		}
};
///////////////////////////////////// ABOUT ////////////////////////////////////////////
timo.About = {
		container: undefined,
		init: function(container){
			this.container = container;
			timo.add_content();
			timo.search();
			timo.hideEmail();
			timo.menuImg();
			$(">.news_wrapper",container).hide().fadeIn("1500");
			$('.findstore_button').click(function(e){
				e.preventDefault();
				var country_id = $('.country').val(),
					city_id = $('.city').val();
				$.ajax({
					url:'../',
					data: {action: 'get_stores', country_id: country_id, city_id: city_id},
					dataType: 'json',
					type: 'POST',
					success: function(data){
						if(data.status == 1) {
							$('.findstore_result', container).html(data.html);
							$('body,html').animate({scrollTop:$('.findstore_result', container).offset().top},300);
							timo.hideEmail();
						}
					}
				});
			});
			$('.city').dropkick();
			$('.country').dropkick({
				
				change: function(value, label){
					$.ajax({
						url:'../',
						data: {action: 'get_city',	country_id: value},
						dataType: 'json',
						type: 'POST',
						success: function(data) {
							if (data.status == 1){
								$('.city').html(data.html).dropkick('update');
							}
						}
					});
				}
			});
		}
};
//////////////////////////////////// LOOKBOOK //////////////////////////////////////////
timo.Lookbook = {
		container: undefined,
		nextNav: undefined,
		prevNav: undefined,
		images: [],
		view_port1: undefined,
		view_port2: undefined,
		image1: undefined,
		image2: undefined,
		leave_url: undefined,
		active_slide: 0,
		hot_spot_data: undefined,
		slides: undefined,
		
		init: function(container){
			this.container = container;
			var collection_id = $(">ul", this.container).attr("id");
			this.view_port1 = $("<div class='viewport loading'>").prependTo(container);
			this.view_port2 = $("<div class='viewport'>").prependTo(container).hide();
			$("#menu").css({'bottom':'0', 'position': 'fixed'});$("#menu>div").hide();
			
			if (this.container.attr("id") == "lookbook") {
				$.ajax({
					url: "./",
					data: {action:"get_hot_spot", collection_id: collection_id},
					type: "POST",
					dataType: "json",
					success: function(data){
						if (data != '')	timo.Lookbook.hot_spot_data = data;
						timo.Lookbook.initSlider();
					}
				});
			} 
	
			if (this.container.attr("id") == "lovestory") {
				$("<span>").appendTo($("<div>").appendTo($("<div class='text'>").appendTo(this.view_port1))).hide();
				$("<span>").appendTo($("<div>").appendTo($("<div class='text'>").appendTo(this.view_port2))).hide();
				this.initSlider();
			}
			$(window).resize($.proxy(this.onWindowResize, this)).resize();
			

			
			// just show the menu if no slides
			
			// make all links that leave the page expand the menu before leaving
			$('a').live('click', $.proxy(this.onLeavePage, this));

		},
		initSlider: function() {
			this.slides = $(">ul>li", this.container);
			// preload the first slide
			this.slides.each($.proxy(function (i, slide) {
				var img = $('<img>');
				var id = this.slides.eq(i).attr("id");
				img.bind("load error", $.proxy(function (event) {
					this.images[i] = img;
					var width = img.prop("width"), height = img.prop("height");
					var ratio = width ? (height / width) : 0; 
					img.data({
						w: width,
						h: height,
						r: ratio,
						html: $(">p", slide).html(),
						id: id
					});
					if (this.hot_spot_data != undefined) {
						var ht_sp = new Array();
						$.each(this.hot_spot_data['hot_spot'], function(k,v){
							if (v['img_id'] == id) {
								ht_sp.push(v);
								vp_w = v['vp_w'];
								vp_h = v['vp_h'];
								vp_t = v['vp_t'];
								vp_l = v['vp_l'];
								vp_c = (v['vp_c'] != '')?v['vp_c']:'ffffff';
								base_w = v['base_w'];
								base_h = v['base_h'];
							}});
							img.data({
								h_sp: ht_sp,
								base_w: base_w,
								base_h: base_h,
								vp_data: {vp_w: vp_w, vp_h: vp_h, vp_l: vp_l, vp_t: vp_t, vp_c: vp_c}
						});
					}
					if (i == 0) {
						// show the first slide
						this.image1 = img;
						this.view_port1.prepend(img).removeClass("loading");
						$(">.text>div>span", this.view_port1).html(img.data("html")).delay(1000).fadeIn(1000);

						this.addHotSpot(img.data(),this.view_port1);
						this.onWindowResize("noreset");
						img.hide().fadeIn(2000, function(){
							timo.Lookbook.hotSpotAnimate(this.view_port1);
						});
						this.showMenu();
					} else {
						// check which view port is waiting for the uploaded image
						var vp = '';
						if (this.view_port1.data("wait_for_image_id") === i) {
							vp = this.view_port1;
						} else if (this.view_port2.data("wait_for_image_id") === i) {
							vp = this.view_port2;
						}
						if (vp) {
							vp.prepend(img).removeClass("loading");
							//vp.append(img.data("h_sp"));
							this.addHotSpot(img.data(),vp);
							$(">.text>div>span", vp).html(img.data("html")).fadeIn(1000);
							this.onWindowResize("noreset");
							img.hide().fadeIn(2000, function(){
								timo.Lookbook.hotSpotAnimate(vp);
							});
						}
					}
					var text_b = $('div.text>div>span');
					if ($('>span', text_b).length > 0){
						var span_c = $('>span', text_b).css('color');
						text_b.css({'border-left': '1px dashed '+  span_c,
						'border-right': '1px dashed '+  span_c});
						}
				}, this)).attr("src", $(">img", slide).attr("src"));
			}, this));
			
			if (!this.slides.length) {
				this.showMenu();
			}
		},
		addHotSpot: function (imgData, viewport){
			if (imgData['h_sp'] == undefined) return; 
			$(".hot_spot, .view_port").detach();
			$.each(imgData['h_sp'], function(k,v){
				var hot_spot = $('<div class="hot_spot"></div>');
				$('<div>').appendTo(hot_spot);
				hot_spot.data({
					w: v['hs_w'],
					h: v['hs_h'],
					t: v['hs_t'],
					l: v['hs_l'],
					c: v['hs_c'],
					hd: v['hs_header'],
					text: v['hs_text'],
					link: v['hs_link']
				});
				if (v['hs_c'] == 2) {
					$(">div", hot_spot).addClass('d_hot_spot');
				} else {
					$(">div", hot_spot).addClass('l_hot_spot');
				}
				viewport.append(hot_spot);
			});
			if (imgData['vp_data'].vp_h != null) {
				var view_port = $('<div class="view_port"><div class="vp_header"></div><div class="vp_text"></div></div>');
				view_port.data({
					w: imgData['vp_data'].vp_w,
					h: imgData['vp_data'].vp_h,
					t: imgData['vp_data'].vp_t,
					l: imgData['vp_data'].vp_l,
					c: imgData['vp_data'].vp_c
				}).css('color','#'+imgData['vp_data'].vp_c);
				$('.vp_header', view_port).css('borderBottom','1px dashed #'+imgData['vp_data'].vp_c);
				viewport.append(view_port);					
			}
		},
		showMenu: function () {
			$('#menu>div').delay(1000).slideDown(1000, $.proxy(function () {
				if (this.slides.length > 1) {
				/*	if (timo.mobile) {
						var active_slide_to_be;
						var started = false;
						var doEnd = $.proxy(function(xDiff, yDiff) {
							if (started) {
								started = false;
								var w = this.view_port1.width();
								var forward = (xDiff >= 0);
								if (Math.abs(xDiff) < this.view_port1.width() / 2) {
									// put the active slide back
									this.view_port1.animate({left: 0});
									this.view_port2.animate({left: (forward ? w : -w) + "px"});
								} else {
									// slide to next image
									this.active_slide = active_slide_to_be; 
									this.view_port1.animate({left: (forward ? -w : w) + "px"}, "fast");
									this.view_port2.animate({left: 0}, "fast", $.proxy(this.swapViewPorts, this));
								}
							}
							return true; // override the standard swipe
						}, this);
						new FingerSwipe(this.container, {
							'onStart': $.proxy(function(x, y, event) {
								if (event.originalEvent.touches.length == 1) {
									started = true;
								} else if (started) {
									doEnd(0, 0);
								}
							}, this),
							'onMove': $.proxy(function(xDiff, yDiff, event) {
								if (started) {
									if (Math.abs(xDiff) > Math.abs(yDiff)) {
										event.preventDefault();
									}
									var w = this.view_port1.width();
									var forward = (xDiff >= 0);
									active_slide_to_be = this.navigateSlides(forward, true);
									// we are just moving the helper viewer to the new position
									this.view_port1.css("left", -xDiff + "px");
									this.view_port2.css("left", (forward ? w : -w) - xDiff + "px");
								}
							}, this),
							'onEnd': doEnd
						});
					}*/
					this.navFunction();
				}
			},this));
		},
		navFunction: function(){
			this.nextNav = $("a.next").click($.proxy(this.navigateNextSlide, this));
			this.prevNav = $("a.prev").click($.proxy(this.navigatePrevSlide, this));
			if (timo.mobile) {
				this.prevNav.stop(true, true).fadeIn();
				this.nextNav.stop(true, true).fadeIn();
			} else {
				var on_left = false, on_right = false;
				var hideLeftLink = $.proxy(function() {
					if (on_left) {
						on_left = false;
						this.prevNav.stop(true, true).fadeOut();
					}
				}, this);
				var hideRightLink = $.proxy(function() {
					if (on_right) {
						on_right = false;
						this.nextNav.stop(true, true).fadeOut();
					}
				}, this);
				this.container.mousemove($.proxy(function (event) {
					if ($(event.target).parents('#menu').length || $(event.target).is(".hot_spot, .hot_spot>div")) { // ignore when the mouse is over the menu and hot spot
						hideLeftLink();
						hideRightLink();
						return;
					}
					if (event.pageX < $(window).width() / 4) { // in left part
						hideRightLink();
						if (!on_left) {
							on_left = true;
							this.prevNav.stop(true, true).fadeIn();
						} 
					} else if(event.pageX > ($(window).width()*3) / 4){ // in right part
						hideLeftLink();
						if (!on_right) {
							on_right = true;
							this.nextNav.stop(true, true).fadeIn();
						} 
					} else {
						hideLeftLink();
						hideRightLink();
					}
				}, this));
			}
		},
		enterHotSpot: function (e) {
			e.stopPropagation();
			var hot_spot = $(e.currentTarget);
			$(">div", hot_spot).stop(true,true).fadeIn("300");
		},
		leaveHotSpot: function (e) {
			e.stopPropagation();
			var hot_spot = $(e.currentTarget);
			$(">div", hot_spot).stop(true,true).fadeOut("300");
		},
		clickHotSpot: function (e) {
			e.stopPropagation();
			var hot_spot = $(e.currentTarget);
			var view_port = $('.view_port', this.view_port1);
			if (view_port.length > 0){
				view_port.fadeOut("1000", function(){
					$(".vp_header", view_port).text(hot_spot.data("hd"));
					$(".vp_text", view_port).html(hot_spot.data("text"));
					if ($("a>.vp_text", view_port).length > 0) $(".vp_text", view_port).unwrap();
					if (hot_spot.data("link") != "") {
						$(".vp_text", view_port).wrap('<a href="'+hot_spot.data("link")+'">');
					}
					view_port.fadeIn("1000");
				});
			}
		},
		hotSpotAnimate: function(container) {
			var hot_spot = $("div.hot_spot", container);
			if (timo.mobile) {
				$(">div", hot_spot).fadeIn("slow");
			} else {
				$(">div", hot_spot).fadeIn("slow", function(){$(this).delay(1000).fadeOut("slow");});
				hot_spot.hover($.proxy(this.enterHotSpot, this), $.proxy(this.leaveHotSpot, this));
			}
			hot_spot.click($.proxy(this.clickHotSpot, this));
		},
		onLeavePage: function (event) {
			var a = $(event.currentTarget);
			var url = a.attr("href");
			if (url == '#' || a.hasClass('facebook_url')) return;
			
			event.preventDefault();
			
			// if the menu is already rolling up we'll just change the url we'll go 
			/*if (this.leave_url) {
				this.leave_url = url;
				return;
			} else {
				this.leave_url = url;
			}*/
			this.leave_url = url;
			if (a.hasClass('standart_menu')) {
				timo.tools.setCookie('module',this.container.attr("id"),2);
				timo.tools.setCookie('img_id', this.images[this.active_slide].data("id"),2);
				//console.log(this.images[this.active_slide].data("id"));
				$('#menu').animate({'bottom': $(window).height()-125 + "px"}, "slow", $.proxy(function (event) {
					// switch the positioning to fix the menu to the top of the window 
					$('#menu').css({top: 0});
				}, this));
				this.view_port1.animate({'top': ($(window).height()-125)*-1 + "px"}, "slow", $.proxy(function (event) {
					// switch the positioning to fix the image to the top of the window 
					window.location.href = this.leave_url;
				}, this));
			} else {
				this.container.fadeOut('800', $.proxy(function (event) {window.location.href = this.leave_url;},this));
			}
		},
		navigatePrevSlide: function (event) {
			event && event.preventDefault();

			this.navigateSlides(false);
		},
		
		
		navigateNextSlide: function (event) {
			event && event.preventDefault();

			this.navigateSlides(true);
		},

		
		navigateSlides: function (forward, noanimation) {
			// interrupt the active animations
			this.view_port1.stop(true, true);
			this.view_port2.stop(true, true);
			
			var active_slide = this.active_slide;
			if (forward) {
				if (++active_slide == this.slides.length) active_slide = 0;
			} else {
				if (--active_slide < 0) active_slide =  this.slides.length - 1;
			}
			
			// update the links text
			var other_slide_id;
			if (this.nav_left && this.nav_right) {
				other_slide_id = this.active_slide - 1;
				if (other_slide_id < 0) other_slide_id =  this.slides.length - 1;
				this.nav_left.text((other_slide_id + 1) + "/" + this.slides.length);
				other_slide_id = this.active_slide + 1;
				if (other_slide_id == this.slides.length) other_slide_id = 0;
				this.nav_right.text((other_slide_id + 1) + "/" + this.slides.length);
			}
			
			// animate the slides
			var w = this.view_port1.width();
			var img = this.images[active_slide];
			this.view_port2.show().removeClass("loading");
			$(">img", this.view_port2).stop(true, true).detach(); // stop image fadein if active
			$(">.text>div>span", this.view_port2).stop(true, true).empty();  // stop text fadein if active
			if (img) {
				this.image2 = img;
				this.view_port2.prepend(img);
				this.addHotSpot(img.data(),this.view_port2);
				$(">.text>div>span", this.view_port2).html(img.data("html")).show();
				var text_b = $(">.text>div>span", this.view_port2);
				if ($('>span', text_b).length > 0){
					var span_c = $('>span', text_b).css('color');
					text_b.css({'border-left': '1px dashed '+  span_c,
					'border-right': '1px dashed '+  span_c});
					} else {
					text_b.css({'border-left': '1px dashed #FFFFFF',
						'border-right': '1px dashed #FFFFFF'});	
					}
				this.onWindowResize("noreset");
				this.view_port2.removeData("wait_for_image_id");
			} else {
				this.view_port2.data("wait_for_image_id", active_slide);
				this.view_port2.addClass("loading");
			}
			if (noanimation) {
				return active_slide;
			} else {
				this.active_slide = active_slide;
				this.view_port1.animate({left: (forward ? -w : w) + "px"}, "slow");
				this.view_port2.css('left', (forward ? w : -w) + "px").animate({left: 0}, "slow", $.proxy(this.swapViewPorts, this));
			} 
		},
		swapViewPorts: function() {
			var vp = this.view_port1;
			this.view_port1 = this.view_port2;
			this.view_port2 = vp;
			this.view_port1.insertAfter(this.view_port2);
			this.hotSpotAnimate(this.view_port1);

			var img = this.image1;
			this.image1 = this.image2;
			this.image2 = img;
		},
		/**
		 * resizes the slides and images in them
		 * 
		 */
		onWindowResize: function (event) {
			var win_h = $(window).height();
			var win_w = $(window).width();
		
			if (event !== 'noreset') {
				// interrupt any active animation
				this.view_port1.stop(true, true);
				this.view_port2.stop(true, true);
			}
			
			// resize viewports
			this.view_port1.width(win_w).height(win_h);
			this.view_port2.width(win_w).height(win_h);
			
			if (!this.image1 && !this.image2) return;
			
			// resize images to cover the viewports
			var win_ratio = win_h / win_w;
			var img_w, img_h, img_ratio;
			var w, h;
			
			var images = [this.image1, this.image2];
			for (var i in images) {
				var image = images[i];
				if (image) {
					img_w = image.data("w");
					img_h = image.data("h");
					img_ratio = image.data("r");
					if (img_ratio) { // !0 if loaded ok
						if (img_ratio > win_ratio) { // image should be cropped on top and bottom
							w = win_w;
							h = w * img_ratio;
						} else { // image should be cropped on left and right
							h = win_h;
							w = h / img_ratio;
						}
						image.width(w + "px").height(h + "px").css("left", ((win_w - w) / 2) + "px");
						var hot_spot = image.siblings(".hot_spot");
						if (hot_spot.length > 0) {
							var p_w = (w / image.data("base_w"));
							var p_h = (h / image.data("base_h"));
							hot_spot.each(function(i){
								var hs_t = $(this).data('t')*p_h;
								var hs_l = $(this).data('l')*p_w;
								var hs_h = $(this).data('h')*p_h;
								var hs_w = $(this).data('w')*p_w;
								$(this).css({
									top: hs_t+'px',
									left: hs_l+'px',
									width: hs_w+'px',
									height: hs_h+'px'
								});
							});
							var view_port = image.siblings(".view_port");
							if (view_port.length > 0) {
								var fs_h = parseInt($(".vp_header", view_port).css("font-size"));
								var vp_t = image.data('vp_data').vp_t*p_h;
								var vp_l = image.data('vp_data').vp_l*p_w;
								var vp_h = image.data('vp_data').vp_h*p_h;
								var vp_w = image.data('vp_data').vp_w*p_w;
								view_port.css({
									top: vp_t+'px',
									left: vp_l+'px',
									width: vp_w+'px',
									height: vp_h+'px'
									
								});
							}
						}
					}
				}
			}
		}
};

$(document).ready(function(){
	timo.init();
});
