// JavaScript Document



/* Lopro Behaviors */

 Event.addBehavior({
      //".cal img.nextmonth:click" : function(event) { nextcal(this); },
	  //".cal img.prevmonth:click" : function(event) { prevcal(this); },
      //"div.cal tbody tr td.block:click, div.cal tbody tr td.blockstart:click, div.cal tbody tr td.blockend:click" : function(event) { CalSelectDate(this); },
     // "div.cal tbody tr td.range:click" : function(event) { CalSelectRangeStart(this); },
	 // The above 4 lines are moved into "/modules/rpmCart/ajax/frontendCal.inc.php" so ther are reaplied after being loaded. 
	 // This "should" happen any ways, but for some reason is not... 
	 
     // "img.calinfo:load" : function(event) { callinfo(this); },
     // "#starbox:load" : function(event) { setupstars(this); },
     // "#bookingdates input.checkbox:click" : function(event) { togglestartend(this); },
      "#numbernights:change" : function(event) { CalSelectRangeEnd(this); },
      "#closebooking:click" : function(event) { CloseBooking(this); },
	  "#mod_rpb_li_adults:keyup,  #mod_rpb_li_children:keyup, #mod_rpb_li_pets:keyup" : function(event){ GetBookingRates();}


 
 });
 



 
//var hltend = "#FFFFCD";
var hltend = "#e4eaea";
var minimum = 3;

// Start booking for weekly blocks

function CalSelectDate(el){

	block_id = el.classNames().toArray().first();

	if(el.hasClassName('nodata')){
		//alert("do nothing");
		return false;
	}else if(el.hasClassName('booked')){
		alert("Date already booked. Please select a different date");		
	}else if(el.hasClassName('pending')){
		alert("Date already has a pending booking. Please select a different date");		
	}else{
		
		

		// Start and end of actual block. Even if date is not visable on curent month
		start = el.title.split(" ")[1].split(":")[1];
		end = el.title.split(" ")[3].split(":")[1];
		
	

		//first = $('calbox').getElementsByClassName(block_id).first().id.split(".")[1];
		//last = $('calbox').getElementsByClassName(block_id).last().id.split(".")[1];
		
		rule = "#calbox ."+block_id;
		first = $$(rule).first().id.split(".")[1];
		last = $$(rule).last().id.split(".")[1];
		
		if(first != start || last != end) {
			alert("When booking a block that crosses to the next or previouse month, please ensure that the calendar displays both months that the booking will cover");
			return false;
		}
		
		minimum = 7; // Weekly
		
		$('minstay').value = minimum;
		
		$('rangestart').value = start;
		//$('rangeend').value = end;
		
		var d = Date.parseString(start, "yyyy-MM-dd");
		$('startstring').innerHTML = d.format("E NNN d, yyyy");
		
		//var d = Date.parseString(end, "yyyy-MM-dd");
		//$('checkoutstring').innerHTML = d.format("E NNN d, yyyy");
		
		
		//console.log(start);
		//console.log(end);
		
		// Get posable end days and build nights select
		BuildNumberofDays();
		
		// Open Panel
		if(!Element.visible('bookdetails')) new Effect.BlindDown('bookdetails',{ duration: 1});
		
		// Auto set range days to current value
		CalSelectRangeEnd($('numbernights'));
		el.addClassName('selected');
		
		
		
		
//		
		//console.log(checkin);
    	//console.log(checkout);
		//var prop_name = $F('prop_name');
		//var prop_id = $F('prop_id');
		
		
//		var pars = "checkin="+checkin+"&checkout="+checkout+"&prop_name="+prop_name+"&prop_id="+prop_id+"&block_id="+block_id+"&action=addtocart";
//		var page = '/modules/rpmCart/ajax/bookings.inc.php';
		//console.log("open sais me");
		//var myAjax = new Ajax.Updater(
//			'bookings', page, 
//			{
//				method: 'post',
//				parameters: pars,
//				onComplete:function(){  new Effect.Highlight('bookings',{duration: 1.5, restorecolor:hltend, endcolor:hltend});}
//			});
//		
		
		//alert("you clicked the cal last: "+ checkout);
	}
}


