

function pa( obj )
{
   if(!obj || typeof(obj) != 'object') {
      var _type = typeof(obj);
      if(_type == 'undefined') {
         alert("["+_type+"]");
      }
      else {
         var _output = "[" + _type + "] => `" + obj + "`";
         alert(_output);
      }
      return;
   }
   
   var
      _output = "\t OBJECT PROPERTIES: \n";
      separator = "";
      spacer = "";
      i = 0;
   
   try{
      for( var _key in obj ) {
         if((i % 2) == 1){ separator = "\n"; spacer = "\t\t"; }
         else{ separator = ""; spacer = ""; };
         
         _output += spacer + "[" + _key + '] => `' + obj[_key] + '`' + separator;
         ++i;
      }
   }
   catch(err){
      _output += "Can't get properties for: " + obj;
   }
   
   alert(_output);
} 


var defaultSearchBoxContent = 'Enter keywords to search for';
var defaultBreadCrumbsTop = 0;
var defaultBottomSliderTop = 0;
var commentSliderScrollTop = 0;

var defaultLogin = '';
var defaultPassword = '';

var opened = 'true';

var bookmarkIds = new Array(
	'google',
	'digg',
	'netscape',
	'yahoo-my-web',
	'reddit',
	'technorati',
	'furl',
	'del-icio-us',
	'newsvine',
	'slashdot',
	'stumbleupon',
	'magnolia',
	'squidoo',
	'backflip',
	'buddymarks',
	'feedmarker',
	'hyperlinkomatic',
	'linkagogo',
	'maple',
	'rawsugar',
	'shadows',
	'tailrank',
	'plugim',
	'blinkbits',
	'citeulike',
	'feedmelinks',
	'igooi',
	'linkroll',
	'mesfavs',
	'rojo',
	'simpy',
	'unalog',
	'blogmemes',
	'blinklist',
	'diigo',
	'givelink',
	'kinja',
	'looklater',
	'netvouz',
	'scuttle',
	'spurl',
	'wink',
	'wists',
	'blogmarks',
	'dzone',
	'gravee',
	'lilisto',
	'segnalo',
	'tagtooga'
);

var bkmkTitle = 'W3 EDGE';
var bkmkUrl = document.location.href;

var bookmarkLinks = new Array(
	'http://www.google.com/bookmarks/mark?title=' + bkmkTitle + '&bkmk=' + bkmkUrl + '',
	'http://digg.com/submit?phase=2&url=' + bkmkUrl + '&title=' + bkmkTitle + '',
	'http://www.netscape.com/submit/?U=' + bkmkUrl + '&T=' + bkmkTitle + '',
	'http://myweb2.search.yahoo.com/myresults/bookmarklet?u=' + bkmkUrl + '&t=' + bkmkTitle + '',
	'http://reddit.com/submit?url=' + bkmkUrl + '&title=' + bkmkTitle + '',
	'http://technorati.com/faves/?add=' + bkmkUrl,
	'http://www.furl.net/storeIt.jsp?t=' + bkmkTitle + '&u=' + bkmkUrl + '',
	'http://del.icio.us/post?v=2&url=' + bkmkUrl + '&title=' + bkmkTitle + '',
	'http://www.newsvine.com/_wine/save?u=' + bkmkUrl + '&h=' + bkmkTitle + '',
	'http://slashdot.org/bookmark.pl?url=' + bkmkUrl + '&title=' + bkmkTitle + '',
	'http://www.stumbleupon.com/submit?url=' + bkmkUrl + '&title=' + bkmkTitle + '',
	'http://ma.gnolia.com/bookmarklet/add?url=' + bkmkUrl + '&title=' + bkmkTitle + '',
	'http://www.squidoo.com/lensmaster/bookmark?' + bkmkUrl + '',
	'http://www.backflip.com/add_page_pop.ihtml?url=' + bkmkUrl + '&title=' + bkmkTitle + '',
	'http://buddymarks.com/add_bookmark.php?bookmark_title=' + bkmkTitle + '&bookmark_url=' + bkmkUrl + '',
	'http://www.feedmarker.com/admin.php?do=bookmarklet_mark&url=' + bkmkUrl + '&title=' + bkmkTitle + '',
	'http://www.hyperlinkomatic.com/lm2/add.html?LinkTitle=' + bkmkTitle + '&LinkUrl=' + bkmkUrl + '',
	'http://www.linkagogo.com/go/AddNoPopup?title=' + bkmkTitle + '&url=' + bkmkUrl + '',
	'http://www.maple.nu/bookmarks/bookmarklet?bookmark[url]=' + bkmkUrl + '&bookmark[name]=' + bkmkTitle + '',
	'http://www.rawsugar.com/tagger/?turl=' + bkmkUrl + '&tttl=' + bkmkTitle + '&editorInitialized=1',
	'http://www.shadows.com/shadows.aspx?url=' + bkmkUrl + '',
	'http://tailrank.com/share/?title=' + bkmkTitle + '&link_href=' + bkmkUrl + '',
	'http://www.plugim.com/submit?url=' + bkmkUrl + '&title=' + bkmkTitle + '',
	'http://blinkbits.com/bookmarklets/save.php?v=1&source_url=' + bkmkUrl + '&title=' + bkmkTitle + '',
	'http://www.citeulike.org/posturl?url=' + bkmkUrl + '&title=' + bkmkTitle + '',
	'http://feedmelinks.com/categorize?from=toolbar&op=submit&name=' + bkmkTitle + '&url=' + bkmkUrl + '&version=0.7',
	'http://www.igooi.com/addnewitem.aspx?self=1&noui=yes&jump=close&url=' + bkmkUrl + '&title=' + bkmkTitle + '',
	'http://www.linkroll.com/index.php?action=insertLink&url=' + bkmkUrl + '&title=' + bkmkTitle + '',
	'http://mesfavs.com/bookmarks.php/?action=add&address=' + bkmkUrl + '&title=' + bkmkTitle + '',
	'http://www.rojo.com/add-subscription/?resource=' + bkmkUrl + '',
	'http://simpy.com/simpy/LinkAdd.do?title=' + bkmkTitle + '&href=' + bkmkUrl + '&v=6&src=bookmarklet',
	'http://unalog.com/my/stack/link?url=' + bkmkUrl + '&title=' + bkmkTitle + '',
	'http://www.blogmemes.net/post.php?url=' + bkmkUrl + '&title=' + bkmkTitle + '',
	'http://www.blinklist.com/index.php?Action=Blink/addblink.php&Title=' + bkmkTitle + '&Url=' + bkmkUrl + '',
	'http://www.diigo.com/post?url=' + bkmkUrl + '&title=' + bkmkTitle + '',
	'http://www.givealink.org/cgi-pub/bookmarklet/bookmarkletLogin.cgi?&uri=' + bkmkUrl + '&title=' + bkmkTitle + '',
	'http://kinja.com/id.knj?url=' + bkmkUrl + '',
	'http://api.looklater.com/bookmarks/save?url=' + bkmkUrl + '&title=' + bkmkTitle + '',
	'http://netvouz.com/action/submitBookmark?url=' + bkmkUrl + '&title=' + bkmkTitle + '&popup=no',
	'http://scuttle.org/bookmarks.php/?action=add&address=' + bkmkUrl + '&title=' + bkmkTitle + '',
	'http://www.spurl.net/spurl.php?v=3&title=' + bkmkTitle + '&url=' + bkmkUrl + '',
	'http://www.wink.com/_/tag?url=' + bkmkUrl + '&doctitle=' + bkmkTitle + '',
	'http://www.wists.com/r.php?r=' + bkmkUrl + '&title=' + bkmkTitle + '',
	'http://blogmarks.net/my/new.php?mini=1&simple=1&url=' + bkmkUrl + '&title=' + bkmkTitle + '',
	'http://www.dzone.com/links/add.html?url=' + bkmkUrl + '&title=' + bkmkTitle + '',
	'http://www.gravee.com/account/bookmarkpop?u=' + bkmkUrl + '&t=' + bkmkTitle + '',
	'http://lister.lilisto.com/?t=' + bkmkTitle + '&l=' + bkmkUrl + '',
	'http://segnalo.com/post.html.php?url=' + bkmkUrl + '&title=' + bkmkTitle + '',
	'http://www.tagtooga.com/tapp/db.exe?c=jsEntryForm&b=fx&title=' + bkmkTitle + '&url=' + bkmkUrl + ''
);


