/**
 * Shortcut to post json data to a url
 * @param url A string containing the URL to which the request is sent. (put any get parameters into the url)
 * @param data A map or string that is sent to be posted to the server with the request.
 * @param callback A callback function that is executed if the request succeeds.
 */
jQuery.postJSON = function(url, data, callback) {
    jQuery.post(url, data, callback, "json");
}

/**
* Json Count function
*/
function countJson(obj) {
	var prop;
	var count = 0;
	for (prop in obj) {
		count++;
	}
	return count;
}

/**
* Native set cookie function
* @param cookie name
* @param cookie value
* @param cookie expiration days
*/
function setCookie(c_name, value, exdays) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate() + exdays);
	var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
	document.cookie=c_name + "=" + c_value;
}

/**
* Native cookie retrieval function
* @param cookie name
* @return cookie value
*/
function getCookie(c_name) {
	var i,x,y,ARRcookies=document.cookie.split(";");
	for (i=0;i<ARRcookies.length;i++) {
		x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
		y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
		x=x.replace(/^\s+|\s+$/g,"");
		if (x==c_name) {
			return unescape(y);
		}
	}
}

/**
* Function used to check a cookie exists and has a specific value
* @param cookie name
* @param cookie value
* @return boolean on validation
*/
function checkCookie(c_name, value) {
	var c_value = getCookie(c_name);
	return (c_value != null && c_value != "" && c_value == value);
}


jQuery(document).ready(function(){	
	
	// Creating custom :external selector
	jQuery.expr[':'].external = function(obj) { return !obj.href.match(/^mailto\:/) && (obj.hostname != location.hostname); };

	// Add 'external' CSS class to all external links
	jQuery('a:external').click(function() {
		if(checkCookie("external_link", "true")) {
			return true;
		}
		else {
			setCookie("external_link", "true", 1);
			jQuery(".modal-loader").remove();
			if(jQuery(".modal-loader").size() == 0) {
				jQuery(this).append("<span class='modal-loader'></span>");
				var href = jQuery(this).attr("href");
				jQuery(".popup-modal").remove();
				var $dialog = jQuery('<div class="popup-modal"></div>').load('/external-link/?url=' + href, function() {
					jQuery(this).dialog({
						autoOpen: false,
						dialogClass: 'popup-modal-window',
						modal: true,
						width: 350,
						height: 'auto',
						title: 'Please Note',
						resizable: false
					});
					jQuery(".modal-loader").remove();
					jQuery(this).dialog('open');
				});
			}
			return false;
		}
	});
	
	// Close modal link
	jQuery(".pop-up-close").live("click", function() {
		jQuery('.popup-modal-window').remove();
		return false;
	});
	
	// Take me there validation
	jQuery(".take-me-there-button").live("click", function() {
		var href = jQuery(this).attr("href");
		// Source list available
		if(jQuery(".source_list").size() > 0) {
			if(jQuery(".source_list").val() != "") {
				jQuery.get('/cottages/save_source/' + jQuery(".source_list").val() + '?url=' + href, '', function() {
					window.location.href = href;
				}, 'html');
				return false;
			}
			else {
				alert("Please select a source");
				return false;
			}
		}
		else {
			return true;
		}
	});
	
	if(jQuery("input.date").size() > 0) {
		jQuery("input.date").datepicker({showOn: 'both', buttonImage: '/assets/cottageline/images/calendar-icon.gif', buttonImageOnly: true, dateFormat: 'dd M yy', buttonText: 'Choose a date', minDate: -1});
	}
	var $dialog;
	jQuery("#area-select").click(function() {
		jQuery(".modal-loader").remove();
		if(jQuery(".modal-loader").size() == 0) {
			jQuery(this).append("<span class='modal-loader'></span>");
			var href = jQuery(this).attr("href");
			jQuery(".popup-modal").remove();
			$dialog = jQuery(".location-list").dialog({
				autoOpen: true,
				dialogClass: 'search-areas-window',
				modal: true,
				width: 600,
				height: 350,
				title: 'Please select all of the regions that you wish to search',
				resizable: false,
				close: function(event, ui) {
					jQuery("input", this).each(function() {
						if(jQuery(this).is(":checked")) {
							jQuery(this).clone().attr("checked", true).appendTo(jQuery(".location-list-container"));
							if(jQuery(".location-list-container input").size() == 0) {
								jQuery("#area-select").html("Click here to select an area");
							}
							else {
								jQuery("#area-select").html(jQuery(".location-list-container input").size() + " Area" + ((jQuery(".location-list-container input").size() > 1) ? "s" : "") + " selected");
							}
						}
					});
				}
			});
			jQuery(".location-list-container").html("");
			jQuery(".modal-loader").remove();
		}
		return false;
	});
	jQuery(".area-checkbox").live("click", function() {
		jQuery(".area-" + jQuery(this).data("slugname")).attr("checked", jQuery(this).is(":checked"));
	});
	jQuery(".select-all-areas").live("click", function() {
		if(jQuery(this).hasClass("checked")) {
			jQuery(".area-checkbox, .location-checkbox").attr("checked", false);
			jQuery(this).removeClass("checked");
		}
		else {
			jQuery(".area-checkbox, .location-checkbox").attr("checked", true);
			jQuery(this).addClass("checked");
		}
		return false;
	});
	jQuery("#close-search-form").live("click", function() {
		$dialog.dialog("close");
		return false;
	});
	jQuery("#toggle-search-form").click("click", function() {
		jQuery(".ui-datepicker-trigger").hide();
		jQuery(".search-form").slideToggle(1000, function() {
			if(jQuery(this).css("display") == "none") {
				jQuery("#toggle-search-form").html("Filter Results");
			}
			else {
				jQuery("#toggle-search-form").html("Hide");
			}
			jQuery(".ui-datepicker-trigger").show().css("display", "inline");
		});
		return false;
	});
	
	jQuery("#enquiry_form, #ebrochure_form").submit(function() {
		var form_id = jQuery(this).attr("id");
		jQuery("#" + form_id + " span.field_error").remove();
		jQuery.postJSON(jQuery(this).attr("action"), jQuery(this).serialize(), function(json) {
			if(json.status == "ok") {
				if(countJson(json.fields) > 0) {
					if(json.fields.confirmation_url) {
						window.location = json.fields.confirmation_url;
					}
					else {
						alert("Thank you for your enquiry");
					}
				}
			}
			else {
				if(countJson(json.fields) > 0) {
					jQuery.each(json.fields, function(key, val) {
						if(jQuery("#" + form_id + " div." + key).size() > 0) {
							jQuery("#" + form_id + " div." + key).append("<span class='field_error'>" + val + "</span>").hide().fadeIn(300);
						}
					});
				}
			}
		});
		return false;
	});
});
