/**
 * Hide links
 */
 /*
if (document.addEventListener) {
	document.addEventListener("DOMContentLoaded", OnPageLoad, false);
} else {
	window.addEvent("domready", function () {alert(1)});
}
*/

//format phone field to smart view
function formatPhone(phoneField) {
	var regExpNotDigit = /[^\d]+/g;
	var onlyDigit = phoneField.value.replace(regExpNotDigit, "");
	var formatPhone = /(\d{3})(\d{2})(\d{2})(?:\d*)/;
	phoneField.value = onlyDigit.replace(formatPhone, "$1-$2-$3");
}

//format sms phone field to smart view
function formatSMSPhone(phoneField) {
	var regExpNotDigit = /[^\d]+/g;
	var onlyDigit = phoneField.value.replace(regExpNotDigit, "");
	var formatPhone;
	if (onlyDigit.substring(0,3) == '375') {
		formatPhone = /(\d{3})(\d{2})(\d{3})(\d{2})(\d{2})(?:\d*)/;
	} else {
			formatPhone = /(\d)(\d{3})(\d{3})(\d{2})(\d{2})(?:\d*)/;
	}
	phoneField.value = onlyDigit.replace(formatPhone, "+$1 ($2) $3-$4-$5");
}

function formatPhoneForFrends(phoneField) {
	var regExpNotDigit = /[^\d]+/g;
	var onlyDigit = phoneField.value.replace(regExpNotDigit, "");
	var formatPhone = /(\d)(\d{3})(\d{3})(\d{2})(\d{2})(?:\d*)/;
	phoneField.value = onlyDigit.replace(formatPhone, "+$1 ($2) $3-$4-$5");
}

// gets body vertical scroll value
function getBodyScrollTop() {
	return window.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);
}

function savePageScrollValue(form) {
	if (form.pageScrollField) {
		form.pageScrollField.value = getBodyScrollTop();
	}
}

Events.attach(window, "load", onPageLoad);

function onPageLoad() {
	//scroll page if need
	if (typeof needPageScrollValue != "undefined" && needPageScrollValue != 0) {
		window.scrollTo(0, needPageScrollValue);
	}

	var tags = ['a', 'div'];

	for(var j=0; j<tags.length; j++)
	{
		var elementsByTag = document.getElementsByTagName(tags[j]);

		if(elementsByTag!=null)
		{
			var elementsByTagToActivate=new Array();

			if(!elementsByTag.length) {
				var elementsByTag_ = new Array();
				elementsByTag_[0] = elementsByTag;
				elementsByTagToActivate = elementsByTag_;
			} else {
				elementsByTagToActivate = elementsByTag;
			}

			for(var i=0;i<elementsByTagToActivate.length;i++) {
				var current = elementsByTagToActivate[i];
				if(current.id=='waitLoad') {
					//current.style.display='block';
					current.style.visibility='visible';
				}
			}
		}
	}

	var elementsByTag = document.getElementsByTagName('ul');

	if(elementsByTag) {
		var elementsByTagToActivate=new Array();

		if(!elementsByTag.length) {
			elementsByTagToActivate = new Array(elementsByTag);
		} else {
			elementsByTagToActivate = elementsByTag;
		}

		var reg = /FlowerOfTime_\d+_(\d+)/i;

		for(var i=0; i<elementsByTagToActivate.length; ++i) {
			var d = reg.exec(elementsByTagToActivate[i].id);
			if( d ) {
				new FlowerOfTime(elementsByTagToActivate[i].id, d[1], 86400000, ULOfTime);
			}
		}
	}

	var divs = document.getElementsByTagName("div");

	var dialogRE = /dialog/; // Any alert window
	var terrorRE = /t-error/; // Tapestry validation errors
	var popupRE = /pop-up-win2/; // Pop-ups excepting Waitnglist
	var popupActRE = /PopUp/; // Campaign change warning

	for (var i = 0; i < divs.length; i++) {

		var div = divs[i];

		if ( popupRE.test(div.className) || popupActRE.test(div.className) || dialogRE.test(div.className) || terrorRE.test(div.className) ) {

			if(popupActRE.test(div.className)) {
				div.id="dialog";
				div.style.display = "none";
			} else {
				if (div.id=="") {
					var header = document.createElement("h1");
					var headerText = document.createTextNode("Внимание:");
					div.firstChild.className="description";
					div.insertBefore(header, div.firstChild);

					//div.appendChild(header,div.firstChild);

					header.appendChild(headerText);
					div.id="dialog";
					div.style.display = "none";
					var ok = document.createElement("div");
					ok.className = "we_do-choise";
					var a = document.createElement("a");
					a.className="button";
					a.href = "javascript: void(0)";
					a.onclick = ___hide;
					a.appendChild(document.createElement("i"));
					a.appendChild(document.createElement("b"));
					var s = document.createElement("span");
					s.appendChild(document.createTextNode("Закрыть"));
					a.appendChild(s);
					ok.appendChild(a);
					div.appendChild(ok);
				}
			}

			div.className = "PopUp";
			Lightview.show({ href: "dialog", rel: 'inline', autosize: true});
			//Lightview.show("#dialog");

			$j(".we_do_choise_a_link").css("float", "right");

			break;
		}
	}

	//If hash not empty - open overlay with video
	function redirFromHash(){
		var hash = 'url='+window.location.hash.substr(1)+'.swf';
		var testit = window.location.hash.substr(1)+'_banner.jpg';
		var flag;

		$j("img").each(function (i) {
			if($j(this).attr('src')==testit){
				flag=true;
			}
		});
		if (hash != '' && flag) {
			 Lightview.show({
				href: '/flash/preloader.swf',
				options: {
					flashvars: hash,
					autosize: true
				}
			  });

		}
	}
	redirFromHash();

}

