$(function(){

   $("a.gal").bind('click', function(event){
		event.preventDefault();
		var categ = $(this).attr('rev');
		
		getData('assets/gallery3.json?v=1.1', categ);
		
	});
	if($(".fancybox").length) {
		$("a.fancybox").fancybox({
				'transitionIn'	:	'elastic',
				'transitionOut'	:	'elastic',
				'speedIn'		:	600, 
				'speedOut'		:	200,
				'cyclic' : true,
				'centerOnScroll' : true,
				'overlayOpacity' : 0.8,
				'overlayColor' : '#000',
				'overlayShow'	:	true
			});
	}

	// Main menu dropdown
	$("#Mainmenu li").hover(
		function () {
			$(this).addClass('hover');
		}, 
		function () {
			$(this).removeClass('hover');
		}
	);
	
	// Main menu dropdown background animation
	
	$('#Mainmenu ul li a')
		.css( {backgroundPosition: "-293px 0"} )
		.mouseover(function(){
			$(this).stop().animate({backgroundPosition:"(-60px 0)"}, {duration:300})
		})
		.mouseout(function(){
			$(this).stop().animate({backgroundPosition:"(173px 0)"}, {duration:200, complete:function(){
				$(this).css({backgroundPosition: "-293px 0"})
			}
		})
	});
	
	// Submenu dropdown background animation
	
	$('#Container .submenu ul li a')
		.css( {backgroundPosition: "-333px 0"} )
		.mouseover(function(){
			$(this).stop().animate({backgroundPosition:"(-60px 0)"}, {duration:300})
		})
		.mouseout(function(){
			$(this).stop().animate({backgroundPosition:"(213px 0)"}, {duration:200, complete:function(){
				$(this).css({backgroundPosition: "-333px 0"})
			}
		})
	});
		
	// target="_blank"
	$('a[rel="external"], form.form-external').attr({'target':'_blank'});


	//
	var HeBS_Link_Checkin_Checkout_Inputs = function HeBS_Link_Checkin_Checkout_Inputs_function(checkin_selector, checkout_selector) {
			Date.format = 'mm/dd/yyyy';



			$(checkin_selector).bind('dateSelected', function(e, selectedDate, $td, state) {
				var t = new Date(selectedDate);
				var dt = new Date.fromString($(checkin_selector).val());		
			    var edate = new Date.fromString($(checkout_selector).val());			
			    var one_day=1000*60*60*24;
			    var days_diff = Math.ceil((edate.getTime() - dt.getTime())/(one_day));

			    if(edate.getTime() <= dt.getTime()) {
			        $(checkout_selector).val(t.addDays(1).asString());
			    }
			});

			$(checkout_selector).bind('dateSelected', function(e, selectedDate, $td, state) {
				var t = new Date(selectedDate);
				var dt = new Date.fromString($(checkin_selector).val());	
			    var edate = new Date.fromString($(checkout_selector).val());				
			    var one_day=1000*60*60*24;
			    var days_diff = Math.ceil((edate.getTime() - dt.getTime())/(one_day));

			    var edate = new Date.fromString($(checkout_selector).val());			
			    if(edate.getTime() <= dt.getTime()) {
			        $(checkin_selector).val(t.addDays(-1).asString());
			    }		
			});

			var today = new Date();
			$(checkin_selector).val(today.asString());
			$(checkout_selector).val(today.addDays(1).asString());

		    $(checkout_selector).dpSetStartDate(today.asString());
		};
		
		if($('#dateofstay').length){
			$('#dateofstay').datePicker({startDate:'01/01/1996'});
		} else {

		$('#checkin, #checkout, .date-pick').datePicker({'clickInput' : true });

		HeBS_Link_Checkin_Checkout_Inputs('#checkin', '#checkout');
		
		}

		//toggleSocialPanel("tw");

	// Stylish Select
	$('#Booking select').sSelect();

	// Dates
	//$('#header .booking .date-pick').datePicker({'clickInput' : true });

	//var today = new Date();
	//$('#arrival').val(today.asString());

	// Footer stay connected
	var defaultConnectWidgetInputText = $("#Footer .stay-connected .text").val();
	$("#Footer .stay-connected .text").focus(function() { if ($(this).val() == defaultConnectWidgetInputText) $(this).val("").removeClass('inactive'); });
	$("#Footer .stay-connected .text").blur(function() { if ($(this).val() == "") $(this).val(defaultConnectWidgetInputText).addClass('inactive'); });




	// Social
	
	initTwitter();
	initFacebook();
	
	$('#fb, #tw').click(function(event) {
		event.preventDefault();
		var type = $(this).attr('id');
		toggleSocialPanel(type);
		return false;
	});
	$('.socialclose').click(function(){
		$('.social li span').removeClass('active');
		var type = $(this).attr('rel');
		toggleSocialPanel(type);
	});
	
	
	// Specials

	jQuery('#Specials ul').jcarousel({ scroll: 1, wrap: 'circular' });
	
	// Facebook Like, Google +1
	
	var pathname = window.location.pathname;
	if (pathname == "/index.php") pathname = "/";
		
	var current_url = window.location.protocol + "//" + window.location.hostname + pathname;
	$('#Like').html('<iframe src="http://www.facebook.com/plugins/like.php?app_id=253574681323910&amp;href=' + current_url + '&amp;send=false&amp;layout=button_count&amp;width=85&amp;show_faces=true&amp;action=like&amp;colorscheme=light&amp;font&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:85px; height:21px;" allowTransparency="true"></iframe>');
	//$('#PlusOne').html('<g:plusone size="small"></g:plusone>');
	renderPlusone();
	
	$('#Like, #PlusOne').hover(function() { 
	    $(this).stop().animate({"opacity": 1}, 200); 
	},function() { 
	    $(this).stop().animate({"opacity": 0.5}, 500); 
	});
	

	// Top Image Slider
	
	initTopImage();
	
	// Google Map

	if($("#map_canvas").length > 0) {
		$("#map_canvas").gMap({
			markers: [{
				latitude: 40.758082745042216,
				longitude: -73.97513151168823,
				html: "<h3>The New York Palace Hotel</h3><p>455 Madison Avenue<br>New York, NY 10022, United States<br>Phone: (212) 888-7000</p>",
				popup: true
			}],
			zoom: 16,
			controls: ["GLargeMapControl3D", "GMapTypeControl"],
			scrollwheel: false,
			icon: {
				image:              virtual + "images/pointer.png",
				shadow:             virtual + "images/pointer-shadow.png",
				iconsize:           [31, 39],
				shadowsize:         [31,39],
				iconanchor:         [10, 39],
				infowindowanchor:   [8, 2]
			}
		});
	}
	
	// Ping Pong
	$("#ping").after($('<input>').attr({'name':'pong','value':$("#ping").val(),'class':'hide'}));

	
});

