var onReqToolTip = null, waitpage = null;
$(function() {

	// Cookie tracking (Analytics)
	var itnId = $("input:hidden[name='itinId']").val();
	trackPricingView(itnId);

	initSummaryPage();
	waitpage = new WaitPage();
});

/**
 * Initialize summary page
 * @return
 */
function initSummaryPage(){

	// Add ### buttons
	$("img.summaryAddButtons").click(function(){
		addOption($(this).attr('id'));
	});
	// On request tool tip
	$("span.onRequest").hover(
		function(){
			onReqToolTip = new AEVToolTip('whatIsOnRequest',{alwaysVisible: false});
			onReqToolTip.show();},
		function(){
			if(onReqToolTip)onReqToolTip.hide();
			onReqToolTip=null;}
	);
	// Rush order popup
	$("span.rushOrderUrl").click(function(){
		popUp("/aev/pages/static/RushOrderFee.html",605,130,"rushOrder");
	});
	// Hotel ratings
	$("a").find("#ratingLink").each(function(i) {
		$(this).css( {'text-decoration':'underline'} );
		$(this).click( function(){
			popUp('/aev/pages/static/Ratings.html',600,450,'hotelRating','menubar=no,toolbar=no,resizable=0');
		});
	});
	// Load trip advisor
	// loadTripAdvisor();
}

/**
 * Add items to trip
 * @param options
 * @return
 */
function addOption(options){
	if( options ){
		var params = options.split(',');
		if( document.forms['dataform'] && params.length > 1 ){
			document.forms['dataform'].dCode.value = params[0];
			var actionUrl = '/aev/summary.action';
			if( params[1] == 'car' ){
				actionUrl = '/aev/carSearch.action';
			} else if( params[1] == 'activity' ){
				actionUrl = '/aev/activity.action';
				document.forms['dataform'].didx.value = params[2];
			} else if( params[1] == 'transfers' ){
				document.forms['dataform'].requestFor.value = 'addTransfers';
			} else if( params[1] == 'gcevent' ){
				actionUrl = '/aev/gcbookit.action';
				document.forms['dataform'].didx.value = params[2];
			}
			document.forms['dataform'].action = actionUrl;
			document.forms['dataform'].submit();
		}
	}
}

/**
 * Modify Search
 * @return
 */
function modifySearch(stype){
	var param = '';
	if( stype == 'ss' ){	param = '?adv=Y';	}
	document.forms['dataform'].action = '/aev/search.action'+param;
	document.forms['dataform'].submit();
	if( waitpage ){waitpage.show('LOADING SEARCH PAGE',2000);}
}

/**
 * Loads trip advisor iframe
 * @param dhc
 * @return
 */
function loadTripAdvisor(){
	var inHtm = '', dhc = '';
	$("td.tripAdvisor").parent().find("div").each(function(){
		dhc = $(this).attr('id');
		inHtm = '<iframe src="' + TRIP_ADVISOR_URL + dhc + '" width="240" height="320" scrolling="no" frameborder="0" marginheight="0" marginwidth="0"></iframe>';
		$(this).html( inHtm );
	});
}

/**
 * Pops up hotel info page
 * @return
 */
function popUpHInfo(dc,hc,rtg){
	var src = document.forms['dataform'].source.value
	var pUrl = '/aev/hotelinfo.action?source='+src
		+ '&pop=Y'
		+ '&dCode=' + dc
		+ '&hCode=' + hc
		+ '&rating=' + rtg;
	popUp(pUrl,800,600,"hinfo");
}

/**
 * Purchase vacation
 * @return
 */
