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;
    }
};


var sw_cache = {};

$(document).ready(
	function() {

		//------------------
		// INPUT fields default values
		//------------------

		$('INPUT[onempty]').focus(
			function() {
				var obj = $(this).get(0);
				if(obj.value == $(this).attr('onempty')) { obj.value = ''; $(this).removeClass('Dim');}
			}
		)

		$('INPUT[onempty]').blur(
			function() {
				var obj = $(this).get(0);
				if(obj.value == '') { obj.value = $(this).attr('onempty'); $(this).addClass('Dim'); }
			}
		)
/*		
		 $('input').keydown(function(e){
			if (e.keyCode == 13) {
				$(this).parents('form').submit();
				return false;
			}
		});
*/		
		$('a.BtnGravar').mouseover(function(ev){ev.preventDefault(); window.status = 'Gravar'; return true;})
						.mouseout(function(ev){ev.preventDefault(); window.status = ''; return true;});
		
		$('a.BtnCancelar').mouseover(function(ev){ev.preventDefault(); window.status = 'Cancelar';  return true;})
						  .mouseout(function(ev){ev.preventDefault(); window.status = ''; return true;});

		
		//----------------------
		// Servicos Tabs
		//----------------------
		$('.DivMenuTabs A[page]').click(
			function() {
				$('.DivMenuTabs A[page]').each(
					function() {
						$(this).removeClass('Sel');
					}
				)

				$(this).addClass('Sel');
				try{ if(swfu) swfu.destroy(); } catch(e) {};	//Try to destroy SwfUpload object before removing the page
				$('.DivTabs').html('');

				var type = this.id;
				var page = $(this).attr('page');
				var rel_id = $(this).attr('rel_id');
				var tag = page + '_' + type + '_' + rel_id;
				
				if(sw_cache[tag]) {
					$('.DivTabs').html(sw_cache[tag]);
					DocumentReady($('.DivTabs').get(0));
				} else {
					$('.DivTabs').addClass('LoadingBkg');

					$.get("/ajx.get_tab.php", { type:type, page:page, rel_id:rel_id },
						function(data){
							$('.DivTabs').removeClass('LoadingBkg');
							$('.DivTabs').html(data);
							DocumentReady($('.DivTabs').get(0));
							sw_cache[tag] = data;
						}
					);

				}

				return(false);
			}						
		);
		
		DocumentReady(document);
	}
)

function DocumentReady(obj) {
	// On hover effect for submit buttons
	$(obj).find('.ButtonSubmit, .ButtonCancel').hover(
		function() { $(this).addClass('Hover'); },
		function() { $(this).removeClass('Hover'); }
	);

	// Highlight selected options
	$(obj).find('.TablePesquisa SELECT OPTION[selected]').each(function() {
		if($(this).attr('value')) { $(this).addClass('Sel'); }
	});
	
	
//	if($(obj).find("a.AjaxLoadContentWithHistory").length > 0 && !historyInited) {
//		$.historyInit(historyPageLoad);
//		historySetClick();
//		historyInited = true;
//	}
	
//	alert('DocumentReady')
	$(obj).find("a.AjaxLoadContent[rel!='history']").click(
		function() { return (AjxLoadContent(this)); }
	);

	//----------------------
	// Image Galleries
	//----------------------
	$(obj).find('.SWIG_Thumb').swImageGallery({imageLoading:'/images/icons/loading-bigrotation.gif', imgCanvasPath:'.SWIG_Image', selectedLinkClass:'Sel', idThumbs:'thumbsImages' });
	if($(obj).find('.SWIG_Thumb').length) { HidePrevNextGaleryImage('thumbsImages'); }

}

function CheckCookiesEnabled(sHtmlMsg, $oPrependMsgTo) {
	if(!$oPrependMsgTo) $oPrependMsgTo = '.ContentText';
	if(!sHtmlMsg) sHtmlMsg='<div class="Messages"><div class="ERROR">A funcionalidade de cookies do seu browser está desativada. <br/>Por favor, active a utilização de cookies para poder utilizar esta página.</div></div>';
	if(!$.cookie('DESTAKCLASSIFICADOS')) {$($oPrependMsgTo).prepend(sHtmlMsg); return false;}
	return true;
}

//----------------------
// Utils
//----------------------
function fixDottedLinksOutline(domChunk) { $(domChunk).focus(function(){this.blur();});  }