$(document).ready(function() {

	/*initCustomInput();*/
	initVisualRotate();	
	initMenu();	
	initTopSlider();	
	initBottomSlider();
	initCommentSlider();
	initExternalLinks();
	initSearchBox();
	initBookmark();
/*
	initPackages();
	initTabs();
*/
	initBreadCrumbs();
	initFormInputs();
/*
	initHostingPlans();
*/
	initRowsHighlighting();
	initProductHovers();
	initContactForm();
	//initCommentForm();
	initBackToTop();
	initLocalLinks();
	initLoginBox();
	initAjaxSorting();
	initContactFields();
	
	preloadImages = [];
	if ($('#jsscript').attr('id') != undefined) {
		preloadImages = $.merge(preloadImages,largeProjectImages);
		preloadImages = $.merge(preloadImages,smallProjectImages);
		preloadImages = $.merge(preloadImages,originalProjectImages);
	}
	
	var preloaded = [];
	$.each(preloadImages, function(index, item){
		preloaded[index] = $.create('img', {
		    'src': item
		});
	});
        
        initAboutBio();
		
});

function initContactFields(){
	var inputs = $("#contact_form input");
	var currid = ''; var currvalue = '';
	$.each(inputs, function() {
		currid = $(this).attr('id');
		currvalue = $("#contact_form label[for='" + currid + "']").html();
		$(this).attr('onclick', 'this.value=(this.value=="' + currvalue + '") ? "" : this.value;');
		$(this).attr('onblur', 'this.value=(this.value=="") ? "' + currvalue + '" : this.value;');
		if ($(this).val() == '') $(this).val(currvalue);
	});
	currvalue = $("#contact_form label[for='message']").html();
	if ($('#message').val() == '') $('#message').val(currvalue);
	$('#message').attr('onclick', 'this.value=(this.value=="' + currvalue + '") ? "" : this.value;');
	$('#message').attr('onblur', 'this.value=(this.value=="") ? "' + currvalue + '" : this.value;');
}


function initAboutBio(){
   $('.people .heading').hover(function(){
      user = $(this).attr('rel');
      $(this).parent('li').addClass('hover');
   }, function(){
      $(this).parent('li').removeClass('hover');
   })
   
   $('.people .heading').click(function(){
      user = $(this).attr('rel');
      $('.about-bio').height($('.about-bio li[class!=hidden]').height());
      $('.about-bio li').each(function(){
         $(this).addClass('hidden');
      })
      $('.people li').each(function(){
         $(this).removeClass('active');
      })
      $(this).parent('li').addClass('active');
      $('.about-bio li[rel=' + user + ']').width(745);
      var new_height = $('.about-bio li[rel=' + user + ']').height();
      $('.about-bio').animate({height: new_height + "px"}, 1000);

      $('.about-bio li[rel=' + user + ']').removeClass('hidden');
   })
}
/*
function initCustomInput()
{	
	if ($('#custom-input').attr('id') != undefined)
	{	
		$('#custom-input').css('opacity','0');
		var value_html = $('#custom-input').val();
		var regexp = /(\w|[-.])+$/
		var file = regexp.exec(value_html);
		if(file)
		{	
			$('#custom-file-path').val(file[0]);
		}
		
		var aboveButtonCoords = $('#above-custom-button').getCoordinates();
			
		$('#custom-container').mousemove(function(e) {
			
			var page_y = e.pageY;
  		var page_x = e.pageX;
			
			if (page_y > aboveButtonCoords.top && page_y < aboveButtonCoords.bottom && page_x > aboveButtonCoords.left && page_x < aboveButtonCoords.right)
			{
				if ($('#above-custom-button').css('display') == 'block')
				{
					$('#custom-input').css('opacity','0.001');
					$('#above-custom-button').css('display','none');
				}
			}
			else
			{
				if ($('#above-custom-button').css('display') == 'none')
				{
					$('#custom-input').css('opacity','0');
					$('#above-custom-button').css('display','block');
				}
			}
		});
		
		$('#custom-input').change(function() {	
			var regexp = /(\w|[-.])+$/
			var file = regexp.exec(this.value);		
			$('#custom-file-path').val(file[0]);
		});
		
		$('#custom-file-path').change(function() {	
			if($('#custom-input').val() != '')
			{
				$('#custom-input').val('');
				if(!isUrl($('#custom-file-path').val()))
				{
					$('#custom-input').val('');
					$('#custom-file-path').val('');
				}
			}
			else
			{
				if(!isUrl($('#custom-file-path').val()))
				{
					$('#custom-input').val('');
					$('#custom-file-path').val('');
				}
			}				
		});
		
	}
}
*/
function isUrl(s) {
	var regexp = new RegExp();
  regexp.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$");
	return regexp.test(s);
}

function initVisualRotate()
{
	$('div.visual img').attr('id','visual');
	if ($('#visual').attr('id') != undefined)
	{
		var currentImage = 0;
		var nextImage = 0;
		
		var image_cookie = $.cookie('current-image');
		if (isNaN(parseInt(image_cookie)))
		{
			currentImage = 1;
		}
		else
		{
			currentImage = image_cookie;
		}
		
		if (currentImage >= 3)
		{
			nextImage = 1;
		}
		else
		{
			nextImage = parseInt(currentImage) + 1;
		}
		$('#visual').css('height','289px');
		$.cookie('current-image',nextImage);
	}
}

