// START jslib/popup.js --------------------------------------------------------
$(document).ready(function(){
    $("#popup li").mouseenter(function() {
        alert(1);
    });
});
function popup(region_id){
    var id = region_id ;
    var count_t = 1;
    var popup  = '#popup_country_id_region_'+id;
    var htmlStr = $(popup).html();

    $('#popup_country').hide();
    $('#popup_country').html(htmlStr);

    $('.click').click(function(e){
        $('#popup_country').css({
        'top':e.pageY-10,
        'left':e.pageX
        });

        $('#popup_city').css({
        'top':e.pageY-10,
        'left':e.pageX+150
        });
    });
    $("#popup_country").show(200);

    $('#popup_main').mouseleave(function(){
        $('#popup_country').hide();
        $('#popup_city').hide()
    });
}
function popup_city(country_id,el){
    var id = country_id ;
    var count_t = 1;
    var popup  = '#popup_city_id_country_'+id;

    var htmlStr = $(popup).html();

    var y = $(el).offset().top;
    var x = $(el).offset().left;

    $('#popup_city').hide();
    $('#popup_city').html(htmlStr);
    if(x > 950){
        $('#popup_city').css({
            'top':y-20,
            'left':x-162
        });
    } else {
        $('#popup_city').css({
            'top':y-20,
            'left':x+140
        });
    }
    $('#popup_country a').mouseenter(function(e){
        if(x > 950){
            $('#popup_city').css({
                'top':y-20,
                'left':x-162
            });
        } else {
            $('#popup_city').css({
                'top':y-20,
                'left':x+140
            });
        }
    })
    $('#popup_city').show(400);

}
// END jslib/popup.js ----------------------------------------------------------

// START js/search.js ----------------------------------------------------------
$(document).ready(function() {
    function findValueCallback(event, data, formatted) {
            $("<li>").html( !data ? "No match!" : "Selected: " + formatted).appendTo("#result");
    }

    function formatItem(row) {
    alert(row);
            return row[0] + " (<strong>id: " + row[1] + "</strong>)";
    }

    function formatResult(row) {
            return row[0].replace(/(<.+?>)/gi, '');
    }

    $("#city").autocomplete("/rpc.php", {
            width: 260,
            selectFirst: false
    });

    $(":text, textarea").result(findValueCallback).next().click(function() {
            $(this).prev().search();
    });
    $("#clear").click(function() {
            $(":input").unautocomplete();
    });
    $("a.leftregion").bind("click", function(){
        $(this).siblings('ul').toggle();
    });
});

function fill(thisValue) {
    $('#inputString').val(thisValue);
    setTimeout("$('#suggestions').hide();", 200);
}
// END js/search.js ------------------------------------------------------------

// START jslib/common.js -------------------------------------------------------

//=============== isDate ========================
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s) 
{
    var i;
    for (i = 0; i < s.length; i++){   
            // Check that current character is number.
            var c = s.charAt(i);
            if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag)
{
    var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
            var c = s.charAt(i);
            if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year)
{
    // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n)
{
    for (var i = 1; i <= n; i++) {
            this[i] = 31;
            if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
            if (i==2) {this[i] = 29}
    } 
    return this;
}

function isDate(dtStr)
{
    var daysInMonth = DaysArray(12)
    var pos1=dtStr.indexOf(dtCh)
    var pos2=dtStr.indexOf(dtCh,pos1+1)
    var strMonth=dtStr.substring(0,pos1)
    var strDay=dtStr.substring(pos1+1,pos2)
    var strYear=dtStr.substring(pos2+1)
    strYr=strYear
    if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
    if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
    for (var i = 1; i <= 3; i++) {
            if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
    }
    month=parseInt(strMonth)
    day=parseInt(strDay)
    year=parseInt(strYr)
    if (pos1==-1 || pos2==-1){
            alert("The date format should be : mm/dd/yyyy")
            return false
    }
    if (strMonth.length<1 || month<1 || month>12){
            alert("Please enter a valid month")
            return false
    }
    if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
            alert("Please enter a valid day")
            return false
    }
    if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
            alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
            return false
    }
    if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
            alert("Please enter a valid date")
            return false
    }
    return true
}