function ___hide(a) {
    if(a!= null && a.href != undefined){
	   a.href="#dummy";
    }
	Lightview.hide();
	return false;
}

/**
 * Shop details viewer
 */

var lock = false;
var cur_src;
var flag_cur = false;
var binded_zoom = new Array();
//jqZoom styles:
var options =
{
	zoomWidth: 290,
	zoomHeight: 276,
	title: false,
	xOffset: 10,
	lens:false
}

function releaseLock() {
	lock = false;
}

ShopDetailsViewer = {
	hoverhandler:null,
	spanRE:/span/i,
	imgRE:/img/i,
	init:Events.attach(window, "load", function() {
		$j(".showBlock").attr('class','lightview showBlock jqzoom');
		$j(".jqzoom").jqzoom(options);

		//subpic
		var subpicHeight;
		var subpicCount = $j("#PreImg img").length/2;
		var rows = Math.floor(subpicCount/3)+1;
		subpicHeight = rows*90;

		$j(".subpic").attr('height',subpicHeight);
		//Пишем в массив забинденных
		var first_small_img = $j("#PreImg img").slice(0, 1).attr('src');
		binded_zoom[0] = first_small_img;

		ClickHandler.addHandler("enlarge", ShopDetailsViewer.enlarge);
		var viewer = document.getElementById("PreImg");
		ShopDetailsViewer.hoverhandler = Events.attach(viewer, "click", ShopDetailsViewer.hover);
		Events.detach(ShopDetailsViewer.init); //cleanup
	}),

	hover:function(e) {
	    var zoomMode = "jqzoom";
	    var zoomOptions = options;
		var e = e||event;

		target = e.target||e.srcElement;
		//alert(target);
		if (ShopDetailsViewer.spanRE.test(target.nodeName)) {
			var target = target.nextSibling;
		}

		if (ShopDetailsViewer.imgRE.test(target.nodeName)) {

			//zoom button has been pressed
			if(target.src.endsWith("i_zoom_sml1.png")) return;

			//alert(cur_src+' - '+target.src)
			if (cur_src != target.src) {
				cur_src = target.src;
				flag_cur = false;

				//Делаем массив уже забинденных зумов
				var is_there = false;
				for (t = 0; t < binded_zoom.length; t++) {
					if (binded_zoom[t]==cur_src){is_there=true;}
				}
				if(!is_there){binded_zoom.push(cur_src);}
			} else {
				flag_cur = true
			}

			if (!flag_cur) {

				if (lock == true) {
					return;
				}
				else {
					lock = true;
				}

				var images = document.getElementsByTagName("img");
				for (var i = 0; i < images.length; i++) {
					var currentImg = images[i];
					if (currentImg.id != "previewImg") {
						continue;
					}
					//var expectedLargeImageSrc = target.src.replace("tmb", "detail");
					var expectedLargeImageSrc = target.src.replace("detail", "original");
					expectedLargeImageSrc = expectedLargeImageSrc.replace(".png", ".jpg");
					if (currentImg.src == expectedLargeImageSrc) {
						currentImg.parentNode.className = 'lightview showBlock ' + zoomMode;
						currentImg.parentNode.style.display = 'block';
						$j('#imgBig').attr("href", currentImg.src.replace("detail", "original"));
					}
					else {
						currentImg.parentNode.className = 'hideBlock';
						currentImg.parentNode.style.display = 'none';
					}
				}

				if (!is_there) {
					//alert('привязка');
					$j("." + zoomMode).jqzoom(zoomOptions);
				}

				setTimeout('releaseLock()', 200);
			}
		}

	},
	enlarge:function(target) {
		var win = window.open("about:blank", "b4fgallery", "menubar=0,location=0,toolbar=0,personalbar=0,status=0,scrollbars=0,width=150,height=150");
		var content = "<html><head><title>kupivip.ru</title></head><body style=\"width: 100%; height: 100%; overflow: hidden;\">"
		content += "<img onclick=\"window.close()\" src=\"" + target.href + "\" />";
		content += "<script>" +
				"window.onload = function() {" +
				" var body = document.getElementsByTagName(\"body\")[0];" +
				" var img = document.images[0];" +
				" var width = img.width + (150 - body.offsetWidth);" +
				" var height = img.height + (150 - body.offsetHeight);" +
				" if (width < img.width) width = img.width+20;" + //Firefox statusbar-bug might prevent me from making a correct guess
				" if (height < img.height) height = img.height;" + // set correct height for safari
				" window.resizeTo(width, height);" +
				"};" +
				"</script>";
		content += "</body></html>"
		win.document.open("text/html");
		win.document.write(content);
		win.document.close();
		return true;
	}
}

