/**
 * @author djohansson
 * Plan your trip javascript
 */

function compareRates(sectionName, isRegionPage, locationName)
{	
	var section = sectionName;
	var regionPage = isRegionPage;
	var url = '/util/generateCompareUrls.php';
	var compareSites = '';
	var uniqueIDs = '';
	var separator = '';
	var separator2 = '';
	var elem = $(section + 'Form').elements;
	var left = 0;
	var top = 0;

	if (section == 'flights')
	{
		var fromAirport = $('from_airport').value;
		var toAirport = $('to_airport').value;
		var departDate = $('depart_date').value;
		var returnDate = $('return_date').value;
		var numberAdults = $('flights_number_adults').value;
	}
	else if (section == 'cars')
	{
		var searchNear = $('search_near').value;
		var carsCity = $('cars_city').value;
		var carsCityLocation = $('cars_city_location').value;
		var carsAirport = $('cars_airport').value;
		var pickupDate = $('pickup_date').value;
		var pickupTime = $('pickup_time').value;
		var dropoffDate = $('dropoff_date').value;
		var dropoffTime = $('dropoff_time').value;
	}
	else
	{
		return false;
	}

	for (var i = 0; i < elem.length; i++)
	{
		if (elem[i].type == 'checkbox' && elem[i].checked == true)
		{
			compareSites += separator + elem[i].name.substring(5 + section.length);
			separator = ',';
		}
	}

	if (section == 'flights')
	{
		if ($('from_airport').value == '' && $('to_airport').value == '' && !compareSites)
		{
			alert('You must select a From, To, and at least one website.');
			return false;
		}
		
		if ($('from_airport').value == '' && $('to_airport').value == '')
		{
			alert('You must select a From and a To.');
			return false;
		}
		
		if ($('from_airport').value == '' && !compareSites)
		{
			alert('You must select a From and at least one website.');
			return false;
		}
		
		if ($('to_airport').value == '' && !compareSites)
		{
			alert('You must select a To and at least one website.');
			return false;
		}
		
		if ($('from_airport').value == '')
		{
			alert('You must select a From.');
			return false;
		}
		
		if ($('to_airport').value == '')
		{
			alert('You must select a To.');
			return false;
		}
		
		if ($('depart_date').value == '' && $('return_date').value == '' && !compareSites)
		{
			alert('You must select a Depart Date, Return Date, and at least one website.');
			return false;
		}

		if ($('depart_date').value == '' && $('return_date').value == '')
		{
			alert('You must select a Depart Date and Return Date.');
			return false;
		}

		if ($('depart_date').value == '' && !compareSites)
		{
			alert('You must select a Depart Date and at least one website.');
			return false;
		}

		if ($('return_date').value == '' && !compareSites)
		{
			alert('You must select a Return Date and at least one website.');
			return false;
		}

		if ($('depart_date').value == '')
		{
			alert('You must select a Depart Date.');
			return false;
		}

		if ($('return_date').value == '')
		{
			alert('You must select a Return Date.');
			return false;
		}
	}
	else if (section == 'cars')
	{
		if ($('search_near').value == 'cars_switch_city')
		{
			var elementTempName = 'cars_city';
			var valueTempName = 'a City';
		}
		else if ($('search_near').value == 'cars_switch_airport')
		{
			var elementTempName = 'cars_airport';
			var valueTempName = 'an Airport';
		}
		else
		{
			return false;
		}

		if ( $(elementTempName).value == '' && $('pickup_date').value == '' && $('dropoff_date').value == '' && !compareSites)
		{
			alert('You must select ' + valueTempName + ', Pick-Up Date, Drop-Off Date, and at least one website.');

			return false;
		}
	
		if ($(elementTempName).value == '' && $('pickup_date').value == '' && !compareSites)
		{
			alert('You must select ' + valueTempName + ', Pick-Up Date, and at least one website.');

			return false;
		}
	
		if ($(elementTempName).value == '' && $('dropoff_date').value == '' && !compareSites)
		{
			alert('You must select ' + valueTempName + ', Drop-Off Date, and at least one website.');

			return false;
		}
	
		if ($(elementTempName).value == '' && !compareSites)
		{
			alert('You must select ' + valueTempName + ' and at least one website.');

			return false;
		}
	
		if ($(elementTempName).value == '')
		{
			alert('You must select ' + valueTempName + '.');

			return false;
		}

		/*
		| No pickup date, dropoff date, or websites selected
		*/
		if ($('pickup_date').value == '' && $('dropoff_date').value == '' && !compareSites)
		{
			alert('You must select a Pick-Up Date, Drop-Off Date, and at least one website.');
			return false;
		}

		/*
		| No pickup date or dropoff date
		*/
		if ($('pickup_date').value == '' && $('dropoff_date').value == '')
		{
			alert('You must select a Pick-Up Date and Drop-Off Date.');
			return false;
		}

		/*
		| No pickup off date or websites selected
		*/
		if ($('pickup_date').value == '' && !compareSites)
		{
			alert('You must select a Pick-Up Date and at least one website.');
			return false;
		}

		/*
		| No drop off date or websites selected
		*/
		if ($('dropoff_date').value == '' && !compareSites)
		{
			alert('You must select a Drop-Off Date and at least one website.');
			return false;
		}

		/*
		| No pickup date
		*/
		if ($('pickup_date').value == '')
		{
			alert('You must select a Pick-Up Date.');
			return false;
		}

		/*
		| No drop off date
		*/
		if ($('dropoff_date').value == '')
		{
			alert('You must select a Drop-Off Date.');
			return false;
		}
	}
	else
	{
		return false;
	}

	if (!compareSites)
	{
		alert('You must select at least one website');
		return false;
	}

	if (section == 'flights')
	{	
		new Ajax.Request(url, {
			method: 'post',
			parameters: {
				ota_ids: compareSites,
				from_airport: fromAirport,
				to_airport: toAirport,
				depart_date: departDate,
				return_date: returnDate,
				number_adults: numberAdults,
				region_page: regionPage,
				compare_section: section
			},
			onException: function(request, exception)
			{
				//alert("JS Exception: " + exception);
			},
			onComplete: function (transport)
			{
				/*
				| Use json for this to return an array and loop through it.
				*/
				var data = transport.responseText.evalJSON();
				track(data.tracking, 'ota-flights-' + locationName + '-compare');
				for (var i = 0; i < data.urls.length; i++)
				{
					left = (i * 30) + 100;
					top = (i * 50) + 50;

					var settings = 'height=700,width=500,resizable=1,toolbar=1,location=yes,status=yes,menubar=yes,scrollbars=yes,left=' + left + ',top=' + top;

					window.open(data.urls[i], i + '_flights_compare', settings);
				}
			}
		});
	}
	else if (section == 'cars')
	{	
		new Ajax.Request(url, {
			method: 'post',
			parameters: {
				ota_ids: compareSites,
				search_near: searchNear,
				cars_city: carsCity,
				cars_city_location: carsCityLocation,
				cars_airport: carsAirport,
				pickup_date: pickupDate,
				pickup_time: pickupTime,
				dropoff_date: dropoffDate,
				dropoff_time: dropoffTime,
				region_page: regionPage,
				compare_section: section
			},
			onException: function(request, exception)
			{
				//alert("JS Exception: " + exception);
			},
			onComplete: function (transport)
			{	
				/*
				| Use json for this to return an array and loop through it.
				*/
				var data = transport.responseText.evalJSON();
				track(data.tracking, 'ota-cars-' + locationName + '-compare');
				for (var i = 0; i < data.urls.length; i++)
				{
					left = (i * 30) + 100;
					top = (i * 50) + 50;

					var settings = 'height=700,width=500,resizable=1,toolbar=1,location=yes,status=yes,menubar=yes,scrollbars=yes,left=' + left + ',top=' + top;

					window.open(data.urls[i], i + '_cars_compare', settings);
				}
			}
		});
	}
	else
	{
		return false;
	}
}

