function passDataThrough(uri) {
		var getCheckInDate = $('input[name="checkIn"]').val();
		var getCheckOutDate = $('input[name="checkOut"]').val();
		var numberofPpl = $('#numberOfPeople span span.value').text();
		var	numberofPplInt = parseInt(numberofPpl)
		var roomType = $('#roomType span span.value').text();
		
		if ( roomType == "" ) {
			roomType = "Select room"
		}
		
		//update values
		$('#enquirePopup').children().find('input[name="checkIn"]').val(getCheckInDate)
		$('#enquirePopup').children().find('input[name="checkOut"]').val(getCheckOutDate)
		$('#enquirePopup').children().find('a#numberOfPeople').children('span').empty().append(numberofPpl+' Persons <span class="value">'+numberofPpl+'</span>')
		$('#enquirePopup').children().find('.dropdown2 a#roomType').children('span').empty().append(roomType+ '<span class="value">'+roomType+'</span>')
		
	
}


function validateForm() {

	
$("#contactLightBox, #enquirePopup").validate({
 messages: {
   Name: {acceptOnly: "Characters Only", minlength:"Please specify your name",maxlength: "Too many characters" },
   Email: {required: "Email address is required",email: "E.g yourname@gmail.com",maxlength: "Too many characters"},
   Cellphone: {required: "Is your number valid?",number: "Only use numbers",minlength: jQuery.format("At least {0} numbers required!"), maxlength: jQuery.format("Maximum of {0} numbers allowed!") },
   captchaInputLive:  {required: "The captcha you have entered is incorrect"}
 } ,
errorPlacement: function(error, element) {
      //error.appendTo(element.parents('.errors')).hide()
}   
});	
	
		$("#contactLightBox").validate().element('#enquirePopup input[name="checkIn"]')
		$("#contactLightBox").validate().element('#enquirePopup input[name="checkOut"]')
	    $("#contactLightBox").validate().element('#enquirePopup input[name="contactName"]')
	    $("#contactLightBox").validate().element('#enquirePopup input[name="contactMC"]')
		$("#contactLightBox").validate().element('#enquirePopup input[name="contactEmail"]')
		$("#contactLightBox").validate().element('#enquirePopup input[name="contactLname"]')
		$("#contactLightBox").validate().element('#enquirePopup input[name="contactTel"]')
		$("#contactLightBox").validate().element('.contactLightBox')
		


		if ($('input, textarea').hasClass('error')){
		} else {  
			$.fancybox.showActivity
		
			var checkInDate = $('#enquirePopup input[name="checkIn"]').val();
			var checkOutDate = $('#enquirePopup input[name="checkOut"]').val();
			var numberofPpl = $('#enquirePopup #numberOfPeople span span.value').text();
			var roomType = $('#enquirePopup #roomType span span.value').text();	
			var personType = $('#enquirePopup #personType span span.value').text();			
		    var contactName = $('#enquirePopup input[name="contactName"]').val();
			var contactEmail = $('#enquirePopup input[name="contactEmail"]').val();
			var contactLname = $('#enquirePopup input[name="contactLname"]').val();
			var contactTel = $('#enquirePopup input[name="contactTel"]').val();
			var contactMc = $('#enquirePopup input[name="contactMC"]').val();
			var contactMessage = $('.contactLightBox').val();
	
			


	        $.get("includes/formProcess.php", {
	            checkInDate: checkInDate,
	            checkOutDate: checkOutDate,
	            numberofPpl: numberofPpl,
	            roomType: roomType,
	            personType: personType,
	            contactName: contactName,
	            contactEmail: contactEmail,
	            contactLname: contactLname,
	            contactTel: contactTel,
	            contactMc: contactMc,
	            contactMessage: contactMessage,
	            type: "count",
	            success: function(){
	            }
	        }, function(data){
	        	if ( data == "success" ) {
	        		$.fancybox.hideActivity
	        		$('.lightboxContentWrapper, .lightboxFooter').hide();
					$("#thanks").show();
			    	$.fancybox.resize();	        		
	        	}				
	        });	

				
		
		
		}		
		
}


