﻿//mh
//GoBooking Replacement
//Strategy: Unobtrusive Approach which will work w/ every booking engine by using the form as the primary driver,
//instead of hard-coding urls into js, use the form to create the parameters of the url and then redirect it to Google Tracking + window.open.
//Since the form is supplied by the vendor or can easily be copied this should work w/ every booking engine.


//form tag:  class="Booking_Mask" needed and class = "popup" for popup window
//    <form id="frmRoomInventory" name="frmRoomInventory" class="Booking_Mask popup selectboxplugin" method="get"
//    action="https://indecorp.ibe.netbooker.com/web/FrontController.nb4" target="_blank" rel="resizable,scrollbars,width=800,height=600,top=500,left=500">
//resnet has very different form from others give form extra class of resnet   class="Booking_Mask iframe resnet"

//classes:  Booking_Mask, popup, noGoogleLinkerUrl, resnet, iframe, (.startmonth ->zeroBasedMonth)

//page loaded
jQuery(document).ready(function() {

    //if booking mask overrides datepickers from document.ready
    if (jQuery(".Booking_Mask").length > 0) {



        //Booking Mask Form Submitted
        jQuery(".Booking_Mask").submit(function() {


           
            if  (jQuery('.numbernights').length > 0) {
                window.pushDateVal = parseInt(jQuery('.numbernights').val());
                pushDate(window.pushDateVal);
            }


            //serialize all form values
            var values = jQuery(this).serialize();
            var action = jQuery(this).attr('action')
            var strLink = action + '?' + values;

            var linkerUrl = pageTracker._getLinkerUrl(strLink);  //gets url w/ GA link params

            //myfidelio throws errors if u send google vars - doesnt support.
            if (jQuery(this).hasClass("noGoogleLinkerUrl")) linkerUrl = strLink;

            //resnet has custom url /w iframe
            if (jQuery(this).hasClass("resnet")) {
                GoBooking_Resnet(action);
                return false;
            }

            //need to handle iframe here -- target self - same site so no outgoing
            if (jQuery(this).hasClass("iframe")) {
                window.open(linkerUrl, jQuery(this).attr('target'), '');
                return false;
            }

            //track here as after this  point all outgoing links.        
            pageTracker._trackPageview(stripProtocol('/outgoing/' + strLink));   //calls gif asynch

            if (jQuery(this).hasClass("popup")) {
                var popup_params = 'resizable,scrollbars,width=1020,height=600,top=800,left=800';

                //pull popup parameters from forms' rel attribute
                if (jQuery(this).attr('rel') != undefined) {
                    popup_params = jQuery(this).attr('rel');
                }
                window.open(linkerUrl, '', popup_params);
                return false;  //so form doesn't submit as well as popup
            }

            //if not popup class returns  w/ target=_blank
            window.open(linkerUrl, jQuery(this).attr('target'), '');
            return false;

        }); //end .Booking_Mask submit

        dateFormat = 'm/d/yy'

        //start datepickers

        //TODO: calc numberOfNights based on startdate.getValue - enddate.getvalue
        if (jQuery("#startdate").length > 0) {

            window.pushDateVal = 1;  //put in rel attribute of #startdate or .numbernights field
            if (jQuery('#startdate').attr('rel') > 0) {
                window.pushDateVal = parseInt(jQuery('#startdate').attr('rel'));
            }



            //too much recursion b/c im clicking this again
            jQuery(".selectbox-wrapper").click(function() {
                refreshDatepickers();
                window.pushDateVal = parseInt(jQuery('.numbernights').val());
                pushDate(window.pushDateVal);
                //alert('wrapper');
            });


            if (jQuery('.numbernights').length > 0) {
                window.pushDateVal = parseInt(jQuery('.numbernights').val());  //!parseInt important
            }


            jQuery.datepicker.setDefaults({
                minDate: 0,
                buttonText: '',
                defaultDate: +1,
                showOn: 'both',
                buttonImageOnly: false,
                dateFormat: dateFormat //leading zeros breaks selectbox plugin integration -should handle that at b4 sending to selectbox -- resnet needs leading zeros
            });

            jQuery('#startdate').datepicker({

                onClose: function() {
                    window.pushDateVal = parseInt(jQuery('.numbernights').val());
                    pushDate(window.pushDateVal)
                    fillStartDateDropdowns(jQuery(this).val())  //instance data issue here if no #enddate - cascading to ?

                }
                //TODO: push dropdowns ahead
            });

            jQuery('#enddate').datepicker({
                beforeShow: minRange,
                defaultDate: +0,
                onClose: function() {
                    fillEndDateDropdowns(jQuery(this).val())
                }
            });


            //initial setup after initialize datePickers()
            //fillStartDateDropdowns(jQuery('#startdate').val());
            // pushDate(window.pushDateVal);
            //refreshDatepickers();


        } //end datepicker

        //if submit button is img tag w/ mouseovers already attached so i can't change to <input type=image
        jQuery('.booking_submit').click(function() {
            jQuery('.Booking_Mask').submit();
        })


    } //end if booking mask form 
});        //end ready


 

 
        //pushes the endDate back to +numberDaysAhead days of startdate
        function pushDate(numberDaysAhead) {
            if (jQuery("#enddate").length > 0) {

                var startDate = jQuery("#startdate").datepicker("getDate");
                var endDate = jQuery("#enddate").datepicker("getDate");
                var startDatePlus = jQuery("#startdate").datepicker("getDate"); //need to compare startdate plus num nights    
                startDatePlus.setDate(startDatePlus.getDate() + numberDaysAhead);

                //stardate was updated and is greater
                if (startDatePlus > endDate) {
                    jQuery('#enddate').datepicker('setDate', startDatePlus);
                    fillEndDateDropdowns(jQuery('#enddate').val())
                }
                //enddate updated

 
            }
        }


        //customize mindate so that enddate cannot be b4 startdate
        function minRange(input) {
            return {
                minDate: (jQuery("#startdate").datepicker("getDate") != null ? jQuery("#startdate").datepicker("getDate") : 2)
            };
        }
        //startdate cannot be after enddate
        function maxRange(input) {
            return {
                maxDate: (jQuery("#enddate").datepicker("getDate") != null ? jQuery("#enddate").datepicker("getDate") : null)
            };
        }

        //TODO: dateformat on multilang site.
        function fillStartDateDropdowns(date_m_d_yy) {


            //fills in selectbox plugin dropdowns or hidden fields containing the dates split
            // assumes classes of .startmonth, .startday, .startyear
            var strFilled;
            strFilled = date_m_d_yy.split("/");

            var month_id = '#' + jQuery(".startmonth").attr('id');
            //some booking engines only take zeroBased month
            if (jQuery(".startmonth").hasClass("zeroBasedMonth")) {
                strFilled[0]--;
            }
            jQuery(".startmonth").val(strFilled[0]);  //put values

            var day_id = '#' + jQuery(".startday").attr('id');
            jQuery(".startday").val(strFilled[1]);

            var year_id = '#' + jQuery(".startyear").attr('id');
            //TODO: make it so they can stack classes in any format w/ delimiters !think
            if (jQuery(".startyear").hasClass('startmonth')) {
                jQuery(".startyear").val(strFilled[0] + strFilled[2]);
            } else {
                jQuery(".startyear").val(strFilled[2]);
            }

            //if selectbox plugin
            if (jQuery(".selectboxplugin .startmonth").length > 0) {
                if (jQuery(".selectboxplugin .startmonth").attr("type") != 'hidden' && jQuery(".selectboxplugin .startmonth").attr("type") != 'text') {


                    //refresh dropdowns if they exist should make fn.
                    jQuery(month_id + '_input').remove();
                    jQuery(month_id + '_container').remove();
                    jQuery('.selectboxplugin ' + month_id).selectbox();

                    jQuery(day_id + '_input').remove();
                    jQuery(day_id + '_container').remove();
                    jQuery('.selectboxplugin ' + day_id).selectbox();

                    jQuery(year_id + '_input').remove();
                    jQuery(year_id + '_container').remove();
                    jQuery('.selectboxplugin ' + year_id).selectbox();

                    jQuery(".selectbox-wrapper").bind("click", function(e) {
                        refreshDatepickers();
                    });
                }
            }
        }

        function fillEndDateDropdowns(date_m_d_yy) {


            //fills in selectbox plugin dropdowns or hidden fields containing the dates split
            //  assumes classes of .endmonth, .endday, .endyear
            var strFilled;
            strFilled = date_m_d_yy.split("/");
            //strFilled[1]--;  //day too low?

            var month_id = '#' + jQuery(".endmonth").attr('id');
            //some booking engines only take zeroBased month
            if (jQuery(".endmonth").hasClass("zeroBasedMonth")) {
                strFilled[0]--;
            }
            jQuery(".endmonth").val(strFilled[0]);  //if hidden field or separate text


            var day_id = '#' + jQuery(".endday").attr('id');


            jQuery(".endday").val(strFilled[1]);  //if hidden field or separate text

            //TODO: make it so they can stack classes in any format w/ delimiters !think

            if (jQuery(".endyear").hasClass('endmonth')) {
                jQuery(".endyear").val(strFilled[0] + strFilled[2]);
            } else {
                jQuery(".endyear").val(strFilled[2]);
            }


            //check if end month is select!!!
            if (jQuery(".selectboxplugin .endmonth").length > 0) {
                if (jQuery(".selectboxplugin .endmonth").attr("type") != 'hidden' && jQuery(".selectboxplugin .endmonth").attr("type") != 'text') {  //needs hidden too!


                    //refresh dropdowns here fi they exist    
                    jQuery(month_id + '_input').remove();
                    jQuery(month_id + '_container').remove();
                    jQuery('.selectboxplugin ' + month_id).selectbox();

                    jQuery(day_id + '_input').remove();
                    jQuery(day_id + '_container').remove();
                    jQuery('.selectboxplugin ' + day_id).selectbox();


                    jQuery(year_id + '_input').remove();
                    jQuery(year_id + '_container').remove();
                    jQuery('.selectboxplugin ' + year_id).selectbox();

                    jQuery(".selectbox-wrapper").bind("click", function(e) {
                        refreshDatepickers();
                    });
                }
            }
        }


        //remove http:// & https://
        function stripProtocol(inStrip) {

            inStrip = inStrip.replace(/http:\/\//gi, '');
            inStrip = inStrip.replace(/https:\/\//gi, '');
            return inStrip;
        }

        //add leading zeros if needed 9 -> 09
        function leadZero(num) {
            if (num < 10) {
                num = '0' + num;
            }
            return num;
        }

        //convert long year to short year 2010 -> 10
        function yyToy(year) {
            if (year.length > 2) {
                year = year.substring(2, 4);
            }
            return year;
        }


        //resnet does not support key-value pairs in its url... only semi-colon delimited ...  usually iFramed on same site
        //also its a cgi-bin app so booking domain is same.
        //cgi-bin/lansaweb in form action,  res.domain
        function GoBooking_Resnet(action) {
            //build w/ SaharaV1 as model

            //resnet url format                                       .booking_link      ratecode;mmddy;nights;adults;children; -- question mark terminates !important
            //https://res.saharavegas.com/cgi-bin/lansaweb?procfun+rn+resnet+sh1+funcparms+UP%28A2560%29:;Luv;050510;03;02;01;?#
            var resnet = [];

            startmonth = leadZero(jQuery('.startmonth').val());
            startday = leadZero(jQuery('.startday').val());
            startyear = yyToy(jQuery('.startyear').val());

            //in order by resnet !important 
            //using everything before the ":"  in the .booking_link
            resnet.push(jQuery('.booking_link').val());

            resnet.push(jQuery('.ratecode').val());
            resnet.push(startmonth + '' + startday + '' + startyear);

            resnet.push(jQuery('.nights').val());
            resnet.push(jQuery('.adults').val());
            resnet.push(jQuery('.children').val());
            resnet.push('?'); //must end in ?

            var url = resnet.join(';');  //adds ';' between all vars

            var linkerUrl = pageTracker._getLinkerUrl(url);



            if (jQuery('.Booking_Mask').hasClass("popup")) {
                var popup_params = 'resizable,scrollbars,width=600,height=600,top=800,left=800';

                //pull popup parameters from forms' rel attribute
                if (jQuery('.Booking_Mask').attr('rel') != undefined) {
                    popup_params = jQuery(this).attr('rel');
                }
                window.open(linkerUrl, '', popup_params);
                return false;  //so form doesn't submit as well as popup
            } else {
                //regular TODO: make above a popup function
                window.open(action + "?url=" + linkerUrl, jQuery('.Booking_Mask').attr('target'), '');
            }


            //iframe page should just have 1 asp var in iframe src. - build all of url here - src="<%=Replace(Replace(Request.QueryString, " ", "+"),"url=", "") %>
        }

        //debug function for creating form from booking engine url string
        function alertForm(url) {
            //var url = prompt("Enter Url to create form.");
            var form_string = "";

            url_arr = url.split('?');

            if (url_arr.length > 1) {
                form_string = "<form class=\"Booking_Mask\" method=\"get\" action=\"" + url_arr[0] + "\" > \n";
            } else {
                form_string = "<form class=\"Booking_Mask\" method=\"get\" action=\"put url here\" > \n";
            }

            //split params
            hidden_arr = url_arr[1].split('&');

            var num_of_params = hidden_arr.length;

            for (i = 0; i < num_of_params; i++) {

                //split key/values
                var key_value = hidden_arr[i];

                key_value_arr = key_value.split('=');
                var this_key = key_value_arr[0];
                var this_val = key_value_arr[1];

                form_string = form_string + this_key + ": \n ";
                form_string = form_string + "   <input type=\"text\" name=\"" + this_key + "\" value=\"" + this_val + "\" />\n";

            }
            form_string = form_string + "   <input type=\"submit\" value=\"submit\" />\n";
            form_string = form_string + "</form>\n";

            alert(form_string);
            return false;
        }


        function Booking_Mask(startmonth, startday, startyear, endmonth, endday, endyear, adults, children, rooms, nights, ratecode, propertyIndex) {

            alert(" startmonth: " + startmonth + "\n startday: " + startday + "\n startyear: " + startyear + "\n endmonth: " + endmonth + "\n endday: " + endday + "\n endyear: " + endyear + "\n adults: " + adults + "\n children: " + children + "\n rooms: " + rooms + "\n nights: " + nights + "\n ratecode: " + ratecode + "\n propertyIndex: " + propertyIndex);

            //flash team having issues w/ flash datepicker sending null, just use current year if null
            if (startyear == 'null') {
                //alert("startyear  ==> " + startyear);
                var d = new Date();
                startyear = d.getFullYear();
            }


            //do funstuff to build url here;
            //pagetracker(url) etc
            // window.open( url etc)
            jQuery(".startmonth").val(startmonth);
            jQuery(".startday").val(startday);
            jQuery(".startyear").val(startyear);

            jQuery(".endmonth").val(endmonth);
            jQuery(".endday").val(endday);
            jQuery(".endyear").val(endyear);
            //it will push if less than but need flash team to send null of the user didn't fill enddate

            jQuery("#startdate").val(startmonth + '/' + startday + '/' + startyear);
            fillStartDateDropdowns(startmonth + '/' + startday + '/' + startyear);

            //pushdate if enddate empty or less than startdate.
            if (endmonth == 'null' || endmonth < startmonth) {
                //   alert('enddate pushed');
                refreshDatepickers();
                //fill hidden form
            }



            //submit form of html booking mask

            if (jQuery('.Booking_Mask').length > 0) {
                jQuery('.Booking_Mask').submit();
            } else {
                // alert('need to add hidden booking mask form for selected booking engine to page for flash booking to work');
            }

        }





//end my functions & begin plugins & libraries


 