/**
 * 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: 310,
	zoomHeight: 238,	
	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("#detailViewer img").length/2;
		var rows = Math.floor(subpicCount/3)+1;		
		subpicHeight = rows*90;
		
		$j(".subpic").attr('height',subpicHeight);
		//Пишем в массив забинденных
		var first_small_img = $j("#detailViewer img").slice(0, 1).attr('src');
		binded_zoom[0] = first_small_img;
		
		ClickHandler.addHandler("enlarge", ShopDetailsViewer.enlarge);
		var viewer = document.getElementById("detailViewer");
		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");
					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");
    if (document.getElementById(myDiv) != 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) {}
            }
            document.getElementById(myDiv).innerHTML = DisplayStr;
            setTimeout("CountBack('" + myDiv + "'," + (secs - 1) + ",'" + myDisplayFormat
                + "', '" + myEndMessage + "');", 990);
        } else {
            document.getElementById(myDiv).innerHTML = myEndMessage;
        }
    }
}

/**
 * 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) {}
}

$j(document).ready(function(){
	//Click on Lightwindow
	
	changeImgs();
	
	$j("input[value='В корзину']").click(function() {
		$j("#dialog").remove();
		var errorText = '<div id="dialog" class="PopUp" style="display:none"><h1>Сообщение:</h1><div class="description">Вы не выбрали товар<br/><br/>Для добавления товара в корзину, необходимо выбрать из выпадающего списка интересующий Вас товар и нажать на кнопку «В Корзину»</div><div class="we_do-choise"><a onclick="Lightview.hide();return false;" class="button" href="/shop/productdetail/12769"><i></i><b></b><span>Закрыть</span></a></div></div>';			
		var what = $j(this).parent('div').prev('div').find('select option:selected').attr('value');		
		if(what=="" || what=='undefined'){			
			$j('body').append(errorText);
			Lightview.show('#dialog');		

			return false;
		}	
	})
	
	$j(function() {

		   $j(".clickable").click(function(){
		   document.location = $j(this).attr('href');
		   })
		 
		   $j(".inner").mouseover(function(){
		    //$j(this).css('cursor','pointer');
		    $j(this).prev('.podsvetka').css('visibility','visible');
		    if(navigator.userAgent.indexOf("MSIE") > -1) {
		    	$j(this).prev('.podsvetka').css('top','-130px');
		    }
			//$j(this).prev('.podsvetka').pngfix({ });
		   }).mouseout(function(){
		    //$j(this).css('cursor','pointer');
		    $j(this).prev('.podsvetka').css('visibility','hidden');
		   });
		   
		   $j("a.button").hover(
				function(){
					$j(this).toggleClass("over");
				},
				function () {
					$j(this).toggleClass("over");
				}
			);


		//init zoom
		$j(".jqzoom").jqzoom(options);

		   
		// init Flower of Time
		if (typeof 'runFT'=='function') {
			runFT();
		}   
	});	
	
	
	  $j('.current_action').find('.inner').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);
	});
	
	/* fade pix in shop/directory */
function changeImgs(){ //������� ����� �������� � ������� �������
	var int_duration = 2000;
	var animation_duration = 700;

	var all_img = new Array(); // ������ ���� ������� �������� all_img[][]
	var count = 0;
	var img_box = $j("div#content_site .pix_holder");
	var mouse_over, fade_out_started, i, aImages;
	var intervalID = new Array();
	var interval_started = false;
	
	
	//������� ��� ����������
	img_box.each(function(i){
		all_img[count] = new Array();
		$j(this).attr('rel', count);
		
		var sub_count = 0; //������� ������ ����������
		var img_to_array = $j(this).find('input');
		
		//������� ��� ������ � ���������� ������ ����������
		img_to_array.each(function(i){
			var tmp_src = $j(this).attr('val');
			all_img[count][sub_count] = tmp_src;
			sub_count++;
		});
		
		//���������� ������ ��������
		var insert_image = '<img width="240" height="240" src="' + all_img[count][0] + '">'
		$j(this).find('.img_link').append(insert_image);
		
		
		
		$j(this).mouseenter(function(){			
			
			for(i=0; i<all_img.length;i++){
				clearTimeout(intervalID[i]);				
			}
			
			var what = $j(this);
			mouse_over = true;
			if (all_img[$j(what).attr('rel')].length > 1) { // ���� �������� ����
				changeImg(what, 0, true);
			}
		}).mouseleave(function(){
		
			mouse_over = false;
			var count = $j(this).attr('rel');
			
			if (interval_started == true) {
			
				clearTimeout(intervalID[count]);
				interval_started = false;
			}
			
			$j(this).stop(true);
			$j(this).find('img').attr("src", all_img[count][0]);
			$j(this).animate({
				opacity: 1
			}, 500);
		});
		
		count++;
		
		
		function changeImg(what, step, first_step){
			var count = $j(what).attr('rel');
			
			if (!first_step) {
				clearTimeout(intervalID[count]); // clear interval
				interval_started = true;
			}
			else {
				step = 1;
			}
			
			var preload_step;
			if (step == all_img[count].length) {
				preload_step = 0;
			} else {
				preload_step=step;
			}
			var preload = all_img[count][preload_step];
			//alert(preload);
			
			aImages = new Image();
			aImages.src = preload;
			
			if (mouse_over) {
				

				$j(what).animate({
					opacity: 0
				}, animation_duration, function(){
					$j(this).find('img').attr("src", all_img[count][step]);
					step++;
					
				});
				
				$j(what).animate({
					opacity: 1
				}, animation_duration, function(){
				
					if (step == all_img[count].length) {
						step = 0;
					}
					
					intervalID[count] = setTimeout(function(){
						changeImg(what, step); // use function
					}, int_duration);		
				});
			}	
		}
	});
}

	//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' });
	});
	
});

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) {
			var tb = document.getElementById('_wa_table');
			var ls = tb.getElementsByTagName('a');
			for(var i=ls.length; i>-1; i--) {
				if(ls[i])
				if(ls[i].className=="btn btn_invite") {
					var pr = ls[i].parentNode;
					var n = document.createElement('i');
					n.style.color="#DC2D8A";
					n.innerHTML="Ждём 10 человек.";
					pr.replaceChild(n,ls[i]);
				}
			}
		} else {
			showErrorMessage("Возможно этого пользователя уже пригласили");
		}
	}
}
function _acceptWA(action,hash) {
	if(hash) {
		var data = {};
		var url = "/shop/start.shoppagetemplate.rightcolumn.waitinglist:internalevent/"+action+"/"+hash;
		jQuery.getJSON(url, data, waitingListJson);
		Lightview.hide();
		var ch = document.getElementById('_wa_link_id_'+hash).parentNode.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 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);
	}
}