function StartCountDown(myDiv, myDisplayFormat, myEndMessage, myTargetDate, currentServerDate)
{
    var dthen = new Date(myTargetDate);
    var dnow = new Date(currentServerDate);
    ddiff = new Date(dthen - dnow);
    gsecs = Math.floor(ddiff.valueOf() / 1000);
    CountBack(myDiv, gsecs, myDisplayFormat, myEndMessage);
}

function Calcage(secs, num1, num2)
{
    s = ((Math.floor(secs / num1)) % num2).toString();
    if (s.length < 2) {
        s = "0" + s;
    }
    return (s);
}

function CountBack(myDiv, secs, myDisplayFormat, myEndMessage)
{
    var DisplayStr = myDisplayFormat.replace(/%%D%%/g, Calcage(secs, 86400, 100000));
    DisplayStr = DisplayStr.replace(/%%H%%/g, Calcage(secs, 3600, 24));
    DisplayStr = DisplayStr.replace(/%%M%%/g, Calcage(secs, 60, 60));
    DisplayStr = DisplayStr.replace(/%%S%%/g, Calcage(secs, 1, 60));
	var isEmptyBasket = document.getElementById("emptyBasket");
    var divElement = $j(myDiv);
    if (divElement != null) {
        if (secs > 0) {
            if(myDiv == "clock_basket" && secs == 180 && isEmptyBasket != null && isEmptyBasket.value == "false") {
                    $j("#dialog").remove();
                    var div = document.createElement('DIV');
                    div.id = 'dialog';
                    div.className = 'PopUp';
                    div.style.display = 'none';
                    div.innerHTML = '<h1>Сообщение:</h1>'+
                    '<div class="description">Срок резервирования товара заканчивается через 3 минуты. Пожалуйста оформите покупку, либо товар будет удален из корзины.</div><div class="we_do-choise">'+
                    '<a onclick="Lightview.hide();return false;" class="button" href="/shop/basket"><i></i><b></b><span>Закрыть</span></a></div>';
                    //jQuery('body').append(errorText);
                    document.body.appendChild(div);
                    try {
                    Lightview.show('#dialog');
                    }catch (e) {}
            }
            divElement.innerHTML = DisplayStr;
            setTimeout("CountBack('" + myDiv + "'," + (secs - 1) + ",'" + myDisplayFormat
                + "', '" + myEndMessage + "');", 990);
        } else {
        	$j('#' + myDiv).parent().html('<span id="clock_basket">' + myEndMessage + '</span>');
        }
    }
}

/**
 * WaitingList
 */

ClickHandler.addHandler("open_waitinglist_popup", function(target) {
	var id = target.href;
	id = id.substr(id.indexOf("#") + 1);
	var node = $(id);
	if (node) {

		if (node.getStyle("display") != 'block') {
			if (this.currentDialog) {
				ClickHandler.handlers["close_waitinglist_popup"](this.currentDialog);
			}
			node.style.display = "block";

			//Let's figure out if the user can 'see' the dialog.
			var nt = node.cumulativeOffset().top;
			var nb = nt + node.offsetHeight;
			var sc = (document.documentElement||document.body)
			var sp = sc.scrollTop;
			var spb = sp + sc.clientHeight;
			if (nt < sp) { //top is cut of, should be rare with the dialog positioned next to the info
				node.scrollTo();
			} else if (nb > spb) { //bottom is cut of, let's determine how far to move, if at all
				var offset = nb - spb;
				sc.scrollTop = (sp + offset > nt)?nt:(sp + offset);
			}
		} else {
			ClickHandler.handlers["close_waitinglist_popup"](this.currentDialog);
		}
	}
	this.currentDialog = target;
	return true;
});

ClickHandler.addHandler("close_waitinglist_popup",function(target) {
	var id = target.href;
	id = id.substr(id.indexOf("#") + 1);
	var node = document.getElementById(id);
	if (node && !node.isFolding) {
			node.style.display = "none";
	}
	ClickHandler.handlers["open_waitinglist_popup"].currentDialog = null;
	return true;
});


/**
 * Shop past
 */
