$(document).ready(function() {
	$("#b_button").bind("click", function()
		{	
			$.get("/proj/trevireceipts/html__/contact.html?"+Math.random(),
				function (data)
				{
					$("#info").html(data);
					$("#content").jScrollPane({maintainPosition: false});
				}
			);
		}
	);
	$("#btnhs").bind("click", Main.toggleBody);
	$("#counters img").animate({opacity:.4}, 20);

});


function historyCall(hash, sl) 
{
	if(hash) 
	{
		if (!sl) 
		{
			if (hash == 'fc')
			{
				hash = $.cookie('last_url');
			}

			issue	= Main.historyPull[hash]['issue'];

			if (issue == 'loadReceipts_')
			{
				title		= Main.historyPull[hash]['title'];
				id			= Main.historyPull[hash]['id'];
				href		= Main.historyPull[hash]['href'];
				Main.loadReceipts_(title, id, href, 1);
			}
			else if (issue == 'loadReceipt')
			{
				id			= Main.historyPull[hash]['id'];
				url		= Main.historyPull[hash]['url'];
				Main.loadReceipt(id, url, 1);
			}
			else if (issue == 'go_')
			{
				id			= Main.historyPull[hash]['id'];
				Main.go_(id, 1);
			}
		}
	} else 
	{
		window.location.href = '/';
	}

}


var noTrack = 0;

