/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


$(document).ready(function() {

   setupHomeClick();

   setupNavClicks();

   setupAdminClicks();

   //setupAboutBrokerClicks();

   setupIRMStuff();

   setupDatePickers();

});

function setupHomeClick() {

    $('#headerLogoImg').livequery(
        function(){
            $(this).hover(
                function() {
                    $(this).css('cursor', 'pointer');
                },
                function() {
                    $(this).css('cursor', 'default');
                });
        },
        function() {
             $(this).unbind('mouseover').unbind('mouseout');
        }
    );

    $('#headerLogoImg').livequery('click',
        function() {
            window.location.href = "/";
        }
    );

}

function setupNavClicks() {

    $('.NavigationBTN').livequery(
        function() {
            $(this).hover(
                function() {
                    $(this).css('cursor','pointer');
                    $(this).append('<div id="navAniBlock" />');
                    $(this).find('#navAniBlock').animate({
                        //backgroundColor: "#FFF",
                        opacity: 0//,
                        //color: "#712600"
                     //   paddingTop: '0px',
                     //   height: '20px'
                      //  heigth: '-=24px'
                    },700);

                    //$(this).css('background-color','#FFF');
                    //$(this).css('color','#712600');
                    //$(this).css('border','1px solid #712600');
                },
                function() {
                    $(this).css('cursor','default');
                    /*$(this).find('#navAniBlock').animate({
				//opacity:0.8,
				//height: '-=24px'
			},10,function(){ $(this).remove();} );
                        */
		    $(this).find('#navAniBlock').remove();
                    /*$(this).animate({
                        //backgroundColor: "#712600",
                       // opacity: 1,
                        //color: "#FFF"
                        paddingTop: '4px',
                        height: '20px'
                    },10);*/
                    //$(this).css('background-color','#712600');
                    //$(this).css('color','#FFF');
                    //$(this).css('border','');
                }
            );
        },
        function() {
            $(this).unbind('mouseover').unbind('mouseout');
        }
    );

    $('.NavigationBTN').livequery(
        'click',
        function() {
            //alert($(this).attr('id'));

           /* if ( $("#irmFrame").length > 0 ) {

                $('#MainContentHolder').empty();


            }*/


            var viewType = $(this).attr('id');
            switch (viewType) {
                case 'about':
                        //alert("hello world");
                        window.location.href = "/about";
                    break;
                case 'contact':
                        window.location.href = "/contact";
                    break;
                case 'login':
                        loadIrmWindow('http://208.72.40.253/IRMNet/Login.aspx?ReturnUrl=%2firmnet%2fOwner%2fOwnerHome.aspx%3fResort%3d01&Resort=01');
                    break;
                default :
                        //$('#MainContent').load('/view/'+$(this).attr('id'));
                        window.location.href = '/view/'+$(this).attr('id');
                        //window.location.hash = $(this).attr('id');
                    break;                
            }
           
        }

    );

}


function setupAdminClicks() {

    $('#adminAddMore').livequery(
        function(){
            $(this).hover(
                function() {
                    $(this).css('background-color','#EEA');
                    $(this).css('cursor', 'pointer');
                },
                function() {
                    $(this).css('background-color','');
                    $(this).css('cursor', 'default');
                });
        },
        function() {
             $(this).unbind('mouseover').unbind('mouseout');
        }
    );

    $('#adminAddMore').livequery('click',
        function(){
            var i = parseInt($('.adminBroker:last').attr('id'))+1;
            $(this).before('<tr><td></td><td><input class="adminBroker" type="text" name="brokerName_'+i+'" id="'+i+'" /></td><td><input class="adminBroker" type="text" name="brokerPosition_'+i+'" id="'+i+'" /></td><td><input type="file" name="brokerPic_'+i+'" id="brokerPic_'+i+'" /></td><td class="adminDelBroker">X</td><tr><td></td><td colspan="3"><textarea name="brokerBio_'+i+'" id="brokerBio_'+i+'" cols="65" rows="5"></textarea></td><td></td></tr></tr>');
        }
    );


    $('.adminDelBroker').livequery(
        function(){
            $(this).hover(
                function() {
                    $(this).css('background-color','#EEA');
                    $(this).css('cursor', 'pointer');
                },
                function() {
                    $(this).css('background-color','');
                    $(this).css('cursor', 'default');
                });
        },
        function() {
             $(this).unbind('mouseover').unbind('mouseout');
        }
    );

    $('.adminDelBroker').livequery('click',
        function() {
            $(this).parent().next().remove();
            $(this).parent().remove();
        }
    );


    $('#logoutBtn').livequery(
        function(){
            $(this).hover(
                function() {
                    $(this).css('cursor', 'pointer');
                },
                function() {
                    $(this).css('cursor', 'default');
                });
        },
        function() {
             $(this).unbind('mouseover').unbind('mouseout');
        }
    );

    $('#logoutBtn').livequery('click',
        function() {
            window.location.href = "/login/logout";
        }
    );
}