ShopPastHelper = {
	init:Events.attach(window, "load", function() {
		if (ClickHandler) ClickHandler.addHandler("teaser", ShopPastHelper.teaser);
		Events.detach(ShopPastHelper.init); //cleanup
	}),
	teaser:function(target, size) {
		var x = size?size.x:400;
		var y = size?size.y:288;
		var win = window.open("about:blank", "b4fgallery", "menubar=0,location=0,toolbar=0,personalbar=0,status=0,scrollbars=0,width=150,height=150");
		var content = "<html><head><title>Brands4friends.de</title></head><body style=\"width: 100%; height: 100%; overflow: hidden;\">"
		content += "<script>" +
				"window.onload = function() {" +
				" var body = document.getElementsByTagName(\"body\")[0];" +
				" var width = " + x + " + (150 - body.offsetWidth);" +
				" var height = " + y + " + (150 - body.offsetHeight);" +
				" window.resizeTo(width, height);" +
				" window.location.href = \"" + target.href + "\";" +
				"};" +
				"</script>";
		content += "</body></html>"
		win.document.open("text/html");
		win.document.write(content);
		win.document.close();
		return true;
	}
}

function openNewWindow(URLtoOpen, windowName, windowFeatures) {
	var features = windowFeatures?windowFeatures:"";
  	ShopPastHelper.teaser(URLtoOpen, {x:600,y:400}, features);
}

/**
 * Flower of time
 *
 * This is a helper to make the 'Flower of Time' dynamically
 * countdown it's clock...
 * @author Martin Reurings
 * @constructor
 * @requires Events
 * @depends events.js
 * @param {String} id The id of the node that will be used for rendering in.
 * @param {Integer} millies The amount of millisecond towards which the clock runs.
 * @param {Integer} bignum The largest time-amount to be calculated, week, day, hour or second. For numeric values see FlowerOfTime.DURATION[]
 * @param {Function} render An optional alternate rendering function, in case this class is used for a different html-construct.
 **/
function FlowerOfTime(id, millies, bignum, render) {
	this.flower = document.getElementById(id);
	if (this.flower == null) alert("464F54.001: Flower cannot be initiated, id '" + id + "' cannot be found!");
	var now = new Date();
	var millisek = parseInt(millies);
	this.doom = new Date(now.getTime() + millisek);
	this.bignum = bignum || this.DURATION.week;
	this.render = render || this.defaultRender;
	//Render the first time
	this.render(this.difference(this.bignum));
	var self = this;
	var timer = window.setInterval(function() {
		self.showtime();
	}, this.DURATION.second * 1);
	var cleanup = Events.attach(window, "unload", function() {
		window.clearInterval(timer);
		Events.detach(cleanup);
	});
};

FlowerOfTime.prototype = {
	/**
	 * Time related constants.
	 */
	DURATION:{
		second:1000,
		minute:60000,
		hour:3600000,
		day:86400000,
		week:604800000
	},
	/**
	 * Div that returns an integer value instead of float.
	 * @param {Integer} a The number that is to be divided.
	 * @param {Integer} b The divider.
	 * @return An integer that is the whole number without fraction, not rounded down.
	 * @private
	 */
	ntgr:function(a, b) {
		var m = a % b;
		return (a - m) / b;
	},
	/**
	 * Calculate and return the difference between now and 'doom'.
	 * Returns a wrapper of the same structure as this.DURATION.
	 * @param {Integer} bignum The largest time-amount to be calculated, week, day, hour or second. For numeric values see FlowerOfTime.DURATION[]
	 * @return A 'Duration' object containing the remaining weeks/days/hours/minutes/seconds and millies.
	 */
	difference:function(bignum) {
		var now = new Date();
		var dif = this.doom.getTime() - now.getTime();
		//weeks
		if (bignum >= this.DURATION.week) {
			var weeks = this.ntgr(dif, this.DURATION.week);
			dif = dif % this.DURATION.week;
		}
		//days
		if (bignum >= this.DURATION.day) {
			var days = this.ntgr(dif, this.DURATION.day);
			dif = dif % this.DURATION.day;
		}
		//hours
		if (bignum >= this.DURATION.hour) {
			var hours = this.ntgr(dif, this.DURATION.hour);
			dif = dif % this.DURATION.hour;
		}
		//minutes
		if (bignum >= this.DURATION.minute) {
			var minutes = this.ntgr(dif, this.DURATION.minute);
			dif = dif % this.DURATION.minute;
		}
		//seconds
		if (bignum >= this.DURATION.second) {
			var seconds = this.ntgr(dif, this.DURATION.second);
			dif = dif % this.DURATION.second;
		}

		return {
			second:seconds,
			minute:minutes,
			hour:hours,
			day:days,
			week:weeks,
			millies:dif
		}
	},
	/**
	 * Calculate the difference and call the render method.
	 */
	showtime:function() {
		var dif = this.difference(this.bignum);
		this.render(dif);
	},
	/**
	 * The default rendering method.
	 * @argument {Duration} dif The duration until point 0 pre-calculated in weeks/days/hours/minutes/seconds
	 * @private
	 */
	defaultRender:function(dif) {
		var el = this.flower;
		var node = document.createTextNode(dif.hour + ":" + dif.minute + ":" + dif.second);
		el.replaceChild(node, el.lastChild);
	}
};

/**
 * Rendering method for FlowerOfTime based on the implementation in B4F.
 * @argument {Duration} dif The duration until point 0 pre-calculated in weeks/days/hours/minutes/seconds
 */