function initMenu()
{
	var submenuDivs = $('div.sub-menu');
	submenuDivs.css('width',$(window).width() + 'px');
	
	var submenuLis = $('ul#nav > li');
	var lis_count = $(submenuLis).length;	
	$.each(submenuLis, function(index, item) {			
		$(item).hover(
      function () {
        $(this).addClass('hover');		
      }, 
      function () {
        $(this).removeClass('hover');	  
      }
    );
	});
}

function initTopSlider()
{
	$('#products-detail div.content').attr('id','products-slider');
	$('ul.thumbs').attr('id','thumbs-slider');
	if ($('#products-slider').attr('id') != undefined)
	{
		if ($('#thumbs-slider').hasClass('hidden-default')) {
			$('thumbs-slider').css('opacity','0');
		}

//Max-min bw pages
		var top_slider_state = $.cookie("topSlider");
		if (top_slider_state == "on") {
			if ($('div.t-box a').hasClass('maximize'))
			{
				$('#products-slider').attr('_height',211);
				if ($('#products-slider').hasClass('no-pager')){
					$('#products-slider').attr('_height',175);
				}
				if ($('#thumbs-slider').attr('id') != undefined)
				{
					sliderSmoothHideBlock('thumbs-slider');
				}
				sliderSmoothShowBlock('products-slider');
				$.cookie('topSlider', 'on', {expires: 30});
				$('div.t-box a').removeClass('maximize')
				$('div.t-box a').addClass('minimize');
			}			
			//return false;
		};

//Maximize-minimize		
		$('div.t-box a').click(function() {
			if ($(this).hasClass('minimize'))
			{
				if ($('#products-slider').attr('id') != undefined)
				{
					$('#thumbs-slider').attr('_height',32);
					sliderSmoothShowBlock('thumbs-slider');
				}
				sliderSmoothHideBlock('products-slider');
				$.cookie('topSlider', 'off', {expires: 30});
				$(this).removeClass('minimize')
				$(this).addClass('maximize');
			}
			else
			{
				$('#products-slider').attr('_height',211);
				if ($('#products-slider').hasClass('no-pager')){
					$('#products-slider').attr('_height',175);
				}
				if ($('#thumbs-slider').attr('id') != undefined)
				{
					sliderSmoothHideBlock('thumbs-slider');
				}
				sliderSmoothShowBlock('products-slider');
				$.cookie('topSlider', 'on', {expires: 30});
				$(this).removeClass('maximize')
				$(this).addClass('minimize');
			}			
			return false;
		});
		
	}
}

function sliderSmoothHideBlock(id,useScroll,scrollToValue)
{
	var element_height = $('#'+id).height();	
	$(id).attr('_height',element_height);	
	$('#'+id).animate({opacity:0}, 500, 'linear',
		function() {
			$('#'+id).css('min-height','0px');
			$('#'+id).css('overflow','hidden');
			if (useScroll)
			{				
				$(window).scrollTo({top:scrollToValue}, 500, {onAfter:function() {
						$('#'+id).animate({height:0}, 500, 'swing', function() {$('#'+id).css('visibility','hidden');$('#'+id).css('display','none');}  );
					}}
				);
			}
			else
			{
				$('#'+id).animate({height:0}, 500, 'swing', function() {$('#'+id).css('visibility','hidden');$('#'+id).css('display','none');} );
			}
			//$('#'+id).css('visibility','hidden');
		}
	);
}

function sliderSmoothShowBlock(id,useScroll,scrollToValue)
{
	$('div.breadcrumbs').attr('id','bread-crumbs-div');
	if ($('#bread-crumbs-div').attr('id') != undefined)
	{
		var breadcrumbsHeight = $('#bread-crumbs-div').height();
	}
	else
	{
		var breadcrumbsHeight = 0;
	}	
	$('#'+id).css('opacity','0');
	$('#'+id).css('visibility','visible');
	$('#'+id).css('display','block');
	$('#'+id).animate({height:$('#'+id).attr('_height')}, 500, 'swing',
		function() {		
			$('#'+id).css('overflow','visible');
			if (useScroll)
			{
				$(window).scrollTo({top:scrollToValue - breadcrumbsHeight}, 500, {onAfter:function() {
						$('#'+id).animate({opacity:1}, 500);
					}}
				);
			}
			else
			{
				$('#'+id).animate({opacity:1}, 500);
			}	
		}
	);	
}

function initBottomSlider()
{
	$('#exploring div.content').attr('id','exploring-slider');
	if ($('#exploring-slider').attr('id') != undefined)
	{
		$('#exploring-slider').css('display','none');
		hideBlock('exploring-slider');
		
		$('a.start').click(function() {
			if ($(this).hasClass('stop'))
			{
				var coords = $(this).getCoordinates();
				var footerCoords = $('#footer').getCoordinates();
				var newTop = coords.bottom - $(window).height() + $('#footer').height();
				sliderSmoothHideBlock('exploring-slider',true,newTop);
				$.cookie('bottomSlider', 'off', {expires: 30});
				$(this).removeClass('stop')
				$(this).addClass('start');
			}
			else
			{	
				var coords = $(this).getCoordinates();
				$('#exploring-slider').attr('_height',331);
				sliderSmoothShowBlock('exploring-slider',true, coords.top);
				$.cookie('bottomSlider', 'on', {expires: 30});
				$(this).removeClass('start')
				$(this).addClass('stop');
			}
			return false;
		});
		
	}
}

function hideBlock(id)
{
	$('#'+id).css('opacity','0');
}

function initBreadCrumbs()
{
	$('div.breadcrumbs').attr('id','bread-crumbs-div');
	if ($('#bread-crumbs-div').attr('id') != undefined)
	{
		defaultBreadCrumbsTop = $('#header').height() + 2;
	
		$(window).scroll(function() {
			scrollBreadCrumbs();
		});
		
		$(window).ready(function() {
			scrollBreadCrumbs();
		});
	}
}

function scrollBreadCrumbs()
{
	if ($('#bread-crumbs-div').attr('id') != undefined)
	{
		var scrollTop = $(window).scrollTop();
		
		if ($.browser.msie && $.browser.version == 6)
		{
			if (scrollTop < defaultBreadCrumbsTop)
			{
				//scrollTop = defaultBreadCrumbsTop;
				$('#bread-crumbs-div').css('position','absolute');
				$('#bread-crumbs-div').css('top',defaultBreadCrumbsTop + 'px');
			}
			else
			{
				$('#bread-crumbs-div').css('position','absolute');
				$('#bread-crumbs-div').css('top',scrollTop + 'px');
			}
		}
		else
		{
			if (scrollTop < defaultBreadCrumbsTop)
			{
				//scrollTop = defaultBreadCrumbsTop;
				$('#bread-crumbs-div').css('position','absolute');
				$('#bread-crumbs-div').css('top',defaultBreadCrumbsTop + 'px');
			}
			else
			{
				$('#bread-crumbs-div').css('position','fixed');
				$('#bread-crumbs-div').css('top','0px');
			}
		}
		//$('#bread-crumbs-div').css('top',scrollTop + 'px');
	}
}