// Start booking for range
function CalSelectRangeStart(el){
	
	if(el.hasClassName("booked")) return false;
	if(el.hasClassName("incart")){ 
		alert("If you would like to add to or modify dates already in your booking, please remove and re add with your new dates");
		return false;
	}
	if(el.hasClassName("pending")){ 
		alert("Date already has a pending booking. Please select a different date");
		return false;
	}
	//console.log("Selecting Range Start");
	// Get Mim stay
	minimum = el.title.split(" ")[3];
	$('minstay').value = minimum;
	
	//var block_id = el.classNames().toArray().first();
	//var prop_name = $F('prop_name');
	//var prop_id = $F('prop_id');

	// convert click to date
	var date = el.id.replace("date.", "");
	var d = Date.parseString(date, "yyyy-MM-dd");
	
	$('rangestart').value = date;
	$('startstring').innerHTML = d.format("E NNN d, yyyy");
	
	// Get posable end days and build nights select
	BuildNumberofDays();
	
	// Open Panel
	if(!Element.visible('bookdetails')) new Effect.BlindDown('bookdetails',{ duration: 1});
	
	// Auto set range days to current value
	CalSelectRangeEnd($('numbernights'));
	el.addClassName('selected');
	
	
		
}



// Get number of days list
function BuildNumberofDays(){
	
	daysavailable = 0;
	count = false;
	days = new  Array();
	
	$$('#calbox table tbody tr td:not(.blank)').each( function(el)
		{ 
			var tddate = el.id.replace("date.", "")	
			if(tddate == $F('rangestart')){ count =true };
			if(el.hasClassName('booked')){ count = false};
			if(el.hasClassName('incart')){ count = false};
			
			
			if(count){ 
			daysavailable++;
				if(el.hasClassName('blockend') || el.hasClassName('range')){ // Checkout must be a range or block end
					// Valid Checkout day
					days[daysavailable] = daysavailable;
				};
			}
			
		}
	);
	daysavailable = daysavailable*1;// make sure its an intiger
	minimum = minimum*1;// make sure its an intiger
    //days = $R(1, daysavailable);
	//console.log(daysavailable);
	//console.log(foo.inspect());
	$('numbernights').innerHTML = "";
	days.each(function(value) {
  		//alert("day " +value);
		text = value;
		if(value >= minimum){
			//var text = value+" (min stay)";
			//console.log(text);
			addOption($('numbernights'),text,value );
		}
		
		
		
	});
}


// Calculate end dates
function CalSelectRangeEnd(el){
	//alert(el.id);
	var start = Date.parseString($F('rangestart'), "yyyy-MM-dd");
	var end = start.add("d",$F(el)-1);
	$('rangeend').value = end.format("yyyy-MM-dd");
	CalSetRangeEnd();
	
	var checkout = end.add("d",1);
	$('checkoutstring').innerHTML = checkout.format("E NNN d, yyyy");

	
}
function CalSetRangeEnd(){
	state = "closed";
	//$('calbox').getElementsByClassName('range').each( function(el){
	$$('#calbox table tbody tr td:not(.blank)').each( function(el){

			// deselect to start	
			var tddate = el.id.replace("date.", "")
			el.removeClassName('selected');
			if(tddate == $F('rangestart')){ // Highlight start date
				state = "open";
				el.addClassName('selected');
			}
			if($F('rangeend') != ""){ // If end is set
				if(tddate == $F('rangeend')){ // Highlight end date and close state
					state = "closed";
					el.addClassName('selected');
				}
				if(state == "open"){
					el.addClassName('selected');
				}
				
			}
				
		});	
	
	GetBookingRates();
}