function buildSlider(sliderImages) {
	var imageDirectory = sliderImages;
	if (imageDirectory == undefined) {
		return false
	}
	
	$.get("includes/getImages.php", {
		dir: imageDirectory,
		success: function(){
		},
		complete: function() {
	
		}
	}, function(data){
		$(".slidePromo").html(data);
		$(".slidePromo img").not(':first').css('opacity','0');
		$('.slidePromo').cycle({ 
		    delay:  8000, 
		    speed:  1000
		});								
	});	
}



$(document).ready(function(){
	
	
	$(".video").click(function() {
		$.fancybox({
			'padding'		: 0,
			'autoScale'		: false,
			'transitionIn'	: 'none',
			'transitionOut'	: 'none',
			'title'			: this.title,
			'width'			: 640,
			'height'		: 385,
			'href'			: this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
			'type'			: 'swf',
			'swf'			: {
			'wmode'				: 'transparent',
			'allowfullscreen'	: 'true'
			}
		});
		return false;
	});	
	
	
	$('#header').append('<div class="tripAdvisorLogo"></div>')
	
	$('.tripAdvisorLogo').live('click',function(){
		var url = "http://www.tripadvisor.com/Hotel_Review-g1576918-d1094003-Reviews-Michamvi_Sunset_Bay_Resort-Michamvi_Zanzibar_Zanzibar_Archipelago.html"
		window.open(url);	
	})

	
	$(function() {
		$( ".datepicker" ).datepicker();
		$("#ui-datepicker-div").appendTo('#pageIntro');

	});	
	
	var getSlider = $('.slidePromo').attr('rel')
	buildSlider(getSlider)

	$("a.galleryLink").fancybox({
		'titlePosition'		: 'inside',
		'onClosed'		: function() {
			window.location.reload()
		}		
	});
	

	$('.dropdown3 dd li a').live('click',function(){
		var personValue = $(this).children('.value').text()
		if ( personValue == "Individual" ) {
			$('#mCode').hide()
			$('#mCode').children('input').val('0')
			$('#IATACode').hide()
			$('#IATACode').children('input').val('0')				
		} else if ( personValue == "Travel agent" ) {
			$('#mCode').hide()
			$('#mCode').children('input').val('0')
			$('#IATACode').show()
			$('#IATACode').children('input').val('')			
		} else {
			$('#mCode').show()
			$('#mCode').children('input').val('')
			$('#IATACode').hide()
			$('#IATACode').children('input').val('0')				
		}
	})
	
	
	$('.accommodationButtons').live('click',function(){
		
		if ( $(this).hasClass('accommodationButtonsClose') ) {
			$(this).removeClass('accommodationButtonsClose')
			$(this).parents('.accommodationHolder, .accommodationPage2').siblings('.accommodationDetails, .accommodationDetailsExtra').slideUp()		
		} else {
			$(this).addClass('accommodationButtonsClose')
			$(this).parents('.accommodationHolder, .accommodationPage2').siblings('.accommodationDetails, .accommodationDetailsExtra').slideDown()	
					
		}


	})
	
		var framePage = 'frame_contact.html?'+Math.random()
		var framePageRegister = 'frame_register.html?'+Math.random()
		var framePageEnquire = 'frame_enquire.html?'+Math.random()
	

		$("a.btnBookNowAction").fancybox({
			'autoDimensions'    : true,
			'autoScale'			: false,
			'transitionIn'		: 'none',
			'transitionOut'		: 'none',
			'modal'				: true,
			'href'				: framePage,
			'onComplete'		: function() {
				var thisHref = $('body').children().find('a.btnBookNowAction').attr('href')
				passDataThrough(thisHref)
				$('#fancybox-close').show();
				return false;
			}			
		});
		
		$("a.register").fancybox({
			'autoDimensions'    : true,
			'autoScale'			: true,
			'transitionIn'		: 'none',
			'transitionOut'		: 'none',
			'modal'				: false,
			'href'				: framePageRegister,
			'onClosed'			: function() {
				$('.btnBookNow').trigger('click')
			}			
		});	
		
		$(".btn_enquire").fancybox({
			'autoDimensions'    : true,
			'autoScale'			: true,
			'transitionIn'		: 'none',
			'transitionOut'		: 'none',
			'modal'				: false,
			'href'				: framePageEnquire,
			'onComplete'		: function() {
				Cufon.replace('h2');
			},			
			'onClosed'			: function() {
				$('.btnBookNow').trigger('click')
			}			
		});				
		
		//how its done
		//$('.bookNowModule').append('<a href="frames/contact.html" class="register" style="display:none">TriggerJS</a>')	
		
		$(".registerBtn").live('click',function(){

			$('a.register').trigger('click')
			
			
		});	
		
		$('.registerFinal, .lightboxFooter .bookNow').live('click', function(){

	    	validateForm()
		});	
	
	$('.btnBookNow, .bookNowRates, .btnBack, .accommodationDetails .bookNow').live('click',function(event){

		var getCheckInDate = $('input[name="checkIn"]').val();
		var getCheckInDate1 = parseInt(getCheckInDate)
		var getCheckOutDate = $('input[name="checkOut"]').val();
		var numberofPpl = $('#numberOfPeople span span.value').text();
		var	numberofPplInt = parseInt(numberofPpl)
		var roomType = $('#roomType span span.value').text();
			
		//Update uri
		$(this).siblings('a.btnBookNowAction').attr('href','frame_contact.html?checkin='+getCheckInDate+'&checkout='+getCheckOutDate+'&ppl='+numberofPplInt+'&type='+roomType)
		var thisHref = $(this).siblings('a.btnBookNowAction').attr('href')
		
		//Trigger click	
		
		
		
		$('a.btnBookNowAction').trigger('click')
		
		
			
	})

	 $("input[type=text][title], input[type=password][title]").each(function() {
		    if($.trim($(this).val()) == "") {
		      $(this).val($(this).attr("title"));
		    } else { 
		    }
		    $(this)
		      .focus(function() {
		        if($(this).val() == $(this).attr("title")) $(this).val("");
		      })
		      .blur(function() {
		        if($.trim($(this).val()) == "") $(this).val($(this).attr("title"));
		      });
	});	
	
	
	$('.calCloseButton').live('click',function(event){
		$( ".datepicker" ).datepicker( "hide" )
	})
	
	// Custom drop down
	$(".dropdown dt a").live('click',function(event) {
		event.preventDefault()
	    $(this).parent().siblings('dd').children("ul").toggle();
	}); 

	$(".dropdown dd ul li a").live('click',function(event) {
		event.preventDefault()
	    var text = $(this).html();
	    $(".dropdown dt a span").html(text);
	    $(".dropdown dd ul").hide();
	}); 


	$(document).bind('click', function(e) {
	    var $clicked = $(e.target);
	    if (! $clicked.parents().hasClass("dropdown"))
	        $(".dropdown dd ul").hide();
	});

	$(".dropdown2 dt a").live('click',function(event) {
		event.preventDefault()
	    $(this).parent().siblings('dd').children("ul").toggle();
	}); 

	$(".dropdown2 dd ul li a").live('click',function(event) {
		event.preventDefault()
	    var text = $(this).html();
	    $(".dropdown2 dt a span").html(text);
	    $(".dropdown2 dd ul").hide();
	}); 

	$(document).bind('click', function(e) {
	    var $clicked = $(e.target);
	    if (! $clicked.parents().hasClass("dropdown2"))
	        $(".dropdown2 dd ul").hide();
	});	
	
	
	
	
	$(".dropdown3 dt a").live('click',function(event) {
		event.preventDefault()
		$(this).addClass('active')
		$(this).children('span').empty().append('You are...')
	    $(".dropdown3 dd ul").toggle();
	}); 

	$(".dropdown3 dd ul li a").live('click',function(event) {
		event.preventDefault()
	    var text = $(this).html();
	    $(".dropdown3 dt a span").html(text);
	    $(".dropdown3 dd ul").hide();
	    $(this).parents('dd').siblings('dt').children('a').removeClass('active')
	}); 

	$(document).bind('click', function(e) {
	    var $clicked = $(e.target);
	    if (! $clicked.parents().hasClass("dropdown3"))
	        $(".dropdown3 dd ul").hide();
	});		
	
	
	
	lightBoxTrigger()
	
	$('#fancybox-close').live('click',function(){
		//window.location.reload()
	})
	

	$('a.shareLink').live('click',function(){
		
		var $this = $(this)
		

		
		var path = window.location.href;
		path = path.replace("#", "");	
		var thisImageId = $(this).attr('rel')
		if ( thisImageId === undefined ) {
			var findTitle = $(this).parent().siblings('#fancybox-title').children('#fancybox-title-inside').text()
			var findId = $('body').find('a.galleryLink[title="'+findTitle+'"]').attr('id')
			var pattern = /[0-9]+/g;
		    var thisImageId = '?galleryImage='+findId.match(pattern)
		    var specificId = findId.match(pattern)
		    buildShares(path+thisImageId,'fb');	    
		    
			//update count
	        var projectID = specificId;
	        projectID = parseInt(projectID)

	        $.get("includes/rate.php", {
	            query: projectID,
	            type: "count",
	            success: function(){
	            }
	        }, function(data){
	        	$($this).parent('.share').siblings(".like").children('span').empty()
	        	$($this).parent('.share').siblings(".like").children('span').html(data);				
	        });		
   
		    
		} else {

			var getThisId = $(this).attr('rel').split('=')[2]
			
			var pattern = /[0-9]+/g;
		    var specificId = thisImageId.match(pattern)
		    
			buildShares(thisImageId,'fb');
		    
			//update count
	        var projectID = specificId;
	        projectID = parseInt(projectID)
	        $.get("includes/rate.php", {
	            query: getThisId,
	            type: "count",
	            success: function(){
	            }
	        }, function(data){
	        	$($this).parent('.share').siblings(".like").children('span').empty()
	        	$($this).parent('.share').siblings(".like").children('span').html(data);				
	        });			    
		    
		}		
        
	})
	
	
	//Load accommodation
	$('p.accommodationPrice').each(function(index){
		var thisIndex = index
	    var roomId = $(this).attr('rel');
	    $.get("includes/accRate.php", {
	        query: roomId,
	        type: "count",
	        success: function(){
	        }
	    }, function(data){
	    	var finalDate = parseInt(data);
	    	$('p.accommodationPrice').eq(thisIndex).children('span').empty()
	    	$('p.accommodationPrice').eq(thisIndex).children('span').html(finalDate);				
	    });	
	})
	
	
	//form submit
	$('.btnSubmit').click(function(event) {
		
		
	});	
	


})