//----------------------
// FAQ
//----------------------
function SwitchFAQ(obj) {
	var iQuestion = $(obj).attr('key');
	
	$('.Question').removeClass('Sel');
	fixDottedLinksOutline('#Q' + iQuestion + ' a');
	$('.Answer').each(function(){
		if(this!=$('#A' + iQuestion).get(0)) { $(this).hide('fast'); }					   
	});
	$('#Q' + iQuestion + '').addClass('Sel');
	$('#A' + iQuestion).show('fast');
}

//----------------------
// Form Submission
//----------------------

function ValidateAndSubmit($form) {
	if($($form).attr('onsubmit') && !$($form).get(0).onsubmit()) return false;
	$($form).submit();
}


function swValidateStandard(obj) {
	var objChecked = new Object();
	var bHasErrors = false;
	var objTexts=new jsVal_Language();

	// See if no default values are set
	$(obj).find('INPUT[type=text]').each(function() {
		if($(this).attr('value')==$(this).attr('onempty') && $(this).attr('required')==1) {
			if($(this).attr('realnameliteral')) { alert($(this).attr('realname')); }
			else if ($(this).attr('err')) { alert($(this).attr('err').replace("%FIELDNAME%", $(this).attr('realname'))); }
			else { alert(objTexts.err_enter.replace("%FIELDNAME%", $(this).attr('realname'))); }
			bHasErrors = true;
			return(false);
		}
	});
	if(bHasErrors) {return(false); }

	// Validate Radios and Checkboxes
	$(obj).find('INPUT[type=radio],INPUT[type=checkbox]').each(function() {
		var sName = $(this).attr('name');
		if($(this).attr('required')==1 && !objChecked[sName]) {
			if(!$(obj).find('INPUT[name="' + sName + '"]').filter('INPUT[checked]').length) {
				obj.focus();
				if($(this).attr('realnameliteral')) { alert($(this).attr('realname')); }
				else if ($(this).attr('err')) { alert($(this).attr('err').replace("%FIELDNAME%", $(this).attr('realname'))); }
				else { alert(objTexts.err_enter.replace("%FIELDNAME%", $(this).attr('realname'))); }
				bHasErrors = true;
				return(false);
			}
			objChecked[sName] = true;
		}
	});
	if(bHasErrors) {return(false); }

	// Validate Selects
	$(obj).find('SELECT[required=1]').each(function() {
		if(!$(this).find('OPTION[selected]').attr('value')) {
			obj.focus();
			if($(this).attr('realnameliteral')) { alert($(this).attr('realname')); }
			else if ($(this).attr('err')) { alert($(this).attr('err').replace("%FIELDNAME%", $(this).attr('realname'))); }
			else { alert(objTexts.err_enter.replace("%FIELDNAME%", $(this).attr('realname'))); }
			bHasErrors = true;
			return(false);
		}
	});
	if(bHasErrors) {return(false); }

	// Validate hiddens
	$(obj).find('INPUT[type=hidden]').each(function() {
		if($(this).attr('required')==1 && !$(this).attr('value')) {
			if($(this).attr('realnameliteral')) { alert($(this).attr('realname')); }
			else if ($(this).attr('err')) { alert($(this).attr('err').replace("%FIELDNAME%", $(this).attr('realname'))); }
			else { alert(objTexts.err_enter.replace("%FIELDNAME%", $(this).attr('realname'))); }
			bHasErrors = true;
			return(false);
		}
	});
	if(bHasErrors) {return(false); }

	return(validateStandard(obj));
}


//----------------------
// Orders
//----------------------

function CheckOrderState(iOrdId, sPage) {
	CheckOrderStateLoop(iOrdId, 0, sPage);
}

function CheckOrderStateLoop(iOrdId, iIteration, sPage) {
	iIteration++;
	if(iIteration > 50) { return(false); }
	setTimeout(function() {
		$.get('/ajx.check_order_state.php', { ord_id : iOrdId }, function(data){ 
			if(data=='PAID') { location.href = sPage; }
			else { CheckOrderStateLoop(iOrdId, iIteration, sPage); }
		});
	}, 3000);

}


//----------------------
// Forms
//----------------------

function showFieldLoading($where) {
	try {
		var pos = $where.offset();    
		var width = $where.width();
		var height = $where.height();
		$('#iFieldLoading').css( { "left": (pos.left+1) + "px", "top":(pos.top+1) + "px", "height":height + "px", "width":(width-20) + "px" } );  
		$("#iFieldLoading").show();
	} catch(err) {}
}

