$(document).ready(function(){
	/* The following code is executed once the DOM is loaded */

	// A global variable, holding a jQuery object 
	// containing the current todo item:
	
	var currentTODO;
	
	// Configuring the delete confirmation dialog
	$("#dialog-confirm").dialog({
		resizable: false,
		height:130,
		modal: true,
		autoOpen:false,
		buttons: {
			'Delete item': function() {
			var id = currentTODO.data('id');
			$.ajax({
				  url: "/cfpages/xml/iglu_data.cfc",
				  cache: false,
				  dataType: 'html',
				  data: { method: "deleteAlert",
							alertID:id},
				  success: function(data) {	
				  		currentTODO.fadeOut('fast');
							}
				});		
				/*
				$.get("ajax.php",{"action":"delete","id":currentTODO.data('id')},function(msg){
					currentTODO.fadeOut('fast');
				})*/
				
				$(this).dialog('close');
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		}
	});
	
	
	
	
	$("#dialog-form").dialog({
			autoOpen: false,
			height: 300,
			width: 350,
			modal: true,
			buttons: {
				
			'New alert': function() {
				
			var newurl=doSearch({theaction:'createurl'});	
				
			$.ajax({
				  url: "/cfpages/xml/iglu_data.cfc",
				  cache: false,
				  dataType: 'html',
				  data: { method: "saveAlert",						  
						  alertTitle:$("#name").val(),
						  QueryString:newurl
							},
				  success: function(data) {	
				  		
						updateAlerts();
						
						
						
							}
				});						
				
				$(this).dialog('close');
				},
				Cancel: function() {
					$(this).dialog('close');
				}
			},
			close: function() {
				
			}
		});
		
	
	
	

	// When a double click occurs, just simulate a click on the edit button:
	$('.todo').live('dblclick',function(){
		$(this).find('a.edit').click();
	});
	
	// If any link in the todo is clicked, assign
	// the todo item to the currentTODO variable for later use.

	$('.todo a').live('click',function(e){
									   
		currentTODO = $(this).closest('.todo');
		currentTODO.data('id',currentTODO.attr('id').replace('todo-',''));
		
		e.preventDefault();
	});




	$('.todo a.run').live('click',function(e){
									   
		currentTODO = $(this).closest('.todo');
		currentTODO.data('id',currentTODO.attr('id').replace('todo-',''));
		
		e.preventDefault();
		
		
		var id = currentTODO.data('id');

		$.ajax({
			  url: "/cfpages/xml/iglu_data.cfc",
			  cache: false,
			  dataType: 'html',
			  data: { method: "retrieveAlert",
			  			alertID:id},
			  success: function(data) {					  									  						
						setsearchform(data);
						}
			});	

	});
	// Listening for a click on a delete button:

	$('.todo a.delete').live('click',function(){
		$("#dialog-confirm").dialog('open');
	});
	
	// Listening for a click on a edit button
	
	$('.todo a.edit').live('click',function(){

		var container = currentTODO.find('.text');
		if(!currentTODO.data('origText'))
		{
			// Saving the current value of the ToDo so we can
			// restore it later if the user discards the changes:
			currentTODO.data('origText',container.text());
		}
		else
		{
			// This will block the edit button if the edit box is already open:
			return false;
		}
		$('<input type="text">').val(container.text()).appendTo(container.empty());
		
		



		var container = currentTODO.find('.checkbox');		
		if(!currentTODO.data('origCheckbox'))
		{
			currentTODO.data('origCheckbox',container.text());
		}
		else
		{
			return false;
		}
		
		if (container.text() == 'Active') {
			$('<input type="checkbox" checked value="1">').appendTo(container.empty());
		} else {
			$('<input type="checkbox" value="1">').appendTo(container.empty());
		}
		
		

		
		
		// Appending the save and cancel links:
		container.append(
			'<div class="editTodo">'+
				'<a class="saveChanges" href="#">Save</a> or <a class="discardChanges" href="#">Cancel</a>'+
			'</div>'
		);
		
	});
	
	// The cancel edit link:
	
	$('.todo a.discardChanges').live('click',function(){
		currentTODO.find('.text')
					.text(currentTODO.data('origText'))
					.end()
					.removeData('origText');
		currentTODO.find('.checkbox')
					.text(currentTODO.data('origCheckbox'))
					.end()
					.removeData('origCheckbox');					
	});
	
	// The save changes link:
	
	
	
	$('#savenewalert').live('click',function(){
		$("#dialog-form").dialog('open');
		
	});
	
	
	
	$('.todo a.saveChanges').live('click',function(){
		var text = currentTODO.find("input[type=text]").val();
		
		if (currentTODO.find("input[type=checkbox]:checked").val() > 0) {
			var checkbox = 1 ;
			var checktext='<span class="active">Active</span>';
		} else {
			var checkbox = 0;
			var checktext='<span class="inactive">Not Active</span>';
		};
		
		var id = currentTODO.data('id');
		
		$.ajax({
			  url: "/cfpages/xml/iglu_data.cfc",
			  cache: false,
			  dataType: 'html',
			  data: { method: "saveAlert",
			  			alertID:id,
						alertTitle:text,
						alertActive:checkbox},
			  success: function(data) {					  									  
						}
			});		
		
		currentTODO.removeData('origText')
					.find(".text")
					.text(text);
					
		currentTODO.removeData('origCheckbox')
					.find(".checkbox")
					.html(checktext);					
					
	});
	
	
	// The Add New ToDo button:
	
	var timestamp=0;
	$('#addButton').click(function(e){

		// Only one todo per 5 seconds is allowed:
		if((new Date()).getTime() - timestamp<5000) return false;
		
		$.get("ajax.php",{'action':'new','text':'New Todo Item. Doubleclick to Edit.','rand':Math.random()},function(msg){

			// Appending the new todo and fading it into view:
			$(msg).hide().appendTo('.todoList').fadeIn();
		});

		// Updating the timestamp:
		timestamp = (new Date()).getTime();
		
		e.preventDefault();
	});
	
	
}); // Closing $(document).ready()




			function updateAlerts() {
				$.ajax({
                  url: "/cfpages/xml/iglu_data.cfc",
				  cache: false,
				  dataType: 'html',
                  data: { method: "showAlerts"},
                  success: function(data) {					  									  
					  			$('#myalerts').html(data).fadeIn();							  
							}
                });
			}
		   
		   
		   
			function gup( name, thestring )
			{
			  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
			  var regexS = "[\\?&]"+name+"=([^&#]*)";
			  var regex = new RegExp( regexS );
			  var results = regex.exec( thestring );
			  if( results == null )
				return "";
			  else
				return results[1];
			}		   
		   	
			
			
			function saveAlert() {
				
			}
			
			
			function setsearchform(data) {
				
				var outputStyle=gup('outputstyle',data);
				var vcountryid=gup('country',data);
				if (isNaN(vcountryid)==true) {vcountryid=0};
				var vfrom=gup('from',data);
				var vdaterange=gup('daterange',data);
				var vPriceRange=gup('pricerange',data);
				var vRatingno=gup('ratingno',data);
				var vAirport=gup('airport',data);
				var curTrees=gup('trees',data);
				var curOffpiste=gup('offpiste',data);
				var curPark=gup('park',data);
				var curHalfpipe=gup('halfpipe',data);
				var curNightriding=gup('nightriding',data);
				var curFreeridePer=gup('freerideper',data);
				var curFreestylePer=gup('freestyleper',data);
				var curPistePer=gup('pisteper',data);
				var curResorts=gup('resorts',data);

				getResults(outputStyle,
								vcountryid,
								vfrom,
								vdaterange,
								vPriceRange,
								vRatingno,
								vAirport,
								curTrees,
								curOffpiste,
								curPark,
								curHalfpipe,
								curNightriding,
								curFreeridePer,
								curFreestylePer,
								curPistePer,
								curResorts)				
				
           		return false;
			}
			
			
			function doSearch(theaction)
            {	
				theaction = typeof(theaction) != 'undefined' ? theaction : 'result';

				
				selIndex=document.getElementById("outputstyle").selectedIndex;
				outputStyle=document.getElementById("outputstyle").options[selIndex].value;	
				
				selIndex=document.getElementById("country").selectedIndex;
				vcountryid=document.getElementById("country").options[selIndex].value;				
				
				vfrom=document.getElementById("from").value;	
				
				selIndex=document.getElementById("daterange").selectedIndex;
				vdaterange=document.getElementById("daterange").options[selIndex].value;	

				selIndex=document.getElementById("pricerange").selectedIndex;
				vPriceRange=document.getElementById("pricerange").options[selIndex].value;				
				
				selIndex=document.getElementById("ratingno").selectedIndex;
				vRatingno=document.getElementById("ratingno").options[selIndex].value;				

				selIndex=document.getElementById("airport").selectedIndex;
				vAirport=document.getElementById("airport").options[selIndex].value;				

				selIndex=document.getElementById("trees").selectedIndex;
				curTrees=document.getElementById("trees").options[selIndex].value;				
				
				selIndex=document.getElementById("offpiste").selectedIndex;
				curOffpiste=document.getElementById("offpiste").options[selIndex].value;				

				selIndex=document.getElementById("park").selectedIndex;
				curPark=document.getElementById("park").options[selIndex].value;							

				selIndex=document.getElementById("halfpipe").selectedIndex;
				curHalfpipe=document.getElementById("halfpipe").options[selIndex].value;	

				selIndex=document.getElementById("nightriding").selectedIndex;
				curNightriding=document.getElementById("nightriding").options[selIndex].value;					

				selIndex=document.getElementById("freerideper").selectedIndex;
				curFreeridePer=document.getElementById("freerideper").options[selIndex].value;	

				selIndex=document.getElementById("freestyleper").selectedIndex;
				curFreestylePer=document.getElementById("freestyleper").options[selIndex].value;	

				selIndex=document.getElementById("pisteper").selectedIndex;
				curPistePer=document.getElementById("pisteper").options[selIndex].value;
				
				curResorts = $('.resortpick:checked').map(function () {
				  return this.value;
				}).get().join(",");	
				
				
				if (theaction=='result') {
				
					getResults(outputStyle,
									vcountryid,
									vfrom,
									vdaterange,
									vPriceRange,
									vRatingno,
									vAirport,
									curTrees,
									curOffpiste,
									curPark,
									curHalfpipe,
									curNightriding,
									curFreeridePer,
									curFreestylePer,
									curPistePer,
									curResorts);
					return false;
				
				} else {
					
					return createURL(outputStyle,
									vcountryid,
									vfrom,
									vdaterange,
									vPriceRange,
									vRatingno,
									vAirport,
									curTrees,
									curOffpiste,
									curPark,
									curHalfpipe,
									curNightriding,
									curFreeridePer,
									curFreestylePer,
									curPistePer,
									curResorts);
				}
				
           		
		   };
			
			function createURL(outputStyle,
								vcountryid,
								vfrom,
								vdaterange,
								vPriceRange,
								vRatingno,
								vAirport,
								curTrees,
								curOffpiste,
								curPark,
								curHalfpipe,
								curNightriding,
								curFreeridePer,
								curFreestylePer,
								curPistePer,
								curResorts) {
				
				
				var newurl='?outputStyle=' + outputStyle +
					'&country=' + vcountryid +
					'&from=' + vfrom +
					'&daterange=' + vdaterange +
					'&pricerange=' + vPriceRange +
					'&ratingno=' + vRatingno +
					'&airport=' + vAirport +
					'&trees=' + curTrees +
					'&offpiste=' + curOffpiste +
					'&park=' + curPark +
					'&halfpipe=' + curHalfpipe +
					'&nightriding=' + curNightriding +
					'&freerideper=' + curFreeridePer + 
					'&freestyleper=' + curFreestylePer +
					'&pisteper=' + curPistePer +
					'&resorts=' + curResorts;
					
				 return newurl;
				
				
			 };
			 
			 
			function getResults(outputStyle,
								vcountryid,
								vfrom,
								vdaterange,
								vPriceRange,
								vRatingno,
								vAirport,
								curTrees,
								curOffpiste,
								curPark,
								curHalfpipe,
								curNightriding,
								curFreeridePer,
								curFreestylePer,
								curPistePer,
								curResorts) {


				
				$('#holidayresults').hide();				
				$('#holidayloadingpanel').show();
				$('#sendrequest').attr("disabled",true);
				
                $.ajax({
                  url: "/cfpages/xml/iglu_data.cfc",
				  cache: false,
				  dataType: 'json',
                  data: { method: "getHolidays", 			
                        outputStyle:outputStyle,
					    AirportCountryID:21, 
                        CountryID:vcountryid, 
                        From:vfrom, 
                        daterange:vdaterange, 
                        PriceRange:vPriceRange,
                        Ratingno:vRatingno,
						Airport:vAirport,
						trees:curTrees,
						offpiste:curOffpiste,
						park:curPark,
						halfpipe:curHalfpipe,
						nightriding:curNightriding,
						freerideper:curFreeridePer,
						freestyleper:curFreestylePer,
						pisteper:curPistePer,
						resortID:curResorts},
                  success: function(data) {					  		
							  
							  $('#holidayresults').html(data[0]);
							  $('#holidaysearch').html(data[1]);
							  $('#debugoutput').html(data[2]);
							  
							  if (outputStyle=='table') {
								  updateTable();
							  	  showdate(vdaterange);
							  }
							  $('#holidayloadingpanel').hide();
							  $('#holidayresults').fadeIn();
							  $('#sendrequest').removeAttr("disabled");
                            }
                });

			}
			
			
            function updateTable()
            { 
                $("#holidaygrid")
				.tablesorter({widthFixed: true, widgets: ['zebra']})				
				.tablesorterPager({container: $("#pager")});
				/*.tablesorterFilter({filterContainer: "#filter-box",
                            filterClearContainer: "#filter-clear-button",
                            filterColumns: [0]});*/
		
            } 	
			
			
			function setlinktips() {
 			$('a.resortname').each(function()
			   {
				  $(this).qtip(
				  {
					 content: {
						// Set the text to an image HTML string with the correct src URL to the loading image you want to use
						text: '<img src="/images/extras/ajax-loader.gif" alt="Loading..." />',
						url: '/cfpages/xml/resortsummary.cfm?id=' + $(this).attr('rel'), // Use the rel attribute of each element for the url to load
						title: {
						   text: 'WSG Review - ' + $(this).text(), // Give the tooltip a title using each elements text
						   button: 'Close' // Show a close link in the title
						}
					 },
					 position: {
						corner: {
						   target: 'bottomMiddle', // Position the tooltip above the link
						   tooltip: 'topMiddle'
						},
						adjust: {
						   screen: true // Keep the tooltip on-screen at all times
						}
					 },
					 show: { 
						when: 'click', 
						solo: true // Only show one tooltip at a time
					 },
					 hide: 'unfocus',
					 style: {
						tip: true, // Apply a speech bubble tip to the tooltip at the designated tooltip corner
						border: {
						   width: 0,
						   radius: 4
						},
						name: 'light', // Use the default light style
						width: 350 // Set the tooltip width
					 }
				  })
			   });





			$('a.offerlink').each(function()
			   {
				  $(this).qtip(
				  {
					 content: {
						// Set the text to an image HTML string with the correct src URL to the loading image you want to use
						text: '<img src="/images/extras/ajax-loader.gif" alt="Loading..." />',
						url: '/cfpages/xml/iglusummary.cfm?id=' + $(this).attr('rel'), // Use the rel attribute of each element for the url to load
						title: {
						   text: 'IGLU Offer - ' + $(this).text(), // Give the tooltip a title using each elements text
						   button: 'Close' // Show a close link in the title
						}
					 },
					 position: {
						corner: {
						   target: 'bottomMiddle', // Position the tooltip above the link
						   tooltip: 'topMiddle'
						},
						adjust: {
						   screen: true // Keep the tooltip on-screen at all times
						}
					 },
					 show: { 
						when: 'click', 
						solo: true // Only show one tooltip at a time
					 },
					 hide: 'unfocus',
					 style: {
						tip: true, // Apply a speech bubble tip to the tooltip at the designated tooltip corner
						border: {
						   width: 0,
						   radius: 4
						},
						name: 'light', // Use the default light style
						width: 415 // Set the tooltip width
					 }
				  })
			   });				
			}
			
			