var Main = {
	imgCntFromMenuLoaded:0,
	imgFromMenu : [],

	historyPull : {},

	preInit : function()
	{

		// Set recipe bg
		$('#plaha').createAppend(
			'div', {className:"plaha-bg"}
		).css({opacity: 0.7}).createAppend(
			'div', {className:"plaha-bg-border"}
		);
		setTimeout("Interface.playCookies()", 10000);
		
		for(var i=1;i<6;i++)
		{
			Main.imgFromMenu.push(_img +"cookie"+i+".gif");
			/*
			if($.browser.msie)
			{
				var img = new Image();
				/*
				img.onload = function()
				{
					Main.imgMenuAdd();
				}
				*/
				/*
				var src = _img + "cookie"+i+".gif";
				Main.imgFromMenu[Main.imgFromMenu.length] =  src;
				img.src = src;

				if(i==5)
					setTimeout("Interface.playCookies()", 10000);					
				
			}
			else
			{
				var img = new Image();
				img.onload = function()
				{
					Main.imgMenuAdd();
				}
				Main.imgFromMenu[Main.imgFromMenu.length] = img.src= _img + "cookie"+i+".gif";
			}*/
		}
		
		$.fn.media.defaults.bgColor="";
		$('#plate').media({
			width:     293,
			height:    286,
			src:       "/proj/trevireceipts/i/swf/tlogo.swf",
			attrs:     {id:"swf_logo", wmode: 'transparent', scale: "noborder", quality:"high"},  // object/embed attrs 
			params:    {id:"swf_logo", wmode: 'transparent', scale: "noborder", quality:"high"} // object params/embed attrs 
		});
		Main.init();

	},

	imgMenuAdd : function()
	{
		Main.imgCntFromMenuLoaded++;
		if(Main.imgCntFromMenuLoaded==5)
		{
			Interface.playCookies();
		}
	},

	init: function()
	{
		for(var i=1;i<6;i++)
		{
			$("#cookie"+i).createAppend(
				'img', {width:143, height:96, src:Main.imgFromMenu[i-1], id:"#cookie"+i}
				);
		}
		if($.browser.mozilla)
			$("#plaha").animate({opacity:.9}, 100);
		$("#receipts").jScrollPane({maintainPosition: false});
		$(".randomRecipe").bind("click", function(){Main.loadReceipt(this.id.replace("rndr", ""), this);});
		Interface.highlightItems();
		$.fn.media.defaults.bgColor="";
		/*
		$('#snd2').media({
			width:     115,
			height:    25,
			src:       "/proj/trevireceipts/i/swf/sound.swf",
			attrs:     {id:"swf_sound", wmode: 'transparent', scale: "noborder", quality:"high", allowscriptaccess:"sameDomain"},  // object/embed attrs 
			params:    {id:"swf_sound", wmode: 'transparent', scale: "noborder", quality:"high", allowscriptaccess:"sameDomain"} // object params/embed attrs 
		});
		*/
		setTimeout(function()		// 15000
		{
			$(".counters").css({display:"block"});
			var rnd =Math.floor(Math.random()*2);
			var clickTAG ="";
			switch(rnd)
			{
				case 0:
					clickTAG = "http://www.trevicarriages.com/";
					break;
				case 1:
					clickTAG = "http://www.liptont.com/";
					break;
			}
			$('#a66c3901').media({
				width:     200,
				height:    200,
				src:       "/proj/trevireceipts/i/swf/src"+rnd+".swf?clickTAG="+clickTAG,
				attrs:     {id:"swf_sound",  quality:"high", allowscriptaccess:"sameDomain"},  // object/embed attrs 
				params:    {id:"swf_sound",  quality:"high", allowscriptaccess:"sameDomain"} // object params/embed attrs 
			});
			switch(rnd)
			{
				case 0:
					clickTAG = "http://ballarini.com";
					break;
				case 1:
					clickTAG = "http://www.bandbliqueur.com";
					break;
			}
			$('#top100').media({
				width:     "100%",
				height:    60,
				src:       "/proj/trevireceipts/i/swf/top"+rnd+".swf?clickTAG="+clickTAG,
				attrs:     {id:"swf_sound",  quality:"high", allowscriptaccess:"sameDomain"},  // object/embed attrs 
				params:    {id:"swf_sound",  quality:"high", allowscriptaccess:"sameDomain"} // object params/embed attrs 
			});
		}, 10000);
		if(document.location.host.indexOf(".klik")==-1)
			setTimeout("loadSound();", 20000);
		Data.load();
		
		$("#content").jScrollPane({maintainPosition: false});
		jQuery.each($("#cookies .cookie"), function()
			{
				$(this).createAppend(
					'div', {className:"eff"}
					);
				$(this).createAppend(
					'div', {className:"layer",onmouseover:function()
						{
							$(".vilka", $(this).parent()).stop();
							try
							{
								document.getElementById("swf_sound").videlec();
							}
							catch (e)
							{
							}
							
							$(".vilka", $(this).parent()).animate({top:-160}, 200, function()
								{	
									$(".vilka", $(this).parent()).animate({top:-180}, 100, function()
										{
											$(".vilka", $(this).parent()).animate({top:-160}, 50);
										}
									);
								}
							);
						},
						onmouseout : function()
						{
							$(".vilka", $(this).parent()).stop();
							$(".vilka", $(this).parent()).animate({top:-290}, 600);
						},

						onclick : function()
						{
							Main.go_($("a", $(this).parent()).attr("id"));
						}
					}
				);
			}
		);
	},

	navigate : function(url)
	{

	},

	go_ : function(id, h)
	{
		// History Add
		if (!h)
		{
			key = 'page:' + id ;
			Main.historyPull[key] = {'issue':'go_', 'id':id};
			$.historyLoad(key, true);
		}
		// --

		var a = id;
		if(a == "/")
			a = "index.html";
		if(/^http/.test(a))
			document.location = a;

		if ($('#i-data').length)
		{
			var data = $('u[a="'+a+'"]', $('#i-data')).html();
			$("#info").html(data);
			$("#content").jScrollPane({maintainPosition: false});
		}
		else
		{
			$.get("/proj/trevireceipts/html__/"+a+"?"+Math.random(),
				function (data)
				{
					$("#info").html(data);
					$("#content").jScrollPane({maintainPosition: false});
				}
			);
		}
	},

	loadData : function(url, func)
	{
		$.get(url,
			function (data)
			{
				Data.data = data;
				func();
			}
		);
	},

	loadReceipts : function(obj)
	{
		$("#left ul").css({opacity:1});
		var cid		= $(obj).attr("id").replace('.html', '').replace('c', '');
		var html	= obj.innerHTML;
		var id		= obj.id;
		var href	= $(obj).attr("href");

		$('#receipt-cat-title').html(html);
		
		$('#receipts').animate({opacity: 0.2}, 500, function() {
				Main.loadData("/proj/trevireceipts/html__/data.php?cid=" + cid, function () {
						Main.loadReceipts_(html, id, href, false);
						$('#receipts').animate({opacity: 1}, 800);
					});
			});

		return false;
	},

	loadReceipts_ : function(title, id, href, h)
	{

		if (!h)
		{
			key = href.replace('/recipes/', '').replace('.html', '').replace('/', ':');
			Main.historyPull[key] = {'issue':'loadReceipts_', 'title':title, 'id':id, 'href':href};
			$.historyLoad(key, true);
		}
		else
		{
			$('#receipts').animate({opacity: 0.2}, 500, function() {

					var cid = id.match(/c([^.]+)\.html/);
					cid = cid[1];

					Main.loadData("/proj/trevireceipts/html__/data.php?cid=" + cid, function () {
							Main.loadReceipts_(title, id, href, false);
							$('#receipts').animate({opacity: 1}, 800);
						});
				});

			return false;
		}

		// --
		document.title = 'TreviGourmet :: ' + title;

		$('#cat-title').html(title);
		var items = Data.loadItems(id);

		if (!$('#i-data').length && !noTrack)
		{
			if(typeof(pageTracker) == "object")
			{
				pageTracker._trackPageview(href);
			}
		}


		$("#receipts").html("");
		for (i=0;i<items.length;i++)
		{
			$("#receipts").createAppend(
				'div', {className:'item'}, [
					'div', {className:'img'}, [
						'a', {id:$(items[i]).attr("id"), href:'#', onclick: function()
							{

								Main.loadReceipt(id, $(items[i]).attr("id"));
								return false;
							}
						}, [
							'img', {src:_img + 'photos/icon/'+$(items[i]).attr("id")+'.jpg',width:'85',height:'86'}
						]
					],
					'div', {}, $(items[i]).attr("name")
				]
			);
		}

		$("#receipts").jScrollPane({maintainPosition: false});
		Interface.highlightItems();
		return false;
	},

	loadReceipt : function(id, url, h)
	{
		if (!h)
		{
			key =  'recipe' + id; // url.replace('/recipes/', '').replace('.html', '').replace(/\//gi, ':');
			Main.historyPull[key] = {'issue':'loadReceipt', 'id':id, 'url':url};
			$.historyLoad(key, true);
		}

		try
		{
			document.getElementById("swf_sound").plate();
		}
		catch (e)
		{

		}
		var d = Data.loadItem(id);
		if($(d).length==0)
			return false;
		var _nm = $(d).attr("name");
		var _n = $(d).attr("name").toLowerCase().replace(/\&/gi, 'and').replace(/ /gi, '-');
		var _nid = $(d).attr("id");
		var _c = $(d).parent().attr("name").toLowerCase().replace(/\&/gi, 'and').replace(/ /gi, '-');
		var _cid = $(d).parent().attr("id");
		var _href="/recipes/"+_cid+"/"+_c+"/"+_nid+"/"+_n+".html";

		$('#b_button').unbind('click').bind('click', function () {
			window.open('/proj/trevireceipts/html__/send_recipe.php?id='+_nid, '', 'status=no, scrollbars=no, height=150, width=300');
		});

		if (!$('#i-data').length && !noTrack)
		{
			if((typeof(pageTracker) == "object") && typeof(pageTracker._trackPageview) == "function")
			{
				pageTracker._trackPageview(_href);
			}
		}

		var img = new Image();
		img.src=_img + "photos/"+id+".jpg"+"?"+Math.random();
		img.style.display="none";
		img.onload = function()
		{
			$("#image").createAppend(
				'img', {src:this.src,id:"img_new",width:"875",height:"446"}
				);
			$("#img_new").animate({opacity:0.01}, 5, function()
				{
					$("#img_new").css({display:"block"});
					var html = "<p>{ingredients}</p><p>{timing}</p><p>{directions}</p><br /><p><a onclick='Main.print();return false;' href='' class='print'><img width='12' height='14' border='0' alt='print version' src='" + _img + "print.gif'/>&nbsp;print version</a></p>";

					html += "";

					html = ($("i[a='d']", Data.item).text() != '-') ? html.replace("{directions}", ('<b>Directions</b><br />' + $("i[a='d']", Data.item).text())) : html.replace("{directions}", '');
					html = ($("i[a='t']", Data.item).text() != '-') ? html.replace("{timing}", ('<b>Timing</b><br />' + $("i[a='t']", Data.item).text())) : html.replace("{timing}", '');
					html = ($("i[a='i']", Data.item).text() != '-') ? html.replace("{ingredients}", ('<b>Ingredients</b><br />' + $("i[a='i']", Data.item).text())) : html.replace("{ingredients}", '');
					
					html = html.replace(/\{id\}/gi, _nid);
					html = html.replace(/\{url\}/gi, _href);
					html = html.replace(/\{name\}/gi, _nm);
					html = html.replace(/\{meta_title\}/gi, $("i[a='mt']", Data.item).text());
					html = html.replace(/\{meta_keyword\}/gi, $("i[a='mk']", Data.item).text());
					html = html.replace(/\{meta_description\}/gi, $("i[a='md']", Data.item).text());

					$("#content").html(html.replace(/\n/g, "<br />"));
					$("#h1").html($(Data.item).attr("name") + '<span style="display:none" id="prid">' + $(Data.item).attr("id") + '</span>'); //$(Data.item).attr("id")
					document.title = 'TreviGourmet :: ' + $(Data.item).attr("name");
					$("#content").jScrollPane({maintainPosition: false});
					$("#img_new").animate({opacity:1}, 1200, function()
						{
							$("#img").remove();
							$("#img_new").attr("id", "img");
						}
					);
				}
			);
		}
	},

	print : function()
	{
		myWindow = window.open("/proj/trevireceipts/html__/print.html", "tinyWindow", 'status=no, scrollbars=yes, height=500, width=550');
	},

	receiptShowForm : function()
	{
		
	},

	toggleBody : function(act)
	{
		var action = parseInt($("img", $("#btnhs")).css("top"))?"show":"hide";
		if(action == "hide")
		{
			$("#btnhs").animate({left:920}, 500, function()
				{
					$("img", $("#btnhs")).css({top:"-36px"});
				}
			);
			$("#plaha").animate({left:921}, 500);
		}
		else
		{
			$("#btnhs").animate({left:862}, 500, function()
				{
					$("img", $("#btnhs")).css({top:0});
				}
			);
			$("#plaha").animate({left:400}, 500);
		}
	}
};