function purchaseVacation(insFlag,login,totalDests){
	var uform = document.UserType;
	var utype,url,waitmsg;
	var depFlightNo,arrFlightNo ,pickUpDate ,pickUpTime,arrAirline ,dropOffDate,dropOffTime,depAirline;
	var tform =document.tranform;


	if( tform ){
		var departFlightNo = tform.departFlightNo.value;
		var arrivalFlightNo = tform.arrivalFlightNo.value;
	    if(tform.arrivalFlightNo.value == ""){
				alert("Enter the Arrival Flight Number");
				tform.arrivalFlightNo.focus();
				return false;
		}

		for (i=0;i<departFlightNo.length ;i++){
			var theChar = departFlightNo.substring(i,i+1);
			if (theChar < "0"|| theChar > "9"){

					alert("Please enter numbers only for the Flight Number ");

				eval( "document." + "tranform" + "." + "departFlightNo"+ ".focus()");
				return false;
			}
		}

		if(tform.departFlightNo.value == ""){
				alert("Enter the Departure Flight Number");
				tform.departFlightNo.focus();
				return false;
		}

		for (i=0;i<arrivalFlightNo.length ;i++){
			var theChar =arrivalFlightNo.substring(i,i+1);
			if (theChar < "0"|| theChar > "9"){

					alert("Please enter numbers only for the Flight Number ");

				eval( "document." + "tranform" + "." + "arrivalFlightNo"+ ".focus()");
				return false;
			}
		}

		document.forms['dataform'].arrFlightNo.value = tform.arrivalFlightNo.value;
		document.forms['dataform'].pickUpDate.value = tform.pickUpDate.value;
		document.forms['dataform'].pickUpTime.value = tform.pickUpTime.value+":00";
		document.forms['dataform'].arrAirline.value = tform.arrivalAirline.value;;
		document.forms['dataform'].depFlightNo.value = tform.arrivalFlightNo.value;
		document.forms['dataform'].dropOffDate.value = tform.dropOffDate.value;
		document.forms['dataform'].dropOffTime.value = tform.dropOffTime.value+":00";
		document.forms['dataform'].depAirline.value = tform.departAirline.value;
	}
	if( uform ){

		if( uform.user[0].checked ){
			utype = 'amexuser';
		}
		else if( uform.user[1].checked ){
			utype = 'guest';
		}
		else{
			var coors = getPosition(document.getElementById('userChoiceTable'));
			coors[0] += 35;
			coors[1] -= 5;
			document.location.href="#purchaseError";
			$('#purchaseOptErrMsg').css({top:coors[1], left:coors[0]});
			$('#purchaseOptErrMsg').fadeIn('fast');
			$('#purchaseOptErrFlag').fadeIn('fast');
			return false;
		}

	}

	// SSO Login
	if( utype == 'amexuser' ){
		url = '/aev/ssorelogin.action?summary=Y';
		waitmsg = 'LOGIN BEFORE PURCHASE';
	}
	else{
		url = '/aev/purchase.action';
		waitmsg = 'WE ARE PRICING YOUR VACATION';
	}

	document.forms['dataform'].userType.value = utype;
	document.forms['dataform'].wantInsurance.value = insFlag;
	document.forms['dataform'].action = url;
	document.forms['dataform'].submit();
	if( waitpage ){waitpage.show(waitmsg,2000);}
	return false;
}
/**
 * Hide error message
 * @return
 */
function hideUTypeErr(){
	$('#purchaseOptErrMsg').fadeOut('fast');
	$('#purchaseOptErrFlag').fadeOut('fast');
}

/**
 * Select a different hotel
 * @param dstn
 * @param destIndex Starts with 0
 * @return
 */
function changeHotel(dstn,destIndex){
	document.forms['dataform'].dCode.value = dstn;
	document.forms['dataform'].action = '/aev/hotels.action';
	document.forms['dataform'].didx.value = destIndex;
	document.forms['dataform'].submit();
	if( waitpage ){waitpage.show('LOADING HOTELS',2000);}
}

/**
 * Select a different transfer
 * @param dstn
 * @return
 */
function changeTransfers(dstn){
	document.forms['dataform'].dCode.value = dstn;
	document.forms['dataform'].action = '/aev/summary.action';
	document.forms['dataform'].requestFor.value = 'changeTransfers';
	document.forms['dataform'].submit();
	if( waitpage ){waitpage.show('LOADING TRANSFERS',2000);}
}

function getHotelActivity(){
	var addOnArray=document.getElementsByName("addOnSummaryCb");
	if(addOnArray.length>0){
		for(var i=0;i<addOnArray.length;i++){
			if (addOnArray[i].value.indexOf("ho") == 0) {
				alert(addOnArray[i].value);
				var input = document.createElement("input");
				input.setAttribute("type", "hidden");
				input.setAttribute("name", "addOnSummaryCb");
				input.setAttribute("value", addOnArray[i].value);
				document.forms['dataform'].appendChild(input);
			}
		}
	}
}
/**
 * Next day arrival
 * Reprices hotels for new checkin dates
 * @param arrivalDate
 */
