/*-----------------------------------------------------------------------------+
| Funções Gerais JavaScript													|
+-----------------------------------------------------------------------------*/

function popup(url,w,h){
	window.open(url,"","toobar=no,location=no,directories=no,maximize=no,menubar=no,scrollbars=yes,status=no,resizable=no,WIDTH="+w+",HEIGHT="+h+",top=0,left=50");
}

function roundNumber(preco) {
	var numberField = preco;
	var rlength = 2; // The number of decimal places to round to
	var newnumber = Math.round(numberField*Math.pow(10,rlength))/Math.pow(10,rlength);
	return newnumber;
}


function IsNumeric(sText)
{
   var ValidChars = "123456789 ";
   var IsNumber=true;
   var Char;


   for (i = 0; i < sText.length && IsNumber == true; i++)
	  {
	  Char = sText.charAt(i);
	  if (ValidChars.indexOf(Char) == -1)
		 {
		 IsNumber = false;
		 }
	  }
   return IsNumber;
}

function RemotePopUpGca(url, wit, hei) {
	var RemotePopUpGca = null
	RemotePopUpGca = window.open(url,'_blank','toolbar=no,location=no,directories=no,status=yes,scrollbars=no,resizable=no,menubar=no,width='+wit+',height='+hei)
	if (RemotePopUpGca != null) {
		RemotePopUpGca.location.href = url
	}
}

var reg = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i; //expressão regular para emails
$(document).ready(function () 
{
	
    //FORM FIELDS VALIDATION (START)
    $.fn.exists = function() { return (this.length > 0); };
    $.show_error_msg = function(id,type,error_msg)
    {
      if($('#'+id+'_ok').exists())
        $('#'+id+'_ok').remove();
      
      text=error_msg[id+'_'+type];
      if(!$('#'+id+'_msg').exists())
        $('<p id="'+id+'_msg" class="error_msg">'+text+'</p>').insertAfter('#'+id).show();
      else if(text!=$('#'+id+'_msg').text())
        $('#'+id+'_msg').text(text);
      
      if(!$.browser.msie)
        $('#'+id).focus();
    };
    
    $.hide_error_msg = function(id)
    {
      if($('#'+id+'_msg').exists())
        $('#'+id+'_msg').slideUp('slow',function(){$(this).remove()});
    };
    //FORM FIELDS VALIDATION (END)
    
    
    // Menu - Big Brotha
	$('#subNav ul.base li.base-child').hover(function() {

		$('#subNav ul.subNavContainer').hide();
		$("ul.subNavContainer", this).show();
		
		$(this).children('a.base-child-anchor').stop(true, true).addClass('base-child-anchorHover');
	}, function() {
		var menu = this;
		$('a.base-child-anchor').removeClass('base-child-anchorHover');
		$("ul.subNavContainer", this).stop(true, true).fadeOut("slow");
	});

	// Timeline Selector
	$('a.timeline_year').click(function() {
		$('a.timeline_year').removeClass('timelineyearSelected');
		$(this).addClass('timelineyearSelected');
		dados =  $(this).attr('id').split('_');
		
		var ano = dados[1];
		var tema = 0;
		if(dados.length > 2){
			tema = dados[2];
		}
		
		golf=0;
		if($(this).is(".golfe_holeinone")){
			golf = 1;
		}
		if($(this).is(".golfe_holeinone_royal")){
			golf = 3;
		}
		if($(this).is(".golfe_holeinone_ocean")){
			golf = 2;
		}
		
		if (ano) {
			timeline.getDocument(ano, tema, golf);
		}
		return false;
	});

	// Tabs Notícias
	$(".newsList #tabsNoticias a").click(function() {
		pageNavigator.parse_qs('#listagemNoticias', $(this).attr("href"));
		$('#tabsNoticias a').removeClass('selected');
		$(this).addClass('selected');

		$('#listagemNoticias').ajaxSubmit({
			target:  '#listNoticias',
			success: showResponse
		}); 

		return false;
	});
	$(".newsList #tabsNoticias a:first").click();

	// Combo Secções Notícias
	$('.newsList .selSeccao').change(function() {
		$('#listagemNoticias').ajaxSubmit({
			target:  '#listNoticias',
			success: showResponse
		}); 
	});

	// Tabs Eventos
	$(".eventsList #tabsEvents a").click(function() {
		loadCalendarEvents();
		// Elimina a Selecção da Data
		pageNavigator.setParam('#listagemEventos', 'cur_data', '');
		pageNavigator.parse_qs('#listagemEventos', $(this).attr("href"))
		$('#tabsEvents a').removeClass('selected');
		$(this).addClass('selected');

		$('#listagemEventos').ajaxSubmit({
			target:  '#listEvents',
			success: showResponse
		}); 

		return false;
	});
	$(".eventsList #tabsEvents a:eq(1)").click();

	// Combo Secções Eventos
	$('.eventsList .selSeccao').change(function() {
		eventsSelectFirstTab();
		$("#datepicker").datepicker('destroy');
		$('#listagemEventos').ajaxSubmit({
			target:  '#listEvents',
			success: showResponse
		});
		loadCalendarEvents();
	});
	
	$("#listEvents .paging-bar a").live("click", function(){
		$("#listEvents").load($(this).attr("href"));
		return false;
	});
	
	$("#listNoticias .paging-bar a").live("click", function(){
		$("#listNoticias").load($(this).attr("href"));
		return false;
	});
	
	$(".tabsProperties ul li span:last-child").addClass("tabclose-last");
	
	$(".pergunta").click(
		function(){
			if($(this).siblings("div").css("display") == "block")
				$(this).siblings("div").slideUp("fast");
			else
				$(this).siblings("div").slideDown("fast");
	});
	
	$("a[rel=fancy_outer_content]").fancybox({
        'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'autoScale'     	: true,
		'type'				: 'iframe',
        'width'             : 1000,		
		'height'            : '100%'
	});
});

