// catch if console doesn't exist (IE)
function log(value) {
	if(typeof(console) != "undefined") {
		console.log(value);
	}
}

function fadeIn(id) {
	$("#"+id).css('display', 'none');
	$("#"+id).css('visibility', 'visible');
	$("#"+id).fadeIn(800, function() {
		if(typeof sIFR == "function" && $('.sIFR-hasFlash').length > 0){
			sIFR.replaceElement("#"+id+" h3", named({sFlashSrc: "/flash/fonts/lubalinob.swf", sColor: "#1D1D1D", sBgColor: "#6EC3E1" }));
		};
	});
}

function fader(el) {
	$(el).animate({ opacity: .6 }, { queue:false, duration:1000, complete: function() {
		$(this).animate({ opacity: 1 }, { queue:false, duration:1000, complete: function() {
			fader(el);
		}})
	}});
}

function loadInWork() {
	$(".workImage").click(
		function() {
			window.location = $(this).find('a').attr('href');
		}
	);

	$('.pager a').click(function() {
		var href = $(this).attr('href');

		// track google stats
		pageTracker._trackPageview(href);
		$('#pasteboard').load(href, { display: "inline" },
		 	function(){
				afterPasteBoardLoad();
			}
		);
		return false;
	});

	$(".workImageWrap").css('cursor', 'pointer');
}

function restructureWorkImages() {
	$("#pasteboard .workImageWrap").each(function(i) {

		var workImagep = this;
		var sort = 0;
		var id = '';

		if($('#workImages #'+workImagep.id).length == 0) {

			// get sort value
			var classes = $(workImagep).attr('class');
			var classesSplit = classes.split(" ");
			for(var c=0; c<classesSplit.length; c++) {
				if(classesSplit[c].substr(0, 5) == 'sort_') {
					sort = classesSplit[c].substr(5);
					break;
				}
			}

			id = workImagep.id;

			if($("#workImages .workImageWrap").length > 0) {

				var inserted = false;
				$("#workImages .workImageWrap").each(function(i) {
					if(inserted == false) {
						var workImage = this;

						// get newsort value
						var newSort = 0;
						var classes = $(workImage).attr('class');
						var classesSplit = classes.split(" ");
						for(var c=0; c<classesSplit.length; c++) {
							if(classesSplit[c].substr(0, 5) == 'sort_') {
								newSort = classesSplit[c].substr(5);
								break;
							}
						}

						if(parseInt(newSort) > parseInt(sort)) {
							inserted = true;
							$(workImagep).addClass('before');
							$(workImage).before(workImagep);
						}
					}
				});

				if(inserted == false) {
					$(workImagep).addClass('inserted');
					$("#workImages").append($(workImagep));
				}
			}
			else {
				$(workImagep).addClass('appended');
				$("#workImages").append($(workImagep));
			}
		}

	});

	$("#workImages .workImageWrap").each(function(i) {
		var top = Math.floor(i / 2) * 235 + 30;
		var left = Math.floor(i % 2) * 450;
		$(this).animate({top: top+'px', left: left+'px', opacity: 1}, 400, function() {
			$(".workImageWrap").css('visibility', 'visible');
			if(typeof sIFR == "function"){
				sIFR.replaceElement("#"+this.id+" h3", named({
						sFlashSrc: "/flash/fonts/lubalinob.swf",
						sColor: "#1D1D1D",
						sBgColor: "#6EC3E1"
				}));
			}
		});
	});
}

