﻿var PK = PK || {}; // namespace

// ----------------------------------------------------------------------------
PK.Lang = function() {};

PK.Lang.text = {
	dateInvalid:"The date is not valid, please try again.",
	dateMustBeInFuture:"The date must be in future!",
	dateTooFarInFuture:"The date is too far in the future.",
	dateDropOffAfterPickUp:"The drop-off date must be after pick-up date."
};

PK.Lang.t = function(key) {
	if (typeof PK.Lang.text[key] == "undefined") {
	    throw "Text \"" + key + "\" is not defined";
	}
	return PK.Lang.text[key];
}

PK.Lang.getLangCode = function(langId) {
    var lc = "en";
    var codes = {
        1:"de",
        2:"en",
        3:"fr",
        4:"it",
        5:"hu",
        6:"pl",
        7:"sk",
        8:"cs",
        9:"es",
        11:"zh-CN",
        13:"bg",
        15:"tr",
        16:"da",
        17:"fi",
        18:"ro",
        19:"no",
        22:"pt-BR" // TODO: temp only
    }
    
    if (typeof codes[langId] != "undefined") {
        lc = codes[langId];
    }
    
    return lc;
}

// ----------------------------------------------------------------------------
PK.CtrlCalenderDateValidationResult = function() {
    this.isValid = true;
    this.errorText = "";
    this.$invalidDates = []; // array of jquery vars holding textboxes with invalid dates
}

PK.CtrlCalenderDate = function(options) {
    
    if (typeof options != "object") { throw 'Incorrect mandatory argument "options"'; }
    
    var requiredOptions = "langId selectorTxtDate1 selectorTxtDate2 selectorDdlTime1 selectorDdlTime2 path".split(" ");
    $.each(requiredOptions, function(i, prop) {
        if (typeof options[prop] == "undefined") {
            throw "Argument options." + prop + " is undefined";
        }
    });

    this.langId = parseInt(options.langId, 10);
    if (isNaN(this.langId) || this.langId < 1) {
        throw "Incorrect language ID passed to PK.CtrlCalenderDate constructor: '+ langId +'. Must be positive integer.";
    }
    
    this.$date1 = $(options.selectorTxtDate1);
    this.$date2 = $(options.selectorTxtDate2);
    if (this.$date1.length !== 1 || this.$date2.length !== 1) {
        throw "Date text input not found or found more than one. (Selectors: \""+ options.selectorTxtDate1 +"\", \"" + options.selectorTxtDate2 + "\")";
    }
    
    this.$time1 = $(options.selectorDdlTime1);
    this.$time2 = $(options.selectorDdlTime2);
    if (this.$time1.length !== 1 || this.$time2.length !== 1) {
        //throw "Time drop-downs not found or found more than one. (Selectors: \""+ options.selectorDdlTime1 +"\", \"" + options.selectorDdlTime2 + "\")";
    }
    
    this.$htmlDateInfo1 = $(options.selectorHtmlDateInfo1);
    this.$htmlDateInfo2 = $(options.selectorHtmlDateInfo2);
    
    this.path = options.path;
    
    this.numberOfMonths = options.numberOfMonths || 3;// Change number to how many month will be displayed
    this.dateInfoFormat = "DD, d. M, yy";
    
    this.init();
}

PK.CtrlCalenderDate.setTimePartInDate = function(dateObj, strTime /* "13:30" */) {
	var timeParts = strTime.split(":");
	if (timeParts.length != 2) { // invalid time string, return date with no changes:
		return dateObj;
	}
	var h = parseInt(timeParts[0], 10);
	var min = parseInt(timeParts[1], 10);
	
	if (h < 0 || h > 23) { // invalid hour, return original date:
		return dateObj;
	}
	if (min < 0 || min > 59) { // invalid minutes
		return dateObj;
	}
	
	dateObj.setHours(h);
	dateObj.setMinutes(min);
	return dateObj;
}

PK.CtrlCalenderDate.prototype.getDateFormat = function() {
    var dateFormat = "dd-M-yy";
    if (this.langId == 2) { // English
    	dateFormat = "dd-M-yy";
	}
	return dateFormat;
}

PK.CtrlCalenderDate.prototype.setPickUpDate = function(dateObj, doUpdateDropOff /*bool, default:true*/) {
	if (typeof doUpdateDropOff == "undefined") { doUpdateDropOff = true; }
	
	var newDropOffDate;
	
	this.$date1.val($.datepicker.formatDate(this.options.dateFormat, dateObj));
	//this.$htmlDateInfo1.html($.datepicker.formatDate(this.dateInfoFormat, dateObj));
	
	if (doUpdateDropOff === true) {
		newDropOffDate = new Date(dateObj); // copy original date
		newDropOffDate.setDate(newDropOffDate.getDate() + 7); // add 7 days
		this.setDropOffDate(newDropOffDate, dateObj); // set drop-off date and its minDate
	}
}

PK.CtrlCalenderDate.prototype.setDropOffDate = function(dateObj, dateObjMinDate) {
	var t = this;
	
	this.$date2.val($.datepicker.formatDate(this.options.dateFormat, dateObj));
	//this.$htmlDateInfo2.html($.datepicker.formatDate(this.dateInfoFormat, dateObj));
	
	if (typeof dateObjMinDate == "object" && typeof dateObjMinDate.getDay == "function") { // = probably is a date object
		window.setTimeout(function() { t.$date2.datepicker("option", "minDate", dateObjMinDate); }, 10);
	}
}