function ULOfTime(dif) {
	var el = this.flower;

	if(el.style.display=='none') {
		el.style.display='block';
	}

	var times = el.getElementsByTagName("li");
	var nrSwap = function (srcNode, nr, f) {
		var re = /^\d+([^\d]+)$/;
		if((nr < 10) && !f) nr = "0" + nr;
		if(!f) nr = ":" + nr;

		var node = document.createTextNode(nr);
		srcNode.replaceChild(node, srcNode.firstChild);
	}
	//days
	times[0] && nrSwap(times[0], dif.day, 1);
	//hours
	times[1] && nrSwap(times[2], dif.hour, 1);
	//minutes
	times[2] && nrSwap(times[3], dif.minute);
	//seconds
	times[3] && nrSwap(times[4], dif.second);
}

/**
 * Shop compact directory
 */
/**
 * ShopCompactDirectory helper to make the compact directory javascripted so that
 * it looks pretty ;)
 *
 * @author: Martin Reurings
 * @copyright: brands4friends
 * @constructor
 * @argument {List<String, Object>} args A List of arguments
 */

function ShopCompactDirectoryHelper(args) {
	if (this.reporter && !this.reporter.className) {
		this.reporter.parentNode.className = "reporterLogger";
		document.body.appendChild(this.reporter.parentNode);
	}
	var self = this; //Circular reference, cleanup must cleanup all events created in this method!
	//Calculate the regions for the directory's animation speed.
	var normal = Math.round((100 - (args.stop||33)) / 2);
	var FR = args.fast||10;
	var R = normal;
	var FF = 100 - FR;
	var F = 100 - R;
	//Store the calculated regions.
	this.regions = {FR:FR,R:R,F:F,FF:FF};
	//'Lazy' initialisation, waits until page finished loading before attempting to attach events etc.
	var init = Events.attach(window, "load", function() {
		self.directory = document.getElementById(args.nodeId);
		if (self.directory == null) {
			alert("Error 534344.001: Can't initiate ShopCompactDirectoryHelper for node with id '" + args.nodeId + "', node does not exist!");
			return false;
		};
		self.replicate(args.replicate||3);
		self.startPosition(args.replicate||3);
		var mouseMoveEvent = Events.attach(self.directory, "mousemove", function(e) {
			window.internetexplorereventcancelationbugfix = true;
			return self.mouseOver(e||event, self);
		});
		var killEvent = Events.attach(document.body||document.documentElement, "mousemove", function(e) {
			if (!window.internetexplorereventcancelationbugfix) self.stop();
		});
		var cleanup = Events.attach(window, "unload", function() {
			Events.detach(mouseMoveEvent);
			Events.detach(killEvent);
			Events.detach(cleanup);
		});
		Events.detach(init);
	});
}