var clientListToggleVar = false;
function clientListToggle() {
	if($('#clientListList').css('display') == 'none') {
		$('body').click(function() {
			if($('#clientListList').css('display') != 'none' && $('#clientListList').css('overflow') != 'hidden') {
				clientListToggle();
			}
		});
		$('.filter_filter').click(function() {
			if($('#clientListList').css('display') != 'none' && $('#clientListList').css('overflow') != 'hidden') {
				clientListToggle();
			}
		});
	}

	$('#clientListList').slideToggle(200);

	if($('.sIFR-hasFlash').length > 0) {
		if(clientListToggleVar == false) {
			if($('.workImageImage .imageDiv').length > 1) {
				ele = $('.workImageImage .imageDiv').get(1);
				$(ele).show();
				ele = $('.workImageImage .imageFlashDivWrap').get(1);
				$(ele).hide();
			}
			clientListToggleVar = true;
		}
		else {
			if($('.workImageImage .imageFlashDivWrap').length > 1) {
				ele = $('.workImageImage .imageFlashDivWrap').get(1);
				$(ele).show();
				ele = $('.workImageImage .imageDiv').get(1);
				$(ele).hide();
			}
			clientListToggleVar = false;
		}
	}
}

$(document).ready(function() {

	// set random background image
	var n = 3; // number of random images
	var num = Math.floor ( Math.random ( ) * n + 1 );
	$("body").css('backgroundImage', 'url(/images/bg/'+num+'.gif)'); // vários backgrounds

	if($('.sIFR-hasFlash').length > 0) {
		if($.cookie('logoplayed') == 1) {
			$('#logo_content img').css('visibility', 'visible');
		}
		else {
			$('#logo_content img').css('visibility', 'hidden');
			$.cookie('logoplayed', 1, {expires:5});
			logoplay = 1;
			swfobject.embedSWF("/flash/logo_anim.swf", "logo_content", "929", "136", "9.0.0", "/flash/expressInstall.swf", {logoplay:logoplay}, {}, {});
		}

		if($('#showreelNoFlash').length > 0) {
			swfobject.embedSWF("/flash/showreel/showreel.swf", "showreelNoFlash", "867", "352", "9.0.0", "/flash/expressInstall.swf", {}, {}, {});
		}
	}

	loadInWork();

	$(".workImageWrap").each(function(i){
		setTimeout("fadeIn('"+this.id+"')", 500 + (70 * i));
	});

	if($('#newsArchive').length) {
		loadArchive();
	}

	$('.filter_filter').click(function() {

		$('.filter_selected').toggleClass('filter_selected');
		$(this).toggleClass('filter_selected');

		var clicked = $(this).attr('id');

		if(clicked == 'filter_All') {
			$('.filter_selected').toggleClass('filter_selected');
			$('#filter_All').addClass('filter_selected');
		}
		else {
			$('#filter_All').removeClass('filter_selected');
		}

		if($('.filter_selected').length == 0) {
			$('#filter_All').addClass('filter_selected');
		}

		var filter = []
		var filterString = '';
		$('.filter_selected').each(function(i) {
			filter.push($(this).attr('id').substr(7));
			filterString += $(this).attr('id').substr(7)+';';
		});

		$("#workImages .workImageWrap").each(function() {
			var workImage = this;
			var keep = false;
			$(workImage).find('.type').each(function() {
				for (var i in filter) {
					if (clicked == 'filter_All' || filter[i] == $(this).attr('alt')) {
						keep = true;
						break;
					}
				}
			});

			if(keep == false) {
				$(workImage).addClass('workNokeep');
			}
		});

		pageTracker._trackPageview('/work/list?workFilter='+filterString);
		$('#pasteboard').load('/work/list', { display: "inline", filter: filterString },
		 	function(){
				afterPasteBoardLoad();
			}
		);

		return false;

	});

	$('#clientListButton').click(function() {
		clientListToggle();
		return false;
	});

	$('#clientListList .clientListClient').click(function() {
		var client = $(this).find('a').html();
		$('.filter_selected').toggleClass('filter_selected');
		pageTracker._trackPageview('/work/list?clientFilter='+client);
		$('#pasteboard').load('/work/list', { display: "inline", clientFilter: client },
		 	function(){
				afterPasteBoardLoad();
			}
		);

		clientListToggle();
		return false;
	});

	$('#homePage #signupLink').click(function() {
		$('#newsletterSignup').animate({width: '20px'}, 400, null, function() {
			$('#signupInfo').hide();
			$('#signupForm').show();
			$('#newsletterSignup').animate({width: '433px'}, 400, null, function() {
				$('#emailAddress').focus();
			});
		});
		return false;
	});

	$('#homePage #submitBtn').click(function() {
		$.post('/index/newsletterSignup',{
		 	email: $('#emailAddress').val()
		},
		 function(data){
			if(data == 'ok') {
				$('#newsletterSignup').animate({width: '20px'}, 400, null, function() {
					$('#signupInfo').hide();
					$('#signupForm').hide();
					$('#signupComplete').html('Thanks! You are now signed up to our newsletter.');
					$('#signupComplete').show();
					$('#newsletterSignup').animate({width: '433px'}, 400, null, function() {
						$('#emailAddress').val('')
					});
				});
			}
			else {
				$('#signupError').html(data);
				$('#signupError').fadeIn(300, function() {
					window.setTimeout(function() {
						$('#signupError').fadeOut(700);
					}, 1000);
				});

			}
		});
		return false;
	});

	var easing = "easeOutQuart";
	var easing2 = "easeOutQuart";
	$('#homePage .cultureFeedItem').hover(function() {
		var feedItem = this;
		$('.cultureFeedItem').stop();
		$('.itemImage').stop();
		$('.itemArrow').stop();
		$(feedItem).addClass('itemSelected');
		$(feedItem).animate({height:"160px"}, 400, easing);

		window.setTimeout(function() { $('#'+feedItem.id + ' .itemDate').fadeIn(200); }, 100);

		$('#'+feedItem.id + ' .itemImage').animate({height:"100px"}, 400, easing);

		$('#'+feedItem.id + ' .itemArrow').animate({top:"95px"}, 400, easing);
		$('.cultureFeedItem').each(function(index) {
			if(this.id != feedItem.id) {
				$('#'+this.id+' .itemArrow').animate({top:"40px"}, 400, easing2);
				$('#'+this.id+' .itemImage').animate({height:"45px"}, 400, easing2);
				$('#'+this.id).animate({height:"67px"}, 400, easing2);
			}
		});
	}, function() {
		$('.cultureFeedItem').stop();
		$('.itemImage').stop();
		$('.itemArrow').stop();

		$(this).removeClass('itemSelected');
		$('.cultureFeedItem').animate({height:"98px"}, 400, easing2);
		$('.itemImage').animate({height:"76px"}, 400, easing2);
		$('.itemArrow').animate({top:"71px"}, 400, easing2);
		$('.itemDate').hide();
	});

	$('#homePage .cultureFeedItem').click(function() {
		window.location = $('#'+this.id+' .itemSlug').attr('href');
	});


	$('#culturePage .newsItem').each(function(index) {
		var newsItem = this;
		if($(newsItem).find('.blog_image').length > 1) {
			$(newsItem).find('.blog_image').each(function(i) {
				var imageItem = this;
				var imageSource = $(imageItem).find('img').attr('src');
				if(i > 0) {
					$(imageItem).hide();
				}
				else {
					$(imageItem).after('<span class="images"></span>');
				}
				$(newsItem).find('.images').each(function(x) {
					if(i == 0) {
						var classes = 'image_nav_item nav_item_selected';
					}
					else {
						var classes = 'image_nav_item';
					}
					$(this).append('<a href="#" class="'+classes+'" image="'+imageSource+'" block="'+index+'">'+(i+1)+'</a>');
				});
			});
		}
	});

	$('#culturePage .image_nav_item').click(function() {
		var nav = this;

		$(nav).parent('.images').find('.nav_item_selected').removeClass('nav_item_selected');
		$(nav).addClass('nav_item_selected');

		$('.newsItem').each(function(index) {
			var newsItem = this;
			if($(nav).attr('block') == index) {
				$(newsItem).find('.blog_image').each(function(i) {
					if(i == 0) {
						$(this).find('img').fadeTo({ queue:false, duration:'fast', complete: function() {
							$(this).attr('src', $(nav).attr('image'));
							$(this).fadeTo('fast', 1);
						}}, 0);
					}
				});
			}
		});
		return false;
	});

	$('#culturePage .archive .yearHeader').click(function() {
		var yearClicked = $(this).parent().get(0).id;
		if($('#'+yearClicked).hasClass('yearOpen')) {
			$('#'+yearClicked+' .yearList').slideUp('fast');
			$('#'+yearClicked).toggleClass('yearOpen');
		}
		else {
			$('#'+yearClicked+' .yearList').slideDown('fast');
			$('#'+yearClicked).toggleClass('yearOpen');
		}

		return false;
	});

	$('#culturePage .archive .monthHeader').click(function() {
		var monthClicked = $(this).parent().get(0).id;
		if($('#'+monthClicked).hasClass('monthOpen')) {
			$('#'+monthClicked+' ul').slideUp('fast');
			$('#'+monthClicked).toggleClass('monthOpen');
		}
		else {
			$('#'+monthClicked+' ul').slideDown('fast');
			$('#'+monthClicked).toggleClass('monthOpen');
		}

		return false;
	});

	$('#culturePage .archive .yearList .monthOpen ul').show();
	$('#culturePage .archive .yearOpen .yearList').show();

	// obscure fix for ie 6 - change them to absolute then back to relative
	$('#culturePage #rightcolumn .content ul.archive li.month ul').css('position', 'absolute');
	$('#culturePage #rightcolumn .content ul.archive li.month ul').css('position', 'relative');

	$('#culturePage #addComment #submit').click(function() {
		return commentFormSubmit();
	});


	$('#footer_anchor').click(function() {
		$.scrollTo( {top:'0px'}, 50 );
	});

	$('#kon a').click(function() {

		var earray = new Array();
		var ecount = new Array();
		var count = 0;

		$('.imageFlashDivWrap').remove();
		$('.imageDiv').show();

		$('.sIFR-flash').remove();
		$('.sIFR-alternate').show().css('visibility', 'visible').removeClass('sIFR-alternate');
		$('body :hidden').remove();

		$('div:visible,img:visible,h3:visible,h2:visible,h1:visible').each(function(index) {
			if(count < 100) {
				$(this).addClass('destroy_'+index);
				$(this).addClass('length_'+$(this).parents().length);
				earray[count] = new Array('destroy_'+index, $(this).parents().length);
			}
			else {
				$(this).fadeOut();
			}
			count ++;
		});

		log('total elements: '+count);

		earray.sort(sortLength);

		for(var i=0; i<earray.length; i++) {
			var el = earray[i][0];
			destroy(el, 50*i);
		}

		$('body').css('overflow', 'hidden');
		return false;
	});
});