function gup( name )
{
	
	
  var name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}


$.extend({URLEncode:function(c){var o='';var x=0;c=c.toString();var r=/(^[a-zA-Z0-9_.]*)/;
  while(x<c.length){var m=r.exec(c.substr(x));
    if(m!=null && m.length>1 && m[1]!=''){o+=m[1];x+=m[1].length;
    }else{if(c[x]==' ')o+='+';else{var d=c.charCodeAt(x);var h=d.toString(16);
    o+='%'+(h.length<2?'0':'')+h.toUpperCase();}x++;}}return o;},
URLDecode:function(s){var o=s;var binVal,t;var r=/(%[^%]{2})/;
  while((m=r.exec(o))!=null && m.length>1 && m[1]!=''){b=parseInt(m[1].substr(1),16);
  t=String.fromCharCode(b);o=o.replace(m[1],t);}return o;}
});


function lightBoxTrigger() {
	   //iframe code
	//read the url and then change the src of the iFrame....
	//replace all [amp] with &

       var results = gup( 'galleryImage' );
	  	if(results == "") {
			results = gup( 'galleryImage' );
		}
		
	   //var niceURI = $.URLDecode(results);
	   var niceURI = decodeURIComponent(results)
       var destinationPage = niceURI;

	   
       var intIndexOfMatch = destinationPage.indexOf( "?" );
       while (intIndexOfMatch != -1){
            // Replace out the current instance.
            destinationPage = strReplaceAll.replace( "?", "?" )
             
            // Get the index of any next matching substring.
            intIndexOfMatch = destinationPage.indexOf( "?" );
       }
       /*
       if(destinationPage != null && destinationPage !="")
               $('#dashboardFrame').attr('src', destinationPage);
       else {
               $('#dashboardFrame').attr('src', 'dashloggediniframe.html');
       }
       */
	   
       if(results != "") {
    	   	   var thisIDOpen = 'galleryItemId_'+results
               $('#'+thisIDOpen).trigger('click');
       }                   
	  //end iframe code	
}