ShopCompactDirectoryHelper.prototype = {
	/**
	 * This method replicates a certain amount of items to make the
	 * seemless wrap-around back to the start of the list.
	 * @private
	 */
	replicate:function(num) {
		var d = this.directory;
		var count = 0;
		//remove whitespace nodes
		while (count < d.childNodes.length) {
			var c = d.childNodes[count];
			if (c.nodeType != 1) {
				d.removeChild(c);
			} else count++;
		}
		var children = d.childNodes;
		if (children.length > (num + 1)) { //(num +1) because when there's 4 products, one is the current one and no scrolling will be needed...
			for (i=0,s=0; (i - s) < num; d.appendChild(children[i++].cloneNode(true))) {
				if (children[i].className.indexOf("current_true") >= 0) s++;
			}
		}
	},
	startPosition:function(num) {
		var d = this.directory;
		var children = d.childNodes;
		if (children.length > (num + 1)) { //(num +1) because when there's 4 products, one is the current one and no scrolling will be needed...
			for (i=num; i < children.length; ++i) { //Skipping the first node because if that's the instace of current_true we want to jump to its' clone
				if (children[i].className.indexOf("current_true") >= 0) this.scroll(children[i - 1].offsetLeft);
			}
		}
	},
	/**
	 * This code stops the directory's animation.
	 */
	stop:function() {
		if (this.timer != false) {
			window.clearInterval(this.timer);
			this.timer = this._forward = this._fastforward = this._reverse = this._fastreverse = false;
			if (this.reporter) this.reporter.nodeValue = "Killed the timer";
			return true;
		} return false;
	},
	/**
	 * This code starts the directory's animation.
	 *
	 * @param {int} The amount of pixels to jump forward per interval.
	 * @private
	 */
	start:function(px) {
		this.stop();
		var self = this;
		this.timer = window.setInterval( function() {
			//if (self.reporter) self.reporter.nodeValue = "Scrolling at a speed of " + px;
			self.scroll(px);
		}, 50 );
		if (this.reporter) this.reporter.nodeValue = "Started the timer";
	},
	/**
	 * @private
	 */
	forward:function() {
		if (this._forward) return true;
		else {
			this.start(1);
			this._forward = true;
		}
	},
	/**
	 * @private
	 */
	fastforward:function() {
		if (this._fastforward) return true;
		else {
			this.start(5);
			this._fastforward = true;
		}
	},
	/**
	 * @private
	 */
	reverse:function() {
		if (this._reverse) return true;
		else {
			this.start(-1);
			this._reverse = true;
		}
	},
	/**
	 * @private
	 */
	fastreverse:function() {
		if (this._fastreverse) return true;
		else {
			this.start(-5);
			this._fastreverse = true;
		}
	},
	/**
	 * This is the code-snippet use to scroll the directory.
	 *
	 * @param {int} The amount of pixels to jump forward.
	 * @private
	 */
	scroll:function(px) {
		window.internetexplorereventcancelationbugfix = false;
		var d = this.directory;
		var c = d.scrollLeft;
		d.scrollLeft=c + px;
		if (c == d.scrollLeft) d.scrollLeft = (c > 0)?0:(d.lastChild.offsetLeft + 1000);
	},
	/**
	 * Get the x and y position of the mouse, relative to the top-left
	 * corner of the directory.
	 *
	 * @param {Event} The event object for the last mouse move.
	 * @private
	 */
	getPosition:function(e, rel) {
		var x = e.pageX||e.clientX;
		var y = e.pageY||e.clientY;
		var offsetX = rel.offsetLeft;
		var offsetY = rel.offsetTop;
		var relOffset = rel;
		while (relOffset = relOffset.offsetParent) {
			offsetX += relOffset.offsetLeft;
			offsetY += relOffset.offsetTop;
		}
		x -= offsetX;
		y -= offsetY;
		return {x:x,y:y};
	},
	/**
	 * A method to handle mouseover events on a directory html-construct.
	 *
	 * @param {Event} The event object for the last mouse move.
	 * @param {ShopCompactDirectoryHelper} The helper object which is associated with this event/directory.
	 * @private
	 */
	mouseOver:function(e,helper) {
		var pos = this.getPosition(e, this.directory);
		var percent = Math.round(pos.x / this.directory.offsetWidth * 100);
		if (percent < this.regions.FR) { //The mouse moves in the leftmost 10 percent, fast-reverse speed
			helper.fastreverse();
			//if (this.reporter) this.reporter.nodeValue = "fr x=" + pos.x + ", y=" + pos.y + ", s=" + this.directory.scrollLeft;
		} else if (percent < this.regions.R) { //The mouse moves in the leftmost 33 percent, normal reverse speed
			helper.reverse();
			//if (this.reporter) this.reporter.nodeValue = "r x=" + pos.x + ", y=" + pos.y + ", s=" + this.directory.scrollLeft;
		} else if (percent > this.regions.FF) { //The mouse moves in the rightmost 10 percent, fast-forward speed
			helper.fastforward();
			//if (this.reporter) this.reporter.nodeValue = "ff x=" + pos.x + ", y=" + pos.y + ", s=" + this.directory.scrollLeft;
		} else if (percent > this.regions.F) { //The mouse moves in the rightmost 33 percent, normal forward speed
			helper.forward();
			//if (this.reporter) this.reporter.nodeValue = "f x=" + pos.x + ", y=" + pos.y + ", s=" + this.directory.scrollLeft;
		} else { //The mouse moves in the center 33 percent, don't move
			helper.stop();
			//if (this.reporter) this.reporter.nodeValue = "stop x=" + pos.x + ", y=" + pos.y + ", s=" + this.directory.scrollLeft;
		}
		return Events.cancel(e); //Need to cancel this event, otherwise the killEvent will stop it...
	},
	/**
	 * @private
	 */
	reporter:false//document.createElement("div").appendChild(document.createTextNode(""))
};

function showErrorMessage(msg) {
	var div = document.getElementById('dialog');
	if(!div) {
		div = document.createElement('DIV');
		div.id = 'dialog';
		div.className = 'PopUp';
		div.style.display = 'none';
	} else {
		div.innerHTML = '';
	}

	div.innerHTML = '<h1>Сообщение:</h1>'+
	'<div class="description">'+msg+'</div><div class="we_do-choise">'+
	'<a onclick="Lightview.hide();return false;" style="float: right;" class="button" href="/shop/basket"><i></i><b></b><span>Закрыть</span></a></div>';

	document.body.appendChild(div);
	try {
	Lightview.show('#dialog');
	}catch (e) {}
}