function GetBookingRates(){
	var prop_id = $F('prop_id');
	var start = $F('rangestart');
	var end = $F('rangeend');
	var adults =  $F('mod_rpb_li_adults');
	var children =  $F('mod_rpb_li_children');
	var pets =  $F('mod_rpb_li_pets');
	var booking_id = "new";
	//var rateoverride = $F('rateoverride');
	var loading = '<div id="rloading">Loading Rates... </div>';
	
	//url = '/webmasterCMS/modules/rpmBookingManager/ajax/rateinfo.inc.php';
	url = '/modules/rpmCart/ajax/rateinfo.inc.php';
	pars = 'prop_id='+prop_id+'&booking_id='+booking_id+'&start='+start+'&end='+end+'&adults='+adults+'&children='+children+'&pets='+pets+'&rateoverride=';
	$('bookingrates').update(loading);
	var myAjax = new Ajax.Updater(
			'bookingrates', url, 
			{
				method: 'get',
				parameters: pars,
				evalScripts: true
			});
	//console.log("New: Getting Rates for : "+pars);
}


function RemoveFromCart(liid){
	if(confirm("Are you sure you want to delete these dates from your booking request")){
		var pars = "liid="+liid+"&action=removefromcart";
		var page = '/modules/rpmCart/ajax/bookings.inc.php';
		// Update cart
		var myAjax = new Ajax.Updater(
			'bookings', page, 
			{
				method: 'post',
				parameters: pars,
				
				onComplete:function(){  
					new Effect.Highlight('bookings',{duration: 1.5});
					updateCal();
				}
			});	
	}else{
		return false;
	}
}


function CloseBooking(){
	if(Element.visible('bookdetails')) new Effect.BlindUp('bookdetails',{ duration: 1});	
	
	// Deselect all dates
	$$('#calbox .selected').each( function(el){ 
				el.removeClassName('selected');}
	);	
}




function AddBooking(){
	var formino = $('bookingdates').serialize(true);
	//console.log(Object.inspect(formino));
	
	var url = "/modules/rpmCart/ajax/InsertBookingRates.php";
	var myAjax = new Ajax.Request(
		 url, 
		{
			method: 'post',
			parameters: formino,
			onSuccess:function(){  
				// console.log("done");
				 window.location.href="/site/mybooking.html";
			}
		});
}

function OLDAddRangeDates(){
	if($F('rangestart')=="" || $F('rangeend')== ""){
		alert("Please make sure you have selected a valid start date and number of days befor adding booking");
		return false;
	}
	var start = $F('rangestart');
	var end = $F('rangeend');
	var firstday = "date."+$F('rangestart');
	var block_id = $(firstday).classNames().toArray().first();
	var prop_name = $F('prop_name');
	var prop_id = $F('prop_id');
	var pars = "start="+start+"&end="+end+"&prop_name="+prop_name+"&prop_id="+prop_id+"&block_id="+block_id+"&action=addrangetocart";
	var page = '/modules/rpmCart/ajax/bookings.inc.php';
	var myAjax = new Ajax.Updater(
		'bookings', page, 
		{
			method: 'post',
			parameters: pars,
			onComplete:function(){  
				new Effect.Highlight('bookings',{duration: 1.5, restorecolor:hltend, endcolor:hltend});
				updateCal();
			}
		});
	// Update Bookinginfo
	var page = '/modules/rpmCart/ajax/bookinginfo.inc.php';
	new Effect.BlindUp('bookinginfo',{duration: 1});
	var myAjax = new Ajax.Updater('bookinginfo', page, { method:'post'});
	
		
	return false;
}

function updateCal(){
	// Update Calendars
	if($('calbox')){
		var page = '/modules/rpmCart/ajax/frontendCal.inc.php';
		var pars = "prop_id="+$F('prop_id');
		var myAjax = new Ajax.Updater('calbox', page, { 
			parameters: pars,
			method:'get'
		});
	}

}

function togglestartend(el){
	if(el.id == $('startend1').id){
		$('rangestartwrap').addClassName("active");
		$('rangeendwrap').removeClassName("active");
	}else{
		$('rangeendwrap').addClassName("active");
		$('rangestartwrap').removeClassName("active");
	}
}
function SAVEaddOption(selectbox,text,value ){
	var optn = document.createElement("OPTION");
	optn.text = text;
	optn.value = value;
	$(selectbox).options.add(optn);
}
function addOption(selectbox,text,value ){
	var selectbox = $(selectbox);
	var l = selectbox.options.length;
	selectbox.options[l] = new Option (text,value);
}