function commentFormSubmit() {
	var data = $('#commentAddForm').serialize();

	$.post('/culture/addcomment', data,
		function (d) {
			var s = JSON.parse(d);
			if (s.status=='OK') {
				$('#addComment').slideUp('fast', function() {
					$('#addComment').html("<h3>Thank you.</h3><p>Your comment has been saved. It will appear once it has been approved.</p>");
					$('#addComment').slideDown('fast');
				});
			}
			else {
				$('#commentFormWrap').html(s.form);
				$('#culturePage #addComment #submit').click(function() { return commentFormSubmit(); });
			}
		}
	);
	return false;
}

function sortLength(a, b) {
	return b[1] - a[1];
}

function destroy(c, t) {
	setTimeout(function() {
		// rotate for safari and firefox 3.1
		$('.'+c).css('-webkit-transform', 'rotate('+rand(-5,5)+'deg)');
		$('.'+c).css('-moz-transform', 'rotate('+rand(-5,5)+'deg)');

		$('.'+c).animate({width: (rand(10,1000)), height: (rand(10,1000)), top: (rand(10,2000)), left: (rand(10,1000)), opacity:0}, rand(500,2000), 'swing', function () {
		 	$(this).remove();
			if($(':animated').length <= 1) {
				window.location = 'http://kingsofnothing.tv';
			}
		});
	}, t);
}

