var scrn_width = 5500;
var scrn_height= 2100;
var map_width  = 275;
var map_height = 105;
var iphone	   = false;
var sizratio   = 20;

//IPHONE CODE --------------------------------------------------------------------------------------------//
var deviceAgent = navigator.userAgent.toLowerCase();
var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
if (agentID) {
	scrn_width = 1375;
	scrn_height= 525;
	sizratio   = 1.2;
	iphone = true;

}

function daylightSaving() {
	var gmt = new Date;
	var lsm = new Date;
	var lso = new Date;
	lsm.setMonth(2); // March
	lsm.setDate(31);
	var day = lsm.getDay();// day of week of 31st
	lsm.setDate(31-day); // last Sunday
	lso.setMonth(9); // October
	lso.setDate(31);
	day = lso.getDay();
	lso.setDate(31-day);
	if (gmt < lsm || gmt >= lso)
		return 0;
	return 1;
}

var IE6 = $.browser.msie && $.browser.version <= 6;
if ($.browser.msie && $.browser.version <= 8)
	jQuery.fx.off = true;

$.fn.extend
({
	hrefId: function() { return $(this).attr("href").substr($(this).attr("href").indexOf("#")); }
,	fixIE7: function() { if ($.browser.msie && $.browser.version == 7) $(this).each(function() { this.style.removeAttribute("filter"); }); return $(this); }
,	typedVal: function() { var t = $(this)[0]; return t.value == t.defaultText ? "" : t.value; }
});


Date.prototype.toTimeString = function() { return (this.getHours() < 10 ? "0" + this.getHours() : this.getHours()) + ":" + (this.getMinutes() < 10 ? "0" + this.getMinutes() : this.getMinutes()) + ":" + (this.getSeconds() < 10 ? "0" + this.getSeconds() : this.getSeconds()); };

Number.prototype.toRemaining = function()
{
	var m = Math.ceil(this / 60000) + 2;
	return m <= 1 ? "1 minute" : (m < 60 ? m + " minutes" : (m / 60 <= 1 ? "1 hour" : (Math.floor(m / 60) <= 1 ? "1 hour" : Math.floor(m / 60) + " hours") + (m % 60 < 1 ? "" : (m % 60 == 1 ? " 1 minute" : " " + (m % 60) + " minutes"))));
};

//LOAD BACKGROUND ---------------------------------------------------------------------------------------------//
$(window).load(function() {
	var $loading = $("body>.loading:first");
	setTimeout(function() { $loading.animate({ opacity: 0 }, 1000, function() { $(this).remove(); }); }, 500);
});