function buildShares(location,type) {
	var niceURI = decodeURIComponent(location);
	var getMetaDesc = jQuery('meta[name=description]').attr("content");
	var title = jQuery('title').html();
	var niceTitle = encodeURIComponent(title);
	var url;
	location = encodeURIComponent(location)
	
	if (type === "mail") {
		var mailtoHref = "mailto:?subject="+niceTitle+"&body="+location;
		window.location.href = mailtoHref;
		var url = 'http://demo102.aquaonline.com/MazdaZoomButtonService/Service/GetSaveZoomButtonLog?data='+type+'|'+location+'';
		//jQuery.get(url);
		trackThis(url)
		return false;
	} else if ( type === "fb" ) {
		url = "http://www.facebook.com/sharer.php?u="+niceURI+"&t="+niceTitle+",toolbar=0,status=0,width=626,height=436";
		window.open(url);		
		
		
		//var url = 'http://demo102.aquaonline.com/MazdaZoomButtonService/Service/GetSaveZoomButtonLog?data='+type+'|'+location+'';
		//jQuery.get(url);	
		//trackThis(url)
		return false;
	} else if ( type === "twitter" ) {
		url = "http://twitter.com/home?status="+niceTitle+"%20-%20"+niceURI;
		window.open(url);	
		var url = 'http://demo102.aquaonline.com/MazdaZoomButtonService/Service/GetSaveZoomButtonLog?data='+type+'|'+location+'';
		//jQuery.get(url);		
		trackThis(url)
		return false;
	}
	return false;
}

