	
	
	/********** utilitarios *************/
	//gera dias existente num mes
	function getMonthDays(m,y)
	{
		if (m == 4 || m == 6 || m == 9 || m == 11)
			return 30;
		if (m == 2)
			return ((y%4 == 0 && y%100 != 0) || y%400 == 0)? 29 : 28;
		return 31;
	}
	//retorna objecto data
	function clearDate(str,c)
	{
		var val = String(str).split(c);
		var tmpDate = new Date(Number(val[2]),(Number(val[1])-1),Number(val[0]),0,0,0);
		return tmpDate;
	}

	Array.prototype.exist = Array_exist;
	function Array_exist()
	{
		for (var i = 0; i < this.length; i++)
			if (Array_exist.arguments[0].getTime() == this[i].getTime())
				return true;
		return false;
	}

	/********** Construcao calendario *************/
	//retorna um calendario
	function buildCalendar(startD, endD, periods,popId,stitle,today,depatureDates)
	{
		var weekDays = new Array("D","S","T","Q","Q","S","S");
		var months = new Array("Janeiro","Fevereiro","Mar&#231;o","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro");
		var i,d,m,thisyear,lastyear,thisMonth,firstDay,lastDay,wd = 0;
		
		
		
		//Criar Datas
		var startDate = new Date(startD);
		startDate.setDate(1);
		var endDate = new Date(endD);
		endDate.setDate(1);
		
		//Cria a tabela
		var myCal = document.createElement("table");
		var myCalTable = document.createElement("table");
		
				
		with (myCal)
		{
			cellPadding = 0;
			cellSpacing = 0;
			
			border = 0;
			id = "vacationMap";

			//Constroi os meses do calendario
			m = 0;
			lastYear = startDate.getFullYear();
			
		while (startDate <= endDate)
			{
				d = 1;
				thisMonth = startDate.getMonth();
				thisyear = startDate.getFullYear();
				firstDay = startDate.getDay()+1;
				lastDay = getMonthDays(startDate.getMonth()+1,startDate.getFullYear());
	            var tds = lastDay;
	      
	            insertRow(m);
				with (rows[m])
				{
				
				      insertRow(m);
				with (rows[m])
				{
			        insertCell(0);
			         with (cells[0])
					 {
					     colSpan = tds;
		               	 className = "mths";                       
	                     innerHTML = months[thisMonth]+":"+"&#160;";
	                 }
	            }
	      
	            m++;
				
				
				
				
				insertRow(m);
				with(rows[m])
				{
				    insertCell(0);
				    
				    with(cells[0])
				    {
				        var newTable = document.createElement("table");
				        
				        with(newTable)
				        {
				            cellPadding = 1;
			                cellSpacing = 2;
                			align="left";
			               
				            border =  1;
				            insertRow(0);
				            
				            with(rows[0])
				            {
				                for (i = 0; i < tds; i++)
					            {
						            insertCell(i);
            		
						            with (cells[i])
						            {
            						   
            						  
                                                                             
                                       if(document.all)
                                        style.font="7px;"
                                       else
                                        style.fontSize = "8px";
                                      
                                       style.textDecoration="none";
                   				            if (i >= 0 && d <= lastDay){
									            returnDay(cells[i],d,thisMonth,thisyear,periods,today,depatureDates,popId);
									            d++;
								            }
							            else
									               innerHTML = "";
            									  
							            }
            							
							            //Nota fim do mes!!
            						
					            }
				            
				            }
				        }
				        
				        var auxHTML = "";
				        //alert(newTable.innerHTML );
				        if(!document.all)
				        auxHTML = "<table>" + newTable.innerHTML + "</table>";
				        
				        
				        if(document.all)
				            cells[0].innerHTML = newTable.outerHTML;
				        else
				            cells[0].innerHTML = auxHTML;
				    }
				    
					
				}	  	  
					
					//mudança de ano
					if (lastYear != thisyear)
						lastYear = thisyear;
				}
				m++;
				startDate.setMonth(thisMonth+1);
	
			}


			//legendas			
			insertRow(m);
			with (rows[m++])
			{
				
				appendChild(buildLegend(tds,periods));
			}
			
			//fechar janela
			insertRow(m);
			with (rows[m])
			{
				insertCell(0);
				with (cells[0])
				{
					colSpan = tds;
					className = "closeButton";
//					innerHTML = String("Fechar").link("javascript:killMenu('"+popId+"')");
				}
			}
			
		}
		return myCal;
		//document.body.appendChild(myCal)
	}
	
	// constroi o dia
	function returnDay(obj,d,m,y,periods,today,depatureDates,popId){
		var mydate = new Date(y,m,d,0,0,0);
		var today = new Date(today[2],today[1],today[0],0,0,0);
		
		var s,e,theLink;
		var found = false;
		for (var i = 0; i < periods.length; i++)
		{
			s = new clearDate(periods[i].start,"/");
			e = new clearDate(periods[i].end,"/");
			
			//alert(periods[0].color);

			if (s <= mydate && mydate <= e && mydate > today)
			{
				found = true;
				with (obj)
				{
					theLink = "javascript:top.location = 'VacationsDetailPeriod.aspx"+ periods[i].key +"'";
					
                    					
					className = periods[i].color;
						
						var periodNumber = periods[i].key;
						periodNumber = periodNumber.split("&",1);
						periodNumber = periodNumber[0].split("=");
					    id = periodNumber[1];
            						  
					
					if (depatureDates != null)
					{
						if (depatureDates.exist(mydate))
						{
						    className = periods[i].color;
							innerHTML = String(d).fontcolor("black").link("javascript:setDateOnCombo("+ periods[i].key +",'"+mydate+"')");
							style.cursor = "pointer";
						}
						else
						{
							if (mydate.getDay() == 0 || mydate.getDay() == 6)
								innerHTML = String(d);
							else
								innerHTML = String(d);
							style.cursor = "default";
						}
					}
					else
					{
						if (mydate.getDay() == 0 || mydate.getDay() == 6)
							//innerHTML = String(d).link(theLink).bold();
							innerHTML = String(d);
						else
							innerHTML = String(d);
							
						style.cursor = "pointer";
						if(document.all)
						    onclick = "ChangeTdColors('"+id+"','"+popId+"','"+periods[i].start+"','"+periods[i].end+"','"+periods[i].price+"')";
						else
						    setAttribute("onclick","ChangeTdColors('"+id+"','"+popId+"','"+periods[i].start+"','"+periods[i].end+"','"+periods[i].price+"')");
					}
					title = periods[i].price;
				}
			}
			
		}
		if (found == false)
		{
			//Se fim de semana
			if (mydate.getDay() == 0 || mydate.getDay() == 6)
				obj.className = "wkD";
			obj.innerHTML = d;
		}
	}

	function checkLastColor(arr, str)
	{
		for (var i = 0; i < arr.length; i++)
			if (arr[i] == str)
				return false;
		return true;
	}

	//contrucao da legenda
	function buildLegend(rows,periods){
		var max = 5; //numero maximo de legendas por fila
		var text = "Desde:"; //texto da legenda
		var prds = new Array();
		for (var i = 0; i < periods.length; i++)
			prds[i] = periods[i];

		prds.sort(compareDate);

		//constroi tabela de legendas		
		var leg = document.createElement("table");
		with (leg)
		{
			id = "legends";
			cellPadding = 0;
			cellSpacing = 2;
			//border = 1;
			width = "100%";

			//texto da legenda
			insertRow(0);
			with (rows[0])
			{
				insertCell(0);
				with (cells[0])
				{
					colSpan = (max*2);
					className = "textLegend";
					innerHTML = text;
					width = "100%";
				}
				
			}

			var rowCount = 1;
			var tdCount = 0;
			var lastColor = new Array();
			prds = prds.sort(comparePrice);
			for (i = 0; i < prds.length; i++)
			{
				if (checkLastColor(lastColor,prds[i].color))
				{
					lastColor[lastColor.length] = prds[i].color;
				
					if (tdCount == 0) //abre a tr
						insertRow(rowCount);

					with (rows[rowCount]) //constroi legendas
					{
						//cria a legenda da cor
						insertCell(tdCount);
						with (cells[tdCount++])
						{
							style.fontSize = "1px";
							width = 10;
							height = 10;
							className = prds[i].color;
							innerHTML = "&#160;";
						}
						
						//cria a legenda do preco
						insertCell(tdCount);
						with (cells[tdCount++])
						{
							width = 10;
							height = 10;
							align = "left";
							className = "priceLegend";
							innerHTML = prds[i].price;
						}
						
						//preenche o resto da tabela
						if (i+1 == prds.length && tdCount != max*2)
						{
							insertCell(tdCount);
							with (cells[tdCount])
							{
								style.fontSize = "1px";
								colSpan = (max*2) - tdCount;
								width = 10;
								height = 10;
								innerHTML = "&#160;";
							}
						}
					}
					
					if (tdCount == max*2) //fecha a tr
					{
						tdCount = 0;
						rowCount++;
					}
				}
			}
		}
		
		var td = document.createElement("td");
		td.colSpan = rows;
		td.appendChild(leg);
		delete leg;
		
		return td;
	}

	//Ordena por data de inicio
	function compareDate(a, b){
		var x = clearDate(a.start,"/");
		var y = clearDate(b.start,"/");
	
		return (x < y)? -1 : ((x > y)? 1 : 0);
	}
	
	

	/********** Objectos Contrutores *************/

	//Para cada periodo
	function period(key,start,end,price){
		this.key = key;
		this.start = start;
		this.end = end;
		this.price = price;
		this.color;
		this.setColor = peridod_setColor;
	}
	
	function peridod_setColor(str){
		this.color = str;
	}

	//Para cada viagem
	var openedMenus = new Array(); //pilha de menus abertos
	
	function trip(xid,title,today,pos){
		this.id = xid;
		this.title = title;
		this.periods = new Array();
		this.today = today.split(",");
		this.draw = trip_draw;
		this.depatureDates = null;		
	    
	}
	
	trip.prototype.setDepartureDays = trip_setDepartureDays;
	function trip_setDepartureDays()
	{
		if (this.depatureDates == null)
			this.depatureDates = new Array();
		this.depatureDates[this.depatureDates.length] = clearDate(trip_setDepartureDays.arguments[0],'/');
	}
	
	function trip_draw(){	    
		var popId = "pop" + this.id; //gera id para o menu		
		
		
		//verifica se jah esta aberto
		var isItOPened = false;
		for (var i = 0; i < openedMenus.length; i++)
			if (popId == openedMenus[i])
				isItOPened = true;
				
		if (isItOPened)
			return killMenu(popId);
	
		//variaveis para datas
		var start = clearDate(this.periods[0].start,"/");
		var end = clearDate(this.periods[0].end,"/");
		
		var s,e;
		
		//variaveis para precos
		var price = 0;
		var clr = 0;
		
		//orderna por preco
		this.periods = this.periods.sort(comparePrice);
	
	    
		for (i = 0; i < this.periods.length; i++)
		{
			//procura as datas de inicio e fim
			s = new clearDate(this.periods[i].start,"/");
			e = new clearDate(this.periods[i].end,"/");
			
			if (s < start)
				start = s;
			if (e > end)
				end = e;
			
			//atribuição de cores por preço
			
			if (getPrice(this.periods[i].price) > price)
			{
				price = getPrice(this.periods[i].price);
				clr++;
			}			
			this.periods[i].setColor("pColor" + clr);
		}
		
		/*
		var str1 = "";
		var str2 = "";
		for (var i = 0; i < this.periods.length; i++){
			str1 += i+ ") "+ getPrice(this.periods[i].price) +"\n";
			str2 += i+ ") "+ this.periods[i].color +"\n";
		}
		
		alert(
			"Prices:\n"+
			str1+
			"\nColors:\n"+
			str2
		);
		*/
		
		if (Number(start.getFullYear()) < Number(this.today[2])){
			start.setFullYear(Number(this.today[2]));
			start.setMonth(0);
		}
		if (Number(start.getFullYear()) == Number(this.today[2])){
			start.setMonth(Number(this.today[1]));
		}
		if (this.depatureDates != null)
		{
			var startDPD = this.depatureDates[0];
			if (Number(start.getMonth()) < Number(startDPD.getMonth())
			 && Number(start.getFullYear()) == Number(startDPD.getFullYear()))
			{
				start.setMonth(Number(startDPD.getMonth()));
			}
		}

		//construir popup
		var cal = new buildCalendar(start, end, this.periods,popId,this.title,this.today,this.depatureDates);
		var pr = 240;
		if (this.depatureDates != null)
			pr = -50;
		var pCal = new popUp(cal,popId,-35,pr);
		delete cal;
		openedMenus[openedMenus.length] = popId;
		pCal.go();
		
	}
	//para ordenar por preco
	function comparePrice(a, b){
		var x = getPrice(a.price);
		var y = getPrice(b.price);
	
		return (x < y)? -1 : ((x > y)? 1 : 0);
	}
	//repara valor de preco	
	function getPrice(str){
		var number = String(str).replace(/[^$A-Za-z0-9+(?!\,)]/gi,'');
		number = new Number(number.replace(/,/gi,'.'));
		return number;

		//return Number(String(String(str).split("€")[0]).replace(/\,/gi,"."));
	}
	
	/********** Objecto Popup ;-) *************/
	//Memoria dos valores totais
	function animVars(x,y,o,sp)
	{
		this.totalX = x;
		this.totalY = y;
		this.totalOP = o;
		this.lastOP = 0;
		this.speed = sp;
		this.setOP = animVars_setOP;
	}
	
	function animVars_setOP(o){
		this.lastOP = o;
	}
	
	//Objecto da popup
	function popUp(content,id,pushDown,pushRight,padding)
	{
		this.content = content;
		this.id = id;
		this.yDown = (Boolean(pushDown))? pushDown : 0;
		this.xRight = (Boolean(pushRight))? pushRight : 0;
		this.pad = (Boolean(padding))? padding : 10;
		this.go = popUp_go;		
		
	}
	
	var tempAnim, anime;
	var selectUnderDiv = new Array();
	
	function popUp_go()
	{
		var speed = 10; //velocidade da animacao

		var div = document.createElement("div");
		with (div)
		{
			id = this.id;
		    className = "test";
			with (style)
			{   
				top = 0;
				left = 0;
				visibility = "";
				//border="1px solid black";
				
			}
			appendChild(this.content);
		}
		
		document.getElementById("tdPeriod_"+this.id).appendChild(div);
	     
		//document.body.appendChild(div);
	}
	
	function clearPx(s){
		return Number(String(s).split("px")[0]);
	}
	
	
	function makeItAlive(obj,anim,close)
	{
		var op = 0;
		var dir = (Boolean(close)? -1 : 1);
		
		if (obj.clientWidth < anim.totalX || obj.clientHeight < anim.totalY || anim.lastOP <= anim.totalOP)
		{
			with (obj.style)
			{
				if (obj.clientWidth < anim.totalX)
					width = clearPx(width) + (parseInt(anim.totalX/anim.speed) * dir);
				if (obj.clientHeight < anim.totalY)	
					height = clearPx(height) + (parseInt(anim.totalX/anim.speed) * dir);
				if (anim.lastOP <= anim.totalOP)
				{
					anim.setOP(anim.lastOP + (parseInt(anim.totalOP/anim.speed) * dir));
					filter = "progid:DXImageTransform.Microsoft.Alpha(Opacity="+ anim.lastOP +", Style=0)";
				}
			}
		}
		else
		{
			//with (obj.style)
				//filter = "progid:DXImageTransform.Microsoft.Alpha(Opacity=100, Style=0)";
				//filter = "progid:DXImageTransform.Microsoft.dropshadow(OffX=5, OffY=5, Color='steelblue', Positive='true')";
			
			with (obj.childNodes.item(0).style)
				visibility = "visible";
		
			window.clearInterval(tempAnim);
		}
	}
	
	function killMenu(popId){
		for (var i = 0; i < openedMenus.length; i++)
			if (popId == openedMenus[i])
				openedMenus.pop(i);

		for (var x = 0; x < selectUnderDiv.length; x++)
			//selectUnderDiv[x].style.visibility = "visible";

		//document.body.removeChild(document.getElementById(popId));
		document.getElementById("tdPeriod_" + this.id).removeChild(document.getElementById(popId));
		window.clearInterval(tempAnim);
	}
	
	function setDateOnCombo(cmb,dt)
	{
		var tmp,dt = new Date(dt);
	
		for (var i = 0; i < cmb.options.length; i++)
		{
			tmp = clearDate(cmb.options[i].value,"/");
			if (dt.getTime() == tmp.getTime())
			{
				cmb.options[i].selected = true;
		    }
		}
		
		killMenu("popnvHoliday");
	}
	
	
	
	
	function ChangeTdColors(index,popId,start,end,price)
	{	
	
	var formName = "Period_"+popId;	
	//alert(index);
	 var x=document.getElementsByTagName("TD");
	 
		for(i = 1 ; i < x.length; i++)
	    {  
	        if(x[i].id == index)
	        {
    	        x[i].style.color= "White";
    	 
    	    }
	        else
	            x[i].style.color= "black";
	    }
	
	    //if(document.all)
	       document.getElementById(formName).value= index;
	    //else
	    //    document.getElementsByName(formName)[0].value= index;
	    if(!document.all)
	    {
	        var allShow = document.getElementsByName("showselectedDivs");
    	    
	        for(var i = 0;  i < allShow.length; i++)
	            allShow[i].innerHTML = "";
	    }
	    else
	    {
	        var i = 1;
	        while(true)
	        {
	            var elem = document.getElementById("popnvHoliday"+i+"_showselected");
	            
	            if(elem != null)
	            {
	                elem.innerHTML = "";
	                i++;
	            }
	            else
	                break;
	        }
	    }
	    
	    
	    var show = document.getElementById(popId+"_showselected");
	    
	    if(show !=null)
	    {
	        show.innerHTML = "Periodo seleccionado<br/>de " + start + " a " + end + "<br/><br/><b>Desde: " + price+"</b>";
	    }
	}
	