var windowW = $(window).width(), windowH = $(window).height();
$(window).resize(function() {
	windowW = $(window).width();
	windowH = $(window).height();
});var map = new function() {
	var
		$map = $('<div class="map"></div>').appendTo("body")
	,	mapW = (scrn_width - windowW) / 2
	,	mapH = (scrn_height - windowH) / 2
	,	angleX = Math.random() * 360
	,	angleY = Math.random() * 360
	,	speed = 0
	,	x = -Math.floor((Math.sin(angleX * Math.PI / 180) + 1) * mapW)
	,	y = -Math.floor((Math.cos(angleY * Math.PI / 180) + 1) * mapH)
	,	pause = false
	,	dragEndTimer = false
	,	markerPos = 0
	,	align = { "r": "", "l": " left", "br": " bottom-right", "bl": " bottom-left", "tr": " top-right", "tl": " top-left" }
	,	calign = { "l": " dots-left" }
	,	dots2Types = [ "many", "design", "programming", "marketing" ]
	;

	var showMarker = function() {
		//alert(markerPos  + ", " + points.length);
		if (markerPos < points.length) {
			var m  = points[markerPos];
			var $m = $('<span class="point' + align[typeof m[4] == "string" ? m[4] : "r"] + (m[4] !== true && m[5] !== true ? ' point-capital' : '') + '" style="left: ' + m[0] + 'px; top: ' + m[1] + 'px"><span>' + m[2] + '</span></span>').appendTo($map);
			if (!$.browser.msie)
				$m.animate({ opacity: 1 }, 2000, function() { $(this).fixIE7(); });
				
			$m.children("span").hide();	
			$m.mouseleave(function() {
				$m.children("span").hide();
			});
			$m.mouseenter(function() {
				$m.children("span").show();
			});	
		}

		if (markerPos < points.length - 1)
		{
			markerPos++;
			setTimeout(showMarker, 25);
		}
	};

	this.resume = function() {
		if (dragEndTimer)
			clearTimeout(dragEndTimer);

		dragEndTimer = setTimeout(function()
		{
			dragEndTimer = false;
			$map.stop(true).animate({ left: x + "px", top: y + "px" }, 10000, function() { speed = 0; pause = false; });
			navigation.animateTo(x, y, 10000);
		}, 10000);
	};

	var moveMap = function() {
		if (pause)
			return;

		speed < 10 ? speed += 0.05 : speed = 10;
		angleX < 360 ? angleX += .01 * speed : angleX -= 360;
		angleY < 360 ? angleY += .003 * speed : angleY -= 360;

		x = -Math.floor((Math.sin(angleX * Math.PI / 180) + 1) * mapW);
		y = -Math.floor((Math.cos(angleY * Math.PI / 180) + 1) * mapH);

		$map.css({ left: x + "px", top: y + "px" });
		navigation.goTo(x, y);
	}

	$map
		.bind("mousedown", function() { 
			pause = true; 
			$map.stop(true); 
			navigation.stop(); 
		})
		.bind("drag", function(event) {
			if(event.offsetX > 0 || event.offsetY > 0) { return; }
			if(event.offsetX- windowW < scrn_width * -1 || event.offsetY- windowH < scrn_height * -1 ) { return; }
		
			$map.stop(true).animate({ left: event.offsetX + "px", top: event.offsetY + "px" }, 0);
			navigation.goTo(event.offsetX, event.offsetY);
		})
		.bind("mouseup dragend", function() { map.resume(); })
	;

	$(window).resize(function()
	{
		mapW = (scrn_width - windowW) / 2;
		mapH = (scrn_height - windowH) / 2;
	});

	this.animateTo = function(x, y, time) { 
		pause = true; 
		$map.stop(true).animate({ left: (-x + windowW / 2) + "px", top: (-y + windowH / 2) + "px" }, time);
	};
	this.goTo = function(x, y) { pause = true; $map.stop(true).css({ left: (-x) + "px", top: (-y) + "px" }); };
	this.getX = function() { return x; };
	this.getY = function() { return y; };
	this.stop = function() { pause = true; $map.stop(true); };
	this.showCities = function() { $map.attr("class", "map map-points"); };

	$(window).load(function() { showMarker(); setInterval(moveMap, 33); });
};

//TWEET FEED ---------------------------------------------------------------------------------------------//
var tweety = new function() {
	var $twitter = $('<div class="twitter"><div><span class="sectionhdr"></span><span id="tweet"></span><span class="social"><a class="twitter" href="http://twitter.com/Recycledrocks">Follow us on Twitter</a><br/><a class="facebook" href="http://www.facebook.com/home.php?#!/recycledpercussionband?ref=ts">Find us on Facebook!</a></span></div></div>').appendTo("body"),
	folded = false;
	
	var tfold   = function() { $twitter.stop(true).animate({ opacity: .15 }, 500); };
	var tunfold = function() { $twitter.stop(true).animate({ opacity: 1 }, 500); };
	this.tfold   = function() { folded = true; tfold(); };
	this.tunfold = function() { folded = false; tunfold(); };
};