/*
function setupAboutBrokerClicks() {

    $('.brokerLink').livequery(
        function(){
            $(this).hover(
                function() {
                    $(this).css('background-color','#EEA');
                    $(this).css('cursor', 'pointer');
                },
                function() {
                    $(this).css('background-color','');
                    $(this).css('cursor', 'default');
                });
        },
        function() {
             $(this).unbind('mouseover').unbind('mouseout');
        }
    );

    $('.brokerLink').livequery('click',
        function() {
            //window.location.href = '/about/broker/'+$(this).attr('id');
            $('#MainContent').load('/about/broker/'+$(this).attr('id'));
            //alert($(this).attr('id'));
        }
    );
}
*/

function setupIRMStuff() {

    $('#searchRDPBtn').livequery(
        function(){
            $(this).hover(
                function() {
                    $(this).css('cursor', 'pointer');
                },
                function() {
                    $(this).css('cursor', 'default');
                });
        },
        function() {
             $(this).unbind('mouseover').unbind('mouseout');
        }
    );

    $('#searchRDPBtn').livequery('click',
        function() {
            callIRM();
        }
    );

}

function loadIrmWindow(url) {
    //alert(url);
	$('#MainContentHolder').empty();
    $('#MainContentHolder').html('<iframe name="irmFrame" src="'+url+'" id="irmFrame" style="width: 99%; height: 600px; border:none;" class="style1">Your browser does not support inline frames.</iframe>');
    /*$('#irmFrame').livequery(function(){
       $(this).attr('src',url);
       $('#irmFrame').expire();
    });*/

}

function setupDatePickers() {

    $('#wdcDeparture_input').datepicker();
    $('#wdcArrival_input').datepicker();

    $('#contactCheckOut').datepicker();
    $('#contactCheckIn').datepicker();

}


///////////////////////////////////////////////////////////////////////
//Sample script for pulling selection criteria from marketing web site
//which is passed to the IRM and put in an iframe
///////////////////////////////////////////////////////////////////////


