/*
	# Copyright 2009, Hoop Associates Ltd
	# Hoop Associates   www.thisishoop.com	 mail@hoopassociates.co.uk
*/
function BrowserUtil(){
	this.fixBugs();
	this.cacheImages();
}
BrowserUtil.prototype.fixBugs = function(){
	// FF2/Mac opacity bug
	($.browser.mozilla && parseFloat($.browser.version) < 1.9 && navigator.appVersion.indexOf('Mac') !== -1) && $('body').css('-moz-opacity',.999);
	if ($.browser.msie) {
		// IE6 background css flickering bug
		try{document.execCommand('BackgroundImageCache', false, true);} 
		catch(e){};
		// IE6 transaprent PNG background fix
		if (/MSIE ((5\.5)|6)/i.test(navigator.userAgent) && navigator.platform == "Win32"){
			$(".iecsspng").each(function(){
				var bgIMG = $(this).css('background-image');
				if (bgIMG.indexOf(".png")!=-1){
					var iebg = bgIMG.split('url("')[1].split('")')[0];
					$(this).css('background-image', 'none');
					$(this).get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='scale')";
				}
			});
		}
	}
};
BrowserUtil.prototype.cacheImages = function(){
	var cacheImages = ["/img/loader_lg.gif"];
	for(var i in cacheImages) {
		var img = new Image();
		img.src = cacheImages[i];
	}
}

String.prototype.text = function(){
	var str = this;
	try {
		str = decodeURIComponent(str);
	} catch(e) {}
	str = (str != null && str != undefined && str.length) ? $.trim(str.replace(/<\S[^><]*>/g, '')) : '';
	return str;
};
String.prototype.safeEscape = function(){
	return encodeURIComponent($.trim(this)).replace(/%20/g, "+").toString();
};

function BookPages(assets) {
	this.assets = assets || [];
	this.pos = -1;
	this.loader = $("#TB_window .book-page-image-loader");
	this.overlay = $("#TB_window .book-page-image-overlay");
	this.image = $("#TB_window .productimage");
	this.init();
}
	
