function str_replace(search, replace, subject) {
    return subject.split(search).join(replace);
}

String.prototype.stripTags = function() {
  return this.replace(/<\/?[^>]+>/g, '');
};

function initselect()
{
	if (!$('#title').length)
	{
		return false;
	}

	var st = false;

	if ($('#title').html().match(/[^r]ring/gi))
	{
		$.browser.msie ? false :  $('#title-size').show();
		st = true;
	}
	else
	{
		$.browser.msie ? false :  $('#title-size').hide();
	}
	
	if ($('#priceRangeSelect').length)
	{
		var price	= parseInt($('#start-price').html()) + '-' + parseInt($('#stop-price').html());

		$.each($('#priceRangeSelect option'), function() {
				var item = $(this);
				if (item.attr('value') == price)
				{
					item.attr('selected', 'selected');
				}
			});

		$.browser.msie ? false :  $('#priceRangeSelect').show();
	}

	if ($('#typeSelect').length)
	{
		var type	= parseInt($('#custom-type').html());

		$.each($('#typeSelect option'), function() {
				var item = $(this);
				if (item.attr('value') == type)
				{
					item.attr('selected', 'selected');
				}
			});

		$.browser.msie || !st ? false : $('#typeSelect').show();
	}

	$.each($('select'), function() {
		
		var width = $(this).width();

		if (parseInt(width) > 2)
		{
			$(this).combobox( { comboboxContainerClass: "comboboxContainer", comboboxValueContainerClass: "comboboxValueContainer", comboboxValueContentClass: "comboboxValueContent", comboboxDropDownClass: "comboboxDropDownContainer", comboboxDropDownButtonClass: "comboboxDropDownButton", comboboxDropDownItemClass: "comboboxItem", comboboxDropDownItemHoverClass: "comboboxItemHover", comboboxDropDownGroupItemHeaderClass: "comboboxGroupItemHeader", comboboxDropDownGroupItemContainerClass: "comboboxGroupItemContainer", animationType: "none", width: width } );
		}

	});
	$('select').css({display:"none"});
	$(".comboboxDropDownContainer").css({display:"none"});
	
	if ($('#priceRangeSelect').length)
	{
		$.browser.msie ? $('#priceRangeSelect').css({visibility:'visible'}) :  false;
	}

	if ($.browser.msie && st)
	{
		$('#title-size').css({visibility:'visible'});
		$(".product	").stop().animate({opacity:1}, 5);
	}

	if ($('#typeSelect').length)
	{
		$.browser.msie && st ? $('#typeSelect').css({visibility:'visible'}) : false;
	}

	//
	Main.categoryId == 113 ?  $('#typeSelect').css({visibility:'hidden'}) : false;
};

var AForm = {

	init : function()
	{
		if ($('#ajax-form'))
		{
			var name = $('#ajax-form').attr('name');

			$(document).ready(function() { 
				var options = { 
			//		target:			'#ajax-form',  
					beforeSubmit:	AForm.request,  // pre-submit callback 
					success:			AForm.response  // post-submit callback 
				};

				$('#ajax-form').ajaxForm(options); 

			});	
		}
	},

	request : function(formData, jqForm, options)
	{
		alert(formData);
	},

	response : function(responseText, statusText)
	{
	},

	RValidate : function()
	{

		if ($("#sfName").val() && $("#sfWidth").val() && $("#sfHeight").val() && $("#sfPhone").val() && $("#sfEmail").val())
		{
			return true;
		}

		return false;
	},

	CValidate : function()
	{

		if ($("#sfName").val() && $("#sfComment").val() && $("#sfPhone").val())
		{
			return true;
		}

		return false;
	}
};


var priceRange = {

	startPrice : 0,
	stopPrice	: 100000,
	ctype		: 0,
	href			: null,

	reset : function()
	{
		this.startPrice	= 0;
		this.stopPrice	= 100000;
		this.ctype			= 0;
	},

	set : function()
	{
		if (m = $('#price-combobox').val().match(/(\d+)-(\d+)/))
		{
			this.startPrice	= m[1];
			this.stopPrice	= m[2];
		}

		if ($('#type-combobox').length)
		{
			this.ctype = $('#type-combobox').val();
		}
		
		Main.navigate('/x-entity.jewelry.grid.aspx?alias_path=' + this.href.match(/http\:\/\/([^/]+)\/(.*)/)[2] + '&StartPrice=' + this.startPrice + '&StopPrice=' + this.stopPrice + '&CustomType=' + this.ctype + '&' + Math.round(Math.random()*1000), false);

	}

};

var menutimer=null;



function historyCall(hash, sl)
{
	if(hash) 
	{
		if (!sl) 
		{

			if (hash == 'fc')
			{
				hash = $.cookie('last_url');
			}

			if (hash == 'jew:h_0')
			{				
				if (!Main.locked)
				{
					Main.navigate('/html/index.html', false, true);
				}
			}

			if (!Main.locked)
			{
				if (hash.indexOf('item') != -1)
				{
					var i = hash.replace('item', '');
				
					if (Main.historyStock[i][5] != Main.CategoryId)
					{
						Main.navigate('/x-entity.jewelry.grid.aspx?categoryID=' + Main.historyStock[i][5] + '&id=' + Main.historyStock[i][6], false, true);
						Main.CategoryId = Main.historyStock[i][5];
					}
					else
					{
						Main.replaceItem(Main.historyStock[i][0], Main.historyStock[i][1], Main.historyStock[i][2], Main.historyStock[i][3], Main.historyStock[i][4], Main.historyStock[i][6])
					}
				}
				else
				{
					var url = hash.replace(/\:\:\:\:/g, '/').replace(/\:\:\:/g, '=').replace(/\:\:/g, '?').replace(/\:/g, '.');
					Main.navigate(url, false, true);
				}
			}
		}
		
		return false;

	} else 
	{

		Main.navigate('/html/index.html', false, true);
		Main.dropMenu();
	}

};


