/* jQuery Color Animation Plugin */
(function(jQuery){jQuery.each(['backgroundColor','borderBottomColor','borderLeftColor','borderRightColor','borderTopColor','color','outlineColor'],function(i,attr){jQuery.fx.step[attr]=function(fx){if(fx.state==0){fx.start=getColor(fx.elem,attr);fx.end=getRGB(fx.end)}fx.elem.style[attr]="rgb("+[Math.max(Math.min(parseInt((fx.pos*(fx.end[0]-fx.start[0]))+fx.start[0]),255),0),Math.max(Math.min(parseInt((fx.pos*(fx.end[1]-fx.start[1]))+fx.start[1]),255),0),Math.max(Math.min(parseInt((fx.pos*(fx.end[2]-fx.start[2]))+fx.start[2]),255),0)].join(",")+")"}});function getRGB(color){var result;if(color&&color.constructor==Array&&color.length==3)return color;if(result=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))return[parseInt(result[1]),parseInt(result[2]),parseInt(result[3])];if(result=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))return[parseFloat(result[1])*2.55,parseFloat(result[2])*2.55,parseFloat(result[3])*2.55];if(result=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))return[parseInt(result[1],16),parseInt(result[2],16),parseInt(result[3],16)];if(result=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))return[parseInt(result[1]+result[1],16),parseInt(result[2]+result[2],16),parseInt(result[3]+result[3],16)];return colors[jQuery.trim(color).toLowerCase()]}function getColor(elem,attr){var color;do{color=jQuery.curCSS(elem,attr);if(color!=''&&color!='transparent'||jQuery.nodeName(elem,"body"))break;attr="backgroundColor"}while(elem=elem.parentNode);return getRGB(color)};var colors={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(jQuery);


var $m = jQuery.noConflict();
var isiPad, isMSIE, isMSIE6, isMSIE7, isiPod, isiPhone, isWii, gallery_icon_expanded, el, galIconA;
isiPad = navigator.userAgent.match(/iPad/i);
isiPhone = navigator.userAgent.match(/iPhone/i);
isiPodTouch = navigator.userAgent.match(/iPod/i);
isMSIE = navigator.userAgent.match(/MSIE/i);
isMSIE6 = $m.browser == 'msie' && $m.browser.version < 7;
isMSIE7 = $m.browser == 'msie' && $m.browser.version == 7;
isWii = navigator.userAgent.match(/Wii/i);
isPSP = navigator.userAgent.match(/PSP/i);

var min_rate, max_rate, nights, pets, business, ci_d, co_d, date_1, date_2, tally1, tally2, senior, addr_query, cacheGoogleMapsCode, cheboyganCenterLongLat, directionsDisplay, directionsObject, directionsService, gMapZoomedInOptions, gMapZoomedOutOptions, google_maps, map3options, mapZoomedIn, mapZoomedOut, marker1, marker2, monarchMotelLongLat, printable_directions;
nights = 1;




















function setUpAttachment() {
	if ($m("body").hasClass("single-attachment")) {
		var target_offset = $m("a[name=entry-content]").offset();
		var target_top = target_offset.top;
		
		var sTO = setTimeout(function(){
			$m("html,body").animate({scrollTop:target_top}, 500, 'easeOut', function(){
				console.log("animation complete");
			});
		},250);
	}
}





















function setUpBrowserSpecific() {
	if (isiPad) {
		
	} else if (isMSIE) {
		
		
	} else {
		
	}
}





















function setUpNonIE6Elements() {
	// this function activates special elements in all browsers OTHER than IE6
	if (!isMSIE6) {
		var top_of_google_sidebar_ad = $m("#google_sidebar_ad").offset().top - parseFloat( $m("#google_sidebar_ad").css('margin-top').replace(/auto/, 0));
		
		
		
		$m(window).scroll(function (event) {
			var y = $m(this).scrollTop();
			
			if (y > 260) {
				$m("#new_header_slideDown").addClass('activated');
			} else {
				$m("#new_header_slideDown").removeClass('activated');
			}
			
		});
	}
	
	if (!isMSIE6) {
		gmap_setup();
	}
}



function setUpContactForm() {
	if ($m.exists("#motel_contact_form")) {
		
		$m("#comment_checkout_date, #comment_checkin_date").datepicker({
			showOn: "button",
			buttonImage: bloginfo.siteurl+"/wp-content/themes/monarch2/img/calendar_icon.gif",
			buttonImageOnly: true,
			onSelect: function(dateText, inst) {
				recalcRate();
			}
		});
		
		$m("#comment_senior, #comment_pets, #comment_business, #comment_total_adults, #comment_total_children, #comment_checkin_date, #comment_checkout_date").change(function(){
			if ($m(this).attr("id") == "comment_business") {
				if ( $m("#comment_business:checkbox:checked").val() ) {
					$m(".business_sub_options").show();
				} else {
					$m(".business_sub_options").hide();
				}
			}
			recalcRate();
		});
		
		$m("#comment_room_type").change(function(){
			if ( $m(this).val() == "1bed") {
				$m("#comment_total_adults option.2bed").attr("disabled","disabled");
				$m("#comment_total_adults").val(2);
			} else if ( $m(this).val() == "2bed") {
				$m("#comment_total_adults option.2bed").attr("disabled","");
			}
			recalcRate();
		});
		
		
		$m("#motel_contact_form_area button.submit").click(function(){
			validations = 0;
			email_valid = 0;
			phone_valid = 0;
			validation_passed = false;
			
			
			// check if email is entered and valid
			if ((validate_email_address($m("#comment_email").val()) == true)) {
				validations++;
				email_valid = 1;
			}
			
			// check if phone is entered and valid
			if ( !isNaN($m("#comment_phone").val()) || $m("#comment_phone").val() == "" || !$m("#comment_phone").val()) {
				validations++;
				phone_valid = 1;
			}
			
			
			if (email_valid == 0) {
				$m("html,body").animate({scrollTop:450}, 500, 'easeOut', function(){});
				alert("There was an error with your email address.  Please recheck your email address and make sure they are entered the same in both fields.");
			}
			
			if (phone_valid == 0) {
				$m("html,body").animate({scrollTop:500}, 500, 'easeOut', function(){});
				alert("There was an error with your phone number.  Please recheck and make sure that your phone number is entered correctly.  Only digits are accepted (0 - 9).  No spaces, parenthesis, dashes or other characters are accepted.");
			}
			
			if ($m("#comment_room_type").val() == "1bed" || $m("#comment_room_type").val() == "2bed") {
				validations++;
			} else {
				// did not validate, display an error
				//console.log("comment_room_type did not validate");
			}
			
			
			
			
			
			
			
			
			if (validations == 3) {
				validation_passed = true;
			}
			
			if (validation_passed == true) {
				submit_contact_form();
			}
			
			return false;
		});
	}
}






function validate_email_address(email) {
	var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	
	if(reg.test(email) == false) {
		//console.log("EMail Address is not valid");
		return false;
	} else {
		if (email == $m("#comment_email_verify").val()) {
			//console.log("EMail Address is valid and matches Verify Address");
			return true;
		} else {
			// Email was typed in differently between the Email and Verify Email fields.
			// notify of error
			//console.log("EMail Address is valid, but does not match the Verify Address");
			return false;
		}
	}
}






function submit_contact_form() {
	$m.ajax({
		type: "POST",
		url: bloginfo.siteurl+"/wp-content/themes/monarch2/test.php",
		dataType: "text",
		timeout: 10000,
		cache: false,
		data: {
			mmpt: "pcfs",
			cname: escape($m("#comment_name").val()),
			cemail: escape($m("#comment_email").val()),
			cphone: escape($m("#comment_phone").val()),
			crtype: escape($m("#comment_room_type").val()),
			ccidate: escape($m("#comment_checkin_date").val()),
			ccodate: escape($m("#comment_checkout_date").val()),
			ctnights: escape($m("#total_nights").text()),
			ctadults: escape($m("#comment_total_adults").val()),
			ctchildren: escape($m("#comment_total_children").val()),
			cpets: escape($m("#comment_pets").attr("checked")),
			csenior: escape($m("#comment_senior").attr("checked")),
			cbiz: escape($m("#comment_business").attr("checked")),
			cbname: escape($m("#comment_business_name").val()),
			cbaddress: escape($m("#comment_business_address").val()),
			cbcity: escape($m("#comment_business_city").val()),
			cbstate: escape($m("#comment_business_state").val()),
			cbzip: escape($m("#comment_business_zipcode").val()),
			ccomment: escape($m("#comment_comments").val()),
			cminrate: escape($m("#estimated_calculation_minimum").text()),
			cmaxrate: escape($m("#estimated_calculation_maximum").text())
		},
		beforeSend: function(jqXHR, settings) {
			
		},
		success: function(data, textStatus, jqXHR) {
			
			if (data == "Not Submitted - Duplicate") {
				
				
				html = "<p>Your message has not been submitted because another message from your current IP Address was submitted within the last 5 minutes.</p>"+
				"<p>Please try again later.</p>"+
				"";
				$m("form#motel_contact_form_area").hide();
				$m("div#motel_contact_form_submitted").html(html).show();
				$m("html,body").animate({scrollTop:0}, 500, 'easeOut', function(){});
				
			} else if (data == "Not Submitted - Blocked") {
				
				
				html = "<p>Your message has not been submitted because the email address provided or the IP address you are posting from is on the motel blacklist.</p>"+
				"";
				$m("form#motel_contact_form_area").hide();
				$m("div#motel_contact_form_submitted").html(html).show();
				$m("html,body").animate({scrollTop:0}, 500, 'easeOut', function(){});
				
			} else {
				
				
				html = "<p>Your message has been submitted.</p>"+
				"<p>Your <strong>Reference Number</strong> is: <span id=\"reference_number\">"+data+"</span></p>"+
				"<p>Please allow for up to 24 hours for our response. Below is a copy of your message.</p>"+
				"";
				$m("form#motel_contact_form_area").hide();
				$m("div#motel_contact_form_submitted").html(html).show();
				$m("html,body").animate({scrollTop:0}, 500, 'easeOut', function(){});
				
			}
		},
		complete: function(jqXHR, textStatus) {
			
		},
		error: function(jqXHR, textStatus, errorThrown) {
			
		}
	});
}



































function recalcRate() {
	if ( $m("#comment_room_type").val() == "1bed" ) {
		min_rate = 40;
		max_rate = 60;
	} else if ( $m("#comment_room_type").val() == "2bed" ) {
		min_rate = 50;
		max_rate = 70;
	}
	
	nights = 1;
	
	// determine the difference in dates
	ci_d = $m("#comment_checkin_date").val().split("/");
	co_d = $m("#comment_checkout_date").val().split("/");
	
	// create and populate javascript Date objects
	date_1 = new Date(); date_2 = new Date();
	date_1.setYear(ci_d[2]); date_1.setMonth(ci_d[0]); date_1.setDate(ci_d[1]);
	date_2.setYear(co_d[2]); date_2.setMonth(co_d[0]); date_2.setDate(co_d[1]);
	
	// determine nights
	nights = days_between(date_1, date_2);
	
	// set 'nights' display text
	$m("#total_nights").text(nights);
	
	// calculate tallys
	tally = parseInt(min_rate) * parseInt(nights);
	tally2 = parseInt(max_rate) * parseInt(nights);
	
	
	
	// add in pets
	if ( nights > 4 ) { $m("#comment_pets:checkbox").attr('disabled','disabled'); } else { $m("#comment_pets:checkbox").removeAttr('disabled'); }
	if ( $m("#comment_pets:checkbox:checked").not(":disabled").val() ) { pets = true; } else { pets = false; }
	
	// is senior
	if ( $m("#comment_senior:checkbox:checked").val() ) { senior = true; } else { senior = false; }
	
	// is business
	if ( $m("#comment_business:checkbox:checked").val() ) {
		$m("#business_options_list").show();
		$m("#comment_business_name").removeAttr('disabled');
		$m("#comment_business_address").removeAttr('disabled');
		$m("#comment_business_city").removeAttr('disabled');
		$m("#comment_business_state").removeAttr('disabled');
		$m("#comment_business_zipcode").removeAttr('disabled');
		business = true;
	} else {
		$m("#business_options_list").hide();
		$m("#comment_business_name").attr('disabled', 'disabled');
		$m("#comment_business_address").attr('disabled', 'disabled');
		$m("#comment_business_city").attr('disabled', 'disabled');
		$m("#comment_business_state").attr('disabled', 'disabled');
		$m("#comment_business_zipcode").attr('disabled', 'disabled');
		business = false;
	}
	
	
	
	
	
	
	
	
	
	
	// if pets is true, rate is an additional $5 per night
	if (pets == true) {
		tally = tally + (5 * nights);
		tally2 = tally2 + (5 * nights);
	}
	
	// if senior is true, guest gets $5 off per night
	if (senior == true) {
		tally = tally - (5 * nights);
		tally2 = tally2 - (5 * nights);
	}
	
	// if business is true, guest gets $5 off per night
	if (business == true) {
		tally = tally - (5 * nights);
		tally2 = tally2 - (5 * nights);
	}
	
	$m("#estimated_calculation_minimum").text("$"+tally+".00");
	$m("#estimated_calculation_maximum").text("$"+tally2+".00");
}




































/* Utility Functions */

function IsNumeric(input){return(input-0)==input&&input.length>0;}

jQuery.exists=function(selector){return(jQuery(selector).length>0);}




































function days_between(date1, date2) {
	var ONE_DAY = 1000 * 60 * 60 * 24;
	var date1_ms = date1.getTime();
	var date2_ms = date2.getTime();
	var difference_ms = Math.abs(date1_ms - date2_ms);
	return Math.round(difference_ms/ONE_DAY);
}

































function setup_google_maps() {
	
	
	monarchMotelLongLat = new google.maps.LatLng(45.654788,-84.487309);
	cheboyganCenterLongLat = new google.maps.LatLng(45.644258,-84.477181);
	directionsService = new google.maps.DirectionsService();
	directionsDisplay = new google.maps.DirectionsRenderer();
	gMapZoomedInOptions = {
		scrollwheel: false,
		zoom: 15,
		center: monarchMotelLongLat,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	gMapZoomedOutOptions = {
		scrollwheel: false,
		zoom: 13,
		center: cheboyganCenterLongLat,
		mapTypeId: google.maps.MapTypeId.SATELLITE
	};
	map3options = {
		zoom:15,
	    mapTypeId: google.maps.MapTypeId.ROADMAP,
	    center: monarchMotelLongLat
	};
	mapZoomedIn = new google.maps.Map(document.getElementById("gmap_zoomed_in"),gMapZoomedInOptions);
	mapZoomedOut = new google.maps.Map(document.getElementById("gsat_zoomed_out"),gMapZoomedOutOptions);
	marker1 = new google.maps.Marker({
		position: monarchMotelLongLat, 
		map: mapZoomedIn
	});
	marker2 = new google.maps.Marker({
		position: monarchMotelLongLat, 
		map: mapZoomedOut
	});
	gmap_directions_map = new google.maps.Map(document.getElementById("gmap_directions"),map3options);
	directionsDisplay.setMap(gmap_directions_map);
	printable_directions = $m("#printable_directions");
	$m("#get_directions_to_motel").click(function(){
		addr_query = $m("#starting_address").val();
		if ( ( addr_query == "" ) || ( addr_query === "" ) || ( !addr_query ) ) {} else {
			var static_map = $m("#static_maps");
			var direction_map = $m("#directions_map");
			directionsObject = {
				origin: addr_query,
				destination: 'Monarch Motel, 1257 Mackinaw Ave, Cheboygan MI 49721',
				travelMode: google.maps.TravelMode.DRIVING,
				provideRouteAlternatives: true
			};
			if ( static_map.css("display") == "none" ) {
				directionsService.route(directionsObject, function(result, status) {
					if (status == google.maps.DirectionsStatus.OK) {
						directionsDisplay.setDirections(result);
					}
				});
			} else {
				static_map.hide();
				directionsService.route(directionsObject, function(result, status) {
					if (status == google.maps.DirectionsStatus.OK) {
						directionsDisplay.setDirections(result);
						$m("#directions_map").removeClass("seeThrough");
					}
				});
			}
			printable_directions.show(0).css("background-color","#ffff00").delay(100).animate({backgroundColor:"#999999"},850);
		}
	});
	printable_directions.click(function(){
		var url = 'http://maps.google.com/maps?f=d&saddr='+encodeURI(addr_query)+'&daddr='+encodeURI('Monarch Motel, 1257 Mackinaw Ave, Cheboygan MI 49721')+'&ie=UTF8&z=12&layer=c&pw=2';
		
		window.open(url,'monarchdirections','width=785,height=514,scrollbars=yes');
	});
}






































function gmap_setup() {
	if ($m("#directions_form").css("display") != "none") {
		setup_google_maps();
	} else {
		google_maps = $m("#google_maps");
		cacheGoogleMapsCode = google_maps.html();
		
		google_maps.html("Click To Load Maps");
		
		
		google_maps.click(function(){
			google_maps.removeClass("hiddenMap").html(cacheGoogleMapsCode);
			$m("#directions_form, #static_maps").removeClass("noDisplay");
			setup_google_maps();
		});
	}
}





























$m(window).load(function(){
	setUpAttachment();
	setUpBrowserSpecific();
	setUpNonIE6Elements();
	setUpContactForm();
	
	
	
	// show gtranslate if jscript is enabled
	$m("#gtranslate").show();
	
	if ($m.exists("span#show_without_tax")){
		$m("span#show_without_tax").show();
		$m("span#show_without_tax").click(function(){
			if ($m(".withoutTax.tester").css("display") == "none") {
				$m(".withTax").hide();
				$m(".withoutTax").show();
			} else {
				$m(".withTax").show();
				$m(".withoutTax").hide();
			}
		});
	}
	
	
	
	if ($m.exists("div#motel_policies")) {
		
		$m("a[name='nosmoking'],a[name='generalpolicy'],a[name='houserules'],a[name='payment'],a[name='reservations'],a[name='weekly'],a[name='monthly'],a[name='cancellation'],a[name='wifipolicy'],a[name='pets'],a[name='parking'],a[name='law'],a[name='housekeeping'],a[name='holidays']").css({
			"margin-top": "-75px",
			"height": "75px",
			"width": "75px",
			"display": "block"
		});
	}
	
});


