﻿/**
 * @author cuong.tran
 * @email cuong.tran@enclaveit.com, cuongtranquoc@gmail.com
 * @function Booking 
 * @version 2.0
 * @create date: 10/27/2009 
 * @last update: 08 Nov 2010
**/
IncludeJavaScript('/Js/Tooltip/Tooltip.js');
IncludeJavaScript('/Js/TimeoutManager.js');

var booking = {
	shipID: 1,
	cruiseCode: '',
	oldRoom: '',
	oldMessage: '',
	bookedCount: 0,
	basketPageURL: '/Basket.aspx',
	inprogressMess: 'Booking in progress, please wait..',
	changeCruiseMess: 'All cabins in your current basket will be removed!\nAre you sure?',
	summary: {
		elementID: 'booking_summary',
		objectName: 'Ind_Body_Right_BookingSummary.ascx',
		loadingError: 'Error on reload booking summary progress'
	},
	fullcharter: {
		enabled: false,
		booked: false,
		disableMess: 'Disable full charter booking in progress, please wait..',
		inprogressMess: 'Full charter booking in progress, please wait..',
		alertMess: 'You are using full charter booking mode in this cruise.\nTo add or remove booking for this cabin, you must disable full charter mode.\nDo you want to disable it?',
		uavailableCabinMess: 'Some cabin(s) is being selected by other passenger. So you can not full charter booking!',
		accessDenied: 'You do not have permissions to perform the requested action!',
		errorMess: 'Unknow error occur in Full charter booking progress!\nPlease try again!',
		confirmMess: 'Full charter booking will book all cabins in this cruise.\nAre you sure?',
		disableConfirmMess: 'Disable full charter booking in this cruise.\nAre you sure?',
		disableUnsuccessMess: 'Unknow error occur in disable full charter booking progress!\nPlease try again!',
		bookingURL: '/Handler/FullCharterBooking.aspx'
	}
};
function selectDeparture(field){
	var enableChange = true;
	if (hasBooking()) {
		enableChange = (confirm(booking.changeCruiseMess) == 1);
	}
	if (enableChange) {
		var redirectURL = '';
		var currentStream = trim(getRequestValue('s'));
		var currentURL = window.location.href.split('#')[0];
		var currentOption = field.options[field.selectedIndex];
		var cruiseDesc = document.getElementById('cruise_desc');
		if (cruiseDesc) {
			var cruiseDescSt = ''
			                 + 'Ship Name: <b>' + currentOption.getAttribute('ship') + '</b>'
                             + ', Cruise code: '
                             + '<b>' + currentOption.getAttribute('code') + '</b>'
                             +', Departure Date: '
                             + '<b>' + currentOption.getAttribute('dep') + '</b>'
                             + ', Arrival Date: '
                             + '<b>' + currentOption.getAttribute('arv') + '</b>';
            cruiseDesc.innerHTML = cruiseDescSt;  
		}
		if (currentStream == ''){
		    currentStream = getCurrentStream();
		}
		if(!(currentStream in ['1','2',''])){		
		    redirectURL = replaceURLPara(currentURL, 's', getCurrentStream());
		    redirectURL = replaceURLPara(redirectURL, 'c', currentOption.getAttribute('code'));		
		}else{
		    redirectURL = removeURLPara('c');
		    redirectURL = removeURLPara('s',redirectURL);
		    redirectURL = AddURLPara(redirectURL , 'c', currentOption.getAttribute('code'));		
		}		
		window.location.href = redirectURL;
	}else{
	    //Restore current cruise	    
	     for (var i = 0; i < (field.options.length); i++) {	        
            if (field.options[i].style.color =='Green') {                
                field.selectedIndex = i;                
                break;
            }
        }
	}
	return false;
};
function getCurrentStream(){
    var stream1 = document.getElementById('stream1');
    var stream2 = document.getElementById('stream2');
    if (stream1){
        if(stream1.checked){
            return 1;
        }
    }
    if (stream2){
        if(stream2.checked){
            return 2;
        }
    }
    return 1;
};
function selectStream(field){
	if (field.getAttribute('crnt') != '1') {
		var enableChange = true;
		if (hasBooking()) {
			enableChange = (confirm(booking.changeCruiseMess) == 1);
		}
		if (enableChange) {
			var currentURL = removeURLPara('c').split('#')[0];
			window.location.href = replaceURLPara(currentURL, 's', field.value);
		}
		else {
			var oldfield;
			if (field.id == 'stream2') {
				oldfield = document.getElementById('stream1');
			}
			else {
				oldfield = document.getElementById('stream2');
			}
			if (oldfield) {
				oldfield.checked = true;
			}
		}
	}
};
function register_Cabin_Action(){
	var deckPlan = document.getElementById('deck_plan');
	if (deckPlan) {
		booking.bookedCount = 0;
		booking.shipID = deckPlan.getAttribute('shipid');		
		booking.cruiseCode = deckPlan.getAttribute('cruisecode');
		
		var allDivTag = deckPlan.getElementsByTagName('div');
		for (var i = 0; i < allDivTag.length; i++) {
			if (allDivTag[i].id.match(/\bc_/ig)) {
				if ((allDivTag[i].className.match(/c_unavl/ig)) || (allDivTag[i].className.match(/c_temp/ig)) || (allDivTag[i].className.match(/c_locked/ig))) {
					XBrowserAddHandler(allDivTag[i], 'mouseover', function(){
						try {
							showtip(getMessage(this));
						} 
						catch (e) {
						}
					});
					XBrowserAddHandler(allDivTag[i], 'mouseout', function(){
						try {
							hidetip();
						} 
						catch (e) {}
					});
				}
				else {
					if (allDivTag[i].className.match(/c_owner/ig)) {
						booking.bookedCount += 1;
					}
					XBrowserAddHandler(allDivTag[i], 'click', function(){
						addBooking(this, true)
					});
					XBrowserAddHandler(allDivTag[i], 'mouseover', function(){
						try {
							showtip(getMessage(this));
						} 
						catch (e) {
						}
					});
					XBrowserAddHandler(allDivTag[i], 'mouseout', function(){
						try {
							hidetip();
						} 
						catch (e) {}
					});
				}
			}
		}
	}
	timeoutManager.load(booking.bookedCount);
};
function hasBooking(){
	return booking.bookedCount > 0;
};
function updateBookedCount(){
	var deckPlan = document.getElementById('deck_plan');
	if (deckPlan) {
		booking.bookedCount = 0;
		var allDivTag = deckPlan.getElementsByTagName('div');
		for (var i = 0; i < allDivTag.length; i++) {
			if (allDivTag[i].className.match(/\bc_owner/ig)) {
				booking.bookedCount += 1;
			}
		}
	}
	return false;
};
function addBooking(field, ajaxBooking){
	var temp;
	var basket = {
		item: '',
		productID: '',
		productCode: '',
		product2: '',
		productCode2: '',
		cabinCode: '',
		quantity: 1,
		ecomAction_AddP1: 99,
		ecomAction_RemoveP1AddP2: 88,
		ecomAction_RemoveP2: 2,
		enableAjax: false
	}
	if (booking.fullcharter.booked) {
		if (confirm(booking.fullcharter.alertMess)) {
			try {
				showMask(booking.fullcharter.disableMess);
			} catch (e) {}
			var returnData = GetData(0, 'http://' 
			                            + fnGetDomain(window.location.href) 
			                            + booking.fullcharter.bookingURL 
			                            + '?sid=' + getSecCode() 
			                            + '&action=3');
            if (returnData <= 0) {
                alert(booking.fullcharter.disableUnsuccessMess );
                try{
                    hideMask();
                }catch(e){}    
            } else {
                // Reload page when error
                window.location.href = window.location.href;
            }					
		}
		return;
	}
	try {
		showMask(booking.inprogressMess);
	} catch (e) {}
	setTimeout(function(){
	    //Process...	    	    
	    temp = field.getAttribute('product').split('|');
	    basket.enableAjax = ajaxBooking;
	    basket.cabinCode = field.getAttribute('code');
	    basket.item = field.getAttribute('basket');
	    if ((basket.item == '') || (basket.item == null)) {
		    basket.item = -1;
	    }
	    basket.product = temp[0];
	    basket.productCode = temp[1];
	    basket.product2 = temp[2];
	    basket.productCode2 = temp[3];
    	
	    if (field.className.match(/cabin c_0p/ig)) {        
            bookingURL = booking.basketPageURL 
                        + '?basket_action=' + basket.ecomAction_AddP1
                        + '&basket_item=' + basket.item
                        + '&basket_quantity=1' 
                        + '&basket_cabincode=' + basket.cabinCode 
                        + '&basket_product=' + basket.product 
                        + '&productcode=' + basket.productCode
                        + '&basket_product2=' + basket.product2
                        + '&productcode2=' + basket.productCode2
                        + '&booking=1';
        }
        else {
            if (field.className.match(/cabin c_1p/ig)) {            
                bookingURL = booking.basketPageURL 
                        + '?basket_action=' + basket.ecomAction_RemoveP1AddP2
                        + '&basket_item=' + basket.item
                        + '&basket_quantity=1' 
                        + '&basket_cabincode=' + basket.cabinCode 
                        + '&basket_product=' + basket.product 
                        + '&productcode=' + basket.productCode
                        + '&basket_product2=' + basket.product2
                        + '&productcode2=' + basket.productCode2
                        + '&booking=1';                        
            }
            else {            
                bookingURL = booking.basketPageURL 
                        + '?basket_action=' + basket.ecomAction_RemoveP2
                        + '&basket_item=' + basket.item
                        + '&basket_quantity=1' 
                        + '&basket_cabincode=' + basket.cabinCode 
                        + '&basket_product=' + basket.product 
                        + '&productcode=' + basket.productCode
                        + '&basket_product2=' + basket.product2
                        + '&productcode2=' + basket.productCode2
                        + '&booking=1';                                   
            }
        }
        
        bookingURL +='&s=' + booking.shipID;
        bookingURL +='&c=' + booking.cruiseCode;
        
	    if (basket.enableAjax) {
		    bookingURL += '&enableAjax=1';
	    }	  	    
	    if (ajaxBooking) {
		    var returnData = GetData(0, 'http://' + fnGetDomain(window.location.href) + bookingURL);				
		    if (returnData == '1') {
			    reloadBookingSummary();
			    if (field.className.match(/cabin c_0p/ig)) {
				    field.className = field.className.replace(/cabin c_0p/ig, 'cabin c_1p c_owner');
			    }
			    else 
				    if (field.className.match(/cabin c_1p/ig)) {
					    field.className = field.className.replace(/cabin c_1p c_owner/ig, 'cabin c_2p c_owner');
				    }
				    else {
					    field.className = field.className.replace(/cabin c_2p c_owner/ig, 'cabin c_0p');
				    }
			    updateBookedCount();
		    }
		    else {
		        if (returnData){
			        alert(returnData);
			    }
			    window.location.reload();
		    }
		    // Booking Timeout Manager
		    timeoutManager.load(booking.bookedCount);
		    try {
			    hideMask();			
		    } catch (e) {}		
	    }
	    else {
		    window.location.href = bookingURL;
	    }
	},100);
};
function rndGen() {
    var d = new Date();
    return d.getTime();
};
function reloadBookingSummary(){
    loadObject(booking.summary.objectName, '&rnd=' + rndGen(), booking.summary.elementID, booking.summary.loadingError)
};
function register_FullCharer_Action() {
    var deckPlan = document.getElementById('deck_plan');
    if (deckPlan){
        var fcmode = parseInt(deckPlan.getAttribute('fcmode'));        
        booking.fullcharter.booked = (fcmode == 2);
        booking.fullcharter.enabled = (fcmode > 0)
        if ( booking.fullcharter.enabled ){
            var btnfullcharter = document.getElementById('btnfcharter');
            if (btnfullcharter) {
                XBrowserAddHandler(btnfullcharter, 'click', function() {
                    try {
                        return fullCharterBooking(this);
                    } catch (e) {}
                });                
            }
        }
    }
};
function fullCharterBooking(field){    
     booking.fullcharter.booked = field.getAttribute('enable') != '1';         
     if (!booking.fullcharter.booked) {                
        if (confirm(booking.fullcharter.confirmMess)) {            
            try{
                showMask(booking.fullcharter.inprogressMess);
            } catch(e){}            
            var returnData = GetData(0, 'http://' 
                                        + fnGetDomain(window.location.href) 
                                        + booking.fullcharter.bookingURL 
                                        + '?sid=' + getSecCode() 
                                        + '&action=2');
            if (returnData <= 0) {
                if (returnData ==-2){
                    alert(booking.fullcharter.accessDenied);
                }else{
                    alert(booking.fullcharter.uavailableCabinMess);
                }
                try{
                    hideMask();
                }catch(e){}                    
            } else if (returnData == 1) {
                window.location.href = window.location.href;            
            }else{
                alert(booking.fullcharter.ErrorMess);
                try{
                    hideMask();
                }catch(e){}                 
            }            
        }        
    } else {         
        if (confirm(booking.fullcharter.disableConfirmMess )) {            
            try{
                showMask(booking.fullcharter.disableMess );
            }catch(e){}            
            var returnData = GetData(0, 'http://' 
                                        + fnGetDomain(window.location.href) 
                                        + booking.fullcharter.bookingURL 
                                        + '?sid=' + getSecCode() 
                                        + '&action=3');
            if (returnData <= 0) {
                alert(booking.fullcharter.disableUnsuccessMess );
                try{
                    hideMask();
                }catch(e){}    
            } else {
                window.location.href = window.location.href;
            }
        }        
    }
};
function getMessage(field) {            
    var returnValue = '';
    try {
        var temporalityMode = 0;
        var roomCode = field.getAttribute('code');
        var deck = roomCode.substring(0, 1);        
        var prices = field.getAttribute('price').split('|');
        
        if (field.className.match(/c_locked/ig)) {
            temporalityMode = 4;
        }else if (field.className.match(/c_owner/ig)) {
            temporalityMode = 3;
        }else if (field.className.match(/c_temp/ig)) {
            temporalityMode = 2;
        }else if (field.className.match(/c_unavl/ig)) {
            temporalityMode = 1;
        }else{
            temporalityMode = 0;
        }

        if (roomCode != booking.oldRoom) {
            /*Cabin Info*/
            returnValue += '<p class="title"><b>Cabin ' + roomCode + '</b>';
            switch (temporalityMode) {
                case 0:
                    returnValue += ' (Available) <i class="available">&nbsp;</i>';
                    break;
                case 1:
                    returnValue += ' (Booked) <i class="booked">&nbsp;</i>';
                    break;
                case 2:
                    returnValue += ' (Temporarily booked) <i class="temp">&nbsp;</i>';
                    break;
                case 3:
                    returnValue += '(owner) <i class="cartadd">&nbsp;</i>';
                    break;
                case 4:
                    returnValue += ' (Locked) <i class="locked">&nbsp;</i>';
                    break;
            }
            returnValue += '</p>';
            returnValue += '<p class="info">';
            if (booking.shipID ==1){
                switch (deck) {
                    case '0':
                        returnValue += '<b>Mekong Deck</b> - Porthole 21 sq. meters';
                        break;
                    case '1':
                        returnValue += '<b>Tonle Deck</b> - Balcony & large Fixed Window 21 sq. meters';
                        break;
                    case '2':
                        returnValue += '<b>Saigon Deck</b> - Balcony & large Fixed Window 21 sq. meters';
                        break;
                    case '3':
                        if ((roomCode == '308') || (roomCode == '307')) {
                            returnValue += '<b>Indochina Deck</b> - Balcony & large Fixed Window 42 sq. meters';
                        }
                        else {
                            returnValue += '<b>Sadec Deck</b> - Balcony & large Fixed Window 27 sq. meters';
                        }
                        break;
                }
            }else{
                switch (deck) {
                    case '0':
                        returnValue += '<b>Saigon Deck</b> - Twin Balconies 21 sq. meters';
                        break;
                    case '1':
                        returnValue += '<b>Saigon Deck</b> - Twin Balconies 21 sq. meters';
                        break;
                    case '2':
                        returnValue += '<b>Saigon Deck</b> - Twin Balconies 21 sq. meters';
                        break;
                    case '3':
                        if ((roomCode == '311') || (roomCode == '312')) {
                            returnValue += '<b>Indochina Deck</b> - Bed room and living room, Twin Balconies, 58 sq. meters';
                        }
                        else {
                            returnValue += '<b>Sadec Deck</b> - Twin Balconies 27 sq. meters';
                        }
                        break;
                }
            }
            
            returnValue += '</p>';
            
            /*Prices*/
            returnValue += '<p class="title"><b>Prices</b></p>';
            returnValue += '<table width="100%;" cellspacing="0" cellpadding="0" border="0">';
            if (field.className.match(/c_1p/ig)) {
                returnValue += '<tr><td>&nbsp;</td><td><i class="Single">&nbsp;</i></td><td class="booked">Single:</td><td class="booked">' + prices[0] + '</td>';
            }
            else {
                returnValue += '<tr><td>&nbsp;</td><td><i class="Single">&nbsp;</i></td><td>Single:</td><td>' + prices[0] + '</td>';
            }
            if (field.className.match(/c_2p/ig)) {
                returnValue += '<td>&nbsp;</td><td><i class="Double">&nbsp;</i></td><td class="booked">Double:</td><td class="booked">' + prices[1] + '</td></tr>';
            }
            else {
                returnValue += '<td>&nbsp;</td><td><i class="Double">&nbsp;</i></td><td>Double:</td><td>' + prices[1] + '</td></tr>';
            }
            returnValue += '</table>';
            if (temporalityMode == 1){
                returnValue += '<p><i>(Cabin has been booked by other passenger)</i></p>';
            }else if(temporalityMode == 2) {
                returnValue += '<p><i>(Cabin has been booked by other passenger)</i></p>';
            }
            booking.oldMessage = returnValue;
            booking.oldRoom = roomCode;
        }
        else {
            returnValue = booking.oldMessage;
        }
    } catch (e) {}
    return returnValue;
}; 
function getSecCode() {
    var secutitycode = document.getElementById('system_secutitycode');
    if (secutitycode) {
        return secutitycode.value;
    } else {
        return '';
    }
};
function fixCruiseInfo(){	
	var streamPanel = document.getElementById('streampanel');
	var cruiseBox = document.getElementById('cruise_id');
	if (streamPanel){		
		var allRadioTag = streamPanel.getElementsByTagName('input');
		for (var i = 0; i < allRadioTag.length; i++) {		
			if (allRadioTag[i].getAttribute('checked')=='checked') {
				allRadioTag[i].checked = true;				
			}else{
				allRadioTag[i].checked = false;				
			}
		}
	}
	if (cruiseBox)	{
	    for (var i = 0; i < (cruiseBox.options.length); i++) {	        
            if (cruiseBox.options[i].style.color =='Green') {                
                cruiseBox.selectedIndex = i;                
                break;
            }
        }
	}
};
/*Onload functions*/
addLoadEvent(function() {    
    fixCruiseInfo();
    register_Cabin_Action();
    register_FullCharer_Action();
    updateBookedCount();    
});