//========================== email validation function =============================
function isEmail(fieldObj)
{
        var str = fieldObj.value;
        var re = /^([a-zA-Z0-9-_\.]+@([a-zA-Z0-9-_]+\.)+[a-zA-Z]{2,4})$/;
        if (re.test(str)) {
                return true;
        } else {				
                return false;
        }

}
function isEmailValid(str)
{
        var re = /^([a-zA-Z0-9-_\.]+@([a-zA-Z0-9-_]+\.)+[a-zA-Z]{2,4})$/;
        if (re.test(str)) {	
                return true; 
        } else {				
                return false;
        }
}

//------------- us phone no check

function validPhoneUS(fieldObj)
{
        var str = fieldObj.value;
        re = /^\(?\d{3}\)?\s|-\d{3}-\d{4}$/;
        if (re.test(str)) {
                return true;
        } else {
                return false;
        }
}
function isPhoneNumber(str){
  var stripped = str.replace('-', '');
          stripped = stripped.replace('-', '');
        //strip out acceptable non-numeric characters
        if (isNaN(parseInt(stripped))) {
          return false;
        } else if (stripped.length != 10) {
                return false;
        }
        return true;
}

function validPhone(mixnumber)
{
        var str = mixnumber;
        if (str.length <= 0)
        {return false}
        var i;
        for (i = 0; i < str.length; i++){   
        // Check that current character is number.
        var c = str.charAt(i);
        if (((c < 0) || (c > 9))) return false; //  && c!="-" removed
        }
        // All characters are numbers.
        return true;
}
function validCreditCard(mixnumber)
{
        var str = mixnumber;
        var i;
        for (i = 0; i < str.length; i++){   
        // Check that current character is number.
        var c = str.charAt(i);
        if (((c < 0) || (c > 17))) return false; //  && c!="-" removed
        }
        // All characters are numbers.
        return true;
}

//------------- zip check
function validZip(fieldObj)
{
        var str = fieldObj.value;
        var re = /\d{5}(-\d{4})?/;
        if (!isNaN(str)===false) {
                return false;
        } else if (str.length <=3 || str.length >=10) {
                return false;
        } else {			
                return true;
        }	
}

//==============  CC Checks ====================================

function isVisa( cc )
{
        if( (cc.substring(0,1) == 4) && (cc.length == 16) || (cc.length == 13) ) {
                return true; // isCreditCard( cc );
        }
        return (false);
}

function isMC( cc )
{
        if( (cc.length == 16) && (cc.substring(0,2) == 51) || (cc.substring(0,2) == 52) || (cc.substring(0,2) == 53) || (cc.substring(0,2) == 54) || (cc.substring(0,2) == 55) ) {
                return true;//isCreditCard( cc );
        }
        return (false);
}

function isAmex( cc )
{
        if( (cc.length == 15) && (cc.substring(0,2) == 34) || (cc.substring(0,2) == 37) ) {
                return true;//isCreditCard( cc );
        }
        return (false);
}


function isDiscover( cc ) {
        if( (cc.length == 16) && (cc.substring(0,4) == 6011) )
        {
                return true;//isCreditCard( cc );
        }
                return (false);
}

function showDOM()
{
        for (it in document)
        {
        alert(it);
        }
}

function getFileSize(obj)
{	
        var oas = new ActiveXObject("Scripting.FileSystemObject");
        var e = oas.getFile(obj.value);
        var f = e.size;
        return f;
}

// whitespace characters
var whitespace = " \t\n\r";

// Check whether string s is empty.
function isEmpty(s) { 
    return ((s == null) || (s.length == 0))
}



function isWhitespace (s) {
    var i;

    // Is s empty?
    if (isEmpty(s)) return true;

    // Search through string's characters one by one
    // until we find a non-whitespace character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {
        // Check that current character isn't whitespace.
        var c = s.charAt(i);

        if (whitespace.indexOf(c) == -1) return false;
    }

    // All characters are whitespace.
    return true;
}



function ForceEntry(val, str) {
    var strInput = new String(val.value);

    if (isWhitespace(strInput)) {
        alert(str);
        return false;
    } else {
        return true;
    }
}