function hideFieldLoading() {
	$("#iFieldLoading").hide();
}

function UpdateDependencies(mySelf, myLkpFieldName, $child, childLkpFieldName, LkpClsType ) {
	
//	var $child = $('select#fields_freguesia');
	if($child == undefined || myLkpFieldName == undefined || childLkpFieldName==undefined) return;
	if(LkpClsType == undefined) LkpClsType = 0;
	
	//unselect freguesia
	$child.get(0).selectedIndex = 0;
	$child.get(0).value = '';
	
	//trigger concelho change
	$child.trigger('change');
	
	//if value > 0 load freguesias
	if(mySelf.value != '' && mySelf.value != '-') {
		//$('#iTrFreguesia').show();
		$child.removeAttr("disabled"); 
		//show loading
		showFieldLoading($child);
		//load freguesias
		$child.load(
			'/ajx.lookup_field.php', 
			{ field: childLkpFieldName, cls_type: LkpClsType, parent_field: myLkpFieldName, parent_value: mySelf.value, output:'select-options-firstempty' }, 
			function() { hideFieldLoading(); $child.focus(); } 
		);
	} else {
		//$('#iTrFreguesia').hide();
		$child.attr("disabled", true); 
	}
}

function UpdateCheckboxHighligh(me) {
	if(me.checked) $(me.form).find("label[for=" + me.id + "]").addClass('checked');
	else $(me.form).find("label[for=" + me.id + "]").removeClass('checked');
}


//----------------------
// Pesquisas
//----------------------

function AjxLoadContentTo(sHref, oTarget) {
	var $container = $(oTarget);
	if(!$container) return true;
	$container.append('<div class="LoadingContentOverlay"></div><div class="LoadingContent"><div><img src="/images/icons/loading-bigrotation.gif" align="absmiddle" /> A carregar dados ...</div></div>');
	$container.load(
		'/ajx.get_content.php', 
		{'href': sHref }, 
		function(data){ DocumentReady($container); }
	);
	return(false);
}

function AjxLoadContent(oLinkObject) {

	if(!oLinkObject || !oLinkObject.href) return true;
	var href = $(oLinkObject).attr('href');
	$(oLinkObject).attr('href','');
	
	return AjxLoadContentTo(href, $(oLinkObject).parents('#ajax_content'));
/*
	var $container = $(oLinkObject).parents('#ajax_content');
	$container.append('<div class="LoadingContentOverlay"></div><div class="LoadingContent"><div><img src="/images/icons/loading-bigrotation.gif" align="absmiddle" /> A carregar dados ...</div></div>');
	$container.load(
		'/ajx.get_content.php', 
		{'href': href }, 
		function(data){ DocumentReady($container); }
	);

	return(false);
	*/
}

function LoadPesquisaPage(iType, objParams) {

	$container = $('#ajax_content');
	$container.append('<div class="LoadingContentOverlay"></div><div class="LoadingContent"><div><img src="/images/icons/loading-bigrotation.gif" align="absmiddle" /> A carregar dados ...</div></div>');

	objParams.cls_type = iType;

	//load freguesias
	$container.load(
		'/ajx.pesquisa.php', 
		objParams, 
		function() { } 
	);

	return(false);
}

function LoadRestrictPage(iType, objParams) {

	$container = $('.TabsContainer');
	$container.append('<div class="LoadingContentOverlay"></div><div class="LoadingContent"><div><img src="/images/icons/loading-bigrotation.gif" align="absmiddle" /> A carregar dados ...</div></div>');

	objParams.cls_type = iType;

	//load freguesias
	$container.load(
		'/ajx.restrict.php', 
		objParams, 
		function() { } 
	);
	return(false);
}


//----------------------
// Galerias de Imagens
//----------------------

function HidePrevNextGaleryImage(id) {
	var objPrev = $('#' + id + ' A.Sel').prev();
	var objNext = $('#' + id + ' A.Sel').next();

	if(objPrev.length > 0) {
		if($(objPrev).get(0).tagName == 'A') { $('.PhotoZone .Prev').show(); }
		else { $('.PhotoZone .Prev').hide(); }
	}
	else { $('.PhotoZone .Prev').hide(); }

	if(objNext.length > 0) {
		if($(objNext).get(0).tagName == 'A') { $('.PhotoZone .Next').show(); }
		else { $('.PhotoZone .Next').hide(); }
	}
	else { $('.PhotoZone .Next').hide(); }
}

