﻿//
//custom methods used in validation process
//
function getURLParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
      var regex = new RegExp(regexS, 'i');
    var results = regex.exec(window.location.href);
    if (results == null)
        return null;
    else {
        try {
            var result = decodeURIComponent(results[1]);
            return result;
        }
        catch (ex) {
            return '';
        }
    }
}

String.prototype.replaceAll = function(search, replace) {
    return this.split(search).join(replace);
}
function citySuggestionLiFormat(row, i, num, searchItem) {
    var locName = row.name.substring(row.name.indexOf('[') + 1, row.name.lastIndexOf(']'));

    return locName.replaceAll('][', '-');
}
function citySuggestionFormatResult(p1, row, p3) {
    var locName = row;

    var locNameParsed = locName.substring(locName.indexOf('[') + 1, locName.indexOf(']'));
    return locNameParsed;
}

function citySuggestionItemSelected(obj, itemSelected) {
    $('#' + name_DestinationID).attr('value', itemSelected.id);
}


function SetMinMaxDates(idCheckinDTP, idCheckoutDTP, isCheckinControlFired) {
    var checkinDate = parseDateLocalized($('#' + idCheckinDTP).val(), currentCultureDateFormat, currentCultureDateSeparator);
    var checkoutDate = parseDateLocalized($('#' + idCheckoutDTP).val(), currentCultureDateFormat, currentCultureDateSeparator);

    if (checkinDate != null && checkoutDate != null) {
        if (checkinDate >= checkoutDate) {
            if (isCheckinControlFired) {
                $('#' + idCheckoutDTP).datepicker('setDate', AddRemoveDay(checkinDate, false));
            }
            else {
                $('#' + idCheckinDTP).datepicker('setDate', AddRemoveDay(checkoutDate, true));
            }
        }
    }
    else if (checkinDate != null && isCheckinControlFired && checkoutDate == null) {
        $('#' + idCheckoutDTP).datepicker('option', 'defaultDate', AddRemoveDay(checkinDate, false));
    }
    else if (checkoutDate != null && !isCheckinControlFired && checkinDate == null) {
        $('#' + idCheckinDTP).datepicker('option', 'defaultDate', AddRemoveDay(checkoutDate, true));
    }
}

function AddRemoveDay(dateToChange, isToRemoveDay)
{    
    var expdate = dateToChange.getTime();
    if (isToRemoveDay)
    {
        expdate -= 24 * 3600 * 1000; //expires in 1 day(milliseconds) 
    }
    else
    {
        expdate += 24 * 3600 * 1000; //expires in 1 day(milliseconds) 
    }
    dateToChange.setTime(expdate);
    return dateToChange;
}


function citySuggestionParseData(data) {
    var results = [];
    $(data).find('locations').each(function() {
        $(this).find('location').each(function() {
            var id = $.trim($(this).attr('id'));
            var code = $.trim($(this).attr('code'));
            var name = $.trim($(this).attr('name'));

            results[results.length] = { data: { id: id, code: code, name: name }, value: citySuggestionFormatResult(name, name, name), result: citySuggestionFormatResult(name, name, name) };
        });
    });

    return results;
}

function ReturnYearMonthDayArray(strDate, currentCultureDateFormat, currentCultureDateSeparator)
{
    var strDay, strMonth, strYear;
    var dateToReturn;

    var strArr = strDate.split(currentCultureDateSeparator);

    // if invalid format
    if (strArr.length != 3)
        return null;

    var formatArr = currentCultureDateFormat.split(currentCultureDateSeparator);

    for (i = 0; i < formatArr.length; i++) {
        // if we can't determine part of date
        if (strArr[i] == undefined)
            return null;

        if (formatArr[i].substring(0, 1).toLowerCase() == "d") {
            strDay = strArr[i];
            if (strDay.startsWith('0'))
                strDay = strDay.replace(/^[0]*/, ""); //strDay.substring(1);
        }
        if (formatArr[i].substring(0, 1).toLowerCase() == "m") {
            strMonth = strArr[i];
            if (strMonth.startsWith('0'))
                strMonth = strMonth.replace(/^[0]*/, ""); //strMonth.substring(1);
        }
        if (formatArr[i].substring(0, 1).toLowerCase() == "y") {
            strYear = strArr[i];
            if (strYear.startsWith('0'))
                strYear = strYear.replace(/^[0]*/, ""); //strYear.substring(1);
        }
    }
    return new Array(parseInt(strYear), parseInt(strMonth) - 1, parseInt(strDay));
}

function parseDateLocalized(strDate, currentCultureDateFormat, currentCultureDateSeparator) 
{
    var yearMonthDay = ReturnYearMonthDayArray(strDate, currentCultureDateFormat, currentCultureDateSeparator);
    if(yearMonthDay != null) {
        var date = new Date();
        date.setFullYear(yearMonthDay[0], yearMonthDay[1], yearMonthDay[2]);
        if (isNaN(date))
            return null;
        else
            return date;  //new Date(yearMonthDay[0], yearMonthDay[1], yearMonthDay[2]);
    }
    else
    {
        return null;
    }
}

//
// common validation methods
//
jQuery.validator.addMethod("compareDatePickers", function(value, element, param) {

    //should we skip checking process?
    if (param[2] != 'on')
        return true;
        
    minDatePicker = $(param[0]);
    maxDatePicker = $(param[1]);

    //check maxDate >= minDate
    if (maxDatePicker != null && minDatePicker != null) {
        var minDate = minDatePicker.datepicker('getDate');
        var maxDate = maxDatePicker.datepicker('getDate');
        if (minDate != null && maxDate != null) {
            if (maxDate <= minDate) {
                return false;
            }
        }
    }

    return true;
});

jQuery.validator.addMethod("shouldNotContainsDefaultValue", function(value, element, param) {

    var defaultValue = param;
    if (element.value == defaultValue.toString())
        return false;

    return true;
});

jQuery.validator.addMethod("dateFuture", function(value, element) {
    var date = $('#' + element.id).datepicker('getDate');

    return this.optional(element) || ((new Date()) < date);
});				
