var GSTrip = {
	LastTimerID: -1,
	Containements: null,
	OriginalGroup: null,
	DayObjects: null,
	DeleteCurrentLi:null,
	DeleteCurrentDay:-1,
	Initialize:function(){
		this.DayObjects=new Array();
	},
	InitializeGroup: function(objid){
		this.OriginalGroup=$(objid).cloneNode(true);
	},
	InitializeDay: function(dayIndex,objid){
		this.DayObjects[dayIndex]=$(objid);
	},
	ItemDeleteConfirm: function(o){
		this.DeleteCurrentLi=this.ParentLINode(o);
		var d=$('panel_delete');
		var s=JsLib.Positioner.GetElementSize(o);
		var p=JsLib.Positioner.GetAbsolutePos(o);
		d.style.top=(p.y-36)+'px';
		d.style.left=(p.x+11)+'px';
		d.style.display='block';
		return false;
	},
	ItemDelete: function(){
		var d=$('panel_delete');
		d.style.display='none';
		var li=this.DeleteCurrentLi;
		var ul=li.parentNode;
		switch(this.ULNodeType(li)){
			case 'Day':
				li.parentNode.removeChild(li);
				this.UpdateDay(-1);
				break;
			case 'Group':
				ItineraryDeleteBookmark(li.attributes['ObjectSiloSectionID'].value, li.attributes['ObjectID'].value);
				break;
		}
	},
	DeleteDayConfirm: function(o,dayIndex){
		var panel=$('panel_delete_day');
		var p1=JsLib.Positioner.GetAbsolutePos($(o));
		var p2=JsLib.Positioner.GetElementSize($(o));
		panel.style.height=(JsLib.Positioner.GetElementSize($('ctl00_MyMTL_ctrEditSchedule_td_D1')).y-47)+'px';
		panel.style.width=(p2.x)+'px';
		panel.style.left=p1.x+'px';
		panel.style.top=(p1.y+30)+'px';
		panel.style.display='block';
		this.DeleteCurrentDay=dayIndex;
	},
	DeleteDay:function(){
		ItineraryDeleteDay(this.DeleteCurrentDay);
		$('panel_delete_day').style.display='none';
	},
	ParentLINode:function(obj){
		var o=obj;
		for(;;o=o.parentNode){
			if(o.tagName.toLowerCase()=='li'){	
				return o;
			}
		}
		return null;
	},
	ULNodeType:function(obj){
		var o=obj;
		for(;;o=o.parentNode){
			if(o.attributes['ChildType']!=null)
				return o.attributes['ChildType'].value;
		}
		return null;
	},
	BookmarkDetails: function(o,oId,fromBookmark){
		var li=this.ParentLINode(o);
		this.DeleteCurrentLi=li;
		var objectType=this.ULNodeType(li);
		var siloSectionID=li.attributes['ObjectSiloSectionID'].value;
		var objectID=li.attributes['ObjectID'].value;
		var objectGuid=li.attributes['ObjectGuid'].value;
		var url='/GoogleMapWindows/BookmarkDetail.aspx?type='+objectType+'&guid='+objectGuid+'&id='+objectID+'&silosectionid='+siloSectionID+'&langid='+currentLanguageId+'&k='+new Date().getTime();
		var html=JsLib.Ajax.LoadTEXT(url);
		var div=$('bookmark_details');
		if(null==div){
			div=document.createElement('div');
			div.id='bookmark_details';
			div.style.position='absolute';
			document.body.appendChild(div);
		}
		div.style.top='200px';
		div.style.left=((JsLib.Positioner.GetElementSize(document.body).x-430)/2)+'px';
		div.style.display='block';
		div.innerHTML=html;
		new Draggable('bookmark_details',{scroll:window,handle:'drag',revert:true,starteffect:null,endeffect:null});
		return false;
	},
	BookmarkDetailsClose: function(){
		$('bookmark_details').style.display='none';
	},
	SaveNote:function(objectGuid){
		var note=$('txt_note').value;
		if(note.length>250){
			$('txt_note').focus();
			$('div_note_length').style.display='block';
			window.setTimeout('$(\'div_note_length\').style.display=\'none\';',2500);
		}else{
			ItineraryUpdateNote(objectGuid,$('txt_note').value);
			$('div_note_saved').style.display='block';
			window.setTimeout('$(\'div_note_saved\').style.display=\'none\';',2500);
		}
	},
	UpdateDay:function(dayIndex){
		for(var i=0;i<(dayIndex+1);i++){
			this.DayObjects[i].parentNode.className='day';
		}
		
		if(this.LastTimerID==-1){
			this.LastTimerID=window.setTimeout('GSTrip.UpdateDayDelay('+dayIndex+')',250);
		}
	},
	UpdateDayDelay:function(dayIndex){
		if(-1!=dayIndex){
			var currentDay=$('Day'+dayIndex);
			for(var i=0;i<currentDay.childNodes.length;i++){
				if(currentDay.childNodes[i].attributes['IsTripPlan'].value=='true'){
					GSTrip.LastTimerID=-1;
					window.setTimeout('ItineraryMergeGroup(\''+currentDay.childNodes[i].attributes['ObjectID'].value+'\','+dayIndex+')',1);
					return;
				}
			}
		}
		var guids=new Array();var objectids=new Array();
		var silosectionids=new Array();var days=new Array();
		var li,cmpt=0;
		var joined;
		var maxItemsCount=0;
		for(var i=0;i<5;i++){
			guids=new Array();
			objectids=new Array();
			silosectionids=new Array();
			var ul=$('Day'+i);
			
			if(ul.childNodes.length>maxItemsCount)
				maxItemsCount=ul.childNodes.length;

			for(var j=0;j<ul.childNodes.length;j++){
				li=ul.childNodes[j];
				guids[j]=li.attributes['ObjectGuid'].value;
				objectids[j]=li.attributes['ObjectID'].value;
				silosectionids[j]=li.attributes['ObjectSiloSectionID'].value;
			}
			if(guids.length>0){
				joined=i+'@'+guids.join('&')+'@'+objectids.join('&')+'@'+silosectionids.join('&')
				if(joined.trim()!=''){
					days[cmpt]=joined;
					cmpt++;
				}
			}
		}
		ItineraryUpdateDay(days.join('+'));
		window.setTimeout('GSTrip.LastTimerID=-1;',250);
		
		var height=maxItemsCount*27;
		if(height<108)
			height=108;
		
		$('Day0').style.height=height+'px';
		$('Day1').style.height=height+'px';
		$('Day2').style.height=height+'px';
		$('Day3').style.height=height+'px';
		$('Day4').style.height=height+'px';
	},
	UpdateGroup:function(element){
//		window.setTimeout('GSTrip.UpdateGroupDelay(\''+element.id+'\')',50);
		
		// just a hack ...
		var id = "drag_container";
		window.setTimeout('GSTrip.UpdateGroupDelay(\''+id+'\')',50);
	},
	UpdateGroupDelay: function(elementid){
		var element=$(elementid);
		Sortable.destroy(elementid);
		while(element.childNodes.length>0){
			element.removeChild(element.childNodes[0]);
		}
		var clone;
		var original=this.OriginalGroup.cloneNode(true);
		for(var j=0; j<original.childNodes.length;j++){
			clone=original.childNodes[j].cloneNode(true);
			element.appendChild(clone);
		}
		var xx=new Date().getTime();
		eval('GroupCreateGroup()');
//		createDay();
		makeSortable();
	/*
		DayCreateDay0();
		DayCreateDay1();
		DayCreateDay2();
		DayCreateDay3();
		DayCreateDay4();
	*/
	},
	CountChildLiNodes: function(ul){
		var count=0;
		for(var y=0;y<ul.childNodes.length;y++){
			if(ul.childNodes[y].tagName=='LI'){
				count++
			}
		}
		return count;
	},
	Debug: function(string){
		$('debug_itinerary').innerHTML+=string+'<br/>';
	},
	DebugClear:function(){
		$('debug_itinerary').innerHTML='';
	}
}