//NAV BOX ---------------------------------------------------------------------------------------------//
var navigation = new function() {
	var $navigation = $('<div class="navigation"><div><p class="map"><a><span class="top"></span><span class="right"></span><span class="bottom"></span><span class="left"></span></a></p></div></div>').appendTo("body")
	,	$navigationWindow = $navigation.find("p.map>a")
	,	folded = false
	;

	var fold = function() { $navigation.stop(true).animate({ opacity: .15 }, 500).find("p.map:first").stop(true).animate({ marginTop: "-126px" }, 500); };
	var unfold = function() { $navigation.stop(true).animate({ opacity: 1 }, 500, function() { $(this).fixIE7(); }).find("p.map:first").stop(true).animate({ marginTop: 0 }, 500); };

	$navigation.find("p.controls a").click(function() { $(this).addClass("on").siblings().removeClass("on"); return false; });
	map.showCities();

	$navigation.find("p.map").click(function(event) {
		
		var pos = $(this).offset(), x = event.pageX - pos.left, y = event.pageY - pos.top;
		lx = (x - $navigationWindow.outerWidth() / 2);
		ly = (y - $navigationWindow.outerHeight() / 2);
		sx = Math.round(x * sizratio);
		sy = Math.round(y * sizratio);
		
		if(lx < 0) { lx = 0; sx=windowW/2; }
		else if (lx+$navigationWindow.outerWidth() > map_width) { lx = map_width -$navigationWindow.outerWidth();  sx = scrn_width - windowW/2;}
		if(ly < 0) { ly = 0; sy = windowH/2}
		else if (ly+$navigationWindow.outerHeight() > map_height) { ly = map_height -$navigationWindow.outerHeight(); sy = scrn_height- windowH/2;}
		
		//REMOVE ME
		//var mapx = $(".map").position();
		//$("#testbox").html("nav:" + ly + "," + lx +" bg:" +  + "," + $navigationWindow.outerHeight() + " m:" + mapx.left + "," + mapx.top  );
		
		$navigationWindow.stop(true).animate({ left: lx + "px", top: ly + "px" }, 333);
		map.animateTo(sx,sy , 333);
		map.resume();
		return false;
	});

	$navigationWindow.css({ display: "block", left: (-map.getX() * .05) + "px", top: (-map.getY() * .05) + "px", width: (windowW * .05) + "px", height: (windowH * .05) + "px" })
		.click(function() { return true; })
		.bind("mousedown dragstart", function() { map.stop(); $navigationWindow.stop(true); })
		.bind("mouseup dragend", function() { map.resume(); })
		.bind("click", function() { return false; })
		.bind("drag", function(event) {
			var pos = $(this).parent().offset();
			var x = event.offsetX - pos.left;
			var y = event.offsetY - pos.top;

			if(x < 0 || y < 0) { return; }
			if(x+$navigationWindow.outerWidth() > map_width || y + $navigationWindow.outerHeight() >  map_height) { return; }
			
			map.goTo(x / map_width * scrn_width , y / map_height * scrn_height);
			$navigationWindow.stop(true).css({ left: x + "px", top: y + "px" });
		});
	;

	$(window).resize(function() { $navigationWindow.css({ width: Math.floor(windowW * .05) + "px", height: Math.floor(windowH * .05) + "px" }); });

	this.stop = function() { $navigationWindow.stop(true); };
	this.goTo = function(x, y) { $navigationWindow.stop(true).css({ left: (-x * .05) + "px", top: (-y * .05) + "px" }); };
	this.animateTo = function(x, y, time) { $navigationWindow.stop(true).animate({ left: (-x * .05) + "px", top: (-y * .05) + "px" }, time); };
	this.fold = function() { folded = true; fold(); };
	this.unfold = function() { folded = false; unfold(); };
	this.addMarker = function(x, y) { $('<span class="dots" style="left: ' + Math.round(x * .05) + 'px; top: ' + Math.round(y * .05) + 'px"></span>').appendTo($navigation.find("p.map:first")); };
};