function initCommentSlider()
{
	$('#respond div.form-container').attr('id','comment-slider');
	if ($('#comment-slider').attr('id') != undefined)
	{
		$('div.maxmindiv a').click(function() {
			if($(this).hasClass('minimize'))
			{
				var coords = $('#comment-slider').getCoordinates();
				sliderSmoothHideBlock('comment-slider', true, coords.top - $(window).height());
				$.cookie('bottomSlider', 'off', {expires: 30});
				$(this).removeClass('minimize')
				$(this).addClass('maximize');
			}
			else
			{
				var coords = $('#respond').getCoordinates();
				$('#comment-slider').attr('_height',337);
				sliderSmoothShowBlock('comment-slider', true, coords.top);
				$.cookie('bottomSlider', 'on', {expires: 30});
				$(this).removeClass('maximize')
				$(this).addClass('minimize');
			}
			return false;
		});
	}
}

var initExternalLinks = function()
{
	$('a[rel*="external"]').attr('target','_blank');
	
	var allLinks = $('#pagewidth a[rel="external"]');
	$.each(allLinks, function(index, item) {
		if ($(item).children().length == 0)
		{
			$(item).addClass('out');
		}
	});
	
	$('a[rel*="popup"]').click(function(link) {
		window.open($(this).attr('href'),'_blank','resizable=yes,titlebar=no,location=no,status=no,menubar=no,toolbar=no');
		return false;
	});
	
}

function initSearchBox()
{
	$('input.txt').DefaultValue(defaultSearchBoxContent);
}

var initBookmark = function()
{
	if ($('#fader').attr('id') != undefined)
	{
		$('a.bookmark').click(function() {
			$('#fader').css('width',$(document).width() + 'px');
			$('#fader').css('height',$(document).height() + 'px');
			$('#bookmark').css('display','block');
			$('#fader').css('display','block');
			
			var newTop = $(window).scrollTop() + $(window).height() / 2 - $('#bookmark').height() / 2;
			var newLeft = $(window).scrollLeft() + $(window).width() / 2 - $('#bookmark').width() / 2;
			
			if (newTop < 0 ) newTop = 0;
			$('#bookmark').css('top',newTop);
			$('#bookmark').css('left',newLeft);
			return false;
		});
	}	
	
	var buttons = $('#bookmark div.submit input');
	$.each(buttons, function(index, item) {
		if ($(item).attr('alt') == 'cancel')
		{
			$(item).click(function() {
				$('#fader').css('display','none');
				return false;
			});
		}
		if ($(item).attr('alt') == 'submit')
		{
			$(item).click(function() {
				$('#fader form').attr('id','bookmark-form');
				var inputs = $('#fader form input');
				var bookmarkLink = '';
				$.each(inputs, function(index, item) {
					if ($(item).attr('checked') == true)
					{
						bookmarkLink = bookmarkLinks[bookmarkIds.indexOf($(item).attr('id'))];
					}
				});
				var fakeForm = $.create('form', {
					'styles': {
						'display': 'none'
					},
					'method': 'post',
					'action': bookmarkLink,
					'target': '_blank'
				});
				
				$(fakeForm).insertAfter('#bookmark-form');
				$('#fader').css('display','none');
				$(fakeForm).submit();
				return false;
			});
		}
	});
}

function initFormInputs()
{
	var inputs = $('form.comment-form input, form.comment-form textarea, form.order input, form.order textarea');
	$.each(inputs, function(index, item) {
		$(item).focus(function() {
			$(this).addClass('focus');
		});
		$(item).blur(function() {
			$(this).removeClass('focus');
		});
	});	
}

function initRowsHighlighting()
{
	var spans = $('pre span');
	$.each(spans, function(index, item) {
		$(item).hover(
      function () {
        $(this).addClass('hover');
      }, 
      function () {
        $(this).removeClass('hover');
      }
    );
	});
}

function initProductHovers()
{
	var lis = $('#pagewidth ul.list li, div.some-case');
	$.each(lis, function(index, item) {
		$(item).hover(
      function () {
        $(this).addClass('hover');
      }, 
      function () {
        $(this).removeClass('hover');
      }
    );
	});
}

function initContactForm()
{
	if ($('#contact_form').attr('id') != undefined)
	{
		var clearButton = $('input[name="Clear"]');
		if ($(clearButton).attr('name') != undefined)
		{
			$(clearButton).click(function(){
				$('#contact_form').clearForm();
				initContactFields();
				return false;
			});
		}
	}
}

function initCommentForm()
{
	if ($('#respond').attr('id') != undefined)
	{
		var clearButton = $('input[name=btnReset]');
		if ($(clearButton).attr('name') != undefined)
		{
			$(clearButton).click(function(){
				$('#respond').clearForm();
				commentFormChangeHandler();
				return false;
			});
		}
		
		$('#respond').submit(function() {
			
			var checkUrl = $('#respond').attr('action');
			var params = $('#respond').serialize() + '&ajax_requested=1';
			$.ajax({
				type: "POST",
				url: checkUrl,
				data: params, 
				success: function(req){
					if (req == '__VALID__') {			
						$('#respond').unbind('submit');
						$('#respond').submit();
					} else {
						alert(req);
					}			
				}
			});
			return false;				
		});
	}
}

function initBackToTop()
{
	var toTopLinks = $('a.back-to-top');
	if ($(toTopLinks).length > 0) {
		$.each(toTopLinks, function(index, item){
			$(item).click(function(){
				$(window).scrollTo({top:0}, 500);
				return false;
			});
		});
	}
}