// Various Functions

/*function initTopImage() {
	var count = $("#Topimage div.peKenBurns").children().length;
	if (count > 1) {
		$('#Topimage div.peKenBurns img').wrap('<div class="peKb_active" data-delay="5" data-align="bottom,center" data-pan="top,center" />');
		$(".peKenBurns").peKenburnsSlider();
		$("#Topimage img").removeClass("hide");
	}
}*/

function initTopImage() {
	var count = $("#Topimage div.peKenBurns").children().length;
	if (count > 1) {
		/*$('.peKenBurns').nivoSlider({
        effect:'fade' // Specify sets like: 'fold,fade,sliceDown'
       
    });*/
		
		$('.peKenBurns').innerfade({
								   'containerheight' : '379px'
								   });

	}
}

function renderPlusone() {
  gapi.plusone.render("PlusOne", {"size" : "small"});
}

function emailCheck(emailFormField, showerror) {

	var txt = emailFormField.value;
	var error = "";

	var emailRe = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*\.(\w{2}|(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum))$/
	var phoneRe = /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/

	if (!(emailRe.test(txt))) {
		error = "Please enter a valid email address.\n";
	}

	var illegalChars = /[\(\)\<\>\,\;\:\\\/\"\[\]]/
	if (txt.match(illegalChars)) {
		error += "The email address contains illegal characters.\n";
	}

	if (error.length > 0) {
		if (showerror) {
			emailFormField.focus();
			alert(error);
		}
		return false;
	}
	return true;
}

function toggleSocialPanel(t) {
	$('.social span').removeClass('active');
	var panel = $('#social-panel');
	var top = panel.hasClass('closed') ? 0 : -226;
	var rel = panel.attr('rel');

	if (t!=rel) {
		panel.animate({
			top: -226
		},200,function() {
			top = 0;
			panel.addClass('closed');
			switchFeed(panel,t,top);
		})
	} else {
		switchFeed(panel,t,top);
	}
}

function switchFeed(panel,t,top) {
	$('.social a').removeClass('active');
	switch(t) {
		case 'fb':
			$('#facebook').show();
			$('#twitter').hide();
		break;
		case 'tw':
			$('#twitter').show();
			$('#facebook').hide();
		break;
	}
	if (top == 0) $('#'+t).addClass('active');
	panel.animate({
		top: top
	},function() {
		panel.toggleClass('closed').attr('rel',t);
	});
}

function initTwitter() {
	// TWITTER

    $("#tw1").tweet({
        count: 2,
        username: "NewYorkPalaceNY",
        loading_text: "",
        template: '<div class="feed-header cln"><h3 class="fl">@{screen_name}</h3><a href="{user_url}" target="_blank">Follow</a></div><p>{text}</p><div class="feed-controls"><a href="http://twitter.com/home?status=RT+@{screen_name}+{tweet_raw_text}" target="_blank">Retweet</a><a href="{user_url}" target="_blank">All Tweets</a></div>',
		callback: function() {
			$("#tw2").tweet({
		        count: 2,
		        username: "NewYorkPalaceNY",
		        loading_text: "",
		        template: '<div class="feed-header cln"><h3 class="fl">@{screen_name}</h3><a href="{user_url}" target="_blank">Follow</a></div><p>{text}</p><div class="feed-controls"><a href="http://twitter.com/home?status=RT+@{screen_name}+{tweet_raw_text}" target="_blank">Retweet</a><a href="{user_url}" target="_blank">All Tweets</a></div>',
				callback: function() {
					$('#twitter .inner').append($('<ul class="feed-content" id="twitter-feed">'));
					$('#tw1 li.feed-item, #tw2 li.feed-item').each(function(i,el) {
						if (i < 2) {
							$('#twitter-feed').append($(el))
						} else {
							$('#twitter-feed li:nth-child('+((i-6)*2-1)+')').after($(el));
						}
					});
					$('#tw1, #tw2').empty().remove();
					//$('#twitter-feed').slider({auto:false,width:340,hover:false,nav:true});
				}
		    });
		}
    });
}

function initFacebook() {
	var facebookname = "117407976160";
	var url = "/json/?m=facebook&profile_id="+facebookname;
	var n = 0;

	var fbhtml = "";

	var regexp = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»""'']))/gi;

	$.getJSON(url,function(json) {
		if (json.data) {
		$.each(json.data,function(i,fb) {
			if (fb.message && n++<2 ) {
				fbhtml += '<li class="feed-item"><div class="feed-header cln"><h3>The New York Palace</h3></div>';
				fbhtml += '<p>';

				var fbhtmlMessage = fb.message.replace(regexp, function(match) {
					var url = (/^[a-z]+:/i).test(match) ? match : "http://"+ match;
					return "<a href=\""+url+"\">"+match+"</a>";
					//return "";
				});

				var fbid = fb.id.split('_');
				var fb_permalink = 'http://www.facebook.com/permalink.php?story_fbid='+fbid[1]+'&id='+fbid[0];

				fbhtml += fbhtmlMessage.substr(0, 150);
				if (fbhtmlMessage.length > 150) fbhtml += '...';
				fbhtml += '<a class="readmore" href="'+fb_permalink+'">Read More</a>';

				fbhtml += '</p>';

				//var fbiframe = '<iframe src="http://www.facebook.com/plugins/like.php?href=' +fb_permalink+ '&amp;layout=button_count&amp;show_faces=false&amp;width=80&amp;action=like&amp;colorscheme=light&amp;height=35" scrolling="no" frameborder="0" allowTransparency="true" class="facebook-like"></iframe>';
				//fbhtml += '<div class="fbbutton">' +fbiframe+ '</div>';
				
				fbhtml += '<div class="feed-controls"><a href="http://www.facebook.com/TheNewYorkPalace">The Palace on FB</a></div>';
				fbhtml += '</li>';
			}
		});

		$('#fb1').html(fbhtml);

		$('#facebook .inner').append($('<ul class="feed-content" id="facebook-feed">'));

		$('#fb1 li.feed-item').each(function(i,el) {

			if (i < 2) {
				$('#facebook-feed').append($(el))
			} else {
				$('#facebook-feed li:nth-child('+((i-6)*2-1)+')').after($(el));
			}
		});
		$('#fb1').empty().remove();
		//$('#facebook-feed').slider({auto:false,width:340,hover:false,nav:true});
		}

	}); // end of getJSON
}

