var httpDest;
var httpSources;
var httpSourceDestinations;
var loading = document.getElementById("loading");
var destList = document.getElementById("DDLDestination");
var sourceList = document.getElementById("DDLSource");
var calendar = document.getElementById("calendar");
var enteredDate = '';
var busType = document.getElementById('DDLBusType');
var mfromCityId = '';
var commingFromIssueTicet = false;

function createRequestObject() {
    var xhhtp;
    if (window.ActiveXObject) {
        xhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    if (window.XMLHttpRequest) {
        xhttp = new XMLHttpRequest();
    }
    if (xhttp == null) {
        alert("You are using an unsupported Browser. Please update it to the latest version. Thanks!");
    }
    return xhttp;
}
var popularCitiesList = ["Ahmedabad", "Bangalore", "Chennai", "Coimbatore", "Delhi", "Dharamsala", "Ernakulam", "Goa", "Hyderabad", "Indore", "Jaipur", "Jamnagar", "Katra", "Kodaikanal", "Madurai", "Mahabaleshwar", "Manali", "Mangalore", "Mumbai", "Nasik", "Nainital", "Pondicherry", "Pune", "Rajkot", "Shirdi", "Tirupati", "Vijayawada"];
var popularCities = {};
for (var i = 0; i < popularCitiesList.length; i++) {
    popularCities[popularCitiesList[i]] = true;
}

function isPopularCity(cityName) {
    if (popularCities[cityName]) {
        return true;
    }
    return false;
}

function loadDestinationsData(result) {
    var sources = result.destinations;
    var toCityIdPreference = getPreference('toCityId');
    var toCityNamePreference = getPreference('toCityName');
    var destinationSelected = false;
    //set Dest List to empty list by setting lenght = 0
    destList.options.length = 0;
    //If destinations list is long... better ui is show popular cities first..
    if (sources.length > 5) {
        //pick popular cities first
        var p = 0;
        for (var i = 0; i < sources.length; i++) {
            if (isPopularCity(sources[i].value)) {
                destList.options[p] = new Option(sources[i].value, sources[i].id);
                if (toCityIdPreference == sources[i].id && toCityNamePreference == sources[i].value) {
                    destList.options[p].selected = true;
                    destinationSelected = true;
                }
                p++;
            }
        }
        //add ----------
        if (destList.options.length > 0) {
            destList.options[destList.options.length] = new Option("--------", 0);
        }
    }
    //add destination list	
    for (var i = 0, l = destList.options.length; i < sources.length; i++, l++) {
        destList.options[l] = new Option(sources[i].value, sources[i].id);
        if (!destinationSelected && toCityIdPreference == sources[i].id && toCityNamePreference == sources[i].value) destList.options[l].selected = true;
    }
    if (destList.value == null) {
        destList.options[0].selected = true;
    }
}

function handleDestResponse() {
    if (httpDest.readyState == 1) {
        loading.style.visibility = 'visible';
    }
    if (httpDest.readyState == 4) {
        loading.style.visibility = 'hidden';
        var result = eval("(" + httpDest.responseText + ")");
        if (result != null) {
            loadDestinationsData(result);
        }
    }
}

function handleSourcesResponse() {
    if (httpSources.readyState == 1) {
        //htmlresults.innerHTML = '<img style="margin-left:49%;margin-top:10%" src="spinner.gif"/>';
    }
    if (httpSources.readyState == 4) {
        var result = eval("(" + httpSources.responseText + ")");
        var sources = result.sources;
        var fromCityIdPreference = getPreference('fromCityId');
        var fromCityNamePreference = getPreference('fromCityName');
        sourceList.options.length = 0;
        for (var i = 0; i < sources.length; i++) {
            sourceList.options[i] = new Option(sources[i].value, sources[i].id);
            if (fromCityIdPreference == sources[i].id && fromCityNamePreference == sources[i].value) {
                if (sourceList.selectedIndex == 0) sourceList.options[i].selected = true;
            }
        }
        if (isNullOrEmpty(fromCityIdPreference) && isNullOrEmpty(fromCityNamePreference)) {
            sourceList.options[0] = new Option("---------", 0);
            sourceList.options[0].selected = true;
        }
        if (sourceList.value == null) {
            sourceList.options[0].selected = true;
        }
        //GetDestinations();  
        //parallelising this req instead of blocking on loading all source cities      
    }
}
var allSourceDestinations = null;

function handleAllSourceDestResponse() {
    if (httpSourceDestinations.readyState == 4) {
        var result = eval("(" + httpSourceDestinations.responseText + ")");
        allSourceDestinations = result;
    }
}

function GetAllSourceDestinations() {
    httpSourceDestinations = createRequestObject();
    httpSourceDestinations.open('get', '/GetDestinationsJSON.aspx?allsourcedestinations=123');
    httpSourceDestinations.onreadystatechange = handleAllSourceDestResponse;
    httpSourceDestinations.send(null);
}

function LoadDestinations(selectedSource) {
    if (selectedSource != '0') {
        if (allSourceDestinations) {
            loadDestinationsData(allSourceDestinations[selectedSource]);
        }
        else {
            httpDest = createRequestObject();
            httpDest.open('get', '/GetDestinationsJSON.aspx?sourceid=' + selectedSource);
            httpDest.onreadystatechange = handleDestResponse;
            httpDest.send(null);
        }
    }
    else {
        destList.options[0] = new Option("---------", 0);
        destList.options[0].selected = true;
    }
}

function GetLoadTimeDestinations() {
    var selectedSource = 0; //removing the preference to Ahmedabad
    var fromCityPreference = getPreference('fromCityId');
    if (fromCityPreference != null) {
        selectedSource = fromCityPreference;
    }
    LoadDestinations(selectedSource);
}

function GetDestinations() {
    var selectedSource = sourceList.value;
    if (selectedSource != null) {
        $("#error").hide();
    }
    LoadDestinations(selectedSource);
}

function GetSources() {
    httpSources = createRequestObject();
    httpSources.open('get', '/GetDestinationsJSON.aspx');
    httpSources.onreadystatechange = handleSourcesResponse;
    httpSources.send(null);
}

function getQueryStringParameter(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(unescape(window.location.href));
    if (results == null) {
        return null;
    }
    else {
        return results[1];
    }
}

function isNullOrEmpty(input) {
    if (input == null || input == '') {
        return true;
    }
    return false;
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function getPreference(param) {
    //prefer values set in page
    // then query string
    // then cookie
    if (document.getElementById(param) != null) return document.getElementById(param).value;
    var queryParam = getQueryStringParameter(param);
    if (!isNullOrEmpty(queryParam)) return queryParam;
    var cookieParam = readCookie(param);
    if (!isNullOrEmpty(cookieParam)) return cookieParam;
    return null;
}

function getPreferenceDoj(param) {
    var fromQuery = getQueryStringParameter(param);
    if (!isNullOrEmpty(fromQuery)) return fromQuery;
    return 'dd-mmm-yyyy';
}

function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

function LoadDateofJourney() {
    if (!isNullOrEmpty(calendar)) {
        enteredDate = document.getElementById("calendar").value;
        calendar.value = getPreferenceDoj('doj');
    }
}

function LoadBusType() {
    if (!isNullOrEmpty(busType)) busType.value = getPreference('busType');
}
GetSources();
GetLoadTimeDestinations();
//GetAllSourceDestinations();
LoadDateofJourney();
LoadBusType();

function CustomDateValidation(enteredDate) {
    var validatedate = new RegExp("^(([012]?[0-9]|3[01])-([Jj][Aa][Nn]|[Ff][Ee][bB]|[Mm][Aa][Rr]|[Aa][Pp][Rr]|[Mm][Aa][Yy]|[Jj][Uu][Nn]|[Jj][u]l|[aA][Uu][gG]|[Ss][eE][pP]|[oO][Cc][Tt]|[Nn][oO][Vv]|[Dd][Ee][Cc])-([2][0-9][0-9][0-9]))$");
    var rdate = validatedate.test(enteredDate);
    if (rdate == false) {
        return "Please enter a valid date.";
    }
    //checking for future date
    var customdate = enteredDate.split("-");
    var tomorrowDate = parseInt(customdate[0], 10) + 1; //incrementing by 1 in the todays date becasue without this todays date was failing
    var splitAndFormed = (customdate[1] + " " + tomorrowDate + "," + customdate[2]);
    //alert(splitAndFormed);
    var selectedDate = new Date(splitAndFormed);
    //alert(selectedDate);
    if (selectedDate < new Date()) {
        return "Please select a future date.";
    }
    return "";
} /*----------------------------------------*/

//
function clearFilterCookies() {
    createCookie('_busType', '', -1);
    createCookie('_bp', '', -1);
    createCookie('_dp', '', -1);
    createCookie('_rating', '', -1);
}
    

function SearchBuses() {
    
    var selectedDate = document.getElementById("calendar").value;
    var returnDate = $("#calendarReturn").val();
    var errorDiv = document.getElementById("error");
    var dateValidationResult = CustomDateValidation(selectedDate);
    var fromCityName = sourceList.options[sourceList.selectedIndex].text;
    var toCityName = destList.options[destList.selectedIndex].text;
    var toSendReturnURL = false;
    if (dateValidationResult != "") {
        errorDiv.style.display = "block";
        errorDiv.innerHTML = dateValidationResult;
        document.getElementById("calendar").focus();
        return;
    }
    if(returnDate != null && returnDate != "" && returnDate != 'dd-mmm-yyyy')
    {
         if(!returnDate.match(/\d{2}-[a-zA-Z]{3}-\d{4}/)){            
            $("#error").show();
            $("#error").html("Please enter valid return date.");
            $("#calendarReturn").focus();
            return;
        }
         
         if(!validateReturnJourney(returnDate)){
            $("#error").show();
            $("#error").html("Please choose a later return date.");
            $("#calendarReturn").focus();
            return;       
         }
         else
         {
            toSendReturnURL = true;
         }
    
        
    }
    
    if (sourceList.value == 0) {
        errorDiv.style.display = "block";
        errorDiv.innerHTML = "Please select the 'From' location";
        return;
    }
    if (destList.value == 0) {
        errorDiv.style.display = "block";
        errorDiv.innerHTML = "Please select the 'To' location";
        return;
    }
    var bustypestring = 'Any';
    if (!isNullOrEmpty(busType)) {
        bustypestring = busType.value;
    }
    //$("#spinnerBar").show();
    var sendToUrl = "/Booking/SelectBus.aspx" + "?fromCityId=" + sourceList.value + "&fromCityName=" + fromCityName + "&toCityId=" + destList.value + "&toCityName=" + toCityName + "&doj=" + selectedDate + "&busType=" + bustypestring;
    var sendToReturnUrl = "/Booking/SelectBus.aspx" + "?fromCityId=" + destList.value + "&fromCityName=" + toCityName + "&toCityId=" + sourceList.value + "&toCityName=" + fromCityName + "&doj=" + returnDate + "&busType=" + bustypestring+"&type=return";
    
    if (!isNullOrEmpty(document.getElementById("pageSource"))) {
        sendToUrl += "&searchSource=" + document.getElementById("pageSource").value;
        sendToReturnUrl += "&searchSource=" + document.getElementById("pageSource").value;
    }
    var SifyAid = getQueryStringParameter('AID');
    if (!isNullOrEmpty(SifyAid)) {
        sendToUrl += "&SIFYAID=" + SifyAid;
        sendToReturnUrl +="&SIFYAID=" + SifyAid;
    }
    
    $(location).attr('href', sendToUrl);
    if(toSendReturnURL)
    {
        var newWindow = window.open(sendToReturnUrl,"ReturnTicket","resizable=yes,scrollbars=yes,toolbar=yes,location=yes,directories=yes");
        newWindow.blur();
    }
    
}
function validateReturnJourney(returnDate)
{
   var doj = $("#calendar").val();
   var dateOfJourney = new Date(doj.replace(/-/g,' '));
   var returndateOfJourney = new Date(returnDate.replace(/-/g,' '));
   if(returndateOfJourney - dateOfJourney < 0)
   {
        return false;
   }
    return true;
   
}
function validateDateFormat(selectedDate) {

    //var selectedDate = document.getElementById("calendar").value;
    var errorDiv = document.getElementById("error");
    var dateValidationResult = CustomDateValidation(selectedDate);
    if (dateValidationResult != null && selectedDate != 'dd-mmm-yyyy') {
        $("#error").show();
        $("#error").html(dateValidationResult);
        return false;
    }
    else {
        return true;
    }
    
}

function SearchBusesCorp() {
    var errorDiv = document.getElementById("error");
    //var dateValidationResult = CustomDateValidation(calendar.value);
    if (!validateDateFormat($('#calendar').val())) {
        return;
    }
    if (sourceList.value == 0) {
        errorDiv.style.display = "block";
        errorDiv.innerHTML = "Please select the 'From' location";
        return;
    }
    var bustypestring = 'Any';
    if (!isNullOrEmpty(busType)) {
        bustypestring = busType.value;
    }
    window.location.href = "/corp/SelectBus1.aspx" + "?F=" + document.getElementById("DDLSource").value + "&T=" + document.getElementById("DDLDestination").value + "&D=" + document.getElementById("calendar").value + "&Typ=Any&Tr=0&N=0";
}

function HideErrorMessage() {
    if ($("#calendar").val() != 'dd-mmm-yyyy' || destList.value != null) {
        $("#error").hide();
    }
}