/**
 * @author adrian marte
 */
// Date Picker

$(function() {
	/* CONFIG */
	var csv_line_header = 0;
	var csv_line_persons = 1;
	var csv_line_desc = 2;
	var csv_line_data = 3;

	/* STD-Text */
	var std_txt = [];
	std_txt.all_inclusive_desc = $("#all-inclusive-description").html();
	
	
	var csv_col_rooms_first = 4;
	var csv_col_rooms_last = 14;
	
	var cfg_age_group = [];
	cfg_age_group.kid = 2004;
	cfg_age_group.school = 1998;
	cfg_age_group.teen = 1980;

	String.prototype.removeWhiteSpaces = function () {
		var txt = this.replace(/\)/g,"");
		txt = txt.replace(/\(/g,"");
		txt = txt.replace(/\s+/g,"");
		return txt;
	};
	
	var currentDate = new Date();
	var csvfile = "http://www.mardusa.com/fileadmin/templates/prices.txt"; // http://test.mardusa.com/fileadmin/templates/
	var prices_csv;

	/*
	 * price for kids
	 * 
	 */	
	function getPriceKid(el) {
		switch(el.val()) {
		  case "baby":
			  if(el.next().next('input[type=checkbox]:checked').length === 0) {
				  price_kids += parseInt(prices_csv[all_inclusive][csv_col_rooms_last + 1],10);
			  } else {
				  price_kids += parseInt(prices_csv[all_inclusive][csv_col_rooms_last + 2],10);
			  }
		  break;
		  case "kid":
			  price_kids += parseInt(prices_csv[all_inclusive][csv_col_rooms_last + 3],10);
		  break;
		  case "school":
			  price_kids += parseInt(prices_csv[all_inclusive][csv_col_rooms_last + 4],10);
		  break;
		  case "teen":
			  price_kids += parseInt(prices_csv[all_inclusive][csv_col_rooms_last + 5],10);
		  break;
		} 
		
		return val;
	}
	/*
	 * calculate price
	 * 
	 */
	function calcPrice() {
		// Datum eingegeben
		if( $('#calendar-container').val().length > 0 &&
				// Gültige Anzahl Erwachsene
				parseInt($('#adults').val(),10) > 0 &&
				// Zimmer ausgewählt
				$("input[name=room-list]:checked").length > 0 &&
				// 2. Datum eingegeben
				$("#calendar-container").val().split("-")[1] !== undefined 
				// 2. Datum nach 1. Datum (Date Lib?)
				// $("#calendar-container").val().split("-")[0] < $("#calendar-container").val().split("-")[1]	
		){
	     
			// holds linenr in csv for current price
			var all_inclusive = 0;
			// is an individual date choosen?
			var is_individual = true;
			// all-inclusive
			if ($("#no-all-inclusive").attr('checked') === false) {
				// check if all_inclusive or other date!!!
				all_inclusive = $("input[name=radio-all-inclusive]:checked").val(); 
				is_individual = false;
			} 
		
			var room = $("input[name=room-list]:checked").val(); 
			
			var dates = $("#calendar-container").val().split("-");
			var sdate = dates[0].split(".");
			var edate = dates[1].split(".");
			var start_date = new Date(sdate[2], sdate[1], sdate[0]);
			var end_date = new Date(edate[2], edate[1], edate[0]);
			
			var days = Math.round((end_date - start_date) / 1000 / 24 / 60 / 60);
			
			var price = 0;
			var price_adults = 0;
			var price_kids = 0;
			
			for(i=1;i<=days;i++) {
				if(is_individual) {
					// this assums that csv data is sorted by date!!!
					for(j=csv_line_data;j<=prices_csv.length-1;j++) {
						var line_date_start = prices_csv[j][2].split(".");
						var line_date_end = prices_csv[j][3].split(".");
						var start_date_line = new Date(line_date_start[2], line_date_start[1], line_date_start[0]);
						var end_date_line = new Date(line_date_end [2], line_date_end [1], line_date_end [0]);
						
						if( Date.parse(dates[0]) < Date.parse(prices_csv[j][2]).add(j).days() ) {
							
							// overwrite actual price_class
							all_inclusive = j;
							
						}
					}
				}
				
				
				price_adults += (parseInt(prices_csv[all_inclusive][room],10) * parseInt($("#adults").val(),10) );
				
				if($("#children").val() > 0) {
					$(".age-group select").each(getPriceKid($(this)));
				}
			}	
			
			
			$("#total-price").html(
				"&euro;&nbsp;" + (price_adults + price_kids)
			);
			
			$("#total-details").html(parseInt($("#adults").val(),10) + " Erwachsene<br />" + $(".age-group select").length + " Kinder");

		} else {
	         $("#total-price").html("Es fehlen noch Eingaben!");
		}
	}
	

    /*
	 * Calendar
	 * 
	 */
	var closeCalendar = function () {
		//if($("#no-all-inclusive").attr('checked') === false) {
			var dates = $("#calendar-container").val().split("-");
			var sdate = dates[0].split(".");
			var edate = dates[1].split(".");
			var start_date = new Date(sdate[2], sdate[1]-1, sdate[0]);
			var end_date = new Date(edate[2], edate[1]-1, edate[0]);
			var msg = '';
			
			if($("#no-all-inclusive").attr('checked') === false && (start_date >= Date.parse($('input[name=radio-all-inclusive]:checked').data('start-date'))  && 
					end_date <= Date.parse($('input[name=radio-all-inclusive]:checked').data('end-date'))) ) {
				$('#error-date-all-inclusive').remove();
				calcPrice();
				
			} else if(start_date >= end_date) {
				msg = 'Achtung: Das Abreisedatum liegt vor dem Anreisedatum. ' 
				      + 'Bitte wählen Sie erneut ein Datum.';
				$('#calendar-container').val(''); 

			} else if($("#no-all-inclusive").attr('checked')) {
				$('#error-date-all-inclusive').remove();
				calcPrice();
				
			} else{
				msg = 'Achtung: Das eingegebene Datum liegt außerhalb der Pauschale ' 
				      + $("#all-inclusive-selected-name").html() + ' ('
				      + $('input[name=radio-all-inclusive]:checked').data('start-date') + ' - ' + $('input[name=radio-all-inclusive]:checked').data('end-date') 
				      + '). Die Pauschale wurde entfernt.';
			}

			// fehlermeldung anzeigen, "keine pauschale" auswählen und 
			// standardbeschreibung einblenden
			if(msg != '') {	
				$('#error-date-all-inclusive').remove();
				$(".date-selection .description").append('<div id="error-date-all-inclusive">' + msg + '</div>');
				$('#no-all-inclusive').trigger('click');
				$('#all-inclusive-description').html(std_txt['all_inclusive_desc']);
			}
		//}
	};
	
	var checkCalendar = function () {
		
	};



	// fill hidden fields: start-date & end-date with current date
	$('#start-date').attr('value', currentDate.getDate() + "." + (currentDate.getMonth() + 1) + "." + currentDate.getFullYear());
	$('#end-date').attr('value', currentDate.getDate() + "." + (currentDate.getMonth() + 1) + "." + currentDate.getFullYear());
	
	/* Calendar */		
	$('#calendar-container').daterangepicker({
		presets: {dateRange: 'Datum auswählen'},
		presetRanges: [],
		earliestDate: Date.parse('24.12.2009'),
		latestDate: Date.parse('11.04.2010'),
		datepickerOptions: {
			numberOfMonths: 1,
			changeMonth: true,
			changeYear: false,
			minDate: Date.parse('24.12.2009'),
			maxDate: Date.parse('11.04.2010'),
			dayNamesMin: ['So', 'Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa'], 
			dayNames: ['Sonntag', 'Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag'], 
			monthNamesMin: ['Jän', 'Feb', 'Mär', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'], 
			monthNames: ['Jänner', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember']
		},
		rangeStartTitle: "Anreise",
		rangeEndTitle: "Abreise",
		doneButtonText: "Zeitspanne übernehmen",
		dateFormat: 'dd.mm.yy',
		closeOnSelect: true,
		onClose: closeCalendar,
                onChange: checkCalendar
	});
	

	$('.ui-daterangepickercontain .range-start .ui-datepicker-next span').bind('click', function(e) {
          
          //DP_jQuery.datepicker._adjustDate($('.ui-daterangepickercontain .range-end').attr('id'), +1, 'M');
          $('.ui-daterangepickercontain .range-end .ui-datepicker-next').trigger('click');

        });	
	
	var clickAllInclusive = function () {
		$("#all-inclusive-description").html("<h3>" + $(this).data("title") + "</h3>" + $(this).data("description"));
		$('#calendar-container').val('');
		$('#error-date-all-inclusive').remove();
	};

	var clickRoom = function () {
		$("#room-description").html($(this).parent().data("description"));
		$("#room-image").html(
			"<img alt='Familienhotel Mardusa Zimmer " + $(this).attr('id') + "' src='http://www.mardusa.com/fileadmin/templates/webpics/rooms/" + $(this).attr('id') + ".jpg'/>"
		);
	};
	
	var selectKid = function () {
		id_nr = $(this).attr("id").substr(5); // "child1"
		
		if($(this).val() == "baby") {
			$(this).after(
				"<label for='check-babycare-" + id_nr + "'>-- Babybetreuung</label><input type='checkbox' name='check-babycare-" + id_nr + "' id='check-babycare-" + id_nr + "'>"
			);
			
			$("#check-babycare-" + id_nr).change(calcPrice);
			
		} else {
			$("#check-babycare-" + id_nr).prev("label").remove();
			$("#check-babycare-" + id_nr).remove();					
		}
		
		calcPrice();
	};
	
	var countPersons = function () {
		var persons = 0;
		$("input.persons").each(function() {
			persons += parseInt($(this).val(),10);
		});
		
		if(persons > 0) {
			$("#room-list-error").hide();
			$("#room-list").show("medium");
		}
		
		$("input:radio[name=room-list]").each(function () {
			if($(this).parent().data("max-persons") < persons ) {
				$(this).parent().hide("medium");
			} else {
				$(this).parent().show("medium");
			}
		});
	};
	/*
	 * get CSV data
	 * 
	 * read CSV fill selection for all-inclusive create room radios
	 */
	$.ajax({
		type: "GET",
		url: csvfile,
		success: function(data){
	
			prices_csv = jQuery.csv(";")(data); // data
			
			// fill all-inclusive selection
			$("#all-inclusive").append("<label for='no-all-inclusive'>Keine Pauschale<br /></label><input type='radio' id='no-all-inclusive' name='radio-all-inclusive' value='no-all-inclusive' checked='checked'><br />");
			for(i=csv_line_data; i<prices_csv.length; i++) {
				if(prices_csv[i][0] != '') {
					// check if all-inclusive is selected
					var id = 'all-inclusive-' + prices_csv[i][0].removeWhiteSpaces();
					$("#all-inclusive").append("<label for='" +  id + "'>" + prices_csv[i][0] + "<br />(" + prices_csv[i][2] + " - " + prices_csv[i][3] + ")" + "</label><input type='radio' id='" +  id + "' name='radio-all-inclusive' value='" + i + "'><br />");
					$('#' + id).data("start-date", prices_csv[i][2] );
					$('#' + id).data("end-date", prices_csv[i][3] );
					$('#' + id).data("description", prices_csv[i][1] );
					$('#' + id).data("title", prices_csv[i][0] );
					
					$("#" + id).click(clickAllInclusive); // ($(this))			
					
					param_all_iclusive = $(document).getUrlParam("all-inclusive");
	
					if(param_all_iclusive !== null && param_all_iclusive == prices_csv[i][0].removeWhiteSpaces()) {
					    $('#no-all-inclusive').attr('checked', false);
					    $('#' + id).trigger('click');
					}
				
				}			
			}
			
			// fill rooms
			// Rooms start in column 4
			for(var j=csv_col_rooms_first; j<=csv_col_rooms_last; j++) {
				var room_id = 'room-' + prices_csv[csv_line_header][j].removeWhiteSpaces();
				$("#rooms #room-list").append(
					"<div class='room-list-item' id='item-" + room_id + "'>" +
					"<label for='" + room_id + "'>" + prices_csv[csv_line_header][j] + "</label>" +  
					"<input type='radio' name='room-list' id='" + room_id + "' value='" + j + "'>" + 
					"</div>");
				$("#item-" + room_id).data("max-persons", prices_csv[csv_line_persons][j]);
				$("#item-" + room_id).data("description", prices_csv[csv_line_desc][j]);
				$("#" + room_id).click(clickRoom);
			}
			
			
			$(":text, :radio").change(function() {
				// if($("#room-list-error:hidden").length == 1) {
				calcPrice();	
				// }
			});
	
		   },
	   failure: function(msg){
		     alert( "Error: " + msg );
	   }   
	});

	
	/*
	 * checkbox for all-inclusive, show list
	 * $('#no-all-inclusive').click(function() {
	 * $('#calendar-container').val(''); });
	 */
	


	
	/* add children age */
	// add input fields for year for every child
	$("#children").change( function() {
		$('.age-group').html('');
		// calc age groups
		age_groups = "";
		count = $(this).attr('value');
		for(i=currentDate.getFullYear()-1;i>currentDate.getFullYear()-18;i--) {
			age_group = "none";
			if(i>=cfg_age_group.teen) {
				age_group = 'teen';
			}	
			if(i>=cfg_age_group.school) {
				age_group = 'school';
			}
			if(i>=cfg_age_group.kid) {
				age_group = "kid";
			}
			
			age_groups += '<option value="' + age_group + '">JG ' + i + '</option>';
		}
		
		for(i=1;i<=count;i++) {
			el = $(this).next('.age-group').append(
				'<label for="child' + i + '">- Kind ' + i + ' Alter</label>' + 
				'<select name="child' + i + '" id="child' + i + '" size="1" class="select-age-group">' + 
				'<option value="NULL">-------------</option>' + 
				'<option value="baby">Unter 24 Monaten</option>' + 
				age_groups + 
				'</select>'
			);
			$("#child" + i).change(selectKid);
		}
	});


	/* filter rooms (max persons) */
	$("input.persons").change(countPersons);
	
	// hide calendar
	// $('#calendar-container').hide();
	// hide room-list
	$("#room-list").hide();	
	// hide all-inclusives
	// $('#all-inclusive').hide();
	// Uncheck all-inclusive (page refresh)
	// $("#check-all-inclusive").removeAttr('checked');
	
	// Show range in calendar
	$('.ui-daterangepickercontain .preset_0 a').trigger('click');



});




// getURLParams

/*
 * Copyright (c) 2006-2007 Mathias Bank (http://www.mathias-bank.de) Dual
 * licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * 
 * Version 2.1
 * 
 * Thanks to Hinnerk Ruemenapf - http://hinnerk.ruemenapf.de/ for bug reporting
 * and fixing. Tom Leonard for some improvements
 * 
 */
jQuery.fn.extend({
/**
 * Returns get parameters.
 * 
 * If the desired param does not exist, null will be returned
 * 
 * To get the document params:
 * 
 * @example value = $(document).getUrlParam("paramName");
 * 
 * To get the params of a html-attribut (uses src attribute)
 * @example value = $('#imgLink').getUrlParam("paramName");
 */ 
 getUrlParam: function(strParamName){
	  strParamName = escape(unescape(strParamName));
	  
	  var returnVal = [];
	  var qString = null;
	  var strHref;
	  var strQueryString; 
	  
	  if ($(this).attr("nodeName")=="#document") {
		  // document-handler
		  if (window.location.search.search(strParamName) > -1 ){
			  qString = window.location.search.substr(1,window.location.search.length).split("&");
		  }
	  } else if ($(this).attr("src")!="undefined") {
		  strHref = $(this).attr("src");
		  if ( strHref.indexOf("?") > -1 ){
			  strQueryString = strHref.substr(strHref.indexOf("?")+1);
			  qString = strQueryString.split("&");
		  }
	  } else if ($(this).attr("href")!="undefined") {
		  strHref = $(this).attr("href");
		  if ( strHref.indexOf("?") > -1 ){
			  strQueryString = strHref.substr(strHref.indexOf("?")+1);
			  qString = strQueryString.split("&");
		  }
	  } else {
		  return null;
	  }

	  if (qString === null) {
		  return null;
	  }
	  
	  
	  for (var i=0;i<qString.length; i++){
		  if (escape(unescape(qString[i].split("=")[0])) == strParamName){
			  returnVal.push(qString[i].split("=")[1]);
		  }
	  }
	  
	  
	  if (returnVal.length === 0) {
		  return null;
	  } else if (returnVal.length == 1) {
		  return returnVal[0];
	  } else {
		  return returnVal;
	  }
	}
});