$(document).ready(function(){

    jQuery.validator.addMethod("acceptOnly", function(value, element, param) { 
      return value.match(new RegExp("^" + param + "$")); }); 
    
    /** To DO: include space using reg expression * */  
    jQuery.validator.addMethod("acceptOnlySpace", function(value, element, param) { 
      return value.match(new RegExp("^[\p{L} \.'\-]" + param + "$")); });          
      
    
    jQuery.validator.addMethod("notEqual", function(value, element, param) {
      return this.optional(element) || value != param;
    }, "This field is required.");
    
    jQuery.validator.addMethod("onlyEqual", function(value, element, param) {
      return this.optional(element) || value == param;
    }, "This field is required.");    
    
    
    jQuery.validator.addMethod('dependsOn', function (value, element, param) {
      return this.optional(element) || value != param;
    }, 'This field is required.');   


    $.validator.addMethod("defaulText", function(value, element, param) {
      return this.optional(element) || param == value;
    }, "Please replace the default text");    
          

  // Name Rule - Class "NameField"
  jQuery.validator.classRuleSettings.NameField = {required: true,minlength: 2, notEqual: "Name", acceptOnly: "[a-zA-Z- ]+", number: false, maxlength:175};
  
  
  // Email Rule - Class "EmailField"
  jQuery.validator.classRuleSettings.EmailField = {required: true, email: true, maxlength:175 }; 
  

  
  // Cellphone Rule - Class "CellphoneField"
  jQuery.validator.classRuleSettings.CellphoneField = {required: true, notEqual: "Cellphone", notEqual:"Cellphone/contact number", minlength: 6  };


  var thisVal = $('.captchaInputLive').val();


  // Captcha Rule - Class "CellphoneField"
  jQuery.validator.classRuleSettings.captchaInputLive = {
	  required: true, 
	  remote: {
       url: "includes/captchaValidate.php",
	   type: "GET",
	   data: {
		   captcha: function() {
			   return $('.captchaInputLive').val();
		   }
	    }
	  }
   }


	jQuery.validator.classRuleSettings.required = {required: true  };



    



});



$(window).load(function() {
	
	var socialLink = $('.social a').attr('href')
	$('.social p').click(function(){
		window.open(socialLink);	
	})


var _gaq = _gaq || [];

_gaq.push(['_setAccount', 'UA-6422940-9']);

_gaq.push(['_trackPageview']);

(function() {

var ga = document.createElement('script'); ga.type = 'text/javascript';
ga.async = true;

ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www')
+ '.google-analytics.com/ga.js';

var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);

})();
});