//other utils
	function searchPlace(id){
		var q = $(id+'-input').value;
		if (q == ''){
			alert('Plase type the place name...');
			return false;
		}
		$(id+'-autoselection').hide();
		$(id+'-results').hide();
		$(id+'-loading').style.display ="";
		$(id+'-placeID').value = "";
		var resultsContent = "";
		var showResults = false;
		var autoSelectionContent = "";
		var res =  GSJSLib.Ajax.LoadTEXT("/PlaceJSONString.action?q="+q);
		if (res == 'FAILURE'){
			autoSelectionContent = 'There was an error while retrieving the data from the server. Please try again.';
			$(id+'-autoselection').innerHTML = autoSelectionContent;
			Effect.Appear(id+'-autoselection', {duration : 0.3, from:0.5});
			return;
		}
		var jsonObj = eval('('+res+')'); //JSON.parse(res);
		if (jsonObj.length == 0){
			autoSelectionContent = 'We did not find any match for the place you have typed. Please try again.<div class="padt5 medium">If the place you are looking for is very small, please try bigger city or town nearby. </div>';
		}else{
			resultsContent = '<div class="medium">Click on the place link below to select the place. You can also verify the place on map.</div><ol>';
			var query = q;
			if (q.indexOf(',') != -1){
				query = q.substring(0,q.indexOf(','));
			}
			var nearby;
			var population;

			if (jsonObj[0]["placeName"].toLowerCase() == query.toLowerCase()){
				$(id+'-input').value = jsonObj[0]["placeName"] + ', ' + jsonObj[0]["country"];
				$(id+'-placeID').value = jsonObj[0]["geoPlaceID"];
				autoSelectionContent = 'We understand that its <a href="javascript:void(0);" class="link" title="View on map" onClick="showMap('+jsonObj[0]["latitude"]+','+jsonObj[0]["longitude"]+',\''+jsonObj[0]["placeName"] + ', ' + jsonObj[0]["country"]+'\')">'+jsonObj[0]["placeName"]+', '+jsonObj[0]["country"]+'</a>';
				
				population = jsonObj[0]["population"];
				if (population < 1000000 || population == null || population =='')
				{
					nearby = jsonObj[0]["nearByPlaces"];
					if (nearby != null && nearby != '')
					{
						autoSelectionContent += ' near '+ nearby +'';
					}
				}		
				
				if (jsonObj.length > 1){
					autoSelectionContent += '. We found total '+jsonObj.length+' results, <a href="javascript:void(0);" class="link" onclick="Effect.BlindDown(\''+id+'-results\');">view them</a>';
				}
			}else{
				autoSelectionContent = 'We did not understand the place you are looking for. We found total '+jsonObj.length+' results, select one from below.';
				showResults = true;
			}
	
			for (var i = 0;i < jsonObj.length; i++ )
			{
				var fullPlaceName = jsonObj[i]["placeName"] + ', ' + jsonObj[i]["country"];
				resultsContent += '<li class="medium"><a href="javascript:void(0);" class="link medium" title="Select '+fullPlaceName+'" onclick="selectPlace(\''+id+'\',\''+jsonObj[i]["geoPlaceID"]+'\',\''+fullPlaceName+'\');">'+fullPlaceName+'</a> ';
	
				population = jsonObj[i]["population"];
				if (population < 1000000 || population == null || population =='')
				{
					nearby = jsonObj[i]["nearByPlaces"];
					if (nearby != null && nearby != '')
					{
						resultsContent += 'Near '+ nearby +' ';
					}
				}
	
				resultsContent += '- <a href="javascript:void(0);" class="link medium" title="Verify '+fullPlaceName+' on map" onClick="showMap('+jsonObj[i]["latitude"]+','+jsonObj[i]["longitude"]+',\''+fullPlaceName+'\')">view on map</a></li>';
			}
			
			if (showResults){
				resultsContent += '</ol><div class="padt5 medium">If the place you are looking for is very small, please try bigger city or town nearby.</div>';
			}else{
				resultsContent += '</ol><div class="padt5 medium">If the place you are looking for is very small, please try bigger city or town nearby. <a href="javascript:void(0);" onclick="Effect.BlindUp(\''+id+'-results\');" title="Hide results" class="link medium">Hide</a></div>';
			}
		}
		$(id+'-autoselection').innerHTML = autoSelectionContent;
		$(id+'-results').innerHTML = resultsContent;
		if (autoSelectionContent != ''){
			Effect.Appear(id+'-autoselection', {duration : 0.3, from:0.5});
		}
		if (showResults){
			Effect.Appear(id+'-results', {duration : 0.3, from:0.5});
		}
		$(id+'-loading').style.display ="none";
	}
	
	function selectPlace(id,placeID,placeName){
		$(id+'-input').value = placeName;
		$(id+'-placeID').value = placeID;
		$(id+'-autoselection').hide();
		$(id+'-results').hide();
	}
	
	/* for searching place */
	function handleEnterKey(e,id){
		var key = e.keyCode || e.which ;
		if (key==13){
			e.returnValue=false;
			e.cancel = true;
			e.cancelBubble = true;
			if (e && e.preventDefault)
			    e.preventDefault();
			searchPlace(id);
		}
	}
	
	function checkPlaceInput(id){
		if ($(id+'-input').value.length > 2){
			searchPlace(id);
		}
	}
	