function nextcal(el){
	t = el.parentNode.id;

	t = t.split("-");
	year = t[2];
	month = t[1]*1+1;
	Cookie.set("calmonth", month);
	Cookie.set("calyear", year);
	
	//alert(year +" / "+month);	
	
	url = '/modules/rpmCart/ajax/frontendCal.inc.php';
	pars = 'year='+year+'&month='+month+'&prop_id='+$F('prop_id');
	var myAjax = new Ajax.Updater(
			'calbox', url, 
			{
				method: 'get',
				parameters: pars,
				evalScripts: true,
				onComplete:function(){ callinfo();}
			});
}

function prevcal(el){
	t = el.parentNode.id;
	t = t.split("-");
	year = t[2];
	month = t[1]*1-1;
	Cookie.set("calmonth", month);
	Cookie.set("calyear", year);
	//alert(year +" / "+month);
	
	var url = '/modules/rpmCart/ajax/frontendCal.inc.php';
	var pars = 'year='+year+'&month='+month+'&prop_id='+$F('prop_id');
	var myAjax = new Ajax.Updater(
			'calbox', url, 
			{
				method: 'get',
				parameters: pars,
				evalScripts: true,
				onComplete:function(){ callinfo();}
			});
}




function callinfo(){
	//alert("tool tip initilised");
	keyinfo = $('calkey').innerHTML;
	//keytooltip = new Effect.Tooltip('calinfo', keyinfo, {className: 'darkborder', title : 'Availability Calendar', offset: {x:10, y:10}});	
	
		//	new Tip(
//				'calinfo', 
//				keyinfo,
//					{
//						className: 'darkborder',
//						effect: 'appear', 
//						duration: 0.5,
//						showOn: 'mouseover',
//						hook: { target: 'bottomRight',
//                                tip: 'leftTop' }
//					}
//				);
}



/* Property list functions */

function SwitchView(view){
	if(view == "grid"){
		$('listview').hide();
		$('gridview').show();
		$('gridbtn').src="/themes/default/images/BTN_GridViewOn.jpg";
		$('listbtn').src="/themes/default/images/BTN_ListViewOff.jpg";
		
	}else if(view == "list"){
		$('listview').show();
		$('gridview').hide();
		$('gridbtn').src="/themes/default/images/BTN_GridViewOff.jpg";
		$('listbtn').src="/themes/default/images/BTN_ListViewOn.jpg";
		
	}
	
}




















/* Signup Form Functions */


function signup(){
	readytosend = "yes"

	if($F('name')==""){
		highlightRequiered('name', "Required")
		readytosend = "no"
	}
	if($F('email')=="" || !isValidEmail($F('email'))){
		highlightRequiered('email', "Required")
		readytosend = "no"
	}
	if(readytosend == "yes"){
		var url = '/modules/members/signup.php';
		var pars = Form.serialize($('signupform'))
			
			var myAjax = new Ajax.Updater(
			'inside', url, 
			{
				method: 'post', 
				parameters: pars, 
				evalScripts: true,
				onComplete: UpdateInside
			});
	}
}
function UpdateInside(originalRequest){
	$('inside').style.display = "none"
	Effect.Appear('inside', {duration: 1.6, queue:{scope:'inside', position:'end'}});

}

function logout(){
	Delete_Cookie( "member_login", "/")

	var url = '/modules/members/signup_form.php';
	var myAjax = new Ajax.Updater(
			'inside', url, 
			{
				method: 'post', 
				evalScripts: true,
				onComplete: UpdateInside
			});
}


/* Cookies */