function track(tracking, category)
{
	var d = new Date();
	var order = d.valueOf();
	
	var total = 0;
	for (var i = 0; i < tracking.length; i++)
	{
		total += Number(tracking[i]['value']);
	}
	
	_gaq.push(['_addTrans',
	  order, // order ID - required
	  'Compare Widget',
	  total,   // total - required
	  0,
	  0
	]);
	
	for (var i = 0; i < tracking.length; i++)
	{
		_gaq.push(['_addItem',
		  order,           	// order ID - required
		  string_to_slug(tracking[i]['account_name'])+'-click',
		  tracking[i]['account_name'],
		  category,   		// category or variation
		  tracking[i]['value'],            // unit price - required
		  '1'               // quantity - required
		]);
	}
	_gaq.push(['_trackTrans']);
	return true;
}
var contractors_location_autocomplete;
var contractors_name_autocomplete;

Event.observe(window,'load',function(){
	contractors_location_autocomplete = new Ajax.Autocompleter(
        'contractors_location_q',
    	'contractors_location_autodiv',
    	'/util/ajax/search-autocomplete.php',
    	{
        	method:'get',
        	paramName: 'q',
    		select: 'name',
    		minChars: 3,
    		frequency: 0.1,
    		parameters: 't=contractors&location=true&p=location',
    		afterUpdateElement: onSelectSearchLocation
    	}
    );
	
	contractors_name_autocomplete = new Ajax.Autocompleter(
        'contractors_name_q',
    	'contractors_name_autodiv',
    	'/util/ajax/search-autocomplete.php',
    	{
        	method:'get',
        	paramName: 'q',
    		select: 'name',
    		minChars: 3,
    		frequency: 0.1,
    		parameters: 't=contractors&location=false&p=name',
    		afterUpdateElement: onSelectSearchName
    	}
    );
});
function toggleContractorsSearch(toggle)
{
	if(toggle == 'location')
	{
		$('contractors-location-form').style.display = '';
		$('contractors-name-form').style.display = 'none';
	}
	else
	{
		$('contractors-name-form').style.display = '';
		$('contractors-location-form').style.display = 'none';
	}
}