// construct the IRM url including all search criteria and dates
// source the irm iframe with this url
function callIRM()
{
  // Query parameters for IRM
  var query = {
    Resort:'01'
  };

   var foundOne = false;

   //Add guest requets if selected
   //These must correspond to GuestRequest1-9 values
   
   var location = $('#ddLocation').val();
   if (location != "*")
   {
      query.Request1 = location;
      foundOne = true;
   } else {
	   query.Request1 = '*';
   }
   
   var bedrooms = $('#ddBedrooms').val();
   if (bedrooms != "*")
   {
       query.RoomType = bedrooms;
       foundOne = true;
   }
   else
   {
	   query.RoomType = '*';
   }

   //Add arrival and departure dates if selected
   var arrival = $('#wdcArrival_input').val();
   var departure = $('#wdcDeparture_input').val();
   if (arrival != "" && arrival != 'Click Here')
   {
      //verify that arrival choice is not in the past
      if (new Date(arrival) < now)
      {
         alert("Arrival date must be later than today.\nPlease change your calendar dates and try again.");
         return false;
      }

      query.Arrival = arrival;

      if (departure != "" && departure != 'Click Here')
      {
         //verify departure > arrival
         var nights = calcNights(arrival, departure);
         if (nights <= 0 )
         {
            alert("Departure date must be later than arrival date.\nPlease change your calendar dates and try again.")
            return false;
         }
         //additional checking
         if (nights > 10)   // for example enforce a maximum stay
         {
            alert("Online Reservations cannot be made for more than a 10 night stay.\nPlease change your calendar dates, or call us about your extended stay.\nThank You");
            return false;
         }
         query.Departure = departure;
      } else {
    	query.Nights = numberNights;  
      }

      //Add people selections
      query.People1 = $('#ddAdults').val();
      query.People2 = $('#ddChildren').val();
   } else {
	  // Attempt to force empty dates (doesn't seem to work)
	  query.Arrival = 'Select Date';
	  query.Departure = 'Select Date';
   }

   //Nothing was selected, get all rooms
   if (!foundOne) {
	 query.AllRooms = true;
   }

   //loadIrmWindow('http://208.72.40.253/irmnet/Res/ResMain.aspx?' + $.param(query));

   // OR open a new window for the IRM
   window.location = '/vacation-rentals?' + $.param(query);
   //window.open('http://208.72.40.253/irmnet/Res/ResMain.aspx?' + $.param(query),'_new','height=700, width=850, scrollbars=yes, resizable=yes');
}  //callIRM

// caclulate number of nights from selected arrival and departure dates
function calcNights(arrival, departure)
{
    var arrDate = arrival.split("/");
    var depDate = departure.split("/");
   	var newArrDate = new Date(arrDate[0]+"/"+arrDate[1]+"/"+arrDate[2]);
	var newDepDate = new Date(depDate[0]+"/"+depDate[1]+"/"+depDate[2]);
	var numNights = (Math.round((newDepDate-newArrDate)/86400000));
	return numNights;
}

//////////////////////////////////////////
// Supporting date variables and functions
//////////////////////////////////////////
// Get today's current date.
var now = new Date();

// Array list of days.
//var days = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');

// Array list of months.
var months = new Array('01','02','03','04','05','06','07','08','09','10','11','12');

// Calculate four digit year.
function fourdigits(number)	{
	return (number < 1000) ? number + 1900 : number;
	}


//Get actual values for date and month from DOM, For security purposes of demo year is not set to current//
var nowdate = now.getDate();
var nowmonth = now.getMonth() + 1; // 2 = March see months array above//
var nowyear = now.getFullYear();

//Default Days ahead of todays date for arrival and departure set to current dates//
//var arr = 2;
//var dep = 4;

//For use with demo -will set the default departure date to x number of days ahead of arrival - remove or comment out for current date functionality;
var arr = 0;
var dep = 2;



//For use with current dates this function Adds 2 days for default Arrival Date & 4 days for default Departure Date.//
//For Demo use this function just returns proper format for default arrival and departure dates//
function checkDate (m, d, y, field){
	//var maxDays = DaysInMonth(m, y);
	var newDay = d + field;
	var newMonth = months[m];
	var newYear = fourdigits(y);
	//if ((newDay) > maxDays){
//		newDay = newDay - maxDays;
//		var nextMonth = m + 1;
//		if (nextMonth > 11){
//			nextMonth = 0;
//			newYear++;
//			}
//		newMonth = months[nextMonth];
//		}
//	newDay = ((newDay<10) ? "0" : "")+ newDay;
	var fieldDate = newMonth + "/" +
					newDay + "/" +
					newYear;
	return fieldDate;
	}

// default arrival and departure dates
var arrivalDate = checkDate(nowmonth, nowdate, nowyear, arr);
var departureDate = checkDate(nowmonth, nowdate, nowyear, dep);
//sets default number of nights
var numberNights = calcNights(arrivalDate, departureDate);