function PrevGaleryImage(id) {
	try { $('#' + id + ' A.Sel').prev().trigger('click') } catch(err) {}
	HidePrevNextGaleryImage(id);
}

function NextGaleryImage(id) {
	try { $('#' + id + ' A.Sel').next().trigger('click') } catch(err) {}
	HidePrevNextGaleryImage(id);
}


//----------------------
// Favoritos
//----------------------

function AddFavourites(id, objLink) {
	var bAdd = true;
	if($(objLink).hasClass('Sel')) { bAdd = false; }
	id = parseInt(id);
	if(id<=0) return false;
	$.post(
		'/ajx.add_favourites.php',
		{ cls_id:id, add:bAdd },
		function(data) {
			if(data=='OK') {
				if(bAdd) {
					if(objLink) {
						$(objLink).addClass('Sel');
						$(objLink).html('remover dos favoritos');
					}
					//alert('O classificado foi adicionado aos favoritos.');
				} else {
					if(objLink) {
						$(objLink).removeClass('Sel');
						$(objLink).html('adicionar aos favoritos');
					}
					//alert('O classificado foi removido dos favoritos.');
				}
			}
			else {
				if(bAdd) { alert('Erro ao adicionar o classificado aos favoritos.'); }
				else { alert('Erro ao remover o classificado dos favoritos.'); }
			}
		}
	);
	return(false);
}


//----------------------
// Classified management
//----------------------

function ConfirmClassifiedDeletion(sUrl) {
	if(confirm('Esta operação vai apagar o classificado e todos os conteúdos relacionados. Tem a certeza que quer continuar?')) { window.location=sUrl; }
	return(true);
}


//----------------------
// History management
//----------------------
var historyClsType=0;
var historyInited = false;

function historyPageLoad(hash) {
	var uriItems = parseUri(window.location.href);
	//alert('historyPageLoad ' + url);
	if(hash) {	
		var url = uriItems.path + '?' + hash;
		uriItems = parseUri(url);
		//alert('historyPageLoad ' + url);
		AjxLoadContentTo(url, $('#ajax_content'));
		//LoadPesquisaPage(historyClsType, uriItems.queryKey);	//!!!
	} else {
		//alert('historyPageLoad ' + uriItems.path);
		AjxLoadContentTo(uriItems.path, $('#ajax_content'));
		//LoadPesquisaPage(historyClsType,{offset:0});	//!!!
	}
}

function historySetClick() {
	//alert('historySetClick 1');
	//if(! historyClsType>0) return false;
	$("a.AjaxLoadContentWithHistory").attr({'onclick':''});
	$("a.AjaxLoadContentWithHistory").unbind('click');
	$("a.AjaxLoadContentWithHistory").click(function(){
		try{
			//alert('historySetClick 2');
			var uriItems = parseUri(this.href);
			hash = uriItems.query;
			$.historyLoad(hash);
		} catch(e) {};
		return false;
	});	
}

$(document).ready(function(){
	//if(historyClsType>0) {

	if($("a.AjaxLoadContentWithHistory").length > 0) {
		$.historyInit(historyPageLoad);
		historySetClick();
	}

});


// -------------------------
// REFERENCE SEARCH
// -------------------------

function referenceSearch(obj) {
	var bStatus = true;
	var ref = $(obj).find('#form_reference_search').attr('value');
	
	$.post(
		'/ajx.get_ref_url.php',
		{ 'ref':ref },
		function(data) {
			if(data=='NOTFOUND') { bStatus = false; alert('Não foi encontrado nenhum classificado com essa referência.'); }
			else { window.location = data; }
		}
	);
	if(!bStatus) { }

	return(false);
}


// -------------------------
// COMMON
// -------------------------

function swPopUpWindow(URLStr, left, top, width, height, scrollbar, windowname) {
	if(!scrollbar) scrollbar = 'scrollbar=no';
	else scrollbar = 'scrollbars';
	if (!left) left = (screen.width/2) - width/2;
	if (!top) top = (screen.height/2) - height/2;
	popUpWin = open(URLStr, windowname, 'toolbar=no,location=no,directories=no,status=no,menubar=no,'+scrollbar+',resizable=no,copyhistory=no,width='+width+',height='+height+',left='+left+', top='+top+',screenX='+left+',screenY='+top+'');
}