function rand( min, max ) {
    var argc = arguments.length;
    if (argc == 0) {
        min = 0;
        max = 2147483647;
    } else if (argc == 1) {
        throw new Error('Warning: rand() expects exactly 2 parameters, 1 given');
    }
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function afterPasteBoardLoad() {
	$('#pasteboard #workImages').attr('id', 'workImagesp');

	$('#workPage #pagerTop').remove();
	$('#workPage #pagerBottom').remove();
	$('#workPage').append($('#pasteboard #pagerTop'));
	$('#workPage').append($('#pasteboard #pagerBottom'));

	$('#workImages .workImageWrap').each(function(){
		if($('#pasteboard #'+this.id).length == 0) {
			$(this).addClass('workNokeep');
		}
	});

	loadInWork();

	if($("#workImages .workNokeep").length > 0) {
		$("#workImages .workNokeep").fadeTo(200, 0, function() {
			$("#workImages .workNokeep").stop();
			$("#workImages .workNokeep object").remove();
			var timeout = 0;
			$("#workImages .workNokeep").each(function(i) {
				timeout = 200 * i;
				setTimeout("$('#"+this.id+"').hide().remove()", timeout);
			});
			setTimeout("restructureWorkImages()", timeout+10);
		});
	}
	else {
		setTimeout("restructureWorkImages()", 100);
	}
}

function loadArchive() {
	$("#newsArchive").load("/news/archivebox/view?page="+currentArchivePage, function(){
		$("#newsArchive").fadeIn('fast', function () { });

		$("#newsArchive #archivePrev").click( function() {
			$("#newsArchive").hide();
			currentArchivePage --;
			loadArchive(currentArchivePage)
		});

		$("#newsArchive #archiveNext").click( function() {
			$("#newsArchive").hide();
			currentArchivePage ++;
			loadArchive(currentArchivePage)
		});

	});
}


function flashPutHref(href) { location.href = href; }

function loadWorkFlash(id) {
	if($('.sIFR-hasFlash').length > 0) {

		var flashvars = {
			imageXMLPath: "/work/images/view/"+id,
			initialURL: '/'
		}

		var params = {
			base: "/",
			quality: "best",
			bgcolor: "#ffffff",
			allowfullscreen: "false"
		}

		var attributes = {}
		swfobject.embedSWF("/flash/slideshowpro.swf", "flashshow", "867", "528", "9.0.0", "/flash/expressInstall.swf", flashvars, params, attributes);
	}
}

function doSifr() {
	if(typeof sIFR == "function") {

		sIFR.replaceElement("#Services_column_wrapper h2", named({
			sFlashSrc: "/flash/fonts/lubalin.swf",
			sColor: "#69c0df",
			sWmode: "transparent",
			sHoverColor: "#6EC3E1"
		}));

		sIFR.replaceElement("#Services_column_wrapper h5", named({
			sFlashSrc: "/flash/fonts/lubalin.swf",
			sColor: "#69c0df",
			sWmode: "transparent",
			sHoverColor: "#6EC3E1"
		}));


		sIFR.replaceElement("#culturePage .leftcolumn .wrapper .content h2 span", named({
			sFlashSrc: "/flash/fonts/lubalinob.swf",
			sColor: "#1D1D1D",
			sBgColor: "#6EC3E1",
			sFlashVars: "underline=true,offsetTop=5"
		}));

		sIFR.replaceElement("#workTitle h1", named({
			sFlashSrc: "/flash/fonts/lubalinthinitalic.swf",
			sColor: "#1D1D1D",
			sBgColor: "#6EC3E1",
			sCase: 'upper',
			sFlashVars: "underline=true,offsetTop=5"
		}));

		sIFR.replaceElement("#workInfo h3", named({
			sFlashSrc: "/flash/fonts/overview.swf",
			sColor: "#1D1D1D"
		}));
	};
}

function googleMapInit() {
	var map = new google.maps.Map2(document.getElementById("googlemap"));
	map.setCenter(new google.maps.LatLng(51.523538, -0.098772), 15);
	map.addControl(new GSmallZoomControl());


	var point = new GPoint(-0.098872, 51.524338);

	html = "<div id=\"googlemaphtml\"><h3>Delete</h3><br /><b>Address:</b><img src=\"/images/delete.jpg\" alt=\"Delete\" /><br />80 Goswell Road<br />London<br />EC1V 7DB<br />UK<br /><br />Tel: +44 (0)203 004 7155<br /><a href=\"http://maps.google.co.uk/maps?f=q&hl=en&geocode=&q=80+Goswell+Rd,+London,+Greater+London,+EC1V+7,+UK&sll=51.52354,-0.09875&sspn=0.004613,0.013947&ie=UTF8&z=16&iwloc=addr\" target=\"_blank\">Get directions</a></div>";
	var marker = createInfoMarker(point, html);
	map.addOverlay(marker);
	marker.openInfoWindowHtml(html);
}

function createInfoMarker(point, html) {
	var venuesIcon = new GIcon();
	venuesIcon.image = "/images/googlemapicon.png";
	venuesIcon.iconSize = new GSize(39, 32);
	venuesIcon.iconAnchor = new GPoint(5, 10);
	venuesIcon.infoWindowAnchor = new GPoint(12, 2);

	var icons = [];
	icons[0] = venuesIcon;

	var marker = new GMarker(point,icons[0]);

	GEvent.addListener(marker, "click",	function() {
		marker.openInfoWindowHtml(html);
	});

	return marker;
}


/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};