function toggleBanner(){
	var	flag = true;
	var banner = $j("#banner");
	var imgg = $j("#banner").find("img");
	$j(".slide").fadeOut(300, function() {
		if (banner.hasClass("min")) {
			//$j(".slide > .icon").removeClass('expand').addClass('cutdown');
			imgg.animate({top: '-36px'}, 300);
			banner.animate({height: '300px'}, 300, function() {
				$j(".slide").fadeIn(300);
			}).removeClass("min");
		} else {
			//$j(".slide > .icon").removeClass('cutdown').addClass('expand');
			banner.animate({height: '36px'}, {
				duration: 300,
				step:function() {
					if ( ( banner.height() < 250 ) && flag) {
						imgg.animate({top: '0px'}, 300);
						flag = false;
					}
				},
				complete: function() {
					$j(".slide").fadeIn(300);
				}
			}).addClass("min");
		};
	});
}
/*
function togglePoster(){
	$j(".slide").fadeOut(300, function() {
		if ( $j("#poster").hasClass("show") ) {
			$j("#poster").animate({height: '74px'}, 600, function() {
					$j(".slide").fadeIn(300);
				});
		} else {
			$j("#poster").animate({height: '700px'}, 300, function() {
				$j(".slide").fadeIn(300);
			});
		};
		$j("#poster").toggleClass("show");
	});
}
*/
function togglePoster(r){
	var flag = true;
	var banner = $j("#poster");
	var imgg = banner.find("img");
	$j(".slide").fadeOut(300, function() {
		if (banner.hasClass("show") && !r) {
			banner.animate({height: '80px'}, {
				duration: 300,
				step:function() {
					if ( ( banner.height() < 260 ) && flag) {
						imgg.animate({top: '0px'}, 300);
						flag = false;
					}
				},
				complete: function() {
					$j(".slide").fadeIn(300);
				}
			}).removeClass("show");
		} else {
			imgg.animate({top: '-80px'}, 300);
			banner.animate({height: '280px'}, 300, function() {
				$j(".slide").fadeIn(300);
			}).addClass("show");
		};
	});
}

$j(document).ready(function(){
	//Click on Lightwindow

	changeImgs();

	$j('form[id*="shoppingform"]').submit(function() {
		if ($j('select', this).val() == '') {
			$j("#dialog").remove();
			var errorText = '<div id="dialog" class="PopUp" style="display:none"><h1>Сообщение:</h1><div class="description">Выберите размер товара.<br/></div><div class="we_do-choise"><a onclick="Lightview.hide();return false;" class="button"><i></i><b></b><span>Закрыть</span></a></div></div>';
			$j('body').append(errorText);
			Lightview.show('#dialog');
			return false;
	    }
	});

	/*
	if ($j('.actions-start img').length > 0) {
		var img = $j('.actions-start img');
		if (img.height() <= 360) {
			img.css({top: '-80px'});
		}
	}
	*/
	if ($j('#poster').hasClass("show")) {
		togglePoster(true);
	}

	$j(function() {
			$j("#banner > .slide").click(function(){
				toggleBanner();
			});

			$j("#poster > .slide").click(function(){
				togglePoster();
			});

		   $j(".clickable").click(function(){
			   document.location = $j(this).attr('href');
			   })
   		   $j(".clickable_past").click(function(){
				   document.location = $j(this).find('a').attr('href');
		   })


		   $j("a.button").hover(
				function(){
					$j(this).toggleClass("over");
				},
				function () {
					$j(this).toggleClass("over");
				}
			);

			$j("i.icon.help").click(function(){
				var position = $j(this).offset();
				var tips = $j(this).attr("href");
				$j(tips).css({left: position.left - 246 + "px", top: position.top + 15 + "px"}).show();
			});

			$j("body").click(function(e) {
                var target = $j(e.target);

                if ((!target.hasClass("tooltips") && !target.parent().hasClass("tooltips") && !target.hasClass("help")) || target.hasClass("close")) {
                   $j(".tooltips").hide();
                }
            });

		//init zoom
		$j(".jqzoom").jqzoom(options);


		// init Flower of Time
		if (typeof 'runFT'=='function') {
			runFT();
		}
	});


	  $j('.banner_action.cik').click(function() {
		var thisLink = $j(this).find('a').attr('href');
		var location_pathname = document.location.pathname;
		document.location = thisLink;
	  });
	  //*
	  //* Pop-up is getting up not only for future actions
	  //* NEED TO FIX
	  //*
	  //$j('.action-item').find('.inner').click(function() {
	  //var thisLink = $j(this).find('a').attr('href');
	  // Lightview.show({
	  //  href: thisLink,
	  //  rel: 'flash'
	  // });
	  // });

	var rollOverBox = $j('div.actions-start');
	rollOverBox.mouseenter(function() {
		$j('div.box-popup').fadeIn(400);
	});
	rollOverBox.mouseleave(function() {
			$j('div.box-popup').fadeOut(400);
	});

	//breadscrumbs
	$j('#breadscrumbs').find('td:last-child').find('a').attr('class', 'last');

	$j('#countrySelect').change(function () {
		var val = $j(this).attr('value');

		$j('select option:selected').each(function () {
			if(val != 'MO' && val != '') {
				$j('#hidden-areas').fadeIn().find('label.basket_zip').focus();
			} else {
				$j('#hidden-areas').fadeOut();
			}
		});
	});

	$j('div.invite-box').find('img').click(function() {
		$j(this).parent().find('div.signin-box').slideToggle("fast", function() {
			if($j(this).attr('style') == 'display: none;') {
				$j(this).find('div.loadinfo').fadeOut("fast");
			}
		});
	});

	// сейчас дополнительный кнтент (а-ля список друзей) показывается при клике
	// на форму авторизации,
	// если я всё правильно понял надо повесить это на сабмит - при верной авторизации
	// немного переписав
	$j('div.invite-box').find('label').click(function() {
		$j(this).parent().find('div.loadinfo').fadeIn("slow");
	});

	// prizes
	$j('div.contenttext').find('p:last-child').find('a.prizes_link').parent().css({
		backgroundImage : 'none',
		marginBottom : '-52px'
	});

	$j('div.contenttext').find('div.post-press-box:last-child').css({
		marginBottom : '-52px'
	});

	$j('div.contenttext').find('div.content-inner').click(function() {
		document.location = $j(this).find('a.b-link').attr('href');
	}).hover(function() {
		 $j(this).find('a.b-link').css({ textDecoration : 'underline' });
	}, function() {
		 $j(this).find('a.b-link').css({ textDecoration : 'none' });
	});

	$j(".nav.next").click(function(e) {
		var id = e.target.id;
		var self = $j('.scrollable', $j(this).parent()),
			itemWrap = self.children(),
			getItems = function(item) {
				return itemWrap.children();
			},
			i = 1;
		var item = getItems().eq(i);
		var props = {left: -item.position().left};
		itemWrap.stop().animate(props, 300, function(){
			getItems().slice(0,i).appendTo(itemWrap);
			itemWrap.css({left: 0});
		});

	});
	$j(".nav.prev").click(function(e) {
			var id = e.target.id;
			var self = $j('.scrollable', $j(this).parent()),
				itemWrap = self.children();
				getItems = function(item){
					return itemWrap.children();
				},
				i = 1;
			var item = getItems().slice(-i).prependTo(itemWrap);
			var props = {left: -getItems().eq(i).position().left};
			itemWrap.stop().css(props);
			itemWrap.animate({left:0}, 300);

	});

	$j('#ifriend').click(function() {
		this.value = '';
	});

	function clear() {
		var input = $j('#ifriend');
		if (input.attr('value') == '') {
			input.attr('value', 'e-mail');
		}
	}

	$j('#ifriend').mouseleave(function() {
		setTimeout(clear, 5000);
	});

});

