var wf = {
    CalS: '',
    CalE: '',
    wz: null,
    selOptions: [],
    initOptions: function() {
        
        this.selOptions['fltTimes'] = [{val:'362',text:'Any'},{val:'12AM',text:'12 AM'},{val:'1AM',text:'1 AM'},{val:'2AM',text:'2 AM'}
            ,{val:'3AM',text:'3 AM'},{val:'4AM',text:'4 AM'},{val:'5AM',text:'5 AM'},{val:'6AM',text:'6 AM'},{val:'7AM',text:'7 AM'}
            ,{val:'8AM',text:'8 AM'},{val:'9AM',text:'9 AM'},{val:'10AM',text:'10 AM'},{val:'11AM',text:'11 AM'},{val:'12PM',text:'12 PM'}
            ,{val:'1PM',text:'1 PM'},{val:'2PM',text:'2 PM'},{val:'3PM',text:'3 PM'},{val:'4PM',text:'4 PM'},{val:'5PM',text:'5 PM'}
            ,{val:'6PM',text:'6 PM'},{val:'7PM',text:'7 PM'},{val:'8PM',text:'8 PM'},{val:'9PM',text:'9 PM'},{val:'10PM',text:'10 PM'}
            ,{val:'11PM',text:'11 PM'},{val:'361',text:'Morn.'},{val:'721',text:'Noon'},{val:'1081',text:'Eve.'}];
        
        this.selOptions['TripType'] = [{val:2,text:'Roundtrip'},{val:'oneway',text:'One-way'}];
        
        this.selOptions['carClass'] = [{val:'NoPreference',text:'No Preference'},{val:'Economy',text:'Economy'}
            ,{val:'Compact',text:'Compact'},{val:'Midsize',text:'Midsize'},{val:'Standard',text:'Standard'},{val:'FullSize',text:'FullSize'}
            ,{val:'Premium',text:'Premium'},{val:'Luxury',text:'Luxury'},{val:'Convertible',text:'Convertible'}
            ,{val:'Minivan',text:'Minivan'},{val:'SUV',text:'Sport Utility Vehicle'},{val:'SportsCar',text:'Sports Car'}];
            
        
        this.selOptions['carRenter'] = [{val:'',text:'-- Select from the list --'},{val:'AC',text:'ACE Rent A Car'}
            ,{val:'AD',text:'Advantage Rent-A-Car'},{val:'AL',text:'Alamo Rent A Car'},{val:'ZD',text:'Budget'}
            ,{val:'ZR',text:'Dollar Rent A Car'},{val:'LM',text:'Economy Rent a Car'},{val:'ET',text:'Enterprise'}
            ,{val:'EP',text:'Europcar'},{val:'FX',text:'Fox Rental Cars'},{val:'ZE',text:'Hertz'},{val:'ZL',text:'National Car Rental'}
            ,{val:'ZA',text:'Payless'},{val:'SX',text:'Sixt'},{val:'ZT',text:'Thrifty Car Rental'}];
        
        this.selOptions['cruiseDests'] = [{val:'',text:'------------------'},{val:'6023184',text:'Africa'},{val:'203',text:'Alaska'}
            ,{val:'6050677',text:'Asia'},{val:'13',text:'Bahamas'},{val:'20',text:'Bermuda'},{val:'6023742',text:'Canada - New England'}
            ,{val:'6022969',text:'Caribbean'},{val:'6023743',text:'Caribbean - Eastern'},{val:'6023744',text:'Caribbean - Southern'}
            ,{val:'6023745',text:'Caribbean - Western'},{val:'6022967',text:'Europe'},{val:'213',text:'Hawaii'}
            ,{val:'6023183',text:'Mediterranean'},{val:'6050655',text:'Mexico'},{val:'6049796',text:'Northern Europe'}
            ,{val:'-2',text:'No port stops'},{val:'6023753',text:'Panama Canal'},{val:'6050676',text:'South America'}
            ,{val:'6023738',text:'South Pacific'},{val:'-3',text:'TransAtlantic'},{val:'6023746',text:'US Pacific Coast'}
            ,{val:'-5',text:'World'}];
            
        // Begin cruise months
        var today = new Date();
        var crDate;
        this.selOptions['cruiseMonths'] = new Array();
        for (var i=0; i<=24; i++){ 
            crDate = new Date(today.getFullYear(), today.getMonth() + i, 1);
            this.selOptions['cruiseMonths'][i] = {val:wf.ShortDateString(crDate), text:wf.CruiseMonthString(crDate)};
        }
        // End cruise months
        
        this.selOptions['cruiseLength'] = [{val:'0',text:'Show All'},{val:'1',text:'1-2 nights'},{val:'2',text:'3-5 nights'},{val:'3',text:'6-9 nights'},{val:'4',text:'10-14 nights'},{val:'5',text:'15+ nights'}];
        
        this.selOptions['hotelDests'] = []; // used in conjunction with wiz_builder tool
        this.selOptions['packageDests'] = []; // used in conjunction with wiz_builder tool

        
    },    
    
    init: function(wiz) {
        this.wz = wiz;
        var ret = '';
        var ctr = 0;
        
        var today = new Date();
        var startDt = new Date(this.wz.startDate)
        this.CalS = (today  > startDt) ? this.ShortDateString(today) : this.ShortDateString(startDt)
        this.CalE = this.wz.endDate;
   
        if (this.wz.startUp && this.OnWizardInit != null)
            this.OnWizardInit();

        $(this.wz.titleContainer).html(this.wz.title);
        for (lob in this.wz.wizards) {
            if (typeof this.wz.wizards[lob] !== "function" && this.wz.wizards[lob] && this.wz.wizards[lob].active) {
                if ((!this.wz.separatePackages) || (!this.wz.wizards[lob].makePkgOption)) {
                    ret += this.BuildLOBOption(lob, ctr);
                    ctr++;
                }
            }
        }
        $(this.wz.optionsContainer).html('<div class="stdLOB">' + ret + '</div>');
        if (this.wz.separatePackages) {
            ret = '';
            for (lob in this.wz.wizards) {
                if (typeof this.wz.wizards[lob] !== "function" && this.wz.wizards[lob].makePkgOption && this.wz.wizards[lob].active)
                    ret += this.BuildLOBOption(lob, ctr);
                    ctr++;
            }
            if (this.wz.pkgOptionsText != null && this.wz.pkgOptionsText != '')
                ret = '<span>' + this.wz.pkgOptionsText + '</span>' + ret;
            $(this.wz.optionsContainer).append('<div class="pkgLOB">' + ret + '</div>');
        }
        $('.stdLOB div, .pkgLOB div').click( 
            function(e) {
                var input = $(this).children('input:first-child');
                input.attr('checked', true);
                wf.BuildFields(input.val());
            }
        );
        $(this.wz.optionsContainer + ' input').focus(function() {wf.HCal();});
        //$(this.wz.form).attr('action', '/daily/testarea/slee/promowiz/fake_eap.asp');
        $(this.wz.form).attr('action', '/pubspec/scripts/eap.asp');
        if ($('#LastOption').val() != '')
            this.BuildFields($('#LastOption').val());
        else
            this.BuildFields(this.wz.defaultLOB);
       // set the value on init in case the user clicked the back button
	   //fix bug 180871, in 24H_sales  default.jsp not use 'CitynameDD' now;in hotelupgrade.asp still use it.
	   if(document.getElementById('CitynameDD'))
	   {
			wf.ParseSelectedDest(document.getElementById('CitynameDD').value);
	   }
    },

    BuildFields: function(sLob) {
        this.HCal();
        if (this.OnLOBChangeStart != null)
            this.OnLOBChangeStart();
        if (!this.wz.startUp)
            this.SaveVals();
        this.HideRooms();
        if (this.wz.activeLOB != null)
            this.ClearFlds();
        this.wz.activeLOB = this.wz.wizards[sLob];
        $('#LastOption').val(sLob);
        if (this.wz.activeLOB.rfrr != null)
            $('#Rfrr').val(this.wz.activeLOB.rfrr);
        this.InitVals();
        for (fld in this.wz.activeLOB.fields) {
            if (typeof this.wz.activeLOB.fields[fld] !== "function" && this.wz.activeLOB.fields[fld].skipOnInit != true)
                this.BuildFld(this.wz.activeLOB.fields[fld]);
        }
        $(this.wz.hiddenContainer).html('');
        for (fld in this.wz.activeLOB.hiddenfields) {
			if (typeof this.wz.activeLOB.hiddenfields[fld] !== "function")
			{
				$(this.wz.hiddenContainer).append(this.BuildHiddenFld(this.wz.activeLOB.hiddenfields[fld]));
			}         
        }
        
        $(this.wz.optionsContainer + ' input[value="' + sLob + '"]').attr('checked', true);
        if ($(this.wz.moreLink) != null && $(this.wz.moreLink) != '')
            $(this.wz.moreLink).html(this.GetLink('morelink'));
        $(this.wz.btnContainer).html('<label>' + this.wz.activeLOB.button + '</label>');
        $(this.wz.btnContainer).click(function() {wf.SaveVals();$(wf.wz.form).submit();});
        $(this.wz.btnContainer).parent().show();
        $('#GOTO').val(this.wz.activeLOB.goto);
        this.CheckCtrlState();
        if (this.OnLOBChangeComplete != null)
            this.OnLOBChangeComplete();
        if (this.wz.startUp && this.OnWizardComplete != null)
            this.OnWizardComplete();
        this.wz.startUp = false;    
    },
    
    InitVals: function() {
        if ($(this.wz.remVals).val() != '') {
            var valAry = $(this.wz.remVals).val().split(this.wz.valDelim);
            for (var i=0; i < valAry.length; i++) {
                this.wz.remValues[valAry[i].split('=')[0]] = valAry[i].split('=')[1];
            }
        } 
    },
    
    SaveVals: function() {
        var sVal = '';
        this.RemAllDates();
        for (val in this.wz.remValues) {
			if (typeof this.wz.remValues[val] !== "function")
			{
				if (sVal != '') sVal += this.wz.valDelim;
					sVal += val + '=' + this.wz.remValues[val].replace(this.wz.valDelim,'').replace('=',''); 
			} 
        }
        $(this.wz.remVals).val(sVal);
    },

    ClearFlds: function() {
        for (fld in this.wz.activeLOB.fields) {
			if (typeof this.wz.activeLOB.fields[fld] !== "function")
			{
				$(this.wz.activeLOB.fields[fld].cont).html('');
				$(this.wz.activeLOB.fields[fld].cont).hide();
			}
        }
    },

    BuildFld: function(fld) {
        var ret = "";
        if (fld == null)
            return;

        switch (fld.type) {
            case 'text':
            case 'date':
                ret = this.BuildTextFld(fld);
                break;
            case 'select':
                ret = this.BuildSelect(fld);
                break;
            case 'radio':
                ret = this.BuildRadio(fld);
                break;
            case 'numrange':
                ret = this.BuildNumrange(fld);
                break;
            case 'readonly':
                ret = this.BuildReadOnly(fld);
                break;
        }
        if (fld.lbl && fld.lbl != '')
            ret = this.BuildLabel(fld)  + ret;
        $(fld.cont).html(ret);

        if (fld.type == 'date') {
            $('#' + fld.name).attr('date', '1');
            $('#' + fld.name).bind('click focus',function(e){e.cancelBubble=true;wf.SC(this);});
            $('#' + fld.name).bind('change', fld.remval, function(e){wf.Rem(this, e.data);});
        }
        else {
            $('#' + fld.name).bind('focus',function(e){wf.HCal();});
            $('#' + fld.name).bind('blur', fld.remval, function(e){wf.Rem(this, e.data);});
        }        

        if (fld.type != 'readonly')
        {
            if (this.wz.remValues[fld.remval] != null)
                if (fld.type == 'radio') 
                    $(fld.cont + ' input').val([this.wz.remValues[fld.remval]]);
                else
                    $('#' + fld.name).val(this.wz.remValues[fld.remval]);
            else if (fld.val != null)
                $('#' + fld.name).val(fld.val);
        }
        $(fld.cont).hide();
        $(fld.cont).show();
    },

    BuildTextFld: function(fld) {
        var ret = '<input type="text" id="'+fld.name+'" name="' + fld.name + '"';
        if (fld.len != '') ret += ' maxlength="' + fld.len + '"';
        else if (fld.type == 'date') ret += ' maxlength="12"';
        ret += this.GetEvents(fld);
        ret += ' />';
        return ret;
    },
    
    BuildReadOnly: function(fld) {
        var ret = '<input type="hidden" id="'+fld.name+'" name="' + fld.name + '" value="' + fld.val + '" />';
        if (fld.display != null && fld.display != '')
            ret += '<span class="readOnly">' + fld.display + '</span>';
        else
            ret += '<span class="readOnly">' + fld.val + '</span>';
        return ret;
    },
    
    BuildSelect: function(fld) {
        var opts;
        if (fld.options == 'custom')
            opts = fld.custom;
        else
            opts = this.selOptions[fld.options];
        var ret = '<select id="'+fld.name+'" name="' + fld.name + '"' + this.GetEvents(fld) + '>';
        for (i=0;i<opts.length;i++) {
            ret += '<option';
            if (opts[i].val == fld.val) 
                ret += ' selected="1"';
            ret += ' value="' + opts[i].val + '">' + opts[i].text + '</option>';
        }
        ret += '</select>';
        return ret;
    },
    
    BuildRadio: function(fld) {
        var opts = this.selOptions[fld.options];
        var ret = '';
        for (i=0;i<opts.length;i++) {
            var id = fld.name + i.toString();
            ret += '<div><input type="radio" name="' + fld.name + '" id="' + id + '"';
            if (opts[i].val == fld.val) 
                ret += ' checked="1"';
            ret += ' value="' + opts[i].val + '" onclick="wf.Rem(this, \'' + fld.remval + '\');' + fld.onclick + '" />';
            ret += '<label for="' + id + '" onclick="wf.DE(\'' + id + '\').click();">' + opts[i].text + '</label></div>';
        }
        return ret;
    },
    
    BuildNumrange: function(fld) {
        var ret = '<select id="'+fld.name+'" name="' + fld.name + '"' + this.GetEvents(fld) + '>';
        for (i=fld.min;i<=fld.max;i++) {
            ret += '<option';
            if (i == fld.val) 
                ret += ' selected="selected"';
            ret += ' value="' + i + '">' + i + '</option>';
        }
        ret += '</select>';
        return ret;
    },
    
    BuildHiddenFld: function(fld) {
        var ret = '<input type="hidden" id="'+fld.name+'" name="' + fld.name + '" value="' + fld.val + '" />';
        return ret;
    },
    
    BuildLOBOption: function(lob, ctr) {
        var ret = '<div><input type="radio" value="' + lob + '" name="lob" id="lob' + ctr + '" />'
            + '<label for="lob' + ctr + '">' + this.wz.wizards[lob].displayname + '</label></div>';
        return ret;
    },
    
    GetEvents: function(fld) {
        var ret = '';
        if (fld.onblur != undefined) ret += ' onblur="' + fld.onblur + '"';
        if (fld.onchange != undefined) ret += ' onchange="' + fld.onchange + '"';
        if (fld.onclick != undefined) ret += ' onclick="' + fld.onclick + '"';
        if (fld.onfocus != undefined) ret += ' onfocus="' + fld.onfocus + '"';
        return ret;
    },

    BuildLabel: function(fld) {
       var lbl = fld.lbl;
       if (lbl.replace(' ', '') != '')
          lbl += this.wz.activeLOB.captionspace;
       lbl = lbl.replace(' ', '&nbsp;');
       var ret = '<label for="' + fld.name + '">' + lbl + '</label>';
       return ret;
    },

    SetRooms: function(num, adultFld, childFld) {
        var ret = '';
        
        for (var i=1; i <= this.GetFldByName('NumRoom').max; i++) {
            $(this.wz.activeLOB.peopleContainerRoot+i + ' span').hide();
            $(this.wz.activeLOB.peopleContainerRoot+i).hide();
        }
        for (var i=1; i <= num; i++) {
            var aFld = this.cloneObject(adultFld);
            var cFld = this.cloneObject(childFld);
            
            aFld.cont = adultFld.cont + i;
            cFld.cont = childFld.cont + i;
            aFld.name = adultFld.name + i;
            aFld.remval = adultFld.remval + i;
            cFld.name = childFld.name + i;
            cFld.remval = childFld.remval + i;
            
            this.BuildFld(aFld);
            this.BuildFld(cFld);
            $(this.wz.activeLOB.peopleContainerRoot+i).show();
            $(this.wz.activeLOB.peopleContainerRoot+i + ' span').toggle((num > 1));
       } 
       $('#people').hide();
    },
    
    ShowRooms: function() {
        $('.people').show();
        $('#people').hide();
    },
    
    HideRooms: function() {
        $('.people').each(
            function() {
                if ($(this).attr('id') != 'people')
                    $('#' + $(this).attr('id') + ' div').html('');
            }
        );
        $('.people').hide();
        $('#people').show();
    },

    GetLink: function(id)
    {
        var linkObj = this.wz.activeLOB[id];
        return '<a href="' + linkObj.url + '">' + linkObj.text + '</a>';
    },
    
    cloneObject: function(obj) {
        var newobj = new Object()
        for (prop in obj) 
            newobj[prop] = obj[prop];
        return newobj;
    },
    
    Rem: function(obj, itm) {
        this.wz.remValues[itm] = obj.value;
    },
    
    RemAllDates: function() {
        $('#frmWiz input:text').each(
            function(){
                if ($(this).attr('date') == '1') 
                    wf.Rem(this, wf.GetRemValForElement($(this)));
            }
        );
    },
    
    DE: function(el){return document.getElementById(el);},

    SC: function(el)
    {
	    if (wf.DE('CalFrame') == null){return;}
	    var id = el.id;
	    var n = el.id.substr(3);
	    var jObj = $('#' + el.name);
	    el.select();
	    //alert(this.CalE);
	    var stDt = new Date(this.GetAssociatedDateForElement(jObj));
	    if (isNaN(stDt))
	        stDt = null;
	    ShowCalendar(el,el,null,stDt,this.CalE);
    },

    HCal: function(e) { 
	    var c = this.DE('CalFrame');
	    if (c!=null){CancelCal();}
    },
    
    ShortDateString: function(date) {
        return (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();
    },
    
    CruiseMonthString: function(date) {
        var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];
        return (months[date.getMonth()] + ' ' +  date.getFullYear().toString());
    },
    
    GetFldByName: function(fldname) {
        var ret = null;
        for (fld in this.wz.activeLOB.fields) {
            if (typeof this.wz.activeLOB.fields[fld] !== "function" && this.wz.activeLOB.fields[fld].name == fldname) {
                ret = this.wz.activeLOB.fields[fld];
                break;
            }
        }
        return ret;
    },
    
    GetRemValForElement: function(jObj) {
        return this.GetFldByName(jObj.attr('name')).remval;
    },

    GetAssociatedDateForElement: function(jObj) {
        sName = this.GetFldByName(jObj.attr('name')).assoc;
        if (sName == null || sName == '')
            return this.CalS;
        else    
            return $('#' + sName).val();
    },
    
    ReplaceFieldsByRemval: function(remval, fldObj) {
        var fldTemp = fldObj;
        fldTemp.remval = remval;
        for (lob in this.wz.wizards) {
			if (typeof this.wz.wizards[lob] !== "function")
			{
				for (fld in this.wz.wizards[lob].fields) {
					if (typeof this.wz.wizards[lob].fields[fld] !== "function")
					{
						var checkFld = this.wz.wizards[lob].fields[fld];
						if (checkFld.remval == remval) {
							// Don't replace container, caption or name
							fldTemp.cont = checkFld.cont;
							fldTemp.lbl = checkFld.lbl;
							fldTemp.name = checkFld.name;
							this.wz.wizards[lob].fields[fld] = fldObj;
						}
					}
				}
			}
        }
    },
    
    CheckCtrlState: function() {
        if (this.wz.activeLOB.type == 'flight') 
            $(this.GetFldByName('ToDate').cont + ', ' + this.GetFldByName('ToTime').cont).toggle(($('#TripType0').attr('checked')));
        if (this.wz.activeLOB.type == 'hotel') {
            this.SetRooms($('#NumRoom').val(), this.GetFldByName('NumAdult'), this.GetFldByName('NumChild'));
        }
        else
            this.HideRooms();
    },
    // Specialized function to support long pre-defined hotel/pkg destination lists (e.g. 24 hour sale page)
    ParseDestinations: function(ary) {
        for (var i=0; i<ary.length; i++) {
            var hidAry = ary[i].hid.split(',');
            var hotelHid = ''; var pkgHid = '';
            for (var j=0; j<hidAry.length; j++) {
                var checkAry = hidAry[j].split(':');
                if (checkAry[1] == 'B' || checkAry[1] == 'P')
                    pkgHid += (pkgHid == '' ? '' : ',') + checkAry[0];
                if (checkAry[1] == 'B' || checkAry[1] == 'S')
                    hotelHid += (hotelHid == '' ? '' : ',') + checkAry[0];
            }
            
            this.selOptions['hotelDests'][i] = {val:ary[i].id + ':' + ary[i].tla + '(' + hotelHid + ')', text:ary[i].name};
            this.selOptions['packageDests'][i] = {val:ary[i].id + ':' + ary[i].tla + '(' + pkgHid + ')', text:ary[i].name};
        }
    },
    // Specialized function to support long pre-defined hotel/pkg destination lists (e.g. 24 hour sale page)
    ParseSelectedDest: function(val) {		        
        $('#hdnHotelIDs').html('');
        if (wf.wz.activeLOB.type == 'hotel') {
            var tempAry = val.split('(');
            var ary = tempAry[1].replace(')', '').split(',');
            for (var i=0; i<ary.length; i++)  
                $('#hdnHotelIDs').append('<input type="hidden" name="HotelID' + (i+1) + '" value="' + ary[i] + '" />');
        } 
        else { 
            var ary = val.split('('); // destid:TLA(hotelids)
            $('#destid').val(ary[0]);
            $('#HotelIDs').val(ary[1].replace(')', ''));
        }
    },
    
    OnWizardComplete:null,
    OnWizardInit:null,
    OnLOBChangeStart:null,
    OnLOBChangeComplete:null

       
    
}
wf.initOptions();

$(document).ready(
    function() {
        wf.init(wiz);
    }
);