/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 *
 * Uses the built in easing capabilities added In jQuery 1.1
 * to offer multiple easing options
 *
 * TERMS OF USE - jQuery Easing
 *
 * Open source under the BSD License.
 *
 * Copyright © 2008 George McGinley Smith
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this list of
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list
 * of conditions and the following disclaimer in the documentation and/or other materials
 * provided with the distribution.
 *
 * Neither the name of the author nor the names of contributors may be used to endorse
 * or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
*/

// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend( jQuery.easing,
{
	def: 'easeOutQuad',
	swing: function (x, t, b, c, d) {
		//alert(jQuery.easing.default);
		return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
	},
	easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t + b;
		return -c/2 * ((--t)*(t-2) - 1) + b;
	},
	easeInCubic: function (x, t, b, c, d) {
		return c*(t/=d)*t*t + b;
	},
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
	easeInOutCubic: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	},
	easeInQuart: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t + b;
	},
	easeOutQuart: function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	},
	easeInOutQuart: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
		return -c/2 * ((t-=2)*t*t*t - 2) + b;
	},
	easeInQuint: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t*t + b;
	},
	easeOutQuint: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t*t*t + 1) + b;
	},
	easeInOutQuint: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
		return c/2*((t-=2)*t*t*t*t + 2) + b;
	},
	easeInSine: function (x, t, b, c, d) {
		return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
	},
	easeOutSine: function (x, t, b, c, d) {
		return c * Math.sin(t/d * (Math.PI/2)) + b;
	},
	easeInOutSine: function (x, t, b, c, d) {
		return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
	},
	easeInExpo: function (x, t, b, c, d) {
		return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
	},
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	},
	easeInOutExpo: function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	},
	easeInCirc: function (x, t, b, c, d) {
		return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
	},
	easeOutCirc: function (x, t, b, c, d) {
		return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
	},
	easeInOutCirc: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
		return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
	},
	easeInElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	},
	easeOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	},
	easeInOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
		return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
	},
	easeInBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*(t/=d)*t*((s+1)*t - s) + b;
	},
	easeOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	},
	easeInOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
	},
	easeInBounce: function (x, t, b, c, d) {
		return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
	},
	easeOutBounce: function (x, t, b, c, d) {
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	},
	easeInOutBounce: function (x, t, b, c, d) {
		if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
		return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
	}
});