function repriceHotels( arrivalDate, dstn ) {

	if( document.getElementById('selectCheckInDate'+dstn) ){
		var startDate = $('#selectCheckInDate'+dstn).val();
		var du = new DateUtil();
		var diff = du.dateDifference( du.toJSDate(startDate), du.toJSDate(arrivalDate) );
		if( diff == 0 ){
			document.forms['dataform'].dCode.value = dstn;
			document.forms['dataform'].requestFor.value = 'repriceHotel';
			document.forms['dataform'].repriceCheckInDate.value = startDate;
			document.forms['dataform'].action = '/aev/hotels.action';
			document.forms['dataform'].submit();
			if( waitpage ){waitpage.show('REPRICING YOUR SELECTED HOTEL',2000);}
		}
		else {
			alert("Please change the check in date to match the flight arrival date");
			document.getElementById('selectCheckInDate'+dstn).focus();
		}
	}
}
/**
 *
 * @return
 */
function changeFlight(){
	document.forms['dataform'].action="/aev/flights.action";
	document.forms['dataform'].submit();
	if( waitpage ){waitpage.show('WE ARE PROCESSING YOUR REQUEST',2000);}
}


/**
 *
 * @return
 */
function changeCar(dstn){
	document.forms['dataform'].dCode.value = dstn;
	document.forms['dataform'].action="/aev/carSearch.action";
	document.forms['dataform'].submit();
}

/**
 * Remove items to trip
 * @param options
 * @return
 */
function removeCar(dstn){
			document.forms['dataform'].dCode.value = dstn;
			document.forms['dataform'].requestFor.value = 'removeCar';
			actionUrl = '/aev/summary.action';
			document.forms['dataform'].action = actionUrl;
			document.forms['dataform'].submit();

}

/**
 *
 * @return
 */
function changeGcEvent(dstn){

	document.forms['dataform'].action="/aev/gcbookit.action";
	document.forms['dataform'].submit();
	if( waitpage ){waitpage.show('SEARCHING GOLD CARD EVENT',2000);}
}

/**
 * Remove items to trip
 * @param options
 * @return
 */
function removeGcEvent(dstn){
	document.forms['dataform'].dCode.value = dstn;
	document.forms['dataform'].requestFor.value = 'removeGcEvent';
	actionUrl = '/aev/summary.action';
	document.forms['dataform'].action = actionUrl;
	document.forms['dataform'].submit();
	if( waitpage ){waitpage.show('REMOVING SELECTED GOLD CARD ACTIVITY',2000);}
}

/**
 * Remove items to trip
 * @param options
 * @return
 */
function removeTransfer(dstn){
	document.forms['dataform'].dCode.value = dstn;
	document.forms['dataform'].requestFor.value = 'removeTransfers';
	actionUrl = '/aev/summary.action';
	document.forms['dataform'].action = actionUrl;
	document.forms['dataform'].submit();
	if( waitpage ){waitpage.show('REMOVING TRANSFER FROM VACATION',2000);}
}
/**
 *
 * @return
 */
function changeDirectionalFlight(){
	document.forms['dataform'].action='/aev/directionalflights.action';
	document.forms['dataform'].submit();
	if( waitpage ){waitpage.show('WE ARE PROCESSING YOUR REQUEST',2000);}
}

function addSuugestedAddon(addonID,showCalendar){

	if(validatePax(addonID.substring(4),showCalendar)==false){
	return false;
	}
	document.forms['suggAddonForm'].addOnId.value=addonID;
	document.forms['suggAddonForm'].action='/aev/summary.action';
	document.forms['suggAddonForm'].submit();

}


/**
 * Validate passenger/date selection for suggest activity.
 * If the passenger/date selection is not available then return true always.
 * @param id
 * @return
 */
function validatePax(id,showCalendar) {

	           if(showCalendar=="false" || showCalendar==false){

	        	   return true;
	           }


			var scheduler_adult = document.getElementsByName("sh_ad_"+id);

			var scheduler_children = document.getElementsByName("sh_ch_"+id);

			var countPax = 0;

			for ( var j = 0; j < scheduler_adult.length; j++) {
				if (parseInt(scheduler_adult[j].value) > 0) {
					countPax++;
				}
			}

			for (j = 0; j < scheduler_children.length; j++) {
				if (parseInt(scheduler_children[j].value) > 0) {
					countPax++;
				}
			}

			if (countPax == 0) {
				alert("Please select at least one passenger for the selected activity");
				return false;
			}


	return true;
}