function onSelectSearchLocation(element,data)
{
	var s = element.id.split('_');
	var prefix = s[0];
	var id = data.id.substring(18);
	$(prefix + '_location_l').value = $(prefix + '_l_'+id).value; 
}

function onSelectSearchName(element,data)
{
	var s = element.id.split('_');
	var prefix = s[0];
	var id = data.id.substring(18);
	$(prefix + '_name_l').value = $(prefix + '_l_'+id).value; 
}

function dates(obj,date,date1,date2)
{
	if(obj.dateField.id == date1)
	{
		var d1 = obj.date;
		var date_split = $(date2).value.split('/');
		if(date_split.length = 3)
		{
			var d2 = new Date(date_split[2],date_split[0]-1,date_split[1]);
		}
		else
		{
			var d2 = new Date(2000,1,1);
		}
		if(d1 >= d2)
		{
			var d2=new Date(d1);
			d2.setDate(d1.getDate()+2);
			$(date2).value = pad(d2.getMonth()+1,2)+'/'+ pad(d2.getDate(),2) + '/' + d2.getFullYear(); 
		}
	}
	if(obj.dateField.id == date2)
	{
		var d2 = obj.date;
		var date_split = $(date1).value.split('/');
		if(date_split.length = 3)
		{
			var d1 = new Date(date_split[2],date_split[0]-1,date_split[1]);
		}
		else
		{
			var d1 = new Date(2000,1,1);
		}
		if(d1 >= d2)
		{
			var d1=new Date(d2);
			d1.setDate(d2.getDate()-2);
			$(date1).value = pad(d1.getMonth()+1,2)+'/'+ pad(d1.getDate(),2) + '/' + d1.getFullYear(); 
		}
	}
	obj.dateField.value = date;
}
function pad(n, len) {
	   
    s = n.toString();
    if (s.length < len) {
        s = ('0000000000' + n.toString()).slice(-len);
    }

    return s;
}
function dealClick(page, regionId, table, filterfield, filtervalue, listingId, target, websiteurl, newpage)
{
	new Ajax.Request('/util/travelDealsClickStats.php', {
		method: 'post',
		parameters: {
			p: page,
			r: regionId,
			t: table,
			f: filterfield,
			v: filtervalue,
			l: listingId,
			u: target
		},
		onComplete: function (transport)
		{
			if ( newpage )
			{
				window.open(websiteurl,'','scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');
			}
			else
			{
				location.href = websiteurl;
			}
		}
	});
}