(function(h){var m=h.scrollTo=function(b,c,g){h(window).scrollTo(b,c,g)};m.defaults={axis:'y',duration:1};m.window=function(b){return h(window).scrollable()};h.fn.scrollable=function(){return this.map(function(){var b=this.parentWindow||this.defaultView,c=this.nodeName=='#document'?b.frameElement||b:this,g=c.contentDocument||(c.contentWindow||c).document,i=c.setInterval;return c.nodeName=='IFRAME'||i&&h.browser.safari?g.body:i?g.documentElement:this})};h.fn.scrollTo=function(r,j,a){if(typeof j=='object'){a=j;j=0}if(typeof a=='function')a={onAfter:a};a=h.extend({},m.defaults,a);j=j||a.speed||a.duration;a.queue=a.queue&&a.axis.length>1;if(a.queue)j/=2;a.offset=n(a.offset);a.over=n(a.over);return this.scrollable().each(function(){var k=this,o=h(k),d=r,l,e={},p=o.is('html,body');switch(typeof d){case'number':case'string':if(/^([+-]=)?\d+(px)?$/.test(d)){d=n(d);break}d=h(d,this);case'object':if(d.is||d.style)l=(d=h(d)).offset()}h.each(a.axis.split(''),function(b,c){var g=c=='x'?'Left':'Top',i=g.toLowerCase(),f='scroll'+g,s=k[f],t=c=='x'?'Width':'Height',v=t.toLowerCase();if(l){e[f]=l[i]+(p?0:s-o.offset()[i]);if(a.margin){e[f]-=parseInt(d.css('margin'+g))||0;e[f]-=parseInt(d.css('border'+g+'Width'))||0}e[f]+=a.offset[i]||0;if(a.over[i])e[f]+=d[v]()*a.over[i]}else e[f]=d[i];if(/^\d+$/.test(e[f]))e[f]=e[f]<=0?0:Math.min(e[f],u(t));if(!b&&a.queue){if(s!=e[f])q(a.onAfterFirst);delete e[f]}});q(a.onAfter);function q(b){o.animate(e,j,a.easing,b&&function(){b.call(this,r,a)})};function u(b){var c='scroll'+b,g=k.ownerDocument;return p?Math.max(g.documentElement[c],g.body[c]):k[c]}}).end()};function n(b){return typeof b=='object'?b:{top:b,left:b}}})(jQuery);