function ValidateRanking() {
// This function ensures document.forms[0].nRanking.value >=1 && <= 10

if (parseInt(document.forms[0].nRanking.value) >= 1 && parseInt(document.forms[0].nRanking.value) <=10)
return true;
else
return false;
}



function ValidateData() {
    var CanSubmit = false;

    // Check to make sure that the full name field is not empty.
    CanSubmit = ForceEntry(document.forms[0].txtName,"You supply a full name.");

    // Check to make sure ranking is between 1 and 10
    if (CanSumbit) CanSubmit = ValidRanking();
        return CanSubmit;
}
function isLeadingWhitespace (s)
{
    // Is s empty?
    if (isEmpty(s)) return true;

    // Search through string's characters one by one
    // until we find a non-whitespace character.
    // When we do, return false; if we don't, return true.
    var c = s.charAt(0);
    if (c == ' ') return true;

    // All characters are whitespace.
    return false;
}

function confirmation(msg) {
    if (confirm(msg)===false) {
        return false;
    }
}

// END jslib/common.js ---------------------------------------------------------

// START js/cruises.js ----------------------------------------------------------
// flag for booking
var cruise_trips_booking =  false;

//------------------------------------------------------------------------------
$(document).ready(function(){
    // labels
    $('.search_type label').click(function() {
       var label_class = $(this).attr('for');
       $('.search_type .'+label_class).trigger('click');
    });

    // cruise_line select
    $('#cruise_line').bind('change', function (){
        $('#cruise_ship').html('<option value="">Select Cruise Ship</option>');
        $('#depart_date').html('<option value="">Select Cruise Ship First</option>');
        $('#cruise_itinerary tbody').html('<tr><td colspan="5">Please complete the search form.</td></tr>');
        findShips();
    });

    // cruise_ship select
    $('#cruise_ship').bind('change', function (){
        $('#depart_date').html('<option value="">Select Departure Date</option>');
        $('#cruise_itinerary tbody').html('<tr><td colspan="5">Please complete the search form.</td></tr>');
        findDepartures();
    });

    // depart_date select
    $('#depart_date').bind('change', function (){
        //$('#cruise_itinerary tbody').html('<tr><td colspan="5">Please complete the search form.</td></tr>');
        //findItineraryDays();
        searchByCruise();
    });
});

function findShips(){
    $('#cruise_ship_indicator').show();
    var vendor_id;
    vendor_id = $('#cruise_line').val();

    $.ajax({
        type: 'POST',
        url: '/ajax/get_cruise_ships.php',
        datatype: 'html',
        data: {"vendor_id": vendor_id},
        success: function(ansver){
                $('#cruise_ship').append(ansver);
                $('#cruise_ship_indicator').hide();
        }
    });
}

function findDepartures(){
    $('#depart_date_indicator').show();
    var ship_id;
    ship_id = $('#cruise_ship').val();

    $.ajax({
        type: 'POST',
        url: '/ajax/get_cruise_departures.php',
        datatype: 'html',
        data: {"ship_id": ship_id},
        success: function(ansver){
                $('#depart_date').append(ansver);
                $('#depart_date_indicator').hide();
        }
    });
}

function findItineraryDays(port_id, day){
    var itinerary_id;
    itinerary_id = $('#depart_date').val();

    $.ajax({
        type: 'POST',
        url: '/ajax/get_cruise_itinerary_days.php',
        datatype: 'html',
        data: {
            "itinerary_id": itinerary_id
        },
        success: function(ansver){
            $('#cruise_itinerary tbody').html(ansver);
            //$('#cruise_itinerary_content').show();
            //$('#uniq_content1').hide();
            if(port_id !== undefined && day !== undefined) {
                findCruiseTrips(port_id, '', day);
            }
        } 
    });
}

function findCruiseTrips(port_id, td, day){
    startWait();
    window.cruise_trips_booking = true;
    $('#cruise_itinerary tbody tr').css('background-color','#fff');
    $('#cruise_itinerary tbody tr').unbind('mouseover');
    $('#cruise_itinerary tbody tr').unbind('mouseout');
    $('#cruise_itinerary tbody tr:nth-child('+day+')').css('background-color', '#9EC4E1');
    $('#itinerary_day').val(day);
    
    $.ajax({
        type: 'POST',
        url: '/ajax/get_cruise_trips.php',
        datatype: 'html',
        data: {
            "port_id": port_id
        },
        success: function(ansver){
            $('#foundCruiseTrips').html(ansver);
            endWait(); 
            window.location = '#tripsanchor';
            
        },
        error: function(){
            $('#foundCruiseTrips').html('<div style="margin: 0 auto;">No trips found</div>');
            endWait();
        }
    });
    return false;
}