var Cookie = {
	set: function(name,value,seconds){
		if(seconds){
			d = new Date();
			d.setTime(d.getTime() + (seconds * 1000));
			expiry = '; expires=' + d.toGMTString();
		}else
			expiry = '';
		document.cookie = name + "=" + value + expiry + "; path=/";
	},
	get: function(name){
		nameEQ = name + "=";
		ca = document.cookie.split(';');
		for(i = 0; i < ca.length; i++){
			c = ca[i];
			while(c.charAt(0) == ' ')
				c = c.substring(1,c.length);
			if(c.indexOf(nameEQ) == 0)
				return c.substring(nameEQ.length,c.length);
		}
		return null
	},
	unset: function(name){
		Cookie.set(name,'',-1);
	}
}

/* Favorate Properties */

var Favprop = {
	add: function(){
		var name = $F('prop_name');
		var id = $F('prop_id');
		var url = location.href;
		//var stars = $F('myRating');
		var data = url;
		var cname  = "fav["+name+"]";
		Cookie.set(cname, data);
		var page = '/themes/TVR08/rental_properties/favlist.inc.php';
		var myAjax = new Ajax.Updater(
			'favlist', page, 
			{
				method: 'post',
				onComplete:function(){  new Effect.Highlight('favlist',{duration: 2.5});}
			});
		//alert(value);
	},
	remove:  function(name){
		cname  = "fav["+name+"]";
		Cookie.unset(cname, url);
	}
}
function setupstars(){
	var side = new Stars({
			bindField: 'myRating',
			value: $F('myRating'),
			callback: bodyrating
		});
}
	
	
function bodyrating(val){
	Favprop.add();
   // alert('--Trying to update body stars to ' + val + ' star(s)');
  }	
  
  
 
/* Form Validation */

checkRequiered = function(formtocheck){
	var readytosend = "true";
	var formerror ="";
	fields = Form.getElements(formtocheck);
	fields.each(function(node){							
		if(Element.hasClassName(node, "required")){
			if (!Element.hasClassName(node, "ccardnumber")){
				if ($F(node) != ""){
					Cookie.set($(node).id, $F(node));
				}
			}
				
			if(Element.hasClassName(node, "email")){
				// Validate email address;
				if($F(node)=="" || !isValidEmail($F(node))){
					highlightinvalid(node, "Invalid email Address")
					readytosend = "false"
				}
			}else if (Element.hasClassName(node, "ccardnumber")){
				// Validate Visa Number 
				var cardtype = document.getElementsByClassName('cardtype');
				if(!isValidCC($F(node),$F(cardtype[0]))){
					formerror = "Credit Card appears to be invalid \n Please verify the number and card type are correct.";
					highlightinvalid(node, "Invalid CC Number")
					readytosend = "false"
				}
			}else if (Element.hasClassName(node, "agree")){
				// Must Agree 
				if($F(node)!="yes"){
					formerror += "You must agree to the Rules and Regulations ";
					readytosend = "false"
				}
			}else{
				// Higlight empty fields
				if($F(node)==""){
					highlightRequiered(node, "required")
					readytosend = "false"
				}
			}
		}
	})		
	if(readytosend=="true"){
		return true;
	}else{
		alert("Please verify that all required fields are completed \nRequired fields have been highlighted in yellow \n\n"+formerror);
		return false;
	}
	

}

isValidEmail = function(val){
    var re = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
    if (!val.match(re)) {
        return false;
    } else {
        return true;
    }
}