/* Copyright (c) 2007 Paul Bakaus (paul.bakaus@googlemail.com) and Brandon Aaron (brandon.aaron@gmail.com || http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $LastChangedDate: 2007-12-20 08:46:55 -0600 (Thu, 20 Dec 2007) $
 * $Rev: 4259 $
 *
 * Version: 1.2
 *
 * Requires: jQuery 1.2+
 */

(function($){

$.dimensions = {
	version: '1.2'
};

// Create innerHeight, innerWidth, outerHeight and outerWidth methods
$.each( [ 'Height', 'Width' ], function(i, name){

	// innerHeight and innerWidth
	$.fn[ 'inner' + name ] = function() {
		if (!this[0]) return;

		var torl = name == 'Height' ? 'Top'    : 'Left',  // top or left
		    borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right

		return this.is(':visible') ? this[0]['client' + name] : num( this, name.toLowerCase() ) + num(this, 'padding' + torl) + num(this, 'padding' + borr);
	};

	// outerHeight and outerWidth
	$.fn[ 'outer' + name ] = function(options) {
		if (!this[0]) return;

		var torl = name == 'Height' ? 'Top'    : 'Left',  // top or left
		    borr = name == 'Height' ? 'Bottom' : 'Right'; // bottom or right

		options = $.extend({ margin: false }, options || {});

		var val = this.is(':visible') ?
				this[0]['offset' + name] :
				num( this, name.toLowerCase() )
					+ num(this, 'border' + torl + 'Width') + num(this, 'border' + borr + 'Width')
					+ num(this, 'padding' + torl) + num(this, 'padding' + borr);

		return val + (options.margin ? (num(this, 'margin' + torl) + num(this, 'margin' + borr)) : 0);
	};
});

// Create scrollLeft and scrollTop methods
$.each( ['Left', 'Top'], function(i, name) {
	$.fn[ 'scroll' + name ] = function(val) {
		if (!this[0]) return;

		return val != undefined ?

			// Set the scroll offset
			this.each(function() {
				this == window || this == document ?
					window.scrollTo(
						name == 'Left' ? val : $(window)[ 'scrollLeft' ](),
						name == 'Top'  ? val : $(window)[ 'scrollTop'  ]()
					) :
					this[ 'scroll' + name ] = val;
			}) :

			// Return the scroll offset
			this[0] == window || this[0] == document ?
				self[ (name == 'Left' ? 'pageXOffset' : 'pageYOffset') ] ||
					$.boxModel && document.documentElement[ 'scroll' + name ] ||
					document.body[ 'scroll' + name ] :
				this[0][ 'scroll' + name ];
	};
});

$.fn.extend({
	position: function() {
		var left = 0, top = 0, elem = this[0], offset, parentOffset, offsetParent, results;

		if (elem) {
			// Get *real* offsetParent
			offsetParent = this.offsetParent();

			// Get correct offsets
			offset       = this.offset();
			parentOffset = offsetParent.offset();

			// Subtract element margins
			offset.top  -= num(elem, 'marginTop');
			offset.left -= num(elem, 'marginLeft');

			// Add offsetParent borders
			parentOffset.top  += num(offsetParent, 'borderTopWidth');
			parentOffset.left += num(offsetParent, 'borderLeftWidth');

			// Subtract the two offsets
			results = {
				top:  offset.top  - parentOffset.top,
				left: offset.left - parentOffset.left
			};
		}

		return results;
	},

	offsetParent: function() {
		var offsetParent = this[0].offsetParent;
		while ( offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && $.css(offsetParent, 'position') == 'static') )
			offsetParent = offsetParent.offsetParent;
		return $(offsetParent);
	}
});

function num(el, prop) {
	return parseInt($.curCSS(el.jquery?el[0]:el,prop,true))||0;
};

})(jQuery);


