$(document).ready(function () {
	
	function URLEncode( plaintext )
	{
	  // The Javascript escape and unescape functions do not correspond
	    // with what browsers actually do...
	    var SAFECHARS = "0123456789" +					// Numeric
			        "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
			        "abcdefghijklmnopqrstuvwxyz" +
			        "-_.!~*'()";					// RFC2396 Mark characters
	    var HEX = "0123456789ABCDEF";

	    var encoded = "";
	    for (var i = 0; i < plaintext.length; i++ ) {
	      var ch = plaintext.charAt(i);
	        if (ch == " ") {
	          encoded += "+";				// x-www-urlencoded, rather than %20
	      } else if (SAFECHARS.indexOf(ch) != -1) {
	          encoded += ch;
	      } else {
	          var charCode = ch.charCodeAt(0);
	        if (charCode > 255) {
	            alert( "Unicode Character '" 
	                          + ch 
	                          + "' cannot be encoded using standard RFC2396 encoding.\n" +
		                  "(URL encoding only supports 8-bit characters.)\n" +
				          "A space (+) will be substituted." );
		        encoded += "+";
	        } else {
		        encoded += "%";
		        encoded += HEX.charAt((charCode >> 4) & 0xF);
		        encoded += HEX.charAt(charCode & 0xF);
	        }
	      }
	    } // for

		return encoded;
	};
	
	$('form#pesquisaForm').submit(function(){
		var form = $(this);
		$.post('http://' + $(this).attr('action').split(/\/+/g)[1] + '/pesquisa_cont.php', $(this).serialize(), function(response){
				top.location = response.replace(form.find('input[name=key]').val(), URLEncode(form.find('input[name=key]').val()));
		});
		return false;
	});
	
	$(".contactostip").tooltip({
		tip: '#contactostip',
		effect: 'fade',
		delay:2000,
		opacity: 0.9,
		position: 'top right'
	});
	
	$(".tip").tooltip({
		tip: '#tip',
		onBeforeShow: function(){
				$('#tip .box').text($('.tip:hover').attr('id'));
			},
		effect: 'fade',
		opacity: 0.9,
	});
	
	/*Botão de Desligar / Ligar o site*/
	$('#onofre').toggle(
		function(){
			$('#page-container').hide();
			$(this).addClass("onofre_off");
		},
		function(){
			$('#page-container').show();
			$(this).removeClass("onofre_off");
		}
	);
	
	function get( num )
	{
		var results = window.location.href.split('/');
		if( results == null )
			return "";
		else
		{
			for(i=0;i<results.length;i++)
			{
				if(i==num)
					return results[i];
			}
				
		}
    }
	
	$('li span.line a').live('click', function(){
		// Explode url
		var urlparts = $(this).attr('href').split('/');
		
		// Get parent <li> AND this <a>
		var li = $(this).parents('li:first');
		var a = $(this);
		
		// Back to normal state
		var main_ul = li.parents('ul').first();
		main_ul.find('a.current').parents('li:first').find('ul').not(li.find('ul')).slideToggle('fast', function(){
			main_ul.find('span.arrow').not(li.find('ul span.arrow')).removeClass('opened').addClass('closed').hide();
			main_ul.find('a').not(a).removeClass('current');
		});
		
		// Make selected
		if($(this).hasClass('current'))
			$(this).removeClass('current');
		else
			$(this).addClass('current');
		
		// Get child cats of selected cat
		$.post('http://' + urlparts[2] + '/catalogo_printcats.php?site='+get(3), {catid: $(this).attr('id')}, function(response){
			li.find('ul span.arrow').hide();
			
			// Toogle arrow
			if(response.length > 0)
			{
				if(li.find('span.arrow:first').hasClass('closed'))
					li.find('span.arrow:first').removeClass('closed').addClass('opened');
				else
					li.find('span.arrow:first').removeClass('opened').addClass('closed');
			}
			
			// Check if exists <ul> child
			if(li.find('ul').length > 0)
			{
				li.find('ul:first').slideToggle('fast', function(){
					li.find('ul span.arrow').show();
				});
			}else{
				// check if response has <ul>
				if(response.length > 0)
				{
					li.append(response);
					
//					li.find('ul span.arrow').slideDown('fast');
				}else{
					top.location = a.attr('href');
				}
			}
			return false;
		});
		return false;
	});
	
	$('#select_cc, #select_id').hover(function(){
			$(this).find('.rede').stop().animate({opacity:0.8},'fast');
			$(this).find('.text').stop().animate({opacity:1},'fast');
		},
		function(){
			$(this).find('.rede').stop().animate({opacity:0},'fast');
			$(this).find('.text').stop().animate({opacity:0},'fast');
		}
	);
	
	$('#pf-slider').cycle({ 
	    fx:     'fade', 
	    speed:  'fast', 
	    timeout: 3000, 
	    pager:  '#nav', 
	    pagerAnchorBuilder: function(idx, slide) { 
	        // return selector string for existing anchor 
	        return '#nav li:eq(' + idx + ') a'; 
	    } 
	});
	$(document).find('.slider').each(function(index){
		$(this).after('<div class="slider-nav" id="slider'+index+'">').cycle({ 
		    fx:     'fade', 
		    speed:  'fast',
		    pager:  '#slider'+index
		});
		
		if(!$(this).hasClass('autostart'))
			$(this).cycle('pause');
	});
	
	$('.produto, .texto').jScrollPane();
	
	function mycarousel_initCallback(carousel) {
		carousel.options.start = $('ul#pf-showroom li.active').index() + 1;
		$('ul#pf-showroom-controls .rede').bind('click', function() {
			if(!carousel.animating){
				// Limpa todos os elementos activos para fazer o novo set
				$(this).parents('ul:first').find('li').removeClass('active');
				$(this).parent('li').addClass('active');
				if($(this).parent('li').index() == 0)
					$(this).parent('li').next().addClass('active');
				else
					$(this).parent('li').prev().addClass('active');
				carousel.scroll($.jcarousel.intval($(this).parent('li').index()));
			}
			return false;
		});
		
		$('.jcarousel-prev, .jcarousel-next').bind('click', function() {
			if($(this).parents('#controls').length == 0 && !carousel.animating){
				var index = $('ul#pf-showroom').position().left / -435;
				if($(this).hasClass('jcarousel-prev') && !$(this).hasClass('jcarousel-prev-disabled')){
					$('ul#pf-showroom-controls').find('li.active:first').next().removeClass('active');
					$('ul#pf-showroom-controls').find('li.active:first').prev().addClass('active');
				}
				
				if($(this).hasClass('jcarousel-next') && !$(this).hasClass('jcarousel-next-disabled')){
					$('ul#pf-showroom-controls').find('li.active:first').next().next().addClass('active');
					$('ul#pf-showroom-controls').find('li.active:first').removeClass('active');
				}
			}
			return false;
		});
	};
	
	$('ul#pf-showroom').jcarousel({
		scroll: 1,
		initCallback: mycarousel_initCallback
	});
	
	$('ul#pf-showroom-controls').jcarousel();

	if($('ul#cats').length > 0 && $('ul#tipos').length > 0){
		var posLeft = $('ul#tipos').position().left;
		$('ul#cats').css('right', (930 - posLeft)+'px');
		$('ul#tipos a.active, ul#tipos ul').hover(
			function(){
				$('ul#cats').css('right', (930 - $(this).parents('ul#tipos').position().left)+'px');
			},
			function(){
				$('ul#cats').css('right', (930 - posLeft)+'px');
			}
		);
	}
	
	$('.submit').live('click', function(){
		var form = $(this).parents('form:first');
		form.parent('div.pp_inline').find('.loading').show();
	    var fem = form.serialize(),
			note = form.parent('div.pp_inline').find('.message');
	    note.hide();
	    form.find('.submit').hide();
	    
	    $.ajax({
	        type: "POST",
	        url: form.attr('action'),
	        data: fem,
	        success: function(msg) {
				form.parent('div.pp_inline').find('.loading').fadeOut(300, function() {
					$(this).hide();
					var php = msg.split('<|>');
					form.find('.submit').fadeIn(700);
					note.html(php[0]).fadeIn(700);
										
					if(php[1] == 'OK'){
						$(':input','#ajax-form')
						 .not(':button, :submit, :reset, :hidden')
						 .val('')
						 .removeAttr('checked')
						 .removeAttr('selected');
						form.hide();
					}else{
						$("input[name="+php[1]+"], textarea[name="+php[1]+"]").focus();
					}
				}); // end loading image fadeOut
	        }
	    });
	});
	
	$(".ajax-form").submit(function() {
		var form = $(this);
		
	    form.parent('div.morada').find('.loading').show();
	    var fem = $(this).serialize(),
			note = form.parent('div.morada').find('.message');
	    note.hide();
	    $('.btn-submit').hide();
	    
	    $.ajax({
	        type: "POST",
	        url: form.attr('action'),
	        data: fem,
	        success: function(msg) {
				form.parent('div.morada').find('.loading').fadeOut(300, function() {
					$(this).hide();
					var php = msg.split('<|>');
					$('.btn-submit').fadeIn(700);
					note.html(php[0]).fadeIn(700);
										
					if(php[1] == 'OK'){
						$(':input','#ajax-form')
						 .not(':button, :submit, :reset, :hidden')
						 .val('')
						 .removeAttr('checked')
						 .removeAttr('selected');
						form.hide();
					}else{
						$("input[name="+php[1]+"], textarea[name="+php[1]+"]").focus();
					}
				}); // end loading image fadeOut
	        }
	    });
	   return false;
	});
	
	$("a[rel^='prettyPhoto']").prettyPhoto({
		opacity: 0.50,
		social_tools: false,
		deeplinking: false
	});
	
	$("a[rel^='prettyForm']").prettyPhoto({
		opacity: 0.50,
		social_tools: false,
		deeplinking: false,
		modal: true,
		keyboard_shortcuts: false
	});
	
	$("a[rel^='prettyForm']").click(function(){
		$('#pedirinfo').find('input[name=item]').val($('div.bloco').find('h1').text());
		$('#pedirinfo').find('input[name=href]').val(window.location.pathname);
		return false;
	});
	
	$('ul#tabs li span').click(function(){
		$('ul#tabs li span').removeClass('current');
		$(this).parents('.cpbloco').find('.tabs-content').hide();
		$(this).addClass('current').parents('.cpbloco').find('div#' + $(this).attr('id')).show();
		return false;
	});
	
	/* autoclear function for inputs */
	$('.autoclear').click(
	function() {
	if (this.value == this.defaultValue) {
	this.value = '';
	}
	}
	);
	$('.autoclear').blur(
	function() {
	if (this.value == '') {
	this.value = this.defaultValue;
	}
	}
	);
	
});