function searchByCruise() {
    var cruise_line = $('#cruise_line').val();
    var cruise_ship = $('#cruise_ship').val();
    var depart_date = $('#depart_date').val();
    
    var city = $('#city').val();
    if(city == 'Enter the city name') {
        city = '';
    }
    
    if(cruise_line != '' && cruise_ship != '' && depart_date != '') {
        window.location.href = '/index.php?cruise_vendor_id=' + cruise_line + '&cruise_ship_id=' + cruise_ship + '&cruise_itinerary_id=' + depart_date + '&scity=' + city + '&stype=cruise';
    } else {
        alert('Please complete the search form.');
    }
}
// END js/cuises.js ------------------------------------------------------------

// START jslib/trip_functions.js -----------------------------------------------

function LTrim( value ) {
	
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
	
}

// Removes ending whitespaces
function RTrim( value ) {
	
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
	
}

// Removes leading and ending whitespaces
function trim( value ) {
	
	return LTrim(RTrim(value));
	
}

function getHttpObject()
{var xmlHttp;
   // Firefox, Opera 8.0+, Safari
	try {xmlHttp=new XMLHttpRequest();} 
	  	catch (e) {    // Internet Explorer    
	  		try {xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");} 
	  			catch (e) { 
	  				try {xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");}
						catch (e) {alert("Your browser does not support AJAX! IE is highly recommended to use this feature !!");return false; 
						} 
					}
	}
	return xmlHttp;
}
// get http response for requested query
function getResponse(URL, Method)
{
	var strResponseText;
	var objHTTP = getHttpObject();
	if (!objHTTP) { // if browser does not support AJAX end program here and return error
			return false;
	}
	
	objHTTP.open(Method, URL, false); 
	objHTTP.send(null); 	 // send http request 	
	if(objHTTP.readyState == 4)
	{				
		 strResponseText = objHTTP.responseText; //return response text	
		 return strResponseText;
	}	
}

// Common function for ajax end here


// General functions //
// add option element to the select element
function addOption(obj, strText, mixValue)
{
	var newOption =document.createElement('option');
		
  		newOption.text 	= strText;
		newOption.value = mixValue;
		try
		{
		obj.add(newOption, null); // standards compliant
		}
	  	catch(ex)
		{
		obj.add(newOption);  // IE only
		}
		
}
// remove a single option from the list of select box
function removeOption(obj, index)
{
	obj.remove(index);
}
// Remove all the elements form the list of select box //
function removeAllOptions(obj)
{	
  var loopLength = obj.length;
  for (var i=0; i < loopLength;i++) {
	  removeOption(obj, obj.options[i]);  
  }
}
// General functions end here //
// functions for search form 'country city list popup' start here
// get list of countries for a region
function getCountries(region)
{
	var Method = "GET"; // set method of request for http
	var URL = "/getResponse.php?region=" + region;	// Http request URL
	var strResponseText = getResponse(URL, Method);	// get Response result from the server for the requested value	
	return strResponseText;

}
// set the list of countries to the list box
function setCountryList(region)
{
	var strOuterHTML 	= "";
	var strCountryList 	= getCountries(region);
	var arryCountryList = strCountryList.split('||');
	var objCountry		= document.getElementById("country");
	removeAllOptions(objCountry); // remove all the options first //
	addOption(objCountry, 'Select Country', "");
	//================================Add by kulvinder ===========================================
	var objcity		= document.getElementById("city");
	removeAllOptions(objcity); // remove all the options first //
	addOption(objcity, 'Select City', "");
	//==========================================================================================
	for (var i=0;i < arryCountryList.length; i++) {
		if (arryCountryList[i] != "") {				
			arryCountry = arryCountryList[i].split('|');	
			if (arryCountry.length==2) {
				addOption(objCountry, arryCountry[1], arryCountry[0]);
				
			}
		}		
	}
}

// get list of cities for a country
function getCities(country)
{
	var Method = "GET"; // set method of request for http
	var URL = "/getResponse.php?country=" + country;	// Http request URL
	var strResponseText = getResponse(URL, Method);	// get Response result from the server for the requested value
	return strResponseText;
}
// set the list of cities to the list box
function setCityList(country)
{
	
	var strOuterHTML = "";
	var strCityList  = getCities(country);
	var arryCityList = strCityList.split('||');	
	var objCity		= document.getElementById("city");
	removeAllOptions(objCity); // remove all the options first //	
	addOption(objCity, 'Select City', "");
	for (var i=0;i < arryCityList.length; i++) {
		if (arryCityList[i] != "") {
			arryCity = arryCityList[i].split('|');			
			if (arryCity.length==2) {
				addOption(objCity, arryCity[1], arryCity[0]);
			}
		}		
	}
}
// functions for search form 'country city list popup' end here

// Search result page AJAX functionalites Start Here


function getTripRateOptions(rate_id, trip, markup, exchange, cur_type, currency)
{
	var Method = "GET"; // set method of request for http
	var URL = "/getResponse.php?rate_id=" + rate_id + '&trip=' + trip + '&markup=' + markup + '&exchange=' + exchange + '&cur_type=' + cur_type + '&currency=' + currency;	// Http request URL
	var strResponseText = getResponse(URL, Method);	// get Response result from the server for the requested value
	return strResponseText;
}
function setTripRateOptions(rate_id, trip, markup, exchange, cur_type, currency)
{
	var strOptions 	= "";
	var strTableID 	= "tripOptions_" + trip;
	
	strOptions	= getTripRateOptions(rate_id, trip, markup, exchange, cur_type, currency); // get the response result
	//console.log(strOptions.length);
	arryOptions     = strOptions.split('|=|'); // explode the result with this parameter
	strOptions      = arryOptions[0]; // lunch, guide, entry fee options
	
	CheckBoxesArr  = strOptions.split("|");
            mainId = document.getElementById(strTableID);
	if (navigator.appName === "Microsoft Internet Explorer") {
            mainId.innerText = "";
	}
	else
	{
            mainId.innerHTML = "";
	}
	var tbdy = document.createElement("tbody");
	
	for(k=0;k<CheckBoxesArr.length - 1;k++)
	{
		checkBoxElement = CheckBoxesArr[k].split(",");
		if(trim(checkBoxElement[0]) != '')
		{
		var tr = document.createElement("tr");
		var td = document.createElement("td");
		var td2 = document.createElement("td");

		checkBoxElement = CheckBoxesArr[k].split(",");
		var check1 =document.createElement("input");
		check1.type = "checkbox";
		check1.name = trim(checkBoxElement[0]);
		check1.id = trim(checkBoxElement[0]);

		var funct = checkBoxElement[1];
		check1.onclick = function() {eval(funct)}
		check1.value = "1";

		var textOfCheckBox = document.createTextNode(checkBoxElement[2]);

		td.appendChild(check1);
		td2.appendChild(textOfCheckBox);

		tr.appendChild(td);
		tr.appendChild(td2);
		tbdy.appendChild(tr);
		}
	}
	mainId.appendChild(tbdy);

	arryOptions	= arryOptions[1].split('||'); // explode the value to set hidden field value order upto person, price, lunch rate, guide rate, entry fee//
	// set hidden field value according to current options choosed //
	
	var objFrm	= eval("document.frmTrip_" + trip);
	eval('objFrm.upto_persons' + trip).value        = Math.round(parseInt(arryOptions[0]));
	eval('objFrm.price' + trip).value 		= Math.round(parseInt(arryOptions[1]));
	eval('objFrm.lunch' + trip).value		= Math.round(parseInt(arryOptions[2]));
	eval('objFrm.guide' + trip).value		= Math.round(parseInt(arryOptions[4]));
	eval('objFrm.entry' + trip).value		= Math.round(parseInt(arryOptions[3]));
	if (calcGroupTotal(trip) == false) {
            var objRad = eval('objFrm.trip_rate_' + trip);
            for (var i=0;i<eval('objFrm.trip_rate_' + trip).length;i++) {			
                if (objRad[i].checked == true) {
                        objRad[i].checked = false;
                }
            }		
            return false;
	}
}
// Search result page AJAX functionalites End Here 
function change_currency(frm, actionURL)
{
    frm.action = actionURL;
    frm.submit();
}
// for person based trip //
function validatePerson(trip, min_price, min_person)
{
	var frm = eval("document.frmTrip_" + trip);
	var per_person_price = 0;
	var num_person = eval('frm.persons_' + trip).value;
	var cur_type   = eval('frm.cur_mode_' + trip).value;
	if (isNaN(num_person) || num_person <= 0) {
            alert("Please enter a valid number of persons!");
            eval('frm.persons_' + trip).focus();
            return false;
	}

	per_person_price = eval('frm.per_person_price_' + trip).value;
	frm.action = "/book.php";
	//eval('frm.total_' + trip).value  = Math.round(per_person_price * num_person);

	frm.submit();
}
// for person based trip
function calcTotal(trip, min_price, min_person)
{
	var frm = eval("document.frmTrip_" + trip);
	var per_person_price = 0;
	var num_person = eval('frm.persons_' + trip).value;
	var cur_type   = eval('frm.cur_mode_' + trip).value;
	if (isNaN(num_person) || (num_person <= 0 && num_person != '') || num_person > 1000) {
		alert("Please enter a valid number of persons !");
		eval('frm.persons_' + trip).focus();
		return false;
	}
	
	if (min_person > parseInt(num_person)) {
            per_person_price =  Math.round(min_price / num_person);
			if (!confirm("You have entered less than minimum number of person!! Price for per person will be " + per_person_price + " (" + cur_type + ") per person ! Do you want to continue ?")) {
					return false;
			} else {
					eval('frm.total_' + trip).value  = Math.round(per_person_price * num_person);
					var id ='#vtotal_' + trip;
                    var id2 ='#total_' + trip;
					var totalPrice = Math.round(per_person_price * num_person);

					$(id).html(totalPrice);
                    $(id2).html(totalPrice);
			}
	} else {
            per_person_price = eval('frm.per_person_price_' + trip).value;
            eval('frm.total_' + trip).value  = Math.round(per_person_price * num_person);
            var id ='#vtotal_' + trip;
            var id2 ='#total_' + trip;
            var totalPrice = Math.round(per_person_price * num_person);

            $(id).html(totalPrice);
            $(id2).html(totalPrice);
	}
	return false;
}



// for group based trip
function validateGroup(trip)
{
	var frm = eval("document.frmTrip_" + trip);
	var per_person_price = 0;
	var num_person = eval('frm.persons_' + trip).value;
	var cur_type   = eval('frm.cur_mode_' + trip).value;

	var objRad = eval('frm.trip_rate_' + trip);
	if (isNaN(num_person) || num_person <= 0) {
		alert("Please enter a valid number of persons !");
		eval('frm.persons_' + trip).focus();
		if (objRad.checked==true) {
			objRad.checked=false;
		}
		return false;
	}

	var sel = false;
	var objRad = eval('frm.trip_rate_' + trip);
	if (!isNaN(objRad.length)) {
		for (var i=0;i<eval('frm.trip_rate_' + trip).length;i++) {		
			if (objRad[i].checked == true) {
				sel = true;
			}
		}
	} else if (objRad.checked==true) {
		sel = true;
	}
	if (sel === false) {
		alert("Please choose group size !");
		return false;
	}

	var max_person	= parseInt(eval('frm.upto_persons' + trip).value, 0);
	var group_price = parseInt(eval('frm.price' + trip).value, 0);
	var lunch_price = parseInt(eval('frm.lunch' + trip).value, 0);
	var guide_price = parseInt(eval('frm.guide' + trip).value, 0);
	var entry_price = parseInt(eval('frm.entry' + trip).value, 0);
	if (num_person > max_person) {
		alert('You have entered number of persons more than the maximum limit of the group please choose suitable group option to continue.');
		return false;
	} else {
			var totalPrice = group_price;
						if (navigator.appName === "Microsoft Internet Explorer")
		{
				var compareWith = "[object]";
		}
		else
		{
			 var compareWith = "[object HTMLInputElement]";
		}
			if(document.getElementById("lunch_"+trip) == compareWith) {
				
					totalPrice +=(document.getElementById("lunch_"+trip).checked === true)?(lunch_price*num_person):(0);
				}
			if(document.getElementById("entry_"+trip) == compareWith) {
					totalPrice +=(document.getElementById("entry_"+trip).checked === true)?(entry_price*num_person):(0);
				}
			
			if (document.getElementById("guide_" + trip)== compareWith) {
					totalPrice +=(document.getElementById("guide_" + trip).checked === true)?(guide_price):(0);
				}

			eval('frm.total_' + trip).value = Math.round(totalPrice);
			frm.action = "/book.php";			
	}
	frm.submit();
}
// for group based trip
function calcGroupTotal(trip)
{
	var frm = eval("document.frmTrip_" + trip);
	var per_person_price = 0;
	var num_person = eval('frm.persons_' + trip).value;
	var cur_type   = eval('frm.cur_mode_' + trip).value;
	
	var objRad = eval('frm.trip_rate_' + trip);
	if (isNaN(num_person) || num_person <= 0) {
            alert("Please enter a valid number of persons !");
            eval('frm.persons_' + trip).focus();
            if (objRad.checked==true) {
                objRad.checked=false;
            }
            return false;
	} 
	
	var sel = false;
	var objRad = eval('frm.trip_rate_' + trip);
	if (!isNaN(objRad.length)) {
            for (var i=0;i < objRad.length;i++) {		
                if (objRad[i].checked == true) {
                    sel = true;			
                }
            }
	} else if (objRad.checked==true) {
            sel = true;
	}

	if (sel === false) {
            alert("Please choose group size !");
            return false;
	}
	
	var max_person	= parseInt(eval('frm.upto_persons' + trip).value, 0);
	var group_price = parseInt(eval('frm.price' + trip).value, 0);
	
		
	if (num_person > max_person) {
		alert('You have entered number of persons more than the maximum limit of the group please choose suitable group option to continue.');
		return false;
	} else {
                var lunch_price = parseInt(eval('frm.lunch' + trip).value, 0);
                var guide_price = parseInt(eval('frm.guide' + trip).value, 0);
                var entry_price = parseInt(eval('frm.entry' + trip).value, 0);

                var totalPrice = Math.round(group_price);

                if (navigator.appName === "Microsoft Internet Explorer") {
                    var compareWith = "[object]";
		} else {
                     var compareWith = "[object HTMLInputElement]";
		}
			if(document.getElementById("lunch_"+trip) == compareWith) {
                            totalPrice +=(document.getElementById("lunch_"+trip).checked === true)?(lunch_price*num_person):(0);
                        }
			if(document.getElementById("entry_"+trip) == compareWith) {
                            totalPrice +=(document.getElementById("entry_"+trip).checked === true)?(entry_price*num_person):(0);
                        }
			
			if (document.getElementById("guide_" + trip)== compareWith) {
                            totalPrice +=(document.getElementById("guide_" + trip).checked === true)?(guide_price):(0);
                        }
			eval('frm.total_' + trip).value = Math.round(totalPrice);
			//eval('frm.total_' + trip).focus();
                        var id ='#vtotal_' + trip;
                        var totalPrice = Math.round(totalPrice);
                        
                     	$(id).html(totalPrice);
	}
	return true;
}
// END jslib/trip_functions.js -------------------------------------------------

// START js/left_inc.js --------------------------------------------------------
function treeregion(region_id, country_trip)
{
    function tree(html)
    {
        $("#content_trips_def").hide();
        $(".ulhide").hide();
        $("#content_trips_def").html(html);
        $("#content_trips_def").slideDown(0);
        $("#image_show").attr("src","images/select_country.jpg");
    }
    var id = region_id;
    count_t = country_trip;
    $.ajax({
        type: 'POST',
        url: '/ajax/treeregion.php',
        datatype: 'html',
        data: {"region_id": id,"country_trip":count_t},
        success: tree
    });
}
function startWait () {
    $("#fuzz").css("height", $('body').css('height'));
    $("#fuzz").show();
    $("#fuzz").css({opacity: .5});

    return false;
}
function endWait () {
    $("#fuzz").fadeOut(1000);
    return false;
};
$('document').ready(function() {
    $("#fuzz").css("height", $('body').css('height'));

    $(window).bind("resize", function() {
        $("#fuzz").css("height", $('body').css('height'));
    });

    $(window).bind("scroll", function() {
        $("#fuzz").css("height", $('body').css('height'));
    });
    $(".item_ballon").click(function(){
        window.location=$(this).find("a").attr("href");return false;
    });
});
// ajax duration order sorting
function ajaxsorting(lnk,duration_order,region_id,country_id,city_id){
    startWait();
    // container
    var container = $(lnk).parent('#sorting').parent('div');

    var order = duration_order;
    var region = region_id;
    var country= country_id;
    var city   = city_id;

    if (city != undefined) {
          $(container).load("/ajax/trip_list.php",{'duration_order':order,'region':region,'country':country,'city':city} );
    }else{
        if (country != undefined){
              $(container).load("/ajax/trip_list.php",{'duration_order':order,'region':region,'country':country} );
        }else{
              $(container).load("/ajax/trip_list.php",{'duration_order':order,'region':region} );
        }
    }
    endWait();
}
function ajaxregion(region_id, country_id) {
    startWait();
    var id = region_id;
    $('#content').load("/ajax/trip_list.php",{region:id});
    endWait();
}
function treecity(country_id,region_id)
{
    var id_count = country_id;
    var id_reg = region_id;
    $.ajax({
        type: 'POST',
        url: '/ajax/treecity.php',
        datatype: 'html',
        data: {"country_id": id_count,"region_id": id_reg},
        success: tree
    });


    function tree(htm)
    {
        $("#content_trips_def").hide();
        $("#content_trips_def").empty();
        $("#content_trips_def").html(htm);
        $("#content_trips_def").slideDown(0);
        $(".ulhide").hide();

   }
}
function ajaxcity(country_id,region_id) {
    startWait();
    var id_count = country_id;
    var id_reg = region_id;
    $('#content').load("/ajax/trip_list.php",{"region": id_reg,"country": id_count} );
    endWait();
}
function treecityregion()
{
    $(".ulhide").show();
    $("#content_trips_def").hide();
    $("#image_show").attr("src","images/select_region.gif");
 }
function treecityo(region_id,country_id,city_id)
{
    startWait();
    var id_count = country_id;
    var id_reg = region_id;
    var id_city = city_id;

    $('#content').load("/ajax/trip_list.php",{'region':id_reg,'country':id_count,'city':id_city} );
    endWait();
}
// END js/left_inc.js ----------------------------------------------------------

function searchNameq()
{
    if ($("#city").val() == $("#city").attr('title') || $("#city").val() == ''  ) {
        alert('Please complete the search form.');
        return false ;
    } else {
        var cruise_line = $('#cruise_line').val();
        var cruise_ship = $('#cruise_ship').val();
        var depart_date = $('#depart_date').val();

        var city = $('#city').val();
        window.location.href = '/shore-excursions-in-'+ $("#city").val().replace(" ", "-") +'/'+ $("#city").val().replace(" ", "-") +'/scity=' + city + '&stype=city';
    }
}
function searchNameq_up(page)
{
    startWait();
    var page = page;
    if ($("#city").val() == $("#city").attr('title') || $("#city").val() == ''  )
    {
        return false;
    } else {
        function tree(html)
        {
            $("#content").empty();
            $("#content").html(html);
            endWait();
        }
        var city = $("#city").val();
        $('#loader').show();
        $.ajax({
            type: 'GET',
            url: '/ajax/in-search.php',
            datatype: 'html',
            data: {"name": city,"pages":page},
            success: tree
        });
    }
}
function TrimString(sInString) {
    sInString = sInString.replace( /^\s+/g, "" );
    return sInString.replace( /\s+$/g, "" );
}

function getBookedList (user_id)
{
    startWait();
    $('#loader').show();
    $.ajax({
        type: 'GET',
        url: '/ajax/getBookedList.php',
        datatype: 'html',
        data: {"user_id": user_id},
        success: function (responce)
        {
            console.log(responce);
            $('div.login_box').append(responce);
            endWait();
        }
    });

    return false;

}//