/* JSON */
if(!this.JSON){JSON={};}
(function(){function f(n){return n<10?'0'+n:n;}
if(typeof Date.prototype.toJSON!=='function'){Date.prototype.toJSON=function(key){return this.getUTCFullYear()+'-'+
f(this.getUTCMonth()+1)+'-'+
f(this.getUTCDate())+'T'+
f(this.getUTCHours())+':'+
f(this.getUTCMinutes())+':'+
f(this.getUTCSeconds())+'Z';};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf();};}
var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==='string'?c:'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4);})+'"':'"'+string+'"';}
function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==='object'&&typeof value.toJSON==='function'){value=value.toJSON(key);}
if(typeof rep==='function'){value=rep.call(holder,key,value);}
switch(typeof value){case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';}
gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==='[object Array]'){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||'null';}
v=partial.length===0?'[]':gap?'[\n'+gap+
partial.join(',\n'+gap)+'\n'+
mind+']':'['+partial.join(',')+']';gap=mind;return v;}
if(rep&&typeof rep==='object'){length=rep.length;for(i=0;i<length;i+=1){k=rep[i];if(typeof k==='string'){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}else{for(k in value){if(Object.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}
v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+
mind+'}':'{'+partial.join(',')+'}';gap=mind;return v;}}
if(typeof JSON.stringify!=='function'){JSON.stringify=function(value,replacer,space){var i;gap='';indent='';if(typeof space==='number'){for(i=0;i<space;i+=1){indent+=' ';}}else if(typeof space==='string'){indent=space;}
rep=replacer;if(replacer&&typeof replacer!=='function'&&(typeof replacer!=='object'||typeof replacer.length!=='number')){throw new Error('JSON.stringify');}
return str('',{'':value});};}
if(typeof JSON.parse!=='function'){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v;}else{delete value[k];}}}}
return reviver.call(holder,key,value);}
cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return'\\u'+
('0000'+a.charCodeAt(0).toString(16)).slice(-4);});}
if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof reviver==='function'?walk({'':j},''):j;}
throw new SyntaxError('JSON.parse');};}})();