var Interface = {
	playCookies : function()
	{
		jQuery.each($("#cookies .cookie"), function()
			{
				var id = parseInt($(this).attr("id").replace("cookie", ""));
				setTimeout("Interface._playCookie("+id+")", id*1000);
			}
		);
	},
	
	_playCookie : function(id)
	{
		var left = parseInt($("#cookies #cookie"+id).css("left").replace("px", ""))-1000;
		$("#cookie"+id+" .vilka").css({display:"block"});
		$("#cookie"+id).animate({left:left}, 800, function()
			{
				$("#cookie"+(id)+" .vilka").animate({top:-290}, 300, function()
					{
						
					}
				);
			}
		);
	},

	highlightItems : function()
	{
		jQuery.each($(".item .img img"), function()
			{
				var id = $(this).parent().attr("id");
				$(this).bind("click", function()
					{
//					debugger;
						Main.loadReceipt(id, $(this).parent().attr("href"));
						return false;
					}
				);
				$(this).bind("mouseover", function()
					{
						$(this).parent().parent().css({backgroundColor:"white"});
						$(this).animate({opacity:.4}, 100, function()
							{
								$(this).animate({opacity:1}, 50, function()
									{
										$(this).animate({opacity:.6}, 80, function()
											{
												$(this).animate({opacity:1}, 50, function()
													{
														$(this).parent().parent().css({backgroundColor:"transparent"});
													}
												);
											}
										);
									}
								);
							}
						);
					}
				);
			}
		);
	}
};