var validation = new function()
{
	var
		self = this
	,	messages =
		{
			"required": "This field is mandatory."
		,	"max_length": "Text is too long."
		,	"valid_email": "This isn't valid e-mail address."
		,	"valid_address": "This isn't valid address."
		}
	,	functions =
		{
			"required": function(s) { return typeof s == "string" && s.length > 0; }
		,	"max_length": function(s, l) { return typeof s == "string" && s.length <= parseInt(l); }
		,	"valid_email": function(s) { return typeof s == "string" && s.match(/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/i); }
		,	"valid_address": function(s) { return typeof s == "string" && s.match(/^(?:(?:ht|f)tp(?:s?)\:\/\/|~\/|\/)?(?:\w+:\w+@)?(?:(?:[-\w]+\.)+(?:com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|travel|[a-z]{2}))(?::[\d]{1,5})?(?:(?:(?:\/(?:[-\w~!$+|.,=]|%[a-f\d]{2})+)+|\/)+|\?|#)?(?:(?:\?(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)(?:&(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)*)*(?:#(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)?$/i); }
		}
	;

	self.check = function(fields)
	{
		var result = true;
		for (var f in fields)
		{
			var rules = fields[f].rules.split("|");
			for (var r = 0; r < rules.length; r++)
			{
				var rule = rules[r], param = rule.indexOf("[");
				if (param > 0)
				{
					rule = rule.slice(0, param);
					param = rules[r].slice(param + 1);
					param = param.slice(0, param.length - 1);
				}

				if (!functions[rule](fields[f].value, param))
				{
					if (result === true)
						result = {};
					result[f] = messages[rule];
					break;
				}
			}
		}

		return result;
	};
};

//GALLEY SYSTEM ---------------------------------------------------------------------------------------------//
$("ul.gallery").each(function()
{
	var $gallery = $(this), c = $gallery.children().length, t = 750;

	$gallery.wrap('<div class="gallery-clip"></div>').width(c * 345);
	$gallery.parent().before('<h3 class="alt"></h3><p class="gallery-nav gallery-nav-prev"><a>&lt;</a></p><p class="gallery-nav gallery-nav-next"><a>&gt;</a></p>');

	var $thumbs = $('<ul class="thumbnails"></ul>').appendTo($gallery.parent()).width(c * 88), $w = $gallery.closest(".frame"), i = 0, $h = $w.find("h3:first");

	var galleryUpdate = function()
	{
		$h.text($gallery.find(">li:eq(" + i + ")>img").attr("title") + " (" + (i + 1) + "/" + c + ")");
		$thumbs.children().eq(i).children("a").addClass("selected").parent().siblings().children("a.selected").removeClass("selected");
	};

	$w.find("p.gallery-nav-prev a").click(function()
	{
		if (i > 0)
		{
			$gallery.stop(true).animate({ left: (--i * -345) + "px" }, t);
			if (c > 4 && i < c - 3)
				$thumbs.stop(true).animate({ left: (i * -88) + "px" }, t);
		}
		galleryUpdate();
		return false;
	});

	$w.find("p.gallery-nav-next a").click(function()
	{
		if (i < c - 1)
		{
			$gallery.stop(true).animate({ left: (++i * -345) + "px" }, t);
			if (c > 4 && i < c - 3)
				$thumbs.stop(true).animate({ left: (i * -88) + "px" }, t);
		}
		galleryUpdate();
		return false;
	});

	$gallery.children().each(function()
	{
		var $img = $(this).find("img");
		$('<li><a><img src="' + $img.attr("src") + '" title="' + $img.attr("title") + '"></a></li>').appendTo($thumbs).children("a").click(function()
		{
			i = $thumbs.children().index($(this).parent()) - 1;
			$gallery.stop(true).animate({ left: (++i * -345) + "px" }, t);
			if (c > 4)
				$thumbs.stop(true).animate({ left: ((i < c - 3 ? i : c - 4) * -88) + "px" }, t);
			galleryUpdate();
			return false;
		});
	});

	galleryUpdate();
});

//MUSIC PLAYER --------------------------------------------------------------------------------------------//
var musicp = new function() {
	var $musicply = $('<div id="jquery_jplayer"></div><div class="jp-playlist-player"><div class="jp-interface">'+
	'<ul class="jp-controls"><li><a href="#" id="jplayer_stop" class="jp-stop" tabindex="1">stop</a></li><li><a href="#" id="jplayer_previous" class="jp-previous" tabindex="1">previous</a></li><li><a href="#" id="jplayer_play" class="jp-play" tabindex="1">play</a></li><li><a href="#" id="jplayer_pause" class="jp-pause" tabindex="1">pause</a></li><li><a href="#" id="jplayer_next" class="jp-next" tabindex="1">next</a></li></ul>'+
	'<div id="jplayer_textinfo"><span id="jplayer_play_time" class="jp-play-time"></span> / <span id="jplayer_total_time" class="jp-total-time"></span></div><div class="jp-sound"><a href="#" id="jplayer_volume_min" class="jp-volume-min" tabindex="1">min</a><a href="#" id="jplayer_volume_max" class="jp-volume-max" tabindex="1">max</a><span>sound</span></div><div class="jp-progress"><div id="jplayer_load_bar" class="jp-load-bar"><div id="jplayer_play_bar" class="jp-play-bar"></div></div></div></div></div>')
	.appendTo("#musicplayer");
	var playItem = 0;

	var myPlayList = [
		{name:"Rock",mp3:"music/rock.mp3",ogg:"music/rock.ogg"},
		{name:"ManVsMachine",mp3:"music/manvsmachine.mp3",ogg:"music/manvsmachine.ogg"},
		{name:"Wipeout",mp3:"music/wipeout.mp3",ogg:"music/wipeout.ogg"}
		];

	// Local copy of jQuery selectors, for performance.
	var jpPlayTime  = $("#jplayer_play_time");
	var jpTotalTime = $("#jplayer_total_time");


	$("#jquery_jplayer").jPlayer({
		ready: function() {
			displayPlayList();
			playListInit(false); // Parameter is a boolean for autoplay.
		},
		oggSupport: true
	})
	
	.jPlayer("onProgressChange", function(loadPercent, playedPercentRelative, playedPercentAbsolute, playedTime, totalTime) {
		jpPlayTime.text($.jPlayer.convertTime(playedTime));
		jpTotalTime.text($.jPlayer.convertTime(totalTime));
	})
	
	.jPlayer("onSoundComplete", function() {
		playListNext();
	});

	$("#jplayer_previous").click( function() {
		playListPrev();
		$(this).blur();
		return false;
	});

	$("#jplayer_next").click( function() {
		playListNext();
		$(this).blur();
		return false;
	});

	function displayPlayList() {
		$("#jplayer_playlist ul").empty();
		for (i=0; i < myPlayList.length; i++) {
			var listItem = (i == myPlayList.length-1) ? "<li class='jplayer_playlist_item_last'>" : "<li>";
			listItem += "<a href='#' id='jplayer_playlist_item_"+i+"' tabindex='1'>"+ myPlayList[i].name +"</a></li>";
			$("#jplayer_playlist ul").append(listItem);
			$("#jplayer_playlist_item_"+i).data( "index", i ).click( function() {
				var index = $(this).data("index");
				if (playItem != index) {
					playListChange( index );
				} else {
					$("#jquery_jplayer").jPlayer("play");
				}
				$(this).blur();
				return false;
			});
		}
	}

	function playListInit(autoplay) {
		if(autoplay) {
			playListChange( playItem );
		} else {
			playListConfig( playItem );
		}
	}

	function playListConfig( index ) {
		$("#jplayer_playlist_item_"+playItem).removeClass("jplayer_playlist_current").parent().removeClass("jplayer_playlist_current");
		$("#jplayer_playlist_item_"+index).addClass("jplayer_playlist_current").parent().addClass("jplayer_playlist_current");
		playItem = index;
		$("#jquery_jplayer").jPlayer("setFile", myPlayList[playItem].mp3, myPlayList[playItem].ogg);
	}

	function playListChange( index ) {
		playListConfig( index );
		$("#jquery_jplayer").jPlayer("play");
	}

	function playListNext() {
		var index = (playItem+1 < myPlayList.length) ? playItem+1 : 0;
		playListChange( index );
	}

	function playListPrev() {
		var index = (playItem-1 >= 0) ? playItem-1 : myPlayList.length-1;
		playListChange( index );
	}	
		
		
};

//Video PLAYER --------------------------------------------------------------------------------------------//
var videop = new function() {


};

//Game PLAYER --------------------------------------------------------------------------------------------//
var gameply = new function() {

	if(iphone == false) {
		$("#playagame").html('<object id="gmeflash" name="gmeflash" width="700" height="400"><param name="wmode" value="transparent"><param name="movie" value="js/rp_game.swf"><embed id="gmeflash" name="gmeflash" src="js/rp_game.swf" wmode="transparent"  width="700" height="400"></embed></object>');
	
		$("#gamefocus").click(function() {
			 $('#gmeflash').focus();

		});		

	} else {
		$('This Feature is not available on Mobile Devices.')
		.appendTo(".game_video");
	
	}
};


//Windows --------------------------------------------------------------------------------------------//
var windows = new function()
{
	$("body").append
	(
		'<div class="frame" id="frame-time-zones"><div class="frame"><div><p class="text-center"><img src="images/' + (IE6 ? 'ie6/' : '') + 'timezones_map.png" width="708" height="376" alt=""></p><p class="location">Poznań / Poland <span></span></p><p class="user-time">Your time is <strong></strong></p><p class="remaining-time"></p><p class="our-time">Merix Studio time is <strong></strong></p></div></div></div>'
	+	'<div class="frame frame-med" id="frame-newsletter"><div class="frame"><iframe src="email.php" border="0" style="border:none;background-color:transparent;width:100%;height:auto;"></iframe></div></div>'
	+	'<div class="frame window-small" id="frame-newsletter-sent"><div class="frame"><h2>Confirm subscription</h2><p>Thank you for signing up for our newsletter. Please check out your inbox to confirm subscription.</p><p class="no-margin"><button class="close"><span><span>Close</span></span></button></p></div></div>'
	+	'<div class="frame window-small" id="frame-sending"><div class="frame"><h2>Sending message…</h2><p class="loading">Please wait, sending data to server.</p></div></div>'
	+	'<div class="frame window-small" id="frame-contact-sent"><div class="frame"><h2>Thank You!</h2><p>Message has been sent! Someone from Recycled Percussion will respond to your message.</p></p><p class="no-margin"><button class="close"><span><span>Close</span></span></button></p></div></div>'
	+	'<div class="frame window-small" id="frame-error-sending"><div class="frame"><h2>Server error</h2><p>Seems to be some technical difficulty sending your message. Please try again later.</p><p class="no-margin"><button class="close"><span><span>Close</span></span></button></p></div></div>'
	+	'<div class="frame frame-med" id="frame-suggest"><div class="frame"><h2>Feedback</h2><form action="" method="post"><p>We want to hear from you.  Your feedback is greatly appreciated!</p><p><input type="text" class="text" name="address" value="Comments" size="64" maxlength="256"></p><p class="no-margin"><button type="submit"><span><span>Add</span></span></button></p></form></div></div>'
	+	'<div class="frame window-small" id="frame-suggest-sent"><div class="frame"><h2>Thank you</h2><p>Your submission has been sent.</p><p class="no-margin"><button class="close"><span><span>Close</span></span></button></p></div></div>'
	);

<!--	$("body>.footer").prepend('<div class="frame window-special" id="frame-legend"><div class="frame"><h2>World map legend</h2><h3>Our Clients</h3><p><span class="marker marker-clients"></span> Number of Merix Studio clients in this country</p><h3>Web Resources</h3><ul><li class="left"><span class="marker marker-dots2-many"></span> Mixed content</li><li class="right"><span class="marker marker-dots2-design"></span> Web design</li><li class="left"><span class="marker marker-dots2-programming"></span> Web development</li><li class="right"><span class="marker marker-dots2-marketing"></span> Marketing, ePR, SEM</li></ul><h3>Cities</h3><ul><li class="left"><span class="marker marker-city-capital"></span> Capital city</li><li class="right"><span class="marker marker-point"></span> Large city</li></ul></div></div><p class="legend"><a href="#frame-legend">Legend</a></p>');-->


	var $windows = $("body>.frame,body>.footer>.frame"), h = {}, mt = {}, time = false, opened = {}, self = this;

	if (!$.browser.opera)
//		$windows.filter("#frame-contact2").removeClass("frame-small").children(".frame").append('<div class="right"><iframe src="./forms/contact.php" width="400px" height="400px" style="border: none;"></iframe></div>');

	$windows.each(function()
	{
		$(this).prepend('<p class="close"><a>X</a></p>');
		var id = $(this).attr("id");
		h[id] = $(this).innerHeight() - parseInt($(this).css("padding-top")) - parseInt($(this).children(".frame").css("padding-bottom"));
		mt[id] = (-$(this).outerHeight()) / 2;
		opened[id] = false;
	});

	$.fn.extend({ close: function()
	{
		navigation.unfold();
		tweety.tunfold();
		
		$("body>.footer:first,body>.header:first").stop(true).animate({ opacity: 1 }, 750, function() { $(this).fixIE7(); });
		return $(this).each(function()
		{
			opened[$(this).attr("id")] = false;
			$(this).trigger("close");
			if (!$(this).hasClass("frame-special"))
				$(this).animate({ opacity: 0 }, 500, function() { $(this).css({ display: "none" }).find(">.frame>div").css({ opacity: 0 }); });
		});
	}});

	$windows.find(">p.close>a,button.close").click(function() { var $w = $(this).parents(".frame:last").close(); var $f = $w.find("form"); if ($f.length) $f[0].reset(); $f.find("p.error").remove(); });
	$windows.find("button[type=reset]").click(function() { $(this).closest("form").find("p.error").remove(); });

	self.open = function(id)
	{
		if (opened[id])
			return;

		$windows.not("#" + id).close();
		opened[id] = true;
		var $w = $windows.filter("#" + id);

		if (!$w.hasClass("frame-special"))
		{
			navigation.fold();
			tweety.tfold();
			$("body>.footer,body>.header").stop(true).animate({ opacity: .15 }, 750);

			$w.children(".frame").removeAttr("style");
			h[id] = $w.innerHeight() - parseInt($w.css("padding-top")) - parseInt($w.children(".frame").css("padding-bottom"));
			mt[id] = (-$w.outerHeight()) / 2;

			$w.children(".frame").height(0).children().stop(true).css({ opacity: 0 });
			$w.trigger("open").css({ display: "block", marginTop: "-40px" }).stop(true).animate({ opacity: 1 }, 750, function() { $(this).fixIE7().animate({ marginTop: mt[id] + "px" }, 750).children(".frame").animate({ height: h[id] + "px" }, 750).children().animate({ opacity: 1 }, 2000, function() { $(this).fixIE7(); }); });
		}
		else
			$w.trigger("open");
	};

	this.toggle = function(id) { if (opened[id]) $windows.filter("#" + id).close(); else self.open(id); };

	this.recalcHeight = function(id)
	{
		var $w = $windows.filter("#" + id);

		var oldH = $w.children(".frame").height();
		$w.children(".frame").removeAttr("style");
		h[id] = $w.innerHeight() - parseInt($w.css("padding-top")) - parseInt($w.children(".frame").css("padding-bottom"));
		mt[id] = (-$w.outerHeight()) / 2;
		$w.children(".frame").height(oldH);

		$w.animate({ marginTop: mt[id] + "px" }, 750).children(".frame").animate({ height: h[id] + "px" }, 750);
	};

	this.get = function(name) { return $windows.filter("#frame-" + name); };

	this.get("time-zones")
		.bind("open", function()
		{
			if (time)
				clearInterval(time);

			var $w = $(this);
			time = setInterval(function()
			{
				var d = new Date();

				$w.find(".user-time strong").text(d.toTimeString());

				var m = d.getTime() + (d.getTimezoneOffset() * 60000) + (1 + daylightSaving()) * 3600000;
				m = new Date(m);
				$w.find(".our-time strong").text(m.toTimeString());
				$w.find(".location span").text(m.toTimeString() + " UTC+1");

				if (m.getHours() >= 8 && m.getHours() < 16 && m.getDay() != 6 && m.getDay() != 0)
				{
					var n = new Date(d.getFullYear(), d.getMonth(), d.getDate(), 16, 0, 0);
					$w.find(".remaining-time").html('Our office is now open and will close at <strong>16:00 UTC+1</strong>.<br>Remaining ' + (n.getTime() - m.getTime() - 2 * 60000).toRemaining() + '.');
				}
				else
				{
					var day = m.getHours() < 8 ? m.getDate() : (m.getDay() >= 5 || m.getDay() == 0 ? m.getDate() + (m.getDay() >= 5 ? 8 - m.getDay() : 1) : m.getDate() + 1)
					var n = new Date(d.getFullYear(), d.getMonth(), day, 8, 0, 0);
					$w.find(".remaining-time").html('Our office will be opened ' + (m.getDay() >= 5 || m.getDay() == 0 ? 'on Monday ' : '') + 'at <strong>8:00 UTC+1</strong>.<br>Remaining ' + (n.getTime() - m.getTime() - 2 * 60000).toRemaining() + '.');
				}
			}, 500);
		})
		.bind("close", function()
		{
			if (time)
			{
				clearInterval(time);
				time = false;
			}
		})
	;

	this.get("legend")
		.bind("open", function()
		{
			var $w = $(this), m = -$w.outerHeight();
			$w.css({ display: "block", marginTop: (m - m / 8) + "px" }).stop(true).animate({ opacity: 1, marginTop: m + "px" }, 750, function() { $(this).fixIE7(); });
		})
		.bind("close", function() { $(this).animate({ opacity: 0 }, 500, function() { $(this).css({ display: "none" }).find(">.frame>div").css({ opacity: 0 }); }); })
	;


	var validateForm = function($form, fields, name, data)
	{
		var result = validation.check(fields);
		$form.find("p.error").remove();

		if (result === true)
		{
			windows.open("frame-sending");
			data["first-rule-of-fight-club"] = "you-dont-talk-about-fight-club";
			$.post(name, data, function(result)
			{
				if (result.status)
					windows.open("frame-" + name + "-sent");
				else
				{
					var $e = {}, any = false;
					for (var err in result.errors)
					{
						$e[err] = $('<p class="error' + (err == "message" ? ' error-alt' : '') + '">' + result.errors[err] + '</p>').insertAfter($form.find("[name='" + err + "']").parent()).css("visibility", "hidden");
						any = true;
					}

					if (any)
					{
						windows.recalcHeight("frame-" + name);
						for (var err in $e)
							$e[err].css("visibility", "visible").animate({ height: "hide", opacity: 0 }, 0).animate({ height: "show", opacity: 1 }, 500);
					}
					else
						windows.open("frame-error-sending");
				}
			}, "json");
		}
		else
		{
			var $e = {};
			for (var r in result)
				$e[r] = $('<p class="error' + (r == "message" ? ' error-alt' : '') + '">' + result[r] + '</p>').insertAfter($form.find("[name='" + r + "']").parent()).css("visibility", "hidden");
			windows.recalcHeight("frame-" + name);
			for (var e in $e)
				$e[e].animate({ height: "hide", opacity: 0 }, 0).animate({ height: "show", opacity: 1 }, 500).css("visibility", "visible");
		}
	};


	var $contact = this.get("contact").find("form:first").submit(function()
	{
		var d =
		{
			"name": $(this).find("input[name='name']").typedVal()
		,	"company": $(this).find("input[name='company']").typedVal()
		,	"e-mail": $(this).find("input[name='e-mail']").typedVal()
		,	"message": $(this).find("textarea[name='message']").typedVal()
		};

		validateForm($contact,
		{
			"name": { "value": d["name"], "rules": "required|max_length[64]" }
		,	"company": { "value": d["company"], "rules": "max_length[64]" }
		,	"e-mail": { "value": d["e-mail"], "rules": "required|max_length[64]|valid_email" }
		,	"message": { "value": d["message"], "rules": "required|max_length[1024]" }
		}, "contact", d);

		return false;
	});


	var $newsletter = this.get("newsletter").find("form:first").submit(function()
	{
		var d =
		{
			"name": $(this).find("input[name='name']").typedVal()
		,	"e-mail": $(this).find("input[name='e-mail']").typedVal()
		};

		validateForm($newsletter,
		{
			"name": { "value": d["name"], "rules": "required|max_length[64]" }
		,	"e-mail": { "value": d["e-mail"], "rules": "required|max_length[64]|valid_email" }
		}, "newsletter", d);

		return false;
	});

	var $suggest = this.get("suggest").find("form:first").submit(function()
	{
		var d = { "address": $(this).find("input[name='address']").typedVal() };
		validateForm($suggest, { "address": { "value": d["address"], "rules": "required|max_length[256]|valid_address" } }, "suggest", d);
		return false;
	});
};


$(":text,textarea").each(function()
{
	this.defaultText = this.value;
	$(this)
		.focus(function() { if (this.value == this.defaultText) this.value = ""; })
		.blur(function() { if (this.value == "" && this.defaultText) this.value = this.defaultText; });
});


var loc = window.location.href;

if (loc.indexOf("#") >= 0)
{
	loc = loc.substr(loc.indexOf("#") + 1);
	if (loc.length)
		windows.open(loc);
}

$("body>.footer p.right").append(' | <a href="#frame-suggest">Feedback</a>');
$("a[href*='#frame-']").click(function() { windows.toggle($(this).hrefId().substr(1)); return false; });

if ($.browser.msie && $.browser.version <= 6) {
	$("body>.header:first,body>.footer:first").bind("mouseenter mouseleave", function() { $(this).toggleClass("hover"); });
	$("a:not([href])").attr("href", "#");
}

var deviceAgent = navigator.userAgent.toLowerCase();
var agentID = deviceAgent.match(/(iphone|ipod|ipad)/);
if (agentID) {
	//var $twitter = $('<div class="iphone">I\'m an iPhone. I wish I could do Flash</div>').appendTo("body");
	
}

Cufon.replace(".frame h2", { fontFamily: "Haptic Light" });
Cufon.replace(".header ul a,.footer ul a", { fontFamily: "Haptic Regular", hover: true });

getTwitters('tweet', {
        id: 'Recycledrocks', 
		enableLinks: true, 
        ignoreReplies: true,
        template: '<img height="24" width="24" src="%user_profile_image_url%" /><span class="twitterPrefix"><span class="twitterStatus">%text%</span> <em class="twitterTime">%time%</em></span>',
        count: 3, 
        withFriends: false,
        ignoreReplies: true,
        newframe: true
});