function initLocalLinks()
{
	var allLinks = $('a');
	var location = window.location.href.match(/^[^#]*/)[0] + '#';
	$.each(allLinks, function(index, link){
		if (link.href.indexOf(location) != 0) return;
		var anchor = link.href.substr(location.length);
		if (anchor && ( $("#"+anchor).attr('id') != undefined || anchor == 'main')) addLocalLinkHandler(link, anchor);
	});
	
	var location = window.location.href.match(/^[^#]*/)[0];	
	var anchor = window.location.href.substr(location.length + 1);
	if (anchor && $("#"+anchor).attr('id') != undefined ) {
		var coords = $("#"+anchor).getCoordinates();
		if (coords) {
			if ($('#bread-crumbs-div').attr('id') != undefined ) {
				var bcCoords = $('#bread-crumbs-div').getCoordinates();
				$(window).scrollTo({top: coords.top - $('#bread-crumbs-div').height() - 5}, 500);
			} else {
				$(window).scrollTo({top: coords.top}, 500);
			}
		}
	}
}

function addLocalLinkHandler(link,anchor)
{
	$(link).click(function(){
		if (anchor == 'main') {
			$(window).scrollTo({top: $('#header').height() + 2}, 500);
			return false;
		} else {
			if ($("#"+anchor).attr('id') != undefined)
			{
				var coords = $("#"+anchor).getCoordinates();
				if (coords) {
					if ($('#bread-crumbs-div').attr('id') != undefined ) {
						$(window).scrollTo({top: coords.top - $('#bread-crumbs-div').height() - 5}, 500);
					} else {
						$(window).scrollTo({top: coords.top}, 500);
					}
				}
			}
			return false;
		}
	});
}

function initLoginBox()
{
	var login = $('form.login-form input[name=login]');
	var passwd = $('form.login-form input[name=password]');
	if ($(login).attr('id') != undefined && $(passwd).attr('id') != undefined)
	{
		defaultLogin = $(login).attr('value');
		defaultPassword = $(passwd).attr('value');
		
		$(login).val('');
		$(passwd).val('');

		$(login).DefaultValue(defaultLogin);
		$(passwd).DefaultValue(defaultPassword);
	}
}

function initAjaxSorting()
{
	var ajaxThumbs = $('#ajax-thumbs');
	if ($(ajaxThumbs).attr('id') != undefined)
	{
		//$.cookie('portfolio_category', 'web');
		$('#products-detail').css('visibility', 'visible');
		var sortFilterLinks = $('#sort-filter a');
		sortFilterLinks.click(function(link){
			var newHTML = '';
			$('ul.thumbs').attr('id','thumbs-slider');
			if ($('#thumbs-slider').attr('id') != undefined && $('#thumbs-slider').css('visibility') == 'visible'){
				opened = 'false';
			} else if ($('#thumbs-slider').attr('id') != undefined && $('#thumbs-slider').css('visibility') == 'hidden') {
				opened = 'true';
			}
			
			//Slider state
			if ($.cookie('topSlider') == 'on') { opened = 'true'; } else { opened = 'false'; }
			
			var portfolio_category = $(this).attr('href').replace('/work/', '').replace('/', '');
			$.cookie('portfolio_category', portfolio_category);
			$.ajax({
				type: "POST",
				url: $(this).attr('href'),
				data: 'ajax=thumbs&opened='+opened, 
				success: function(req){
					
					$(ajaxThumbs).html(req);
					$('#products-detail div.content').attr('id','products-slider');
					$('ul.thumbs').attr('id','thumbs-slider');
					var productDetails = $('#products-detail');
					if ($(productDetails).attr('id') != undefined)
					{
						$('#products-detail').css({
							'visibility':'visible'
						});
					}
					
					initAjaxSorting();
					initTopSlider();
					initHintPager();
					
					if ($('#products-slider').attr('id') != undefined)
					{
						if (opened == 'false')
						{
							if ($('#thumbs-slider').attr('id') != undefined)
							{
								$('thumbs-slider').attr('_height',32);
								sliderShowBlock('thumbs-slider');
							}
							sliderHideBlock('products-slider');
							$.cookie('topSlider', 'off', {expires: 30});
							$('#min-max-button').removeClass('minimize')
							$('#min-max-button').addClass('maximize');
						}
						else if (opened == 'true')
						{
							$('#products-slider').attr('_height',211);
							if ($('#products-slider').hasClass('no-pager')){
								$('#products-slider').attr('_height',175);
							}
							if ($('#thumbs-slider').attr('id') != undefined)
							{
								sliderHideBlock('thumbs-slider');
							}
							sliderShowBlock('products-slider');
							$.cookie('topSlider', 'on', {expires: 30});
							$('#min-max-button').removeClass('maximize')
							$('#min-max-button').addClass('minimize');
						}
					}
				}
			});
			return false;
		});
	}
}

function sliderHideBlock(id)
{
	$('#'+id).css({
		'height':'0',
		'min-height':'0',
		'overflow':'hidden',
		'opacity':'0',
		'visibility':'hidden'
	});
}

function sliderShowBlock(id)
{
	$('#'+id).css({
		'height':$('#'+id).attr('_height') + 'px',
		'min-height':'0',
		'overflow':'visible',
		'opacity':'1',
		'visibility':'visible'
	});
}

//to do after implementing hosting section
/*
function initPackages()
{
	var packageLis = $('ul.package li');
	packageLis.each(function(item, index) {
		item.addEvent('mouseenter',function() {
			this.setProperty('class',this.getProperty('class') + ' hover');
		});
		item.addEvent('mouseleave',function() {
			this.setProperty('class',this.getProperty('class').replace('hover',''));
		});
	});
}
var initTabs = function()
{
	redrawTabs();
	var lis = $$('#bottom-box .tabset li');
	var tabLinks = $$('#bottom-box .tabset a');
	tabLinks.each(function(item, index) {
		item.addEvent('click', function(e) {
			lis.each(function(item, index) {
				item.setProperty('class','');
			});
			this.getParent().setProperty('class','active');
			redrawTabs();
			var event = new Event(e);
			event.stop();
		});
	});
}

var redrawTabs = function()
{
	var lis = $$('#bottom-box .tabset li');
	var divs = $$('.tabs .frame');
	lis.each(function(item, index) {
		if (item.getProperty('class') == 'active')
		{
			var liIndex = index;
			divs.each(function(item, index) {
				if (index == liIndex)
				{
					item.setStyle('display','block');
				}
				else
				{
					item.setStyle('display','none');
				}
			});
		}
	});
}
*/



/******************tools and extends**************/

jQuery.fn.extend({

  getCoordinates: function() {
	  coords = {};
		var coords = $(this).offset()
		coords.bottom = coords.top + $(this).height();
		coords.right = coords.left + $(this).width();
		return coords; 
  },
  
  DefaultValue: function(text) {
  	return this.each(function(){
		//Make sure we're dealing with text-based form fields
		if(this.type != 'text' && this.type != 'password' && this.type != 'textarea')
			return;	
		//Store field reference
		var fld_current=this;	
		//Set value initially if none are specified
        if(this.value=='') {
			this.value=text;
		} else {
			//Other value exists - ignore
			return;
		}	
		//Remove values on focus
		$(this).focus(function() {
			if(this.value==text || this.value=='')
				this.value='';
		});	
		//Place values back on blur
		$(this).blur(function() {
			if(this.value==text || this.value=='')
				this.value=text;
		});	
		//Capture parent form submission
		//Remove field values that are still default
		$(this).parents("form").each(function() {
			//Bind parent form submit
			$(this).submit(function() {
				if(fld_current.value==text) {
					fld_current.value='';
				}
			});
		});
    }); 	
  },
  
  clearForm: function() {
	  return this.each(function() {
		var type = this.type, tag = this.tagName.toLowerCase();
		if (tag == 'form')
		  return $(':input',this).clearForm();
		if (type == 'text' || type == 'password' || tag == 'textarea')
		  this.value = '';
		/*
		else if (type == 'checkbox' || type == 'radio')
		  this.checked = false;
		else if (tag == 'select')
		  this.selectedIndex = -1;
		*/
	  });
	}
	
});

jQuery.extend({
	create: function() {
    if (arguments.length == 0) return [];
    var args = arguments[0] || {}, elem = null, elements = null;
    var siblings = null;

    // In case someone passes in a null object,
    // assume that they want an empty string.
    if (args == null) args = "";
    if (args.constructor == String) {
      if (arguments.length > 1) {
        var attributes = arguments[1];
        if (attributes.constructor == String) {
          elem = document.createTextNode(args);
          elements = [];
          elements.push(elem);
          siblings = jQuery.create.apply(null, Array.prototype.slice.call(arguments, 1));
          elements = elements.concat(siblings);
          return elements;
        } 
				else {
          elem = document.createElement(args);

          // Set element attributes.
          var attributes = arguments[1];
          for (var attr in attributes)
            jQuery(elem).attr(attr, attributes[attr]);

          // Add children of this element.
          var children = arguments[2];
          children = jQuery.create.apply(null, children);
          jQuery(elem).append(children);

          // If there are more siblings, render those too.
          if (arguments.length > 3) {
            siblings = jQuery.create.apply(null, Array.prototype.slice.call(arguments, 3));
            return [elem].concat(siblings);
          }
          return elem;
        }
      } 
			else return document.createTextNode(args);
    } 
		else {
      elements = [];
      elements.push(args);
      siblings = jQuery.create.apply(null, (Array.prototype.slice.call(arguments, 1)));
      elements = elements.concat(siblings);
      return elements;
    }
	},
	
	toInt: function(value) {	
		var intVal = 0;
		if (!isNaN(parseInt(value)))
		{
			intVal = parseInt(value);
		} 	
  	return intVal;
  }

});



var hintCurrentPage = 1;
var hintLeftStatus = [];		

$(document).ready(function() {

	initSmallPager();
	initLargePager();
	initRandomPager();
	initHintPager();
	initProjectNavigation();
	initSmallPagerImageClick(1);
	
});

/* SMALL pager */

initSmallPager = function()
{
	var pager = $('#small-pager');
	var wrapper = $('#small-project-image');
	var pictures = $('#small-project-image img');
	var prevLink = $('#small-pager-prev');
	var nextLink = $('#small-pager-next');
	if ($(pager).attr('id') != undefined && pictures.length > 0 && $(prevLink).attr('id') != undefined && $(nextLink).attr('id') != undefined) {
		var pageLinks = $('#small-pager ul a');
		$.each(pageLinks, function(index, item){
			$(item).click(function(){
				smallPagerClickHandler(this);
				return false;
			});
		});
		$(prevLink).click(function(){
			if (!$(this).hasClass('disabled')) smallPagerClickHandler(this);
			return false;
		});
		$(nextLink).click(function(){
			if (!$(this).hasClass('disabled')) smallPagerClickHandler(this);
			return false;
		});
	}
	if(pictures.length > 0)
	{	
		if(pictures.length == 1)
		{
			$.each(pictures, function(i, item){
				$(item).css('left',((i) * $(wrapper).width()) + 'px');
				$(item).removeClass('hidden');
			});
		}
		else
		{
			/* Starting from 1 page (i) */
			$.each(pictures, function(i, item){
				$(item).css('left',((i) * $(wrapper).width()) + 'px');
				$(item).removeClass('hidden');
			});
		}
		
		//in the work section sometimes the examples don't appear right away 
		//$($('#small-project-image').find('img').images).ready(function(){
		/*$(document.images).ready(function(){
			$('#small-project-image').animate({height: ($(pictures[0]).height() + 15) + 'px' }, 0);
		});*/
		
		/* Fix:
		$('#small-project-image').animate({height: ($(pictures[0]).height() + 15) + 'px' }, 0);*/
		
	}
}

function smallPagerClickHandler(item)
{
	showSmallPager(parseInt($(item).attr('rel')));
}

function showSmallPager(selectedPage)
{
	var wrapper = $('#small-project-image');
	var pictures = $('#small-project-image img');
	setPage('small-pager',selectedPage);
	
	$.each(pictures, function(i, item){
		$(item).animate({left: ((i - selectedPage + 1) * $(wrapper).width()) + 'px' }, 300);
	});
	$(wrapper).attr('href',smallProjectImages[selectedPage - 1]);
	
	$(wrapper).animate({height: ($(pictures[selectedPage - 1]).height() + 15) + 'px' }, 0);
}

/* COMMON */

function setPage(pagerId,selectedPage)
{
	var pager = $('#'+pagerId);
	var prevLink = $('#'+pagerId + '-prev');
	var nextLink = $('#'+pagerId + '-next');
	
	var prevPage = $.toInt(selectedPage) - 1;
	var nextPage = $.toInt(selectedPage) + 1;
	
	var pageCount = $(pager).attr('class').match(/lastpage-(.*)/)[1];
	
	$(prevLink).attr('rel',prevPage);
	$(nextLink).attr('rel',nextPage);
	
	if (prevPage < 1) {
		$(prevLink).addClass('disabled');//css('display','none');
	} else {
		$(prevLink).removeClass('disabled');//css('display','block');
	}
	if (nextPage > pageCount) {
		$(nextLink).addClass('disabled');//css('display','none');
	} else {
		$(nextLink).removeClass('disabled');//css('display','block');
	}
	
	var pageLinks = $('#'+pagerId+' ul a');
	$.each(pageLinks, function(index, item){
		$(item).parent().removeClass('active');
		if (parseInt($(item).attr('rel')) == selectedPage) {
			$(item).parent().addClass('active');
		}
	});
}

/* LARGE pager */

function initLargePager()
{
	var pager = $('#large-pager');
	var wrapper = $('#large-project-image');
	var pictures = $('#large-project-image img');
	var prevLink = $('#large-pager-prev');
	var nextLink = $('#large-pager-next');
	if ($(pager).attr('id') != undefined && pictures.length > 0 && $(prevLink).attr('id') != undefined && $(nextLink).attr('id') != undefined) {
		var pageLinks = $('#large-pager ul a');
		$.each(pageLinks, function(index, item){
			$(item).click(function() {
				if (!$(this).parent('li').hasClass('active')) { largePagerClickHandler(this);
				var prodcoords = $('#product-box').getCoordinates();
				$(window).scrollTo({top: prodcoords.top + 20}, 500); }
				return false;
			});
		});
		$(prevLink).click(function() {
			if (!$(this).hasClass('disabled')) { largePagerClickHandler(this);
			prodcoords = $('#product-box').getCoordinates();
			$(window).scrollTo({top: prodcoords.top + 20}, 500); }
			return false;
		});
		$(nextLink).click(function() {
			if (!$(this).hasClass('disabled')) { largePagerClickHandler(this);
			var prodcoords = $('#product-box').getCoordinates();
			$(window).scrollTo({top: prodcoords.top + 20}, 500); }
			return false;
		});
	}
	
	if(pictures.length > 0)
	{
		$.each(pictures, function(i, item){
			$(item).css('left',(i * $(wrapper).width()) + 'px');
			$(item).removeClass('hidden');
		});
		
		// in the work section sometimes the examples don't appear right away
		//$($('#large-project-image').find('img').images).ready(function () {
		/*$(document.images).ready(function(){
			$(wrapper).animate({height: ($(pictures[0]).height() + 15) + 'px' }, 0);
		});*/
		
		/*Fix:
		$(wrapper).animate({height: ($(pictures[0]).height() + 15) + 'px' }, 0);*/
	}
}

function largePagerClickHandler(item)
{
	$('#large-project-image').css('background', 'none');
	showLargePager(parseInt($(item).attr('rel')));
}

function showLargePager(selectedPage)
{
	var wrapper = $('#large-project-image');
	var pictures = $('#large-project-image img');
	setPage('large-pager',selectedPage);
	
	$.each(pictures, function(i, item){
		$(item).animate({left: ((i - selectedPage + 1) * $(wrapper).width()) + 'px' }, 300);
	});
	$(wrapper).attr('href',originalProjectImages[selectedPage - 1]);
	
	$(wrapper).animate({height: ($(pictures[selectedPage - 1]).height() + 15) + 'px' }, 0);
}

/* RANDOM pager */

function initRandomPager()
{
	var pager = $('#rand-pager');
	var picturesContainer = $('#rand-container');
	var pictures = $('#rand-container img');
	var prevLink = $('#rand-pager-prev');
	var nextLink = $('#rand-pager-next');
	if ($(pager).attr('id') != undefined && pictures.length > 0 && $(prevLink).attr('id') != undefined && $(nextLink).attr('id') != undefined) {
		var pageLinks = $('#rand-pager ul a');
		
		$.each(pageLinks, function(index, item){
			$(item).click(function() {
				randomPagerClickHandler(this);
				return false;
			});
		});
		$(prevLink).click(function() {
			if (!$(this).hasClass('disabled')) randomPagerClickHandler(this);
			return false;
		});
		$(nextLink).click(function() {
			if (!$(this).hasClass('disabled')) randomPagerClickHandler(this);
			return false;
		});
		
		$.each(pictures, function(i, item){
			$(item).css('left',(i * $(picturesContainer).width()) + 'px');
			$(item).removeClass('hidden');
		});
	}	
}

function randomPagerClickHandler(item)
{
	showRandomPager(parseInt($(item).attr('rel')));
}

function showRandomPager(selectedPage)
{
	var pictures = $('#rand-container img');
	var picturesContainer = $('#rand-container');
	setPage('rand-pager',selectedPage);
	
	$.each(pictures, function(i, item){
		$(item).animate({left: ((i - selectedPage + 1) * $(picturesContainer).width()) + 'px' }, 300);
	});	
	
	$('#rand-container a').attr('href',originalProjectImages[selectedPage - 1]); 
}

/* THUMBNAILS pager */
function initHintPager()
{
	var pager = $('#hint-pager');
	var prevLink = $('#hint-pager-prev');
	var nextLink = $('#hint-pager-next');
	if ($(pager).attr('id') != undefined && $(prevLink).attr('id') != undefined && $(nextLink).attr('id') != undefined) {		
		var pageLinks = $('#hint-pager ul a');	
		$.each(pageLinks, function(index, item){
			$(item).click(function() {
				hintPagerClickHandler(this);
				return false;
			});
		});
		$(prevLink).click(function() {
			if (!$(this).hasClass('disabled')) hintPagerClickHandler(this);
			return false;
		});
		$(nextLink).click(function() {
			if (!$(this).hasClass('disabled')) hintPagerClickHandler(this);
			return false;
		});
	}	
	if ($('#products-detail').attr('id') != undefined) {
		setTimeout("showPortfolioHints();", 200);
		var pages = $('#products-detail ul.list');
		$.each(pages, function(index, item){
			hintLeftStatus[index] = $.toInt($(item).css('left').replace('px',''));
		});
	}
}

function showPortfolioHints()
{
	$('#products-detail').css('visibility','visible');
}

function hintPagerClickHandler(item)
{
	showHintPager(parseInt($(item).attr('rel')));
}

function showHintPager(selectedPage)
{
	setPage('hint-pager',selectedPage);
	var prevPage = hintCurrentPage;
	var nextPage = selectedPage;
	hintCurrentPage = selectedPage;
	var pages = $('#products-detail ul.list');
	$.each(pages, function(index, item){
		var currentLeft = hintLeftStatus[index];
		hintLeftStatus[index] = currentLeft - (nextPage - prevPage) * 966;	
		$(item).animate({left: (currentLeft - (nextPage - prevPage) * 966) + 'px' }, 500);
	});
}

/* Project Ajax Navigation */
function initProjectNavigation()
{
/*
	$('#products-detail a').each(function(index, item){
		$(item).click(function() { 
			getProjectDetails(item);
			return false;
		});
	});
	$('#thumbs-slider a').each(function(index, item){
		$(item).click(function() { 
			getProjectDetails(item);
			return false;
		});
	});
*/
}

function getProjectDetails(item)
{
/*
	if (/::/.test($(item).attr('rel'))) {
		var requestUrl = '/work/project-details-ajax';
		var params = 'domain=' + this.getProperty('rel');
		var projectDetailsAjax = new Ajax(requestUrl, {method: 'post',postBody:params,onSuccess: function(req) {
				if (req != '')
				{
					$('product-box').innerHTML = req;
					updateSifr();
					if ($('#jsscript')) {
						var newJS = $('jsscript').innerHTML.replace(/<.*>([^<]*)<.*>/ig,'$1');
						eval(newJS);
					}
					initPagers();
				}
			}
		});	
		return false;
	}
*/
}

function initSmallPagerImageClick(selectedPage)
{

	if ($('#small-project-image').attr('id') != undefined) {
		$('#small-project-image').parent().unbind("click");
		$('#small-project-image').parent().click(function(){
			var selectedPage = parseInt($('#small-pager ul li.active a').attr('rel'));
			showLargePager(selectedPage);
			var prodcoords = $('#product-box').getCoordinates();
			$(window).scrollTo({top: prodcoords.top + 20}, 500);
			return false;
		});
	}
};

/**
 * 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
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
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 * 24 * 60 * 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.ScrollTo
 * Copyright (c) 2007-2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 9/11/2008
 *
 * @projectDescription Easy element scrolling using jQuery.
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 * Tested with jQuery 1.2.6. On FF 2/3, IE 6/7, Opera 9.2/5 and Safari 3. on Windows.
 *
 * @author Ariel Flesler
 * @version 1.4
 *
 * @id jQuery.scrollTo
 * @id jQuery.fn.scrollTo
 * @param {String, Number, DOMElement, jQuery, Object} target Where to scroll the matched elements.
 *	  The different options for target are:
 *		- A number position (will be applied to all axes).
 *		- A string position ('44', '100px', '+=90', etc ) will be applied to all axes
 *		- A jQuery/DOM element ( logically, child of the element to scroll )
 *		- A string selector, that will be relative to the element to scroll ( 'li:eq(2)', etc )
 *		- A hash { top:x, left:y }, x and y can be any kind of number/string like above.
 * @param {Number} duration The OVERALL length of the animation, this argument can be the settings object instead.
 * @param {Object,Function} settings Optional set of settings or the onAfter callback.
 *	 @option {String} axis Which axis must be scrolled, use 'x', 'y', 'xy' or 'yx'.
 *	 @option {Number} duration The OVERALL length of the animation.
 *	 @option {String} easing The easing method for the animation.
 *	 @option {Boolean} margin If true, the margin of the target element will be deducted from the final position.
 *	 @option {Object, Number} offset Add/deduct from the end position. One number for both axes or { top:x, left:y }.
 *	 @option {Object, Number} over Add/deduct the height/width multiplied by 'over', can be { top:x, left:y } when using both axes.
 *	 @option {Boolean} queue If true, and both axis are given, the 2nd axis will only be animated after the first one ends.
 *	 @option {Function} onAfter Function to be called after the scrolling ends. 
 *	 @option {Function} onAfterFirst If queuing is activated, this function will be called after the first scrolling ends.
 * @return {jQuery} Returns the same jQuery object, for chaining.
 *
 * @desc Scroll to a fixed position
 * @example $('div').scrollTo( 340 );
 *
 * @desc Scroll relatively to the actual position
 * @example $('div').scrollTo( '+=340px', { axis:'y' } );
 *
 * @dec Scroll using a selector (relative to the scrolled element)
 * @example $('div').scrollTo( 'p.paragraph:eq(2)', 500, { easing:'swing', queue:true, axis:'xy' } );
 *
 * @ Scroll to a DOM element (same for jQuery object)
 * @example var second_child = document.getElementById('container').firstChild.nextSibling;
 *			$('#container').scrollTo( second_child, { duration:500, axis:'x', onAfter:function(){
 *				alert('scrolled!!');																   
 *			}});
 *
 * @desc Scroll on both axes, to different values
 * @example $('div').scrollTo( { top: 300, left:'+=200' }, { axis:'xy', offset:-20 } );
 */
;(function( $ ){
	
	var $scrollTo = $.scrollTo = function( target, duration, settings ){
		$(window).scrollTo( target, duration, settings );
	};

	$scrollTo.defaults = {
		axis:'y',
		duration:1
	};

	// Returns the element that needs to be animated to scroll the window.
	// Kept for backwards compatibility (specially for localScroll & serialScroll)
	$scrollTo.window = function( scope ){
		return $(window).scrollable();
	};

	// Hack, hack, hack... stay away!
	// Returns the real elements to scroll (supports window/iframes, documents and regular nodes)
	$.fn.scrollable = function(){
		return this.map(function(){
			// Just store it, we might need it
			var win = this.parentWindow || this.defaultView,
				// If it's a document, get its iframe or the window if it's THE document
				elem = this.nodeName == '#document' ? win.frameElement || win : this,
				// Get the corresponding document
				doc = elem.contentDocument || (elem.contentWindow || elem).document,
				isWin = elem.setInterval;

			return elem.nodeName == 'IFRAME' || isWin && $.browser.safari ? doc.body
				: isWin ? doc.documentElement
				: this;
		});
	};

	$.fn.scrollTo = function( target, duration, settings ){
		if( typeof duration == 'object' ){
			settings = duration;
			duration = 0;
		}
		if( typeof settings == 'function' )
			settings = { onAfter:settings };
			
		settings = $.extend( {}, $scrollTo.defaults, settings );
		// Speed is still recognized for backwards compatibility
		duration = duration || settings.speed || settings.duration;
		// Make sure the settings are given right
		settings.queue = settings.queue && settings.axis.length > 1;
		
		if( settings.queue )
			// Let's keep the overall duration
			duration /= 2;
		settings.offset = both( settings.offset );
		settings.over = both( settings.over );

		return this.scrollable().each(function(){
			var elem = this,
				$elem = $(elem),
				targ = target, toff, attr = {},
				win = $elem.is('html,body');

			switch( typeof targ ){
				// A number will pass the regex
				case 'number':
				case 'string':
					if( /^([+-]=)?\d+(px)?$/.test(targ) ){
						targ = both( targ );
						// We are done
						break;
					}
					// Relative selector, no break!
					targ = $(targ,this);
				case 'object':
					// DOMElement / jQuery
					if( targ.is || targ.style )
						// Get the real position of the target 
						toff = (targ = $(targ)).offset();
			}
			$.each( settings.axis.split(''), function( i, axis ){
				var Pos	= axis == 'x' ? 'Left' : 'Top',
					pos = Pos.toLowerCase(),
					key = 'scroll' + Pos,
					old = elem[key],
					Dim = axis == 'x' ? 'Width' : 'Height',
					dim = Dim.toLowerCase();

				if( toff ){// jQuery / DOMElement
					attr[key] = toff[pos] + ( win ? 0 : old - $elem.offset()[pos] );

					// If it's a dom element, reduce the margin
					if( settings.margin ){
						attr[key] -= parseInt(targ.css('margin'+Pos)) || 0;
						attr[key] -= parseInt(targ.css('border'+Pos+'Width')) || 0;
					}
					
					attr[key] += settings.offset[pos] || 0;
					
					if( settings.over[pos] )
						// Scroll to a fraction of its width/height
						attr[key] += targ[dim]() * settings.over[pos];
				}else
					attr[key] = targ[pos];

				// Number or 'number'
				if( /^\d+$/.test(attr[key]) )
					// Check the limits
					attr[key] = attr[key] <= 0 ? 0 : Math.min( attr[key], max(Dim) );

				// Queueing axes
				if( !i && settings.queue ){
					// Don't waste time animating, if there's no need.
					if( old != attr[key] )
						// Intermediate animation
						animate( settings.onAfterFirst );
					// Don't animate this axis again in the next iteration.
					delete attr[key];
				}
			});			
			animate( settings.onAfter );			

			function animate( callback ){
				$elem.animate( attr, duration, settings.easing, callback && function(){
					callback.call(this, target, settings);
				});
			};
			function max( Dim ){
				var attr ='scroll'+Dim,
					doc = elem.ownerDocument;
				
				return win
						? Math.max( doc.documentElement[attr], doc.body[attr]  )
						: elem[attr];
			};
		}).end();
	};

	function both( val ){
		return typeof val == 'object' ? val : { top:val, left:val };
	};

})( jQuery );