var Data = {
	data : null,
	item : null,
	featured : null,

	load: function()
	{
		if ($('#i-data').length)
		{
			Data.data = $('#i-data');
			return true;
		}

		var href = document.location.href;
		var cid = 0;

		if (m = href.match(/recipes\/([^/]+)\//))
		{
			cid = m[1];
		}
		
		Main.loadData("/proj/trevireceipts/html__/data.php?" + (cid ? ('cid=' + cid) : 'top=1'), function () {
		//	debugger;
//				$('#left').css({visibility: 'visible'});
//				$('#right').css({visibility: 'visible'});
			});
	},
	
	loadItems : function(catId)
	{
		return $("i[a='r']", $("b", Data.data));
	},

	loadItem : function(id)
	{
		return Data.item = $("i[id='"+id+"']", Data.data);
	}
};

function loadSound()
{
	var sounds = [
		"/proj/trevireceipts/i/sound/rachmaninov-italian-polaka.mp3",
		"/proj/trevireceipts/i/sound/rimsky-korsakov-bumble-bee-flight.mp3",
		"/proj/trevireceipts/i/sound/tchaikovsky-napoletana.mp3"
	];

	$('#snd').media({
		width:     115,
		height:    25,
		src:       "/proj/trevireceipts/i/sound/snd.swf?mp3String="+sounds.join(";"),
		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 
	});
};

rotateOpenX = function()
{
	return false;
	var ids = ["a66c390a", "aabb8501"];
	var d= null;
	for(i=0;i<ids.length && (d=document.getElementById(ids[i]));i++)
	{
		d.src=d.src.replace(/cb=[a-zA-Z0-9-_]+(&.*)?/, 'cb='+Math.floor(Math.random()*99999999999)+'$1');
	}
}