var Main = {
	categoryId : 44,
	submenu : null,
	pid : null,
	zoomImg : "",
	carouselTimer : null,
	currentBanner : "banner",
	locked	: false,
	historyStock	 : [],
	historyStockI : 0,
	quoteItem : "",
	topMenuId : 0,
	CategoryId : 0,

	init: function() {
		$.fn.media.defaults.flashVersion="8";
		$.fn.media.defaults.bgColor="";
		loadSWF("swf_jewel", "jewel.swf", 380, 520);
		loadSWF("btnCc", "/swf/button.swf", 175, 90);
		setTimeout('loadSWF("ads", "banner.swf", 770, 150);', 3000);
		setTimeout('loadSWF("swf_logo", "logo.swf", 117, 90);', 9000);
		run_writer();setInterval("run_writer();", 30000);
		/*
		$('#swf_diamond').media({
			width:     70,
			height:    42,
			src:       'http://img.trevijewelry.com/i/swf/diamond.swf',
			attrs:     { wmode: 'transparent', scale: "noborder", quality:"high", allowscriptaccess:"sameDomain"},  // object/embed attrs 
			params:    { wmode: 'transparent', scale: "noborder", quality:"high", allowscriptaccess:"sameDomain"} // object params/embed attrs 
		});
		*/

		if (location.href.match(/html$/)) {
			$('#videobox').attr("class", "video_off");
		}
		if (
			window.location.href.match(/cat.html/) 
			|| $.cookie('cat_id') 
			|| window.location.pathname.match(/^\/([\/a-z0-9\-]+)$/) 
			|| window.location.pathname.match(/^([\/a-z0-9\/\-]+)\/([0-9a-z\-]+)-n(\d+)\.html$/))
		{
		jQuery.each($("#page #container div.item"), function() {
					$(this).createAppend(
						'div', {className:"eff"}, "<!-- -->"
						);
					$(this).createAppend(
						'div', {className:"layer",onmouseover:function()
								{
									var a = $("#swf_diamond").html();
									var eff = $(".eff", $(this).parent());
									$(eff).html("<div>"+a+"</div>");
								},
								onmouseout:function()
								{
									$(".eff", $(this).parent()).html("");
								},
								onclick:function()
								{
//debugger; // 5
											var id		= $(".price", $(this).parent()).attr("id");
											var counter	= $(".iid", $(this).parent()).attr("id").replace('id', '');
											var iid		= $(".iid", $(this).parent()).html();
											var title	= $(".title", $(this).parent()).html();
											if ($.browser.msie && ($.browser.version == 8 || $.browser.version == 6)) {
													$p = $(this).parent();
													title		= $p.parent().parent().find('.title').html().replace(/\<[^>]+\>/g, '');
											}
											var descr	= $(".descr", $(this).parent()).html();
											var price	= $(".price", $(this).parent()).html();
							
											Main.replaceItem(id, iid, title, descr, price, counter, true);
								}
							}, "<!-- -->"
						);
				}
			);
			
			$('#videobox').attr("class", "video_off");
			
			Main.pageReplace("index.html");

		} else {
			if ($("#wmp").length ==0 && (document.location.pathname=="/") /* && (document.location.host != "trevijewelry.klik")*/)
			{
				$('#videobox').media({
					width:     480,
					height:    282,
					autoplay:  true,
					src:       'http://img.trevijewelry.com/i/video/russian-gems.wmv',
					attrs:     { id : "wmp", ShowControls: '0', ShowStatusBar: "false", uiMode :"none", ShowAudioControls:"0"},  // object/embed attrs 
					params:    { id : "wmp", ShowControls: '0', ShowStatusBar: "false", uiMode :"none", ShowAudioControls:"0"}, // object params/embed attrs 
					caption:   false // supress caption text 
				});
			}
		}

		// --

		jQuery.each($(".links a"), function()
			{
				$(this).bind("click", function(){Main.pid = this.id; if (this.href.indexOf('/#')==-1) Main.navigate(this.href); return false});
			}	
		);

		jQuery.each($(".jmenu a"), function()
			{
				
				$(this).bind("click", function()
					{
						if (Main.locked)
						{
							return false;
						}
						$("#menu .m, #menu .m0").animate({top:25}, 300, function()
							{
								$("#menu .m0").attr("class", "m");
								$("#m"+Main.topMenuId).parent().parent().animate({top:15}, 300).attr("class", "m0");
							}
						);
						Main.pid = this.id;  
						if (this.href.indexOf('/#')==-1) 
						{
							if((typeof(this.rel) != "undefined") && (Main.currentBanner != this.rel))
							{
								loadBanner((Main.currentBanner = this.rel)+".swf");
							}

							priceRange.reset();

							var href = this.href + '&StartPrice=' + priceRange.startPrice + '&StopPrice=' + priceRange.stopPrice + '&CustomType=' + priceRange.ctype;

							priceRange.href = this.href;

							Main.navigate(this.href);
							return false;
						}
					}
				);
			}	
		);

		var img = new Image();
		img.src="http://img.trevijewelry.com/i/ramka.gif";

		jQuery.each($("#smenu a"), function()
			{
				var id = 's_' + Math.round(Math.random()*1000);
				$(this).attr('id', id);

				$(this).bind('click', function(e) {

						if (Main.locked)
						{
							return false;
						}

						var no_ribbon = false;
						if(this.href.indexOf("replicas") > 0)
							no_ribbon = true;

						if((typeof(this.rel) != "undefined") && (Main.currentBanner != this.rel))
						{
							loadBanner((Main.currentBanner = this.rel)+".swf");
						}

						priceRange.reset();
						var href = this.href;
						if(/\.aspx/.test(this.href))
							var href = this.href + '&StartPrice=' + priceRange.startPrice + '&StopPrice=' + priceRange.stopPrice + '&CustomType=' + priceRange.ctype;

						priceRange.href = this.href;

						Main.navigate(href, no_ribbon);
						return false;

					}
				);
			}
		);

		jQuery.each($("#menu div.item"), function()
			{

				$(this).createAppend(
					'div', {className:'layer',
						onmouseover : function()
						{
							$(".jmenu ul").css({display:"none"});
							var eff = $(".m", $(this).parent());
							$(eff).stop().animate({top:15}, 300);
							$("#sbmn .s").css({display:"none"});
							var id = $("a", $(this).parent()).attr("id").replace("m", "");
							if($("#sbmn"+id).length)
								$("#sbmn"+id).css({display:"block"});
							Main.topMenuId = id;
						},
						onmouseout : function()
						{
							var eff = $(".m", $(this).parent());
							$(eff).stop();
							$(eff).animate({top:25}, 200);
						},
						onclick: function(){
							var id = $(this).attr('id');
							var rel = $(this).parent().find("a").attr("rel");
							if((typeof(rel)!="undefined") && (Main.currentBanner != rel))
							{
								loadBanner((Main.currentBanner = rel)+".swf");
							}
							Main.chPage(id, 0);

						}
					},'<img height="1" width="1" src="http://img.trevijewelry.com/i/pix.gif" />'
				);
			}
		);

		jQuery.each($("#menu div.item .layer"), function() {
			var id = 'a_' + Math.round(Math.random()*1000);
			$(this).attr('id', id);
		});

		$(".homeContent").jScrollPane({maintainPosition: false});

	},

	chPageSub : function(id, hist)
	{
		var a = $('#'+id);
		url = a.attr("href");
		Main.navigate(url);
	},

	dropMenu : function()
	{
		jQuery.each($("#menu div.m0"), function()
			{
				$(this).stop().animate({top:25}, 300, function()
					{
						$(this).attr("class", "m");
					}
				);
			}
		);
		var eff = $(".m", $('#'+id).parent());
	},

	chPage : function(id, hist)
	{

		if (Main.locked)
		{
			return false;
		}

		jQuery.each($("#menu div.m0"), function()
			{
				$(this).stop().animate({top:25}, 300, function()
					{
						$(this).attr("class", "m");
					}
				);
			}
		);

		var eff = $(".m", $('#'+id).parent());

		if (hist)
		{
			$(eff).stop().animate({top:15}, 200);
		}

		$(eff).attr("class", "m0");
		var a = $("a", $('#'+id).parent());
		if(a.attr("href").indexOf("http://")!=-1)
		{
			document.location = a.attr("href");
		}
		else
		{
			var url = a.attr("href");

			if (!hist)
			{
				Main.historyAdd(id);
			}

			priceRange.reset();

	//		var url = url + '&StartPrice=' + priceRange.startPrice + '&StopPrice=' + priceRange.stopPrice + '&CustomType=' + priceRange.ctype;

			priceRange.href = url;

			Main.navigate(url);

			Main.pid = a.attr("id");
		}
	},

	historyAdd : function(url)
	{

		if (url.match(/a\_([\d]+)/))
		{
			return false;
		}

		if (url != 'fc')
		{
			$.cookie('last_url', 'jew:' + url, {path: '/'});
		}

		var m = url.match(/categoryID\=([\d]+)/);

		if(m)
		{
			$.cookie('cat_id', m[1], {path: '/'});
			Main.CategoryId = m[1];
		}
		else
		{
			Main.CategoryId = 0;
		}

		var hurl = url.replace(/http\:\/\/[^/]+\//, '::::').replace(/\./g, ':').replace(/\?/g, '::').replace(/\=/g, ':::').replace(/\//g, '::::');
		$.historyLoad(hurl, true);

	},

	historyAddItem : function(id, iid, title, descr, price, counter)
	{
		Main.historyStock[Main.historyStockI] = [id, iid, title, descr, price, Main.CategoryId, counter];
		//hurl = 'item' + Main.historyStockI;
        var tmpp = document.location.href;
        
        if (tmpp.indexOf('trevijewelry.com/#') != -1) {
            //tmpp = str_replace('http://www.trevijewelry.com/#', '', tmpp);
            
            var t = tmpp.split('#');
            
            tmpp = t[1];
            if (tmpp == undefined) {
                tmpp = '';
            }
            //alert(tmpp);
        } else {
            tmpp = '';
        }
        descr = descr.stripTags();
        descr = str_replace(':', '_', descr);
        descr = str_replace("\n", '', descr);
        
        hurl = tmpp + '#' + str_replace(' ', '_', descr);
        //alert(hurl);
        //hurl = str_replace('http://www.trevijewelry.com/#', '', hurl);
        //Клик
		$.historyLoad(hurl, true);

		Main.historyStockI++;

	},

	loadZoom : function()
	{
		var src = $("img:first", $(this).parent()).attr("src").replace("/medium/", "/large/");
		src = Main.zoomHTML.replace("{img}", src);
		$(".product .img").createAppend(
			"div", {className:"zoomCont",id:"zoomCont"}, src
			);
	},

	removeZoom : function()
	{
		if(document.getElementById("zoomCont"))
		{
			document.getElementById("zoomCont").innerHTML="";
			$("#zoomCont").remove();
		}
	},

	setQuoteImage : function(obj)
	{
		Main.quoteItem = $(obj).parent().parent().attr('id').replace("text_", "").trim();
	},

	navigate : function(url, no_ribbon, no_history)
	{
		if(Carousel.timeout)
		{
			Carousel.curr =1;
			clearTimeout(Carousel.timeout);
		}
		url = url.replace(/(^http:\/\/(www.)?trevijewelry.(klik|com))/, "");
		if(url.match(/^http/))
			document.location = url;
		Main.url		= url;
		Main.locked	= true;
		url = url.replace(document.location.protocol + "//" + document.location.host, "");
		
		var mode="?mode=ajax";
		if( url.match(/\/(\d+)\/cat.html/) )
		{
			var catid = url.match(/\/(\d+)\/cat.html/)[1];
			Main.categoryId = parseInt(catid);
			url = url.replace('/' + catid + '/cat.html', '/x-entity.jewelry.grid.aspx?categoryID=' + catid);
			mode="";
		}else if(url.match(/^\/faberge-art\/$/) || url.match(/^\/faberge-art\/[a-z0-9\-]+\.html$/))
		{
			
		}
		else if(url.match(/^\/([\/a-z0-9\-]+)$/))
		{
			url = '/x-entity.jewelry.grid.aspx?alias_path='+url.match(/^\/([\/a-z0-9\-]+)$/)[1];
			mode="";
		}

		if (!no_history)
		{
			Main.historyAdd(url);
		}

		stopVideo();
		if ($.browser.msie && document.getElementById("wmp"))
		{
			document.getElementById("wmp").controls.stop();
		}
		else
		{
			$("#videobox").html("");
		}
		$('#videobox').attr("class", "video_off");
		
		if($("#carousel").length && (typeof(t1) != "undefined") )
		{
			t1.stop();
		}
		$(".specflash").remove();
		$("#page").stop().animate({opacity:0.1}, 200);
		var flashId=0;
		var bannerFound =false;

		// Google analytics
		try
		{
			pageTracker._trackPageview(url.replace("/x-entity.jewelry.grid.aspx?alias_path=", "/"));
		}
		catch (e)	{}

		$.ajax({
			url: url + mode,
			cache: false,
			dataType: "text",
			success: function(data)
			{
				
				/*************/
				no_ribbon = data.indexOf('id="ribbon"')==-1;
				/*************/
				if(no_ribbon)
					data = data.replace(/\/[i]\//gi, "http://img.trevijewelry.com/i/");
				Ribbon.scroll=true;
				$("#body").createAppend(
						'div', {id:'page0'}, data
					);
				if(!no_ribbon)
				{
					var cnt =0;
					if(cnt = $("#container .item", data).length)
					{
						var num = parseInt((cnt+2)/3);
						$("#page0 #container").css({width:(num*130)+"px"});
					}
	
					jQuery.each($("#page0 #container div.item"), function() {
							$(this).createAppend(
								'div', {className:"eff"}, "<!-- -->"
								);
							$(this).createAppend(
								'div', {className:"layer",onmouseover:function()
										{
											var a = $("#swf_diamond").html();
											var eff = $(".eff", $(this).parent());
											$(eff).html("<div>"+a+"</div>");
										},
										onmouseout:function()
										{
											$(".eff", $(this).parent()).html("");
										},
										onclick:function()
										{
//debugger; // 3
											var id		= $(".price", $(this).parent()).attr("id");
											var counter	= $(".iid", $(this).parent()).attr("id").replace('id', '');
											var iid		= $(".iid", $(this).parent()).html();
											var title	= $(".title", $(this).parent()).html();
											if ($.browser.msie && ($.browser.version == 8 || $.browser.version == 6)) {
													$p = $(this).parent();
													title		= $p.parent().parent().find('.title').html().replace(/\<[^>]+\>/g, '');
											}
											var descr	= $(".descr", $(this).parent()).html();
											var price	= $(".price", $(this).parent()).html();
							
											Main.replaceItem(id, iid, title, descr, price, counter, true);

										}
									}, "<!-- -->"
								);
						}
					);
			
				}
				$("#page").stop().animate({left:-1000}, 2000);
				$("#page0").stop().animate({left:200}, 2000,  function(){
					Main.pageReplace(url); 
					Main.locked	= false;
				});
			}
		});
	},

	replaceItem : function(id, iid, title, descr, price, counter, hist)
	{
		if (hist)
		{
			
			Main.historyAddItem(id, iid, title, descr, price, counter);
		}

		Main.removeZoom();
		Product.reset();
		var img = new Image();
		
		img.src ="http://img.trevijewelry.com/i/products/medium/"+id.replace('n', '')+".jpg?";
		//img.src ="/inc/cache.php"+"?id="+id.replace('n', '');
		Product.init(iid, title, descr, price);
		if ($.browser.msie && $.browser.version == '6.0') {
            setTimeout( function() {
               Product.img = img.src;
               Product.render();
            }, 500);    
        } else {
        
            img.onload = function()
            {
            //    alert("2");
                Product.img = this.src;
                Product.render();
            };
            
        }
        
        $(".product").animate({opacity:0.3},100, function()
			{
				//alert("3");
				Product.effected = true;
				Product.render();
			}
		);
	},

	pageReplace : function(url) {
		if (url && (url !="index.html")) {
			$("#page").remove();
			$("#page0").attr("id", "page");
			MagicMagnify_findMagnifiers();
			if(document.getElementById('sfQuote'))
			{
				document.getElementById('sfQuote').value = Main.quoteItem;
				document.getElementById('quoteImage').src = "http://img.trevijewelry.com/i/carousel/quote/"+Main.quoteItem+".jpg";
			}
		}
		
		$(".article_text a").click(function(){Main.navigate(this.href, false, false);return false;});

		$(".product .content").css({display:"inline"});
		if($(".homeContent").length)
			$(".homeContent").jScrollPane({maintainPosition: false});

		$("#about-category").css({visibility:'visible'}); 
		var linkurl = url.replace("x-entity.jewelry.grid.aspx?alias_path=", "");

		if (linkurl.indexOf("/silver-tableware/") > -1) {
			$("#about-category img").attr('alt', "Our Silver Tableware").attr('src', 'http://img.trevijewelry.com/i/about_categories/silver_tableware.gif').click(function() {
					tb_show("", "/info/silver-tableware.html?height=500&width=700", null,  function () {
							$(".tbContent").jScrollPane({maintainPosition: false});
					});
					return false; 
				}
			);
			
	//		$("#about-category").show();

		} else if(linkurl.indexOf("/enamel-filigree/") > -1) {
			$("#about-category img").attr('alt', "Our Enamel Filigree").attr('src', 'http://img.trevijewelry.com/i/about_categories/enamel_filigree.gif').click(function() {
					tb_show("", "/info/enamel-filigree.html?height=500&width=700", null,  function () {
							$(".tbContent").jScrollPane({maintainPosition: false});
						});
					return false; 
				}
			);
//			$("#about-category").show();

		} else if (linkurl.indexOf("/stone-cut-sculpture/") > -1) {
			$("#about-category img").attr('alt', "Our Enamel Miniature and Stone Carving Art").attr('src', 'http://img.trevijewelry.com/i/about_categories/stone.gif').click(function() {
					tb_show("", "/info/stone-carving.html?height=500&width=700", null,  function () {
							$(".tbContent").jScrollPane({maintainPosition: false});
						});
					return false; 
				}
			);
//			$("#about-category").show();

		} else if (linkurl.indexOf("/royal-jewels/") > -1) {
			$("#about-category img").attr('alt', "Trevi's Royal Jewels").attr('src', 'http://img.trevijewelry.com/i/about_categories/royal.gif').click(function() {
					tb_show("", "/info/royal-jewelry.html?height=500&width=700");
					return false; 
				}
			);
	//		$("#about-category").show();

		} else if(linkurl.indexOf("/egg-collection/") > -1) {
			$("#about-category img").attr('alt', "Our Egg Collection").attr('src', 'http://img.trevijewelry.com/i/about_categories/egg_collection.gif').click(function() {
					tb_show("", "/info/faberge-eggs-collection.html?height=500&width=700", null,  function () {
							$(".tbContent").jScrollPane({maintainPosition: false});
						});
					return false; 
				}
			);
			
		} else {
			$("#about-category").css({visibility:'hidden'}); 
//			$("#about-category").hide(); 
		}
		$("#zoomimg").unbind("click").click(Main.zoomInit);
		$("#goodImg").unbind("click").click(Main.zoomInit);
		if($("#carousel").length)
		{
			Carousel.init($("#egg_descr_all .egg_descr"));
		}
//		if(document.location.host.indexOf(".klik") == -1)
			

		if ((url && url == "/")) {
			$("#snd").empty();
			$('#videobox').attr("class", "video_on");
			if($.browser.msie && document.getElementById("wmp"))
			{
				document.getElementById("wmp").controls.play();
			}
			else
			{
				if(document.location.pathname=="/" || url=="/")
				{
					$('#videobox').media({
						width:     480,
						height:    282,
						autoplay:  true,
						src:       'http://img.trevijewelry.com/i/video/russian-gems.wmv',
						attrs:     { id : "wmp", ShowControls: '0', ShowStatusBar: "false", uiMode :"none", ShowAudioControls:"0"},  // object/embed attrs 
						params:    { id : "wmp", ShowControls: '0', ShowStatusBar: "false", uiMode :"none", ShowAudioControls:"0"}, // object params/embed attrs 
						caption:   false // supress caption text 
					});
				}				
			}
		}
		else
		{
			setTimeout("loadSound();", 10000);
		}

		Ribbon.init();

		initselect();

		// Suggest
		Suggestions.load($('.ProductID').val());

	},

	zoomInit : function ()
	{
		Main.zoomImg="";
		var w = $(document).width();
		var h = $(document).height();
		var src = $("#goodImg").attr("src");
		$("#minWidth").createPrepend(
			'div', {className:"mask", id:"mask", style:"width:"+w+"px;height:"+h+"px;display:none"}
			);
		$("#minWidth").createPrepend(
			'img', {src:src, className:"zoomed", id:"zoomed"}
		);
		var img = new Image();
		src = img.src = src.replace("medium", "large")+"?"+Math.random();
		img.onload = function()
		{
			if($(".zoomed").length && (parseInt($(".zoomed").css("width").replace("px", "")) == 690) )
			{
				$("#zoomed").attr("src", src);
				$("#zoomImage").attr("src", $("#zoomImage").attr("src").replace("_in", "_out"));
			}
			else
			{
				Main.zoomImg = src;
			}
		};
		$("#minWidth").createPrepend(
			'div', {id:"zoomOut"}, $("#zoomimg").html().replace("btnzoom.gif", "btnzoomout.gif").replace("zoom in", "zoom out")
		);
		$("#zoomOut").click(Main.zoomOut);
		$("#zoomed").click(Main.zoomOut);
		$("#mask").animate({opacity:.1}, 100, function()
			{
				$("#mask").css({display:"block"});
				$("#mask").animate({opacity:.7}, 500, function()
					{
						$(".zoomed").animate({width:690,height:459,top:612}, 1500, function()
							{
								if(Main.zoomImg)
									$("#zoomed").attr("src", Main.zoomImg);
								$("#zoomImage").attr("src", $("#zoomImage").attr("src").replace("_in", "_out"));
							}
						);
					}
				);
			}
		);
		$("#image").animate({opacity:.0}, 50);
		$("#zoomimg").animate({opacity:.0}, 50);
	},

	zoomOut : function()
	{
		$(".zoomed").animate({width:460,height:306,top:765}, 1500, function()
			{
				$("#image").animate({opacity:1}, 50);
				$("#zoomimg").animate({opacity:1}, 50);
				$("#mask").remove();
				$(".zoomed").remove();
				$("#zoomOut").remove();
				$("#zoomImage").attr("src", $("#zoomImage").attr("src").replace("_out", "_in"));
			}
		);
	},

	unload : function()
	{
		if($.browser.msie)
		{
			if(typeof(t1) != "undefined")
			{
				t1.stop();
			}
		}
	}
};


var Carousel = {
	items : null,
	curr:1,
	locked:false,
	timeout : null,

	init : function(items)
	{
		Carousel.locked = false;
		this.items = items;
		Carousel.loadImages();
		if(Carousel.items.length >22)
		{
			$("#carousel")
				.css({display:"block"})
				.carousel3d({control: 'continuous', speed:5, centerX:($("#carousel").width()>>1), fadeEffect:1, radiusX:320});
		}
		else
		{
			$("#carousel")
				.css({display:"block"})
				.carousel3d({control: 'continuous', speed:5, centerX:($("#carousel").width()>>1), fadeEffect:1, radiusX:250});
		}
	},

	loadImages : function()
	{
		if(Carousel.items.length >22)
		{
			if($("#carousel img").length >= 22)
			{
				var i=0;
				while(i<10)
				{
					var arr = {}; $.each($("#carousel img"), function(){arr[this.src.replace(/.+\/([^\/]+)\.jpg/, '$1')]="";});
					var rnd = Math.floor(Math.random()*Carousel.items.length);
					var src = $(Carousel.items[rnd]).attr('id').replace('text_', '');

//					if(typeof(arr[src]) != "undefined")
//					{
						
						for(j=0;i<22;j++)
						{
							if($("#carousel img:eq("+j+")").css("opacity")<=0)
							{
//								alert(src);
								$("#carousel img:eq("+j+")").attr("src", "http://img.trevijewelry.com/i/carousel/icon/"+src+".jpg");
								i++;
								break;
							}
						}
//					}
				}
			}
			else
			{
				for(i=0;i<22;i++)
				{
					$("#carousel").createAppend(
						"img", {src:"http://img.trevijewelry.com/i/carousel/icon/"+$(Carousel.items[i]).attr('id').replace('text_', '')+".jpg", width:"100", height:"75"}
						);
				}
			}
			Carousel.timeout = setTimeout("Carousel.loadImages()", 5000);
		}
		else
		{
			for(var i=0;i<Carousel.items.length;i++)
			{
				$("#carousel").createAppend(
					"img", {src:"http://img.trevijewelry.com/i/carousel/icon/"+$(Carousel.items[i]).attr('id').replace('text_', '')+".jpg", width:"100", height:"75"}
				);				
			}
		}
	},

	preloadImages : function(num)
	{
		for(i=num;i<Carousel.items.length;i++)
		{
			var img = new Image();
			img.src="http://img.trevijewelry.com/i/carousel/icon/"+$(this.items[i]).attr('id').replace('text_', '')+".jpg";
		}
	},

	start : function()
	{
		$("#carousel")
			.css({display:"block"})
			.carousel3d({control: 'continuous', speed:6, centerX:($("#carousel").width()>>1), fadeEffect:1, radiusX:320});
	}
};

var Ribbon = {

	scroll	: true,
	step		: 0,
	steps	: [1],
	width	: 0,
	all			: 0,
	last		: 0,
	locked	: false,

	init : function(w)
	{

		Ribbon.scroll		= true;
		Ribbon.width	= w;

		Ribbon.last		= 0;
		Ribbon.step		= 0;
		Ribbon.steps	= [1];
		Ribbon.all			= $('#count-val').length ? parseInt($('#count-val').html()) : 0;

	},

	scrollPrev : function()
	{
		if (Ribbon.locked)
		{
			return false;
		}

		Ribbon.locked	= true;
		Ribbon.scroll		= true;
		Ribbon._prev();
	},

	scrollNext : function()
	{

		if (Ribbon.locked)
		{
			return false;
		}
		r_stop();
		Ribbon.locked	= true;
		$("#page #ribbon div.item").css({display:"block"});
		Ribbon.scroll=true;
		Ribbon._next();
	},

	_prev : function()
	{
		if (left = parseInt($("#container").css("left").replace("px", "")))
		{

			left += 375; 
			
			if (left >= 0)
			{
				left = 0;
				$('#btnPrev').hide(500);
			} 

			Ribbon.step = left > 0 ? 1 : Ribbon.step  - 1;

			$("#container").stop().animate({left:left+"px"},"slow", function () {
				Ribbon.locked	= false;
			});

			$('#btnNext').show(500);

		}

	},

	_next : function()
	{
		Ribbon.step += 1;

		$('#btnPrev').show(500);

		if (Ribbon.steps[Ribbon.step])
		{
			Ribbon._next_cb();

			if (Ribbon.last && Ribbon.last == Ribbon.step)
			{
				$('#btnNext').hide(500);
			}
		}
		else
		{
			$("#ribbon").css({cursor: 'progress'});
			$(".layer").css({cursor: 'progress'});
			$("#btnNext").css({cursor: 'progress'});
			$("#btnPrev").css({cursor: 'progress'});
			
			var count = Ribbon._get_9();
			if (count >= Ribbon.all)
			{
				$('#btnNext').hide(500);
				Ribbon.last = Ribbon.step;
			}

		}

	},

	_get_9 : function()
	{

		var step	= Ribbon.step; 
		var cid		= parseInt($('#cid-val').html()); 

		var url = '/x-entity.jewelry.grid.nop.aspx?categoryID='+cid+'&s=' + (9+step*9) + '&p=' + (18+step*9) + '&StartPrice=' + priceRange.startPrice + '&StopPrice=' + priceRange.stopPrice + '&CustomType=' + priceRange.ctype; 
		var _time1 = (new Date()).getTime();
		$.ajax({
			url: url,
			cache: false,
			dataType: "text",
			success: function(data)
			{

				$("#ribbon").css({cursor: 'default'});
				$(".layer").css({cursor: 'pointer'});
				$("#btnNext").css({cursor: 'pointer'});
				$("#btnPrev").css({cursor: 'pointer'});
				
				if (!data)
				{
					return;
				}

				$.each($(".rthumb", data), function(){r_loadImage(this.id.replace("t_", ""))});
				r_start();

				$("#container").createAppend(
						'div', {id: 'd_' + Ribbon.step, className: 'ribbon-part'}, data
					);
				
				var len = parseInt($('#d_' + Ribbon.step + ' div.item').length);

				var dwidth = 375;
				dwidth = len < 7 ? 250 : dwidth;
				dwidth = len < 4 ? 125 : dwidth;
				dwidth = len == 0 ? 0 : dwidth;
				
				$( '#d_' + Ribbon.step).css({width:dwidth+'px'});

				var width = parseInt($("#container").css("width").replace("px", ""));
				width = isNaN(width) ? 780 : width;

				$("#container").width(width + dwidth);

				jQuery.each($("#d_" + Ribbon.step + " div.item"), function() {
						$(this).createAppend(
							'div', {className:"eff"}, "<!-- -->"
							);
						$(this).createAppend(
							'div', {className:"layer",onmouseover:function()
									{
										var a = $("#swf_diamond").html();
										var eff = $(".eff", $(this).parent());
										$(eff).html(a);
									},
									onmouseout:function()
									{
										$(".eff", $(this).parent()).html("");
									},
									onclick:function()
									{
										var id		= $(".price", $(this).parent()).attr("id");
										var counter	= $(".iid", $(this).parent()).attr("id").replace('id', '');
										var iid		= $(".iid", $(this).parent()).html();
										var title	= $(".title", $(this).parent()).html();
											if ($.browser.msie && ($.browser.version == 8 || $.browser.version == 6)) {
													$p = $(this).parent();
													title		= $p.parent().parent().find('.title').html().replace(/\<[^>]+\>/g, '');
											}
										var descr	= $(".descr", $(this).parent()).html();
										var price	= $(".price", $(this).parent()).html();
						
										Main.replaceItem(id, iid, title, descr, price, counter, true);
									}
								}, "<!-- -->"
							);
					}
				);
				if (len > 0 )
				{
					Ribbon.steps[Ribbon.step] = 1;
					Ribbon._next_cb();
				}

			}
		});

		return (18+step*9);

	},

	_next_cb : function()
	{

		var left = parseInt($("#container").css("left").replace("px", ""));

		left -= 375;

		$("#container").stop().animate({left:left+"px"},"slow", function () {
			Ribbon.locked	= false;
		});
	}

};

function commafy(val)
{
	if (m = val.toString().match(/(^[\d]+)([\d]{3}$)/))
	{
		var r		= m[1] + ',' + m[2]; 
		return r;
	}

	return val;
}

var Product = {
	img			: null,
	effected	: false,

	id				: null,
	title			: null,
	descr		: null,
	price			: null,
	
	init : function(id, title, descr, price)
	{
		this.id = id;
		this.title = title;
		this.descr = descr;
		this.price = price;
	},

	render : function()
	{

		if(this.img && this.effected)
		{
			$(".#suggCont").stop().animate({opacity:0.1}, 300, function() 
				{
					Suggestions.load(Product.id);
				}
			);

			$(".product").animate({opacity:0.1}, 500, function()
				{
					if (!parseInt(Product.price))
					{
						$("#price-block").hide();
					}
					else
					{
						$("#price-block").show();
					}
					
					$(".product #title").html(Product.title);
					$(".product #descr").html(Product.descr);
					$(".product #price").html(Product.price);
					$(".product #price").attr('class', Product.price);

					$(".product #sug-price").html(commafy(Math.round(parseInt(Product.price.split(",").join(""))*2)));
					$(".product #image").html("");
					$(".product #image").createAppend(
						'img', {src:Product.img, id:"goodImg"}
						);
					$(".product").animate({opacity:1}, 500);
					$(".ProductID").val(Product.id);	
					$("#AddToCart").attr('name', 'AddToCart_' + Product.id);
					$(".product .content").css({display:"inline"});

					Product.chSizePrice($('#size').val());
					// Init SIZE select
					if (Product.title && ((!($.browser.msie && ($.browser.version == 8 || $.browser.version == 6)) && Product.title.match(/[^r]ring/gi)) || ($.browser.msie && ($.browser.version == 8 || $.browser.version == 6) && (Product.title.indexOf('Ring') === 0 || Product.title.indexOf('ring') === 0)) ))
					{
						$('#title-size').show();
					}
					else
					{
						$('#title-size').hide();
					}
					$("#zoomimg").unbind("click").click(Main.zoomInit);
					$("#goodImg").unbind("click").click(Main.zoomInit);

				}
			);

		}
	},

	chSizePrice : function(addPrice)
	{
		var prices		= {'5':0,'6':0,'7':50,'8':50,'9':50,'10':75,'11':75,'12':100};
		var price		= parseInt($('#price').attr('class').replace('p', '').replace(',', '')) + prices[addPrice];
		$(".product #price").html(commafy(price));
		$(".product #sug-price").html(commafy(Math.round(price*2)));
	},

	reset : function()
	{
		this.img = null;
		this.effected = false;
	}

};

var Suggestions = {

	load: function(itemID)
	{
		if(typeof(itemID) == "undefined")
			return false;
		var url = "/x-entity.jewelry.related.grid.aspx?ItemCode=" + itemID;
		
		$.ajax({
			url: url,
			cache: false,
			dataType: "text",
			success: function(data)
			{

				if (data)
				{
					$('#suggContItems').html(data);

					jQuery.each($("#suggContItems div.item"), function() {
							$(this).createAppend(
								'div', {className:"eff"}, "<!-- -->"
								);
							$(this).createAppend(
								'div', {className:"layer",onmouseover:function()
										{
											var a = $("#swf_diamond").html();
											var eff = $(".eff", $(this).parent());
											$(eff).html(a);
										},
										onmouseout:function()
										{
											$(".eff", $(this).parent()).html("");
										},
										onclick:function()
										{
//debugger; // 2
											var id		= $(".price", $(this).parent()).attr("id");
											var counter	= $(".iid", $(this).parent()).attr("id").replace('id', '');
											var iid		= $(".iid", $(this).parent()).html();
											var title	= $(".title", $(this).parent()).html();
											if ($.browser.msie && ($.browser.version == 8 || $.browser.version == 6)) {
													$p = $(this).parent();
													title		= $p.parent().parent().find('.title').html().replace(/\<[^>]+\>/g, '');
											}
											var descr	= $(".descr", $(this).parent()).html();
											var price	= $(".price", $(this).parent()).html();
							
											Main.replaceItem(id, iid, title, descr, price, counter, true);
										}
									}, "<!-- -->"
								);
						}
					);

					$('#suggCont').show();
					$(".#suggCont").stop().animate({opacity:1}, 500 );

				}
				else
				{
					$('#suggCont').hide();
				}
			}
		});

	}
};


loadSWF = function(cont_id, fname, w, h, id)
{

	if(!id)
		id="swf"+cont_id;
	if(fname.indexOf("/swf/") == -1)
		fname = 'http://img.trevijewelry.com/i/swf/'+fname;
	$('#'+cont_id).media({
		width:     w,
		height:    h,
		src:       fname,
		attrs:     {id:id,wmode: 'transparent', scale: "noborder", quality:"high", allowscriptaccess:"crossDomain"},  // object/embed attrs 
		params:    {id:id,wmode: 'transparent', scale: "noborder", quality:"high", allowscriptaccess:"crossDomain"} // object params/embed attrs 
	});
};

function loadSound()
{
	if(($("#snd").html().indexOf("swf")==-1) && ($("#fMainPg").length==0))
	{
		var sounds = [
			"http://img.trevijewelry.com/i/sound/beethoven_bagatelle_in_a_minor.mp3",
			"http://img.trevijewelry.com/i/sound/haydn_serenada_andante_cantable.mp3",
			"http://img.trevijewelry.com/i/sound/rahmaninov_italian_polka.mp3",
			"http://img.trevijewelry.com/i/sound/sviridov_sounds_of_waltz.mp3",
			"http://img.trevijewelry.com/i/sound/oginsky_polonez.mp3"
		];
		$('#snd').media({
			width:     115,
			height:    25,
			src:       "http://img.trevijewelry.com/i/sound/snd.swf?mp3String="+sounds.join(";"),
			attrs:     {id:"sndplayer", wmode: 'transparent', scale: "noborder", quality:"high", allowscriptaccess:"crossDomain"},  // object/embed attrs 
			params:    {id:"sndplayer", wmode: 'transparent', scale: "noborder", quality:"high", allowscriptaccess:"crossDomain"} // object params/embed attrs 
		});
	}
}

function stopVideo()
{
	if($.browser.msie)
	{
		if(!(/\/$/.test(Main.url) || Main.url.indexOf("index.html")) && document.getElementById("wmp"))
		{
			document.getElementById("wmp").controls.stop();
		}
		setTimeout("stopVideo()", 2000);
	}
	
}

function loadBanner(name, timeout)
{
	if(!timeout) timeout = 1000;
	if(!name) name = "banner.swf";
	setTimeout('loadSWF("ads", "'+name+'", 770, 150);', timeout);	
}


function choform()
{
	var productId	= $('.ProductID').val();
	var size			= $('#size').val();
//	var action			= $('#order #form1').attr('action');	
//	var sid				= $.cookie('sid');

//	$('#order #form1').attr('action', (action + '%26jid%3d' + sid));

	var url = 'order.php?productId=' + productId + '&size=' + size;

	$.get(url, function (data) {
		//alert(data);
		$(".ProductID").val(data).attr('id', 'ProductID_' + data);
		$(".AddtoCart").attr('name', 'AddToCart_' + data).attr('id', 'AddToCart_' + data);
		$(".IsWishList").attr('name', 'IsWishList_' + data).attr('id', 'IsWishList_' + data);
		$('#add-to-card').submit();
	});

}

var r_loaded=[];
var r_filo=[];
var r_loadTimer=null;
var r_threads =0;
var imgs=[];

var n_threads=0;
if ($.browser.msie) {
	switch(true)
	{
		case /MSIE 6/.test(navigator.userAgent):
			n_threads=2;
			break;
		case /MSIE 7/.test(navigator.userAgent):
		case /MSIE 8/.test(navigator.userAgent):
			n_threads=4;
			break;
		default:
			n_threads=2;
	}
}
else
{
	n_threads=4;
}

function r_loadImage(id)
{
	if(typeof(r_loaded[id]) != "undefined")
		return;
	r_filo.push(id);
}

function r_loader()
{
	if(r_filo.length==0)
	{
		r_stop();
		return;
	}

	if(r_threads>0)
		return;

	for(var i=0;i<n_threads;i++)
	{
		if(r_threads==n_threads)
			return;
		var el = r_filo.pop();
		if(typeof(el) == "undefined")
			return;
		imgs[i] = new Image();
		imgs[i].id = el;
		imgs[i].onload = function()
		{
			var obj = document.getElementById("t_"+this.id);
			if(obj != null)
			{
				obj.src = this.src;
				r_loaded.push(el);
			}
			r_threads--;
		};
		imgs[i].src="http://img.trevijewelry.com/i/products/icon/"+imgs[i].id+".gif";
		
		r_threads++;
	}

	if(r_filo.length==0)
	{
		r_stop();
	}
}

function r_stop()
{
	clearInterval(r_loadTimer);
}

function r_start()
{
	r_loadTimer=setInterval("r_loader()", 50);
}


var prases = [
	[escape("First Time on\nAmerican Continent!!!")+"&sign_scale=0.65&offset_x=10&sign_color=0xCCCCCC&line_height=60&offset_x=40&offset_y=20"],
	[escape("Happy holiday season!!\nSave extra 5% on everything")+"&sign_scale=0.55&offset_x=10&sign_color=0xFFFFFF&line_height=50&offset_x=40&offset_y=20"],
	[escape("Buy directly\nfrom original Faberge factory\nand save! ")+"&sign_scale=0.50&offset_x=10&sign_color=0xCCCCCC&line_height=60&offset_x=40&offset_y=10"]
];
var phrasesLastId=1;

function run_writer()
{
	do{
		var id = Math.floor(Math.random()*prases.length);
	}while(id == phrasesLastId);
	$('#writer').media({
		width:     500,
		height:    150,
		src:       "/swf/demo_jewel.swf?sign_text="+prases[phrasesLastId = id],
		attrs:     {id:'swfwriter',wmode: 'transparent', scale: "noborder", quality:"high", allowscriptaccess:"crossDomain"},  // object/embed attrs 
		params:    {id:'swfwriter',wmode: 'transparent', scale: "noborder", quality:"high", allowscriptaccess:"crossDomain"} // object params/embed attrs 
	});
}







$(document).ready(function() {
	Main.init();
	$(".jmenu a").mouseover(
		function()
		{
			clearTimeout(menutimer);
			if(this.className != "pm_inner")
				$(".pm_inner").parent().parent().css({display:"none"});
			$("ul", $(this).parent()).css({display:"block"});
		}
	);
	$(".jmenu ul a").addClass("pm_inner");
	$(".pm_inner").click(
		function()
		{
			$(this).parent().parent().css({display:"none"});
			return false;
		}
	);
	$(".jmenu ul").mouseout(
		function()
		{
			clearTimeout(menutimer);
			menutimer = setTimeout('$(".pm_inner").parent().parent().css({display:"none"});', 1000);
		}
	);
	$(".jmenu").mouseout(
		function()
		{
			clearTimeout(menutimer);
			menutimer = setTimeout('$(".pm_inner").parent().parent().css({display:"none"});', 1000);
		}
	);
	$(".jmenu ul li a").mouseover(
		function()
		{
			clearTimeout(menutimer);
		}
	);
	$("#btnCcLayer")
		.mouseover(function(){document.getElementById("swfbtnCc").BtnOn();})
		.mouseout(function(){document.getElementById("swfbtnCc").BtnOff();})
		.click(function(){
			if (Main.locked)
			{
				return false;
			}
			Main.pid = '186';  
			priceRange.href = "x-entity.jewelry.grid.aspx?categoryID=186";
			Main.navigate("/curvy-cups/");
			loadBanner("banner_curvy_cups.swf");
			return false;
		});
	$("#smenu span").mouseover(function(){
			var sm = $(".sub[id!='"+$(this).next().attr('id')+"']");
			for(var i=0;i<sm.length;i++)
			{
				if(sm[i].style.display == "block")
					$(sm[i]).stop().animate({height:1}, 300, function(){this.style.display="none"});
			}
			var h="200px";
			if($(this).next().attr('id')=="sub0")
			{
				h="80px";
			}
			if($(this).next().css("display")!="block")
			$(this).next().css({display:"block"}).stop().animate({height:h}, 300, function(){this.style.height="auto"});
		}
	);
	if($("#carousel").length)
	{
		Carousel.init($("#egg_descr_all .egg_descr"));
	}
	MagicMagnify_findMagnifiers();
	$(".article_text a").click(function(){Main.navigate(this.href, false, false);return false;});
	//if (document.location.href.indexOf('#')) historyCall(document.location.hash);
});