PK.CtrlCalenderDate.getMinMaxDates = function() {
    var minDate = new Date(); minDate.setHours(0); minDate.setMinutes(0); minDate.setSeconds(0); minDate.setMilliseconds(0);
    var maxDate = new Date(minDate);
    minDate.setDate(minDate.getDate()+4);//Lead Days will be added here
    maxDate.setDate(maxDate.getDate()+14*30);
    return [minDate, maxDate];
}

PK.CtrlCalenderDate.parseDate = function(val) { // returns false for invalid dates (ie. 30.02.2010)
    var res,d,m,y,D;
    res=val.match(/^(\d{1,2})[\.\/][ ]*(\d{1,2})[\.\/][ ]*(\d{4})$/);
    if(!res||res.length!=4)return false;
    d=parseInt(res[1],10);m=parseInt(res[2],10);y=parseInt(res[3],10);
    D=new Date(y,m-1,d);
    if(D.getDate()!=d||D.getMonth()+1!=m||D.getFullYear()!=y)return false;
    return D;
}

PK.CtrlCalenderDate.handlerTxtDateChange = function(ev) {
	var valErr = ev.data.t.validate();
	if (!valErr.isValid) {
		alert(valErr.errorText);
	}
}

PK.CtrlCalenderDate.handlerPickUpTimeChange = function(ev) {
	ev.data.t.$time2.val(this.value);
}

PK.CtrlCalenderDate.prototype.validate = function() {
    var valErr = new PK.CtrlCalenderDateValidationResult();
	
	var minMaxDates = PK.CtrlCalenderDate.getMinMaxDates();
    
    var pickUpDateTime = PK.CtrlCalenderDate.parseDate(this.$date1.val());
    pickUpDateTime = PK.CtrlCalenderDate.setTimePartInDate(pickUpDateTime, this.$time1.val());

	var dropOffDateTime = PK.CtrlCalenderDate.parseDate(this.$date2.val());
	dropOffDateTime = PK.CtrlCalenderDate.setTimePartInDate(dropOffDateTime, this.$time2.val());
    
    if (!pickUpDateTime || !dropOffDateTime) {
        valErr.errorText = PK.Lang.t("dateInvalid");
        valErr.isValid = false;
    } else if (pickUpDateTime < minMaxDates[0] || dropOffDateTime < minMaxDates[0]) {
        valErr.errorText = PK.Lang.t("dateMustBeInFuture");
        valErr.isValid = false;
    } else if (pickUpDateTime > minMaxDates[1] || dropOffDateTime > minMaxDates[1]) {
        valErr.errorText = PK.Lang.t("dateTooFarInFuture");
        valErr.isValid = false;
    } else if(dropOffDateTime < pickUpDateTime) {
        valErr.errorText = PK.Lang.t("dateDropOffAfterPickUp");
        valErr.isValid = false;
    }
    
	return valErr;
}

PK.CtrlCalenderDate.prototype.init = function() {
	var t = this;
	this.options = {};
	
	if (this.langId != 2) { // English
        $.extend(this.options, $.datepicker.regional[PK.Lang.getLangCode(this.langId)]);
    }
	
	var opt = {
        numberOfMonths:this.numberOfMonths,
        stepMonths:1,
        minDate:4,// Set Lead Days Here
        maxDate:"+24M +0D",// To add years. Changing this you can display as many months
        dateFormat:this.getDateFormat(),
        //buttonImage:this.path+"images/icon/calendar.png",
		//buttonImage:"images/icon/calendar.jpg",
		buttonImage:"images/icon/trans.gif",
        buttonText:"",
        buttonImageOnly:true,
        showOn:"both",
		changeMonth: false,// Tp display Month In dropdown
		changeYear: false,// Tp display Month In dropdown
        duration:0,
        firstDay:1,
        onSelect:function(dateText, inst) {
            if (this === t.$date1[0]) {
				t.setPickUpDate(t.$date1.datepicker("getDate"));
            } else if (this === t.$date2[0]) {
				t.setDropOffDate(t.$date2.datepicker("getDate"));
			}
        }
    };
    
    $.extend(this.options, opt);
	
    this.$date1.add(this.$date2).datepicker(this.options);
    
    $(this.$date1.add(this.$date2)).bind("change", {t:this}, PK.CtrlCalenderDate.handlerTxtDateChange);
    
    // set drop-off time to the same value as pick-up:
    this.$time1.bind("change", {t:this}, PK.CtrlCalenderDate.handlerPickUpTimeChange);
}

// ----------------------------------------------------------------------------
PK.BookingEngine = function(langId, dateControlsOptions) {
    var thisRef = this;    
    this.langId = langId;
	this.dateControls = new PK.CtrlCalenderDate(dateControlsOptions);	
	this.langIdLocations = langId;
	// temporary: get regions in English if language is not German nor English:
	var regionsLangId = langId;
	this.langCode = PK.Lang.getLangCode(this.langId);
    // document fragments for quicker access to the elements we're looking for:
    this.$pickUpDateWrap = $("p.pickUpDateWrap");
    this.$dropOffDateWrap = $("p.dropOffDateWrap"); 
    this.init();
}

PK.BookingEngine.prototype.init = function() {
    var thisRef = this;
    var c = this.controls;
}

// --- date controls