BookPages.prototype = {
	init : function(){
		var self = this, origsrc = this.image.attr("src").replace(/https?:\/\/.*?\//, '/').split("/"), $prev = $("#TB_window .book-pagination .prev"), $next = $("#TB_window .book-pagination .next");
		var orig = this.image.attr("src");

		$next.bind("click", function(){
			var anchor = this, imageSrc = origsrc;
			self.pos++;
			imageSrc[5] = self.assets[self.pos];

			self.loadImage(imageSrc.join("/"), function(){
				$prev.show();
				if (self.pos === self.assets.length-1) {
					$(anchor).hide();
				}
			});
			return false;
		});
		$prev.bind("click", function(){
			var anchor = this, imageSrc = origsrc;
			self.pos--;

			if (self.pos === -1) {
				// show initial image that is not part of the assets array
				self.loadImage(orig, function(){
					$(anchor).hide();
					$next.show();
				});
			} else {
				imageSrc[5] = self.assets[self.pos];
				self.loadImage(imageSrc.join("/"), function(){
					$next.show();
				});
			}
			return false;
		});
	},

	loadImage : function(src, callback, showloader){

		showloader = showloader === undefined ? true : showloader;

		var self = this;

		if (showloader){

			this.loader.show();
			this.overlay.show();
		}

		this.image
		.unbind()
		.load(function(){
			var tb_ajax_width = ( $("#TB_ajaxContent").width() - 40 );
		    	var newsrc = src.split("/");

			$(this).removeAttr('width').removeAttr('height');

			if (this.width > tb_ajax_width) {
				var ratio = this.width/this.height;
				var diff = this.width - $("#TB_ajaxContent").width();
				var w = this.width-diff-20;
				var width = Math.round(this.width*(w/this.width));
				if (width){
					newsrc[6] = width;
					$(this).attr("width", width).attr("src", newsrc.join("/")).get(0).removeAttribute('height');
				}
			}

			var diff2 = 120;

			if (this.height+diff2 > $("#TB_window").outerHeight() ) {

				var ratio = this.width/this.height;
				var diff = this.height - $("#TB_window").outerHeight();
				var h = this.height-(diff+diff2);
				var width = Math.round(this.width*(h/this.height));

				if (width) {
					newsrc[6] = width;
					$(this).attr("width", width).attr("src", newsrc.join("/")).get(0);
				}
			}

			self.loader.hide();
			self.overlay.hide();
			(callback) && (callback());
		})
		.bind("error", function(){
			self.overlay.hide();
			self.loader.hide();
			alert('cant load image: image does not exist: ' + this.src);
			(callback) && (callback());
		})
		.attr("src", src);
	}
}


function CookiePhoto(){
	var _this = this;
	$(".savephoto, .deletephoto").unbind().click(function(e){
		e.preventDefault();
		_this.save($(this), this.className.replace(/photo/i, ''));
	});
}
CookiePhoto.prototype.save = function($anchor, action){
	var xhr = $.ajax({
		type : "GET",
		url : "/_ajax/show_view/site/subtpl_"+action+"_photo?rid="+$anchor[0].href.replace(/.*\=/, ''), 
		cache : false,
		error : function(){return;},
		success : function(data){
			if (action == 'save') {
				$anchor.after("SAVED").remove();
				$("a.savephoto").each(function(){
					if ($anchor[0].href.replace(/.*\=/, '') == this.href.replace(/.*\=/, '')) {
						$(this).after("SAVED").remove();
					}
				});
			}
			if (action == 'delete') {
				setTimeout(function(){
					$anchor.parents().filter(".edition-col:first").fadeOut(function(){$(this).remove();});
				},300);
			};
		}
	});
};

function Carousel(position, offset, initialOffset, total, overlay, loader, nextprevURI){
	this.initialOffset = initialOffset;
	this.resultsURI = "/_ajax/show_view/site/subtpl_weeks_editions_horiz_home";
	this.resultsContainer = "#loadeditions";
	this.nextprevURI = nextprevURI;
	this.overlay = overlay;
	this.loader = loader;
	this.update(position, offset, total);
}
Carousel.prototype.update = function(position, offset, total){
	this.bindNext(position, offset, total);
	this.removeNext(position, offset, total);
	this.bindPrev(position, offset, total);
	this.removePrev(position, offset, total);
};
Carousel.prototype.bindNext = function(position, offset, total){
	var _this = this;
	if (position+offset < total) {
		if (!$("a.next").length) {
			$("span.gt").wrap("<a class=\"next\" href=\""+_this.nextprevURI+"\"></a>");
		}
		$("a.next").unbind().click(function(e){
			e.preventDefault();
			_this.clickNext(position, offset, total);
		});
	}
};
Carousel.prototype.load = function(position, offset, total){
	var _this = this;
	$(this.overlay+", "+this.loader).show();
	$('<div></div>').appendTo(this.resultsContainer).hide().load(this.resultsURI+"?offset="+(position+this.initialOffset), function(){
		$(_this.overlay+", "+_this.loader).hide();
		$("#showeditions").hide().html($(this).html()).show();
		$(this).remove();
		tb_init('a.thickbox');
		new CookiePhoto();
		_this.update(position, offset, total);	
	});
};
Carousel.prototype.clickNext = function(position, offset, total){
	position += offset;
	this.load(position, offset, total);
};
Carousel.prototype.removeNext = function(position, offset, total){
	if (position+offset >= total) {
		$("a.next").after($("span", $("a.next"))).remove();
	}
};
Carousel.prototype.bindPrev = function(position, offset, total){
	var _this = this;
	if (position > 0) {
		if (!$("a.prev").length) {
			$("span.lt").wrap("<a class=\"prev\" href=\""+_this.nextprevURI+"\"></a>");
		}
		$("a.prev").unbind().click(function(e){
			e.preventDefault();
			_this.clickPrev(position, offset, total);
		});
	}
};
Carousel.prototype.clickPrev = function(position, offset, total){
	position -= offset;
	this.load(position, offset, total);

};
Carousel.prototype.removePrev = function(position, offset, total){
	if (position == 0) {
		$("a.prev").after($("span", $("a.prev"))).remove();
	}
};

$(function(){
	new BrowserUtil();
	new CookiePhoto();
	$("select.troikaselectbox").selectbox();
	$("a.smooth-scroll").click(function(){
		$.scrollTo(this.href.replace(/^[^#]*/, ""), 2000);
		return false;
	});
});



/*
 * jQuery selectbox plugin
 *
 * Copyright (c) 2007 Sadri Sahraoui (brainfault.com)
 * Licensed under the GPL license and MIT:
 *   http://www.opensource.org/licenses/GPL-license.php
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * The code is inspired from Autocomplete plugin (http://www.dyve.net/jquery/?autocomplete)
 *
 * Revision: $Id$
 * Version: 0.4
 * 
 * Changelog :
 *  - Fix width when the select is in a hidden div   @Pawel Maziarz
 *  - Add a unique id for generated li to avoid conflict with other selects and empty values @Pawel Maziarz
 */
jQuery.fn.extend({
	selectbox: function(options) {
		return this.each(function() {
			new jQuery.SelectBox(this, options);
		});
	}
});

jQuery.SelectBox = function(selectobj, options) {
	var opt = options || {};
	opt.inputClass = opt.inputClass || "troikaselectbox";
	opt.containerClass = opt.containerClass || "troikaselectbox-wrapper";
	opt.hoverClass = opt.hoverClass || "selected";
	var elm_id = selectobj.id;
	var active = -1;
	var inFocus = false;
	var hasfocus = 0;
	var $select = $(selectobj);
	var $container = setupContainer(opt);
	var $input = setupInput(opt);
	$select.hide().before($input).before($container);
	
	init();
	
	$input
	.click(function(){
	if (!inFocus) {
		  $container.toggle();
		}
	})
	.focus(function(){
	   if ($container.not(':visible')) {
		inFocus = true;
		var offset = $input.offset();
		$container.css({left:offset.left+"px",top:(offset.top+10+$input.outerHeight())+"px"}).show();
	   }
	})
	.blur(function(){});


	function hideMe() { 
		hasfocus = 0;
		$container.hide(); 
	}
	
	function init() {
		$container.append(getSelectOptions($input.attr('id'))).hide();
		var width = parseInt($input.css('width').replace(/[a-zA-Z]/g, ''));
		$container.width(width+3);
		$(document).click(function(e){
			if ($container.is(':visible') && hasfocus > 0 ) {
	
			} else if (!e.target.className.match(/troikaselectbox/)) {
				hideMe();     
			}
		});
	}
	
	function setupContainer(options) {
		var container = document.createElement("div");
		$container = $(container);
		$container.attr('id', elm_id+'_container');
		$container.addClass(options.containerClass);
		return $container;
	}
	
	function setupInput(options) {
		var input = document.createElement("input");
		var $input = $(input);
		$input.attr("id", elm_id+"_input");
		$input.attr("type", "text");
		$input.addClass(options.inputClass);
		$input.addClass($select[0].className);
		$input.attr("autocomplete", "off");
		$input.attr("readonly", "readonly");
		$input.attr("tabIndex", $select.attr("tabindex")); // "I" capital is important for ie
		
		return $input;	
	}
	
	function moveSelect(step) {
		var lis = $("li", $container);
		if (!lis) return;

		active += step;

		if (active < 0) {
			active = 0;
		} else if (active >= lis.size()) {
			active = lis.size() - 1;
		}

		lis.removeClass(opt.hoverClass);

		$(lis[active]).addClass(opt.hoverClass);
	}
	
	function setCurrent() {	
		var li = $("li."+opt.hoverClass, $container).get(0);
		var ar = (''+li.id).split('_');
		var el = ar[ar.length-1];
		$select.val(el);
		$input.val($(li).html());
		return true;
	}
	
	// select value
	function getCurrentSelected() {
		return $select.val();
	}
	
	// input value
	function getCurrentValue() {
		return $input.val();
	}
	
	function getSelectOptions(parentid) {
		var select_options = new Array();
		var ul = document.createElement('ul');
		$select.children('option').each(function() {
			var li = document.createElement('li');
			li.setAttribute('id', parentid + '_' + $(this).val());
			li.innerHTML = $(this).html();
			if ($(this).is(':selected')) {
				$input.val($(this).html());
				$(li).addClass(opt.hoverClass);
			}
			ul.appendChild(li);
			$(li)
			.mouseover(function(event) {
				hasfocus = 1;
				jQuery(event.target, $container).addClass(opt.hoverClass);
			})
			.mouseout(function(event) {
				hasfocus = -1;
				jQuery(event.target, $container).removeClass(opt.hoverClass);
			})
			.click(function(event) {
				$(this).addClass(opt.hoverClass);
				setCurrent();
				hideMe();
			});
		});
		return ul;
	}
};