isValidCC = function(cardNumber, cardType)
{
  var isValid = false;
  var ccCheckRegExp = /[^\d ]/;
  isValid = !ccCheckRegExp.test(cardNumber);

  if (isValid)
  {
    var cardNumbersOnly = cardNumber.replace(/ /g,"");
    var cardNumberLength = cardNumbersOnly.length;
    var lengthIsValid = false;
    var prefixIsValid = false;
    var prefixRegExp;

    switch(cardType)
    {
      case "mastercard":
        lengthIsValid = (cardNumberLength == 16);
        prefixRegExp = /^5[1-5]/;
        break;

      case "visa":
        lengthIsValid = (cardNumberLength == 16 || cardNumberLength == 13);
        prefixRegExp = /^4/;
        break;

      case "amex":
        lengthIsValid = (cardNumberLength == 15);
        prefixRegExp = /^3(4|7)/;
        break;

      default:
        prefixRegExp = /^$/;
        alert("Card type not found: "+cardType);
    }

    prefixIsValid = prefixRegExp.test(cardNumbersOnly);
    isValid = prefixIsValid && lengthIsValid;
  }

  if (isValid)
  {
    var numberProduct;
    var numberProductDigitIndex;
    var checkSumTotal = 0;

    for (digitCounter = cardNumberLength - 1; 
      digitCounter >= 0; 
      digitCounter--)
    {
      checkSumTotal += parseInt (cardNumbersOnly.charAt(digitCounter));
      digitCounter--;
      numberProduct = String((cardNumbersOnly.charAt(digitCounter) * 2));
      for (var productDigitCounter = 0;
        productDigitCounter < numberProduct.length; 
        productDigitCounter++)
      {
        checkSumTotal += 
          parseInt(numberProduct.charAt(productDigitCounter));
      }
    }

    isValid = (checkSumTotal % 10 == 0);
  }

  return isValid;
}


function SelectValueSet(SelectName, Value){
	SelectObject = $(SelectName);
	for(index = 0; index < SelectObject.length; index++){
		if(SelectObject[index].value == Value){
			SelectObject.selectedIndex = index;
		}
	}
}


function highlightRequiered(id, message){
	$(id).style.color = "black"
	$(id).value = message
	new Effect.Highlight(id,{afterFinish: function(){$(id).value="";$(id).style.color = "";$(id).style.background = "#EFF4AE";}})
}


function highlightinvalid(id, message){
	$(id).style.color = "black"
	var v = $(id).value
	$(id).value = message
	new Effect.Highlight(id,{afterFinish: function(){$(id).value=v;$(id).style.color = "";$(id).style.background = "#EFF4AE";}})
}


// Slideshow effect


var SlideShow = Class.create();
SlideShow.prototype = {
   // using css, set imgNodeTop and imgNodeBottom to the same position using top and left
   // then set imgNodeTop's z-index to be higher
   // also pass in an array of the sources
   initialize: function(imgNode, imgCase, imageSources, options) {
       // internally store the given values
       this.imgTop = $(imgNode);
       this.imgBottom = $(imgCase);
       this.sources = imageSources;
       this.options = Object.extend({
           fadeDuration: 1,
           showDuration: 8
           }, options);
                 // set the top image source to the first source
       this.imgTop.src = this.sources[0];
       this.position = 0;
       this.onTop = 1;
   this.started = false;
   this.sources.each(this.prefetch);
   },
 prefetch: function(source) {
   var img = document.createElement('img');
   img.src = source;
 },
   start: function() {
       window.setTimeout(this.next.bind(this), this.options.showDuration*1000);
   this.started = true;
   },
 stop: function() {
   this.started = false;
 },
   next: function() {
       // set the bottom image to the next source
   var pos = this.position==this.sources.length-1 ? 0 : this.position+1;
		this.imgBottom.style.background = "url("+this.sources[pos]+")"
       // fade away the top image to slowly reveal the bottom image
       new Effect.Fade(this.imgTop, {
           duration: this.options.fadeDuration,
           afterFinish: function() {
               // when finished, set the top image to the last image (hopefully it won't flicker)
               this.imgTop.src = this.sources[this.position];
               this.imgTop.show();
               // start over
               if (this.started) this.start();
           }.bind(this)
       });
   // increment the position, wrapping if needed
   this.position++;
   if (this.position==this.sources.length) this.position = 0;
   }
};

 

/* Scroll to anchors */
//Event.observe(window, 'load', function() {
//  $$('a[href^=#]:not([href=#])').each(function(element) {
//    element.observe('click', function(event) {
//	  //var target = document.getElementsByName(this.hash.substr(1));
//	  //console.log(target.innerHTML);
//      new Effect.ScrollTo(this.hash.substr(1));
//      Event.stop(event);
//    }.bindAsEventListener(element))
//  })
//});