function AddEmailInput() {
    try {
        var d = document.getElementById("email_more_fields");
        if (d.childNodes.length < 21) {
            var i = document.createElement("input");
            i.className = "text";
            i.style.width = "280px";
            i.type = "text";
            i.name = "emailFieldValue_" + currentEmailIndex;
            i.value = currentEmailIndex + '. ' + emailMessage;
            i.onclick = BindArgument(ClearInput, i);
            d.appendChild(i);
            i = document.createElement("br");
            d.appendChild(i);
            currentEmailIndex++;
            if ($j.browser.opera) {
                $j("#add_email_input").css("top", $j("#add_email_input").position().top + 32);
            }
        }
    } catch(e) {
    }
    return false;
}

function waitingListJson(json) {
	if (json) {
		if (json.accepted == true) {
			Lightview.hide();
			$j(".acceptArea").html('<span style="vertical-align:middle">Ждём 10 человек.</span>');
		} else {
			showErrorMessage("Возможно этого пользователя уже пригласили");
		}
	}
}

function _acceptWA(action, hash) {
	if (hash) {
		var data = {};
		var url = "/shop/start.newshoptemplate.newrightcolumn.waitinglist:internalevent/" + action + "/" + hash;

		jQuery.getJSON(url, data, waitingListJson);

		var ch = document.getElementById('_wa_link_id_' + hash).parentNode;
		var pr = ch.parentNode;

		pr.removeChild(ch);
	}

	return false;
}

function autoChangeValue(select) {
	for(var i = 0; i < select.length; i++) {
		if(select.options[i].value == "1985")
			select.options[i].defaultSelected = true;
	}
}

function checkOnSelectedCheckbox() {
	var form = document.getElementById("noMoreShowForm");
	var checkbox = document.getElementById("noMoreShowCheckbox");

	Lightview.hide();

	if (checkbox.checked) {
		form.submit();
	}
}

function remindMe(activityId) {
	var emailCheckbox = document.getElementById("remindByEmail_" + activityId);
	var smsCheckbox = document.getElementById("remindBySms_" + activityId);

	Lightview.hide();

	if (emailCheckbox.checked || smsCheckbox.checked) {
		document.getElementsByName("remindByEmail")[0].value = emailCheckbox.checked;
		document.getElementsByName("remindBySms")[0].value = smsCheckbox.checked;
		document.getElementsByName("activityId")[0].value = activityId;
		document.getElementById("remindForm").submit();
	}
}

function showMorePhone() {
	if(document.getElementById('phone1').style.display == 'none') {
		document.getElementById('phone1').style.display = 'inline';
	} else {
		document.getElementById('phone2').style.display = 'inline';
		document.getElementById('showPhoneLink').style.display = 'NONE';
	}
}

function textAreaLimit(obj, limit) {
	if (obj.value.length >= limit) {
		obj.value = obj.value.substring(0, limit - 1);
	}
}