var log = true;
var src = 'images/photos/gallery/';
var smpref = 'sm';
var phpref = 'ph';

function getData(url, cat){
	
	var result = $.getJSON(url, function(data){
		
		var imgs = [];
		
		$.each(data[cat], function(i, val) {
			imgs.push(val);
		});
		
		initImgs(imgs);
		
	});
	
	
}



/*function initImgs(imgs){

	var div = $("<div/>");
	
	for(var i=0; i< imgs.length; i++){
		div.append('<a href="'+src+phpref+imgs[i]+'"><img src='+src+smpref+imgs[i]+' alt=""></a>');
	}
	$.when( 
		div.galleria({
			data_source: div,
			transitionSpeed: 300,
			queue: false,
			preload: 3,
			imageCrop: true,
			imagePan: true,
			width:800,
			height: 500
		})
	).then(function(){
		$.fancybox({
			padding: 0,
			autoDimensions: false,
			centerOnScroll: true,
			titleShow: false,
			width: 800,
			height: 500,
			overlayColor: '#222',
			content: div,
			onClosed: function(){
				div.empty();
			}
		});
		
	});
}*/

function initImgs(imgs){

	var div = $("<div/>");
	
	for(var i=0; i< imgs.length; i++){
		div.append('<a href="'+src+phpref+imgs[i]+'"><img src='+src+smpref+imgs[i]+' alt=""></a>');
	}
	$.when( 
		div.galleria({
			data_source: div,
			transitionSpeed: 400,
			queue: false,
			preload: 3,
			imageCrop: true,
			imagePan: false,
			width:900,
			height: 469
		})
	).then(function(){
		$.fancybox({
			padding: 0,
			autoDimensions: false,
			centerOnScroll: true,
			titleShow: false,
			overlayColor: '#222',
			content: div,
			width:900,
			height: 469,
			onClosed: function(){
				div.empty();
			}
		});
		
	});
}