function eventsSelectFirstTab(dateText) {
	//$('#tabsEvents a').removeClass('selected');
	//$('#tabsEvents a:first').addClass('selected');
	pageNavigator.setParam('#listagemEventos', 'cur_data', dateText);
	pageNavigator.setParam('#listagemEventos', 't', 'now');
}

// Eventos
function loadCalendarEvents() {
	var calendarEvents = "";
	$.ajax({
		url: "/xmlhttprequests/calendario/getEventsDates.php",
		data: { idSec: pageNavigator.getParam('#listagemEventos', 'idSec') },
		dataType: "json",
		success: function(calendarEvents) {
			$("#datepicker").datepicker({
				// [linhas, colunas]
				numberOfMonths: [1, 3],
				showButtonPanel: true,
				showCurrentAtPos: 0,
				showWeek: false,
				beforeShowDay: function (date) {
					for (i = 0; i < calendarEvents.length; i++) {
						if (date.getMonth() == calendarEvents[i][0] - 1 && date.getDate() == calendarEvents[i][1] && date.getFullYear() == calendarEvents[i][2]) {
							// [disable/enable, class for styling appearance, tool tip]
							return [true,"ui-state-active"]; 
						}
					}
					return [false, ""]; //enable all other days
				},
				onSelect: function(dateText, inst) {
					eventsSelectFirstTab(dateText);
					$('#listagemEventos').ajaxSubmit({
						target:  '#listEvents',
						success: showResponse
					});
					return false;
				}
			});
		}
	});
}
// Timeline
var timeline = {
	resultContainer: "#eventsList",
	getDocument: function(year, tema, golf) {
		$.ajax({
			type: "POST",
			cache: false,
			url: "/xmlhttprequests/timeline/geteventslist.php",
			data: { ano: year , theme : tema, golf : golf},
			success: function(data) {
				$(timeline.resultContainer).html(data);
			}
		});
	}
}

// Page Params
var pageNavigator = {
	formContainer: '.pageNavigation',
	setParam: function (form, name, value) {
		$(form + ' input[name='+ name +']').val(value);
	},
	getParam: function (form, name) {
		return $(form + ' input[name='+ name +'], ' + form + ' select[name='+ name +']').val();
	},
	parse_qs: function (form, query) {
		var qsParm = new Array();
		var params = query.split('?');
		if (params[1]) {
			params = params[1].split('&');

			for (var i=0; i<params.length; i++) {
				var pos = params[i].indexOf('=');
				if (pos > 0) {
					var key = params[i].substring(0,pos);
					var val = params[i].substring(pos+1);
					pageNavigator.setParam(form, key, val)
				}
			}
			return true;
		}
	}
}

// post-submit callback 
function showResponse(responseText, statusText, xhr, $form)  { 
	return;
    // for normal html responses, the first argument to the success callback 
    // is the XMLHttpRequest object's responseText property 
 
    // if the ajaxForm method was passed an Options Object with the dataType 
    // property set to 'xml' then the first argument to the success callback 
    // is the XMLHttpRequest object's responseXML property 
 
    // if the ajaxForm method was passed an Options Object with the dataType 
    // property set to 'json' then the first argument to the success callback 
    // is the json data object returned by the server 
 
    alert('status: ' + statusText + '\n\nresponseText: \n' + responseText + 
        '\n\nThe output div should have already been updated with the responseText.'); 
} 
