var width_businessname	= 316;
var width_at_venue		= 225;
var width_at_venue2		= 232;
var width_dish_at_venue	= 232;
var width_cuisine		= 316;
var width_city			= 374;
var width_city_venue	= 198;
var width_buildingname	= 374;
var width_buildingname2	= 250;
var width_creditcard	= 470;
var autocompleteName	= '';

var msgAfterUploadPhoto			= "Move to green camera to see the result";
var msgOnProgressUploadPhoto	= "Uploading. Please wait...";
var progressPiePrevClass		= 'size-0';

var gv_businessUrlDefault		= 'URL (http://www.domain.com)';

var autocomplete_business_flag = false;
var autocomplete_poi_flag = false;
var resultName = '';

var url_redir = "";

/* PROMOTION */

function suggestPromotionInit() {
//	sitoes_hoverImage('mm_hovered', 'PromotionPhotoImage');

	validationSuggestPromotionInit("#txtcity", "#poibuilding");
	focusBlurBehaviour('#PromotionTitle', "#PromotionSuggestForm", 'isNormal');
	focusBlurBehaviour('#PromotionDescription', "#PromotionSuggestForm", 'isNormal');
	focusBlurBehaviour('#CreditcardName', "#PromotionSuggestForm", 'isNormal');
	focusBlurBehaviour('#txt_at_venue', "#PromotionSuggestForm", 'isNormal');
	focusBlurBehaviour('#start_date', "#PromotionSuggestForm", 'isNormal');
	focusBlurBehaviour('#end_date', "#PromotionSuggestForm", 'isNormal');

	if (checkFlashVersion() > 0)
	{
		// uploadify for promotion photo
		uploadifyPromotionPhotoInit();
	}
	// upload without flash
	else
	{
		var options = {
			containerId : gv_promotionPhotoContainer,
			inputId     : 'PromotionPhoto',
			inputName   : 'data[Promotion][photo]',
			imageId     : 'PromotionPhotoImage',
			uploadPath  : '/photos/ajax_upload/promotion',
			messageId   : 'msgUpload',
			removeLinkId: 'PromotionPhoto_remove_link',
			hoveredId   : 'mm_hovered'
		};
		ajaxUploadInit(options);
	}

	autocompleteAtVenue("#txt_at_venue", "#Promotions_businessBusinessId", "#promo_just_submit", "#promo_to_venue_step", "removeAtVenuePromo");
	creditCardFormInit();
	datepickerInit();

	promotionStepValidator("#frm_promo_validator", "#PromotionSuggestForm", "#PromotionTitle", "#txt_at_venue", "#PromotionDescription", "#mm_suggestpromo", "#mm_suggest_venue_part", "#backToDishStep");
}

function autocompleteCityInit(elementCity, elementProvinceId, elementProvince) {

	//console.log(gv_cityList);

	// START autocomplete for city
	$(elementCity).autocomplete(gv_cityList, {
		formatItem: function(item) {
			return item.city + ' (' + item.province + ')';
		},
		formatResult: function(item) {
			return item.city;
		},
		width: width_city_venue,
		matchContains: true,
		highlight: false,
		formatMatch: function(row, i, max) {
			return row.city;
		},
	});


	$(elementCity).result(function(event, data, formatted) {
		var new_container = '<span class="mm_Iconset_14 doUnlock"><a class = "unlock_txt" href="javascript:void(0)"><img width="16px" height="16px" src="/img/icon/clear.gif"></a></span>';
		$(elementCity).after(new_container);
		$(elementProvinceId).val(data.province_id);
		$(elementProvince).val(data.province);
		$(elementProvince).siblings("label").removeClass("isFocus").addClass('isOff');
		$(elementCity).val(data.city);
		$(elementCity).attr("disabled", true);
	});

	$(".unlock_txt").live('click', function() {
		var container = $(this);
		container.parent().remove();

		$(elementCity).removeAttr("disabled").val("");
		$(elementCity).siblings("label").removeClass("isOff");
		$(elementCity).siblings("label").addClass("isFocus");
		$(elementCity).siblings(".mm_Validation").removeClass("isGood").addClass("isError");
		$(elementProvince).val("");
		$(elementProvince).siblings("label").removeClass("isOff");
		$(elementProvince).siblings("label").addClass("isFocus");

		return false;
	});
	// END autocomplete for city

}

function validationSuggestPromotionInit(elementCity, elementPoi) {

	label_phone_number = "dummy";
	label_url = "dummy";

	// START validation for promotion suggest
	var validationSettings  = sitoesModalv4ValidationSettings;

	// validation rules
	validationSettings.rules = {
		"data[restaurant][name]": {
			"required": true,
		},
		"data[restaurant][street_address]": "required",
		"data[restaurant][city]": "required",
		"data[restaurant][phone_number]": {
			"numberwithdefault"  : label_phone_number
		},
		"data[restaurant][cuisine]": "required",
		"data[restaurant][website_address]": {
			"urlwithdefault"  : label_url
		},
		'data[Promotion][title]': {
			'required' : true,
		},
		'data[Promotion][description]': {
			'required' : true
		},
		'data[Promotion][at_venue]': {
			'required' : true
		},
		"data[Promotion][start_date][day]" : "required",
		"data[Promotion][start_date][month]" : "required",
		"data[Promotion][start_date][year]" : "required",
		"data[Promotion][end_date][day]" : "required",
		"data[Promotion][end_date][month]" : "required",
		"data[Promotion][end_date][year]" : "required"


/*		//'data[Promotion][start_date][year]': {
		//	'multiplefields': ['#PromotionStartDateYear', '#PromotionStartDateMonth', '#PromotionStartDateDay']
		//},
		//'data[Promotion][end_date][year]': {
		//	'multiplefields': ['#PromotionEndDateYear', '#PromotionEndDateMonth', '#PromotionEndDateDay']
		//}*/
	};

	// validation messages
	validationSettings.messages = {
		'data[Business][url]': {
			urlwithdefault: 'Only URL ex. http://goorme.com'
		}
	}

	// validation submit handler
	validationSettings.submitHandler = function(form) {
		$("#businessUploadLogoInputUploader").css("visibility", "hidden");
		$("#PromotionPhotoUploader").css("visibility", "hidden");
		processModalSubmit("", ".loadElement");
		$(elementCity).removeAttr("disabled");
		$(elementPoi).removeAttr("disabled");


		// ajax form for suggest promotion
		$('#PromotionSuggestForm').ajaxSubmit({
			beforeSubmit: function(formData, jqForm, options) {
			//	$('#suggestVenueSubmitButton').attr('disabled', 'disabled');
			//	processModalSubmit();

			},
			success: function(responseData) {
				/*
				setFormOkMessage();

				gv_claimBusiness = $('#BusinessOwn').attr('checked');
				$('#mm_general_submit_button').removeAttr('disabled');
				$('#suggestVenueSubmitButton').removeAttr('disabled');

				var objectData    = jQuery.parseJSON(responseData);
				var promotion_url = objectData.promotion_url;
				var new_location  = '/promotion/' + promotion_url;

				if (gv_claimBusiness) {
					var business_id   = objectData.business_id;

					$.nyroModalManual({
						url: '/businesses/claim/' + business_id + '?next=' + new_location
					});
				} else {
					$.nyroModalRemove();
					window.location = new_location;
				}
				*/
				//temp.<b style="color:black;background-color:#ffff66">replace</b>(/[^a-zA-Z 0-9 ]+/g,'');

					var word = $("#PromotionTitle").val().replace(/[^a-zA-Z \d]+/g, "");
					//var gg = word.replace(/[^a-zA-Z 0-9 ]+/g,'');

					word = urlencode(word);

					var out    = jQuery.parseJSON(responseData);

					$.nyroModalManual({
					  url: "/semantics/suggesttag/" + 7 + "/" + out.promotion_id + "/" + word + "/" + promotion_from + "/null/" + promo_mode,
					  endRemove: function() {
							window.location = "/promotion/" + out.promotion_url;
						}
					});


			}
		});

		return false;
	};

	$('#PromotionSuggestForm').validate(validationSettings);
	// END validation for promotion suggest

}

function uploadifyPromotionPhotoInit() {

	// START uploadify for promotion photo
	$('#PromotionPhoto').uploadify({
		'uploader'  : '/swf/uploadify.swf',
		'script'    : '/photos/ajax_upload/promotion',
		'folder'    : '/userfiles/promotion_temp/',
		'buttonImg' : '/img/browse_button.png',
		'width'     : 69,
		'height'    : 28,
		'sizeLimit' : 512000,
		'multi'     : false,
		'auto'		: true,
		'fileDesc'  : 'Images Files',
		'fileExt'   : '*.jpg;*.gif;*.png;*.jpeg',

		onSelect: function(event, queueID, fileObj) {

			modalUploadifyOnSelect(event, queueID, fileObj, gv_promotionPhotoContainer);

			$('#msgUpload').text(msgOnProgressUploadPhoto);
			$('.disableOnUploadPhoto').attr("disabled", "disabled");
			return false;
		},
		onError: function(event, queueID, fileObj, errorObj) {

			modalUploadifyOnError(event, queueID, fileObj, errorObj);

			return false;
		},
		onProgress: function(event, queueID, fileObj, data) {

			modalUploadifyOnProgress(event, queueID, fileObj, data, progressPiePrevClass);

			return false;
		},
		onComplete: function(event, queueID, fileObj, response, data) {

			var imageData  = jQuery.parseJSON(response);
			var imageFile  = imageData.original + '.' + imageData.extension;
			var imageThumb = imageData.thumbnail + '.' + imageData.extension;

			var imgPath = '/userfiles/promotion_temp/' + imageThumb;
			var iconAfterUpload = '<span class="mm_Iconset_14 isPhoto isOn"><img id="mm_hovered" src="/img/icon/clear.gif" width="16px" height="16px" /></span>';

			var imgTag          = '<img style="display:none" id="PromotionPhotoImage" src="' + imgPath + '" class="mm_dev_image24" />';

			var hiddenTag  = '<input type="hidden" name="data[Promotion][photo]" value="' + imageFile + '" />';

			$(gv_promotionPhotoContainer).html(imgTag);
			$(gv_promotionPhotoContainer).append(iconAfterUpload);
			$(gv_promotionPhotoContainer).append(hiddenTag);

			$(gv_promotionPhotoContainer).siblings("label.isPhoto").html(imageData.original_label);

			$('#msgUpload').text(msgAfterUploadPhoto);
			$('.disableOnUploadPhoto').removeAttr("disabled");
			$('#PromotionPhoto_remove_link').css('display', 'block');

			sitoes_hoverImage('mm_hovered', 'PromotionPhotoImage');

			return false;
		}
	});
	// END uploadifty for promotion photo

}

function creditCardFormInit() {

	var elementCard   = '#CreditcardName';


	// START autocomplete for credit card
	$(elementCard).autocomplete(gv_cardList, {
		formatItem: function(item) {
			return item.name;
		},
		width: width_creditcard,
		matchContains: true,
		highlight: false
	});

	$(elementCard).result(function(event, data, formatted) {
		$(elementCard).val("");
		sp_addCreditCardItem('#CreditcardListContainer', data.name, data.id);
	});

	// delete credit card
	$('.deleteCreditCardLink').live('click', function() {
		$(this).parent().remove();

		return false;
	});

}

function datepickerInit() {
	$('#end_date').datePicker(
		{
		clickInput:true,
		createButton:false,
/*		//renderCallback:function($td, thisDate, month, year) {
		//	console.log("ahahaha");
		//}*/
	});

	$('#end_date').change(function() {
		var val = $(this).val();
		var container = $(this);

		if(val.length > 0)
		{
			var arr_time = val.split("/");

			$("#PromotionEndDateDay").val(arr_time[0]);
			$("#PromotionEndDateMonth").val(arr_time[1]);
			$("#PromotionEndDateYear").val(arr_time[2]);

			container.siblings("label.isNormal").addClass("isOff");

//			console.log($("#PromotionEndDateYear").val());
		}

	});

	$('#end_date').keydown(function(e) {
//		console.log(e.keyCode);

		if(e.keyCode == 8 || e.keyCode == 46)
		{
			if($('#end_date').val().length <= 1)
				$('#end_date').siblings("label.isNormal").removeClass("isOff");
		}

		else
			return false;
	});

	$('#start_date').datePicker(
		{
		clickInput:true,
		createButton:false,
/*		//renderCallback:function($td, thisDate, month, year) {
		//	console.log("ahahaha");
		//}*/
	});

	$('#start_date').change(function() {
		var val = $(this).val();
		var container = $(this);

		if(val.length > 0)
		{
			var arr_time = val.split("/");

			$("#PromotionStartDateDay").val(arr_time[0]);
			$("#PromotionStartDateMonth").val(arr_time[1]);
			$("#PromotionStartDateYear").val(arr_time[2]);

			container.siblings("label.isNormal").addClass("isOff");

//			console.log($("#PromotionEndDateYear").val());
		}

	});

	$('#start_date').keydown(function(e) {
//		console.log(e.keyCode);

		if(e.keyCode == 8 || e.keyCode == 46)
		{
			if($('#end_date').val().length <= 1)
				$('#end_date').siblings("label.isNormal").removeClass("isOff");
		}

		else
			return false;
	});
}

function sp_addCreditCardItem(container, name, id) {
	var htmlTag = '<li><input type="hidden" value="' + id + '" name="data[CardId][]"><a class="deleteCreditCardLink" rel="' + id + '" href="#"><span class="mm_Iconset_14 doRemove alignRight"><img height="16px" width="16px" src="/img/icon/clear.gif"></span></a>' + name + '</li>';

	$(container).append(htmlTag);
}

function promotionStepValidator(elementSubmitter, elementForm, elementTitle, elementVenue, elementDescription, elementPromoContainer, elementVenueContainer, elementBack) {
	$(elementSubmitter).click(function() {

		var isTitleValid = $(elementForm).validate().element(elementTitle);
		var isVenueValid = $(elementForm).validate().element(elementVenue);
		var isDescriptionValid = $(elementForm).validate().element(elementDescription);


		if(isTitleValid && isVenueValid && isDescriptionValid)
		{
			$(elementPromoContainer).addClass("isHidden");
			$(elementVenueContainer).removeClass("isHidden");


			$("#restaurantName").val($("#txt_at_venue").val());
			$("#restaurantName").siblings("label").addClass("isOff");
			$(".whole_msg").addClass("isHidden");
		}
		else
		{
			$("#added_whole_msg").html("missing required fields");
			$(elementForm).find(".whole_msg").removeClass("isHidden");
		}

		return false;
	});

	$(elementBack).click(function() {
		$(elementPromoContainer).removeClass("isHidden");
		$(elementVenueContainer).addClass("isHidden");

		return false;
	});
}

/* ************************************************************************** */

/* DISH */
function suggestDishInit() {

/*	//if (jQuery.trim($('#DishName').val()).length == 0) {
	//	$('#DishName').val(labeldish_title).addClass('gm_Watermark');
	//}

	//if (jQuery.trim($('#DishTags').val()).length == 0) {
	//	$('#DishTags').val(label_tag).addClass('gm_Watermark');
	//}

	//if (jQuery.trim($('#restaurantName').val()).length == 0) {
	//	$('#restaurantName').val(labelvenue_title).addClass('mm_watermark');
	//}

	//if (jQuery.trim($('#poibuilding').val()).length == 0) {
	//	$('#poibuilding').val(global_wm_address_building).addClass('mm_watermark');
	//}

	//$('#DishName').val(global_wm_dish_title);
	//$('#restaurantName').val(global_wm_venue_title);
	//$('#restaurantPhoneNumber').val(global_wm_address_phone);
	//$('#restaurantUrl').val(global_wm_website);

	//focusBlurDefault('#DishName', labeldish_title, 'gm_Watermark');
	//focusBlurDefault('#DishTags', label_tag, 'gm_Watermark');
	//focusBlurDefault('#restaurantName', labelvenue_title, 'mm_watermark');
	//focusBlurDefault('#poibuilding', global_wm_address_building, 'mm_watermark');
*/
	focusBlurBehaviour("#DishName", "#sitoes_business_suggestdish", "isNormal");
	focusBlurBehaviour("#price0", "#sitoes_business_suggestdish", "isNormal");
	focusBlurBehaviour("#txt_at_venue", "#sitoes_business_suggestdish", "isNormal");
	focusBlurBehaviour("#DishDescription", "#sitoes_business_suggestdish", "isNormal");


//	sitoes_hoverImage('menu_hover_image', 0, -24);

	// check flash version
	if (checkFlashVersion() > 0)
	{
		// uploadify for dish photo
		uploadifyMenuPhotoInit();
	}
	// upload without flash
	else
	{
		var options = {
			containerId : '#menuPhotoContainer',
			inputId     : 'menuPhoto',
			inputName   : 'data[dish][photo][]',
			imageId     : 'menu_hover_image',
			uploadPath  : '/photos/ajax_upload/photo/menu',
			messageId   : 'msgUpload',
			removeLinkId: 'removePhotoMenu',
			hoveredId   : 'mm_hovered'
		};
		ajaxUploadInit(options);
	}

	/*
	// check flash version
	if (checkFlashVersion() > 0)
	{
		// uploadify for venue photo
		uploadifyBusinessLogo2Init();
	}
	// upload without flash
	else
	{
		var options = {
			containerId : '#businessUploadLogoData',
			inputId     : 'businessUploadLogoInput',
			inputName   : 'data[restaurant][logo][]',
			imageId     : 'business_hover_image',
			uploadPath  : '/photos/ajax_upload/photo/business',
			messageId   : 'msgUpload2',
			removeLinkId: 'removePhotoBusiness',
			hoveredId   : 'mm_hovered2'
		};
		ajaxUploadInit(options);
	}
	*/
	validationSuggestDishInit();

	autocompleteAtVenue("#txt_at_venue", "#restaurantId", "#just_submit", "#detect_new_venue", "removeAtVenue");

	//removePhotoMenuInit();

	//removePhotoBusinessInit();

	//autocompletePoi2Init();

	//autocompleteRestaurantNameInit();

	//autocompleteCityInit();

	//detailLinkSuggestVenue2Init();

	//priceSuggestDishInit();

	//checkboxNewLocationInit();

	//focusBlurDefault('#restaurantPhoneNumber', label_phone_number, 'mm_watermark');
	//focusBlurDefault('#restaurantUrl', label_url, 'mm_watermark');

	$("#backButton").click(function() {
		$("#sitoes_business_suggestdish").parent().css('display', 'block');
		$("#sitoes_business_suggestarestaurant").parent().css('display', 'none');
		return false;
	});

	//manageVenueLocation();

	/*
	//for suggest dish from venue detail step 1 to 2 prefilled
	var business_id = $('#MenuBusinessId').val();

	if(business_id != "")
	{
		autofillPoiResult(business_id);
		$('#restaurantName').removeClass("gm_Watermark");
	}
	*/

	dishStepValidator("#frmDishValidator", "#sitoes_business_suggestdish", "#DishName", "#txt_at_venue", "#price0", "#mm_suggestdish", "#mm_suggestvenue", "#backToDishStep");
}

function uploadifyMenuPhotoInit() {
	// uploadify
	$('#menuPhoto').uploadify({
		'uploader'  : '/swf/uploadify.swf',
		'script'    : '/photos/ajax_upload/photo/menu',
		'folder'    : '/userfiles/photos',
		'cancelImg' : '/img/cancel.png',
		'buttonImg' : '/img/browse_button.png',
		'width'     : 69,
		'height'    : 28,
		'sizeLimit' : 512000,
		'multi'     : false,
		'auto'		: true,
		'fileExt'		: '*.jpg;*.png;*.gif;*.jpeg',
		'fileDesc'		: 'image files',
		onSelect    : function(event, queueID, fileObj) {

			/*
			var fileName   = fileObj.name;
			var fileLength = fileName.length;

			$('.mm_errormessage').css('display', 'none');

			if (fileLength > 15) {
				var fileName = fileObj.name.substring(0, 3);
				var fileName = fileName + '..' + fileObj.name.substring(fileLength-4, fileLength);
			}

			var queueItem = '<div id="menuPhoto' + queueID + '" class="pie-container"><div id="pie' + queueID + '" class="pie size-0"><a href="javascript:jQuery(\'#menuPhoto\').uploadifyCancel(\'' + queueID + '\')">&nbsp;</a></div></div>';

			$('#menuPhotoContainer').html(queueItem);
			*/
			modalUploadifyOnSelect(event, queueID, fileObj, '#menuPhotoContainer');

			$('#msgUpload').text("Uploading. Please Wait...");
			$('.disableOnUploadPhoto').attr("disabled", "disabled");

			return false;
		},
		onError: function(event, queueID, fileObj, errorObj) {

			modalUploadifyOnError(event, queueID, fileObj, errorObj);

			return false;
		},
		onProgress  : function(event, queueID, fileObj, data) {

			modalUploadifyOnProgress(event, queueID, fileObj, data, progressPiePrevClass);

			return false;
		},
		onComplete  : function(event, queueID, fileObj, response, data) {

			var imageData  = jQuery.parseJSON(response);

			var imageFile  = imageData.original + '.' + imageData.extension;
			var imageThumb = imageData.thumbnail + '.' + imageData.extension;

			var imgPath = '/userfiles/photo/' + imageThumb;

			var iconAfterUpload = '<span class="mm_Iconset_14 isPhoto isOn"><img id="mm_hovered" src="/img/icon/clear.gif" width="16px" height="16px" /></span>';
			var imgTag          = '<img id="menu_hover_image" width="24px" height="24px" src="'+ imgPath +'" style="display:none" />';

			var hiddenTag = '<input type="hidden" id="MenuPhotoS" name="data[Menu][photo][]" value="'+ imageFile +'" />';

			$('#menuPhotoContainer').html(imgTag + hiddenTag + iconAfterUpload);

			$('#msgUpload').text(msgAfterUploadPhoto);
			$('.disableOnUploadPhoto').removeAttr("disabled");
			$('#removePhotoMenu').css('display', 'block');

			$('#menuPhotoContainer').siblings("label.isPhoto").html(imageData.original_label);

			sitoes_hoverImage('mm_hovered', 'menu_hover_image');

			return false;
		},
		/*
		onOpen    : function(event, queueID, fileObj) {

			var fileName   = fileObj.name;
			var fileLength = fileName.length;

			if (!/^[0-9a-z-_.]+$/i.test(fileName))
			{
				alert("violated filename 3");
			    $('#' + settings.id).fileUploadCancel(queueID);
			}

			//return true;
			return false;
		}
*/
	});
}

function uploadifyBusinessLogo2Init() {
	// uploadify for venues
	$('#businessUploadLogoInput').uploadify({
		'uploader'      : '/swf/uploadify.swf',
		'script'        : '/photos/ajax_upload/photo/business',
		'folder'        : '/userfiles/photo',
		'cancelImg'     : '/img/cancel.png',
		'buttonImg' 	: '/img/browse_button.png',
		'width'			: 69,
		'height'		: 28,
		'sizeLimit'     : 204800,
		'multi'         : false,
		'auto'			: true,
		'fileExt'		: '*.jpg;*.png;*.gif;*.jpeg',
		'fileDesc'		: 'image file',
		onSelect    : function(event, queueID, fileObj) {

			/*
			var fileName   = fileObj.name;
			var fileLength = fileName.length;

			$('.mm_errormessage').css('display', 'none');

			if (fileLength > 15) {
				var fileName = fileObj.name.substring(0, 3);
				var fileName = fileName + '..' + fileObj.name.substring(fileLength-4, fileLength);
			}

			var queueItem = '<div id="businessUploadLogoInput' + queueID + '" class="pie-container"><div id="pie' + queueID + '" class="pie size-0"><a href="javascript:jQuery(\'#businessUploadLogoInput' + '\').uploadifyCancel(\'' + queueID + '\')">&nbsp;</a></div></div>';
			$('#businessUploadLogoData').html(queueItem);
			*/

			modalUploadifyOnSelect(event, queueID, fileObj, '#businessUploadLogoData');

			$('#msgUpload2').text(msgOnProgressUploadPhoto);
			$('.disableOnUploadPhoto').attr("disabled", "disabled");
			//alert(queueItem);

			return false;
		},
		onError: function(event, queueID, fileObj, errorObj) {

			modalUploadifyOnError(event, queueID, fileObj, errorObj);

			return false;
		},
		onProgress  : function(event, queueID, fileObj, data) {

			modalUploadifyOnProgress(event, queueID, fileObj, data, progressPiePrevClass);

			return false;
		},
		onComplete  : function(event, queueID, fileObj, response, data) {

			var imageData  = jQuery.parseJSON(response);
			var imageFile  = imageData.original + '.' + imageData.extension;
			var imageThumb = imageData.thumbnail + '.' + imageData.extension;

			var imgPath      = '/userfiles/photo/' + imageThumb;

			var iconAfterUpload = '<span class="mm_Iconset_14 isPhoto isOn"><img id="mm_hovered2" src="/img/icon/clear.gif" width="16px" height="16px" /></span>';
			var imgTag          = '<img id="business_hover_image" width="24px" height="24px" src="'+ imgPath +'" style="display:none" />';

			var hiddenTag = '<input type="hidden" name="data[restaurant][logo][]" value="'+ imageFile +'" id="BusinessLogo" />';

			$('#businessUploadLogoData').html(imgTag + hiddenTag + iconAfterUpload);

			$('#msgUpload2').text(msgAfterUploadPhoto);
			$('.disableOnUploadPhoto').removeAttr("disabled");
			$('#removePhotoBusiness').css('display', 'block');

			$('#businessUploadLogoData').siblings("label.isPhoto").html(imageData.original_label);


			sitoes_hoverImage('mm_hovered2', 'business_hover_image');

			return false;
		}
	});
}

function validationSuggestDishInit() {
	// form validation

	label_phone_number = "dummy";
	label_url = "dummy";

// START validation for venue suggest
	var validationSettings  = sitoesModalv4ValidationSettings;

	// validation rules
	validationSettings.rules = {
		"data[restaurant][name]": {
			"required": true,
		},
		"data[restaurant][street_address]": "required",
		"data[restaurant][city]": "required",
		"data[restaurant][phone_number]": {
			"numberwithdefault"  : label_phone_number
		},
		"data[restaurant][cuisine]": "required",
		"data[restaurant][website_address]": {
			"urlwithdefault"  : label_url
		},
		"data[Menu][title]": {
			"required": true,
		},
		"data[Menu][Menuprice][price][0]": {
			'mynumber': "price0",
		},
		"data[Menu][venuename]": "required",
	};

/*	// validation messages
	//validationSettings.messages = {
	//	'data[Business][url]': {
	//		urlwithdefault: 'Only URL ex. http://goorme.com'
	//	}
	//}*/

	// validation submit handler
	validationSettings.submitHandler = function(form) {
			//removeWatermarkValue('#DishName', labeldish_title);
			//removeWatermarkValue('#DishTags', label_tag);
			//removeWatermarkValue('.advanceLabelGroup', label_price);

			//$("#mm_general_submit_button_dish").attr('disabled', 'disabled');
			//$(".disableOnUploadPhoto").attr('disabled', 'disabled');
			//$('.mm_errormessage').css('display', 'none');
			//if(business_id == '')
			//{
			//	$('.mm_formmessage').html('checking. please wait ...');
			//} else
			//{
			//	$('.mm_formmessage').html('processing ...');
			//}
			//$('.mm_formmessage').css('display', 'block');

			/*
			$(form).ajaxSubmit();

			$("#sitoes_business_suggestdish").parent().css('display', 'none');
			$("#sitoes_business_suggestarestaurant").parent().css('display', 'block');
			$("#mm_general_submit_button").removeAttr('disabled');
			$('.mm_formmessage').css('display', 'none');
			*/

			/*
			var business_id = $('#MenuBusinessId').val();

			if(business_id == '')
			{
				$(form).ajaxSubmit();

				$("#sitoes_business_suggestdish").parent().css('display', 'none');
				$("#sitoes_business_suggestarestaurant").parent().css('display', 'block');
				$("#mm_general_submit_button").removeAttr('disabled');
				$("#mm_general_submit_button_dish").removeAttr('disabled');
				$('.mm_formmessage').css('display', 'none');
			}
			else
			{

				$(form).ajaxSubmit({
					success: function(data) {

				//		$.nyroModalRemove();
				//		window.location = '/dish/' + data;
							var word = $("#DishName").val().replace(/[^a-zA-Z \d]+/g, "");

							word = urlencode(word);

							$.nyroModalManual({
							  url: "/semantics/suggesttag/" + word + "/dish",
							  endRemove: function() {
									window.location.reload();
								}
							});
					}
				});
			}
			*/
			$("#poibuilding").removeAttr("disabled");
			$("#txtcity").removeAttr("disabled");
			$("#menuPhotoUploader").css("visibility", "hidden");
			$("#businessUploadLogoInputUploader").css("visibility", "hidden");
			processModalSubmit("", ".loadElement");

				$(form).ajaxSubmit({
					success: function(data) {

/*						//console.log(data);

						//$.nyroModalRemove();
						//window.location = '/dish/' + data;

							//var word = $("#DishName").val().replace(/[^a-zA-Z \d]+/g, "");

							//word = urlencode(word);

							//$.nyroModalManual({
							 // url: "/semantics/suggesttag/" + word + "/dish",
							 // endRemove: function() {
							//		window.location.reload();
							//	}
							//});*/

							var out = jQuery.parseJSON(data);
							var word = $("#DishName").val().replace(/[^a-zA-Z \d]+/g, "");

							$.nyroModalManual({
							  url: "/semantics/suggesttag/" + 1 + "/" + out.tablekey_id + "/" + word + "/null/null/" + mode_dish,
							  endRemove: function() {
									window.location.reload();
								}
							});

					}
				});

			return false;
	};

	$('#sitoes_business_suggestdish').validate(validationSettings);

	/*
	$('#sitoes_business_suggestarestaurant').validate({
		errorClass: "mm_input_error",
		errorElement: "div",
		focusInvalid: false,
		highlight: function(element, errorClass, validClass) {
			$(element).addClass(errorClass);
		},
		onfocusout: false,
		onkeyup: false,
		onclick: false,
		showErrors: function(errorMap, errorList) {

			var errorCount = this.numberOfInvalids();
			if (errorCount == 1)
				var errorText = 'error';
			else
				var errorText = 'errors';

			if (errorCount > 0) {
				$('.mm_formmsg').css('display', 'none');
				$('.mm_errormessage').css('color', 'red');
				$('.mm_errormessage').html(errorCount + ' ' + errorText + '.');
				$('.mm_errormessage').css('display', 'block');
			}

			for (var i = 0; i < errorList.length; i++) {

				var elementId = $(errorList[i].element).attr('id');
				var message   = errorList[i].message;

				var errorElement = setErrorMessage(message);

				if (elementId.length) {
					$('#' + elementId).parent().find('.mm_input_error_container').remove();

					//if(elementId == 'restaurantPhoneNumber')
					//	var errorElement = setErrorMessageLower(message);

					$('#' + elementId).after(errorElement);
					$('#' + elementId).parent().addClass("mm_error");


				}
			}

			this.defaultShowErrors();
		},
		errorPlacement: function(error, element) {
			return true;
		},
		submitHandler: function(form) {

			$("#mm_general_submit_button").attr('disabled', 'disabled');
			$(".disableOnUploadPhoto").attr('disabled', 'disabled');

			$('.mm_errormessage').css('display', 'none');
			$('.mm_formmessage').html('checking. please wait ...');
			$('.mm_formmessage').css('display', 'block');

			//removeWatermarkValue('#restaurantName', labelvenue_title);
			//removeWatermarkValue('#poibuilding', global_wm_address_building);
			//removeWatermarkValue('#restaurantPhoneNumber', label_phone_number);
			//removeWatermarkValue('#restaurantUrl', label_url);
			//removeWatermarkValue('#restaurantTags', global_wm_venue_tag);

			$(form).ajaxSubmit({
				success: function(data) {

					/*
					var isClaiming = $("#chkClaim").attr('checked');

					if(isClaiming)
					{
						var savemenu = sv_savemenu;
						var objectData = jQuery.parseJSON(data);
						if(savemenu == 'y')
							directTo = '/dish/' + objectData.url_title;
						else
							directTo = '/' + objectData.url_title;


						$.nyroModalManual({
							url: '/businesses/claim/' + objectData.business_id,
							endRemove: function() {
								window.location = directTo;
							}
						});
					}

					else
					{
						$.nyroModalRemove();
						var savemenu = sv_savemenu;
						if(savemenu == 'y')
							window.location = '/dish/' + data;
						else
							window.location = '/' + data;
						$("#mm_general_submit_button").attr('disabled', 'disabled');
					}
					*/
					/*
					var word = $("#DishName").val();

					word = urlencode(word);

					$.nyroModalManual({
					  url: "/semantics/suggesttag/" + word + "/dish"
					});
				}
			});
		},
		unhighlight: function(element, errorClass, validClass) {
			$(element).removeClass(errorClass);
		},
		success: function(errorElement) {
			var htmlFor = $(errorElement).attr('htmlfor');
			$('#' + htmlFor).parent().find('.mm_input_error_container').remove();

				if(htmlFor != 'restaurantPhoneNumber' && htmlFor != 'restaurantUrl')
					$('#' + htmlFor).parent().addClass("mm_reqd");
				$('#' + htmlFor).parent().removeClass("mm_error");
		},
		rules: {
			"data[restaurant][name]": {
				"required": true,
				"nodefault": labelvenue_title
			},
			"data[restaurant][street_address]": "required",
			"data[restaurant][city]": "required",
			"data[restaurant][phone_number]": {
				'numberwithdefault': label_phone_number
			},
			"data[restaurant][businesstype_id]": "required",
			"data[restaurant][cuisine_id]": "required",
			"data[restaurant][website_address]": {
				'urlwithdefault': label_url
			}
		}
	});
	*/
}

function removePhotoMenuInit() {
	$('#removePhotoMenu').click(function() {
			var hiddenTag = '<img id="MenuPhotoS" class="mm_dev_image24" style="display:none"><input type="hidden" value="" name="data[dish][photo][]" id="MenuPhotoS">';
			var iconAfterUpload = '<img id="mm_hovered" src="/img/icon/cam_black.png" width="24px" height="24px" />';

			$('#menuPhotoContainer').html(hiddenTag + iconAfterUpload);

			$('#removePhotoMenu').css('display', 'none');
			$('#msgUpload').text('please upload only jpg, png, gif file');
	});
}

function removePhotoBusinessInit() {
	$('#removePhotoBusiness').click(function() {
		var hiddenTag = '<img id="business_hover_image" src="" class="mm_dev_image24" style="display:none"><input type="hidden" id="BusinessLogo" value="" name="data[restaurant][logo][]">';
		var iconAfterUpload = '<img id="mm_hovered2" src="/img/icon/cam_black.png" width="24px" height="24px" />';

		$('#businessUploadLogoData').html(hiddenTag + iconAfterUpload);

		$('#removePhotoBusiness').css('display', 'none');
		$('#msgUpload2').text('please upload only jpg, png, gif file');
	});
}

function autocompletePoi2Init(elementBuildingName, elementAddress1, elementAddress2, elementCity, elementPostalCode, elementSubmitter) {
	$(elementBuildingName).autocomplete(poiList, {
		formatItem: function(row, i, max) {
			var displayString = row.name;

			displayString = displayString + "<small>";

			if(row.address1 != null)
				displayString = displayString + row.address1;

			if(row.address1 != null && row.city != null)
				displayString = displayString + " ,";

			if(row.city != null)
				displayString = displayString + row.city;

			displayString = displayString + "</small>";

			return displayString;
		},
		formatResult: function(row) {
			return row.name;
		},
		width: width_buildingname,
		matchContains: true,
		highlight: false,
		formatMatch: function(row, i, max) {
			return row.name;
		},
	});

	$(elementBuildingName).result(function(event, data, formatted) {
		processModalSubmit("", ".loadElement");

		$.getJSON('/addresses/get_one/' + data.address_id + '/return:json', function(result) {
			autocompleteName = data.name;
			$(elementAddress1).val(result.Address.address1);
			$(elementAddress2).val(result.Address.address2);
			$(elementCity).val(result.Address.city);
			$(elementPostalCode).val(result.Address.postalcode);
			$(elementAddress1).attr("disabled", "disabled").addClass("mm_disabled");
			$(elementAddress2).attr("disabled", "disabled").addClass("mm_disabled");
			$(elementCity).attr("disabled", "disabled").addClass("mm_disabled");
			$(elementPostalCode).attr("disabled", "disabled").addClass("mm_disabled");

			//$('#sitoes_business_suggestarestaurant :disabled').parent().find('.mm_reqd').css('background-color', '#cccccc');

			completeModalSubmit(elementSubmitter);
		});

	});

	/*
	$("#poibuilding").keyup(function(e) {

		if(e.keyCode != 13 && e.keyCode != 9) {

			var temp =  jQuery.trim($(this).val());

			if(temp == "" ||  temp != autocompleteName)
			{
				$("#txtaddress1").val("").removeClass("mm_disabled");
				$("#txtaddress2").val("").removeClass("mm_disabled");
				$("#txtcity").val("").removeClass("mm_disabled");
				$("#txtpostalcode").val("").removeClass("mm_disabled");
				$("#txtaddress1").attr("disabled", false).removeClass("mm_disabled");
				$("#txtaddress2").attr("disabled", false).removeClass("mm_disabled");
				$("#txtcity").attr("disabled", false).removeClass("mm_disabled");
				$("#txtpostalcode").attr("disabled", false).removeClass("mm_disabled");
				$("#building_address").attr("disabled", false).removeClass("mm_disabled");
			}

		}
	});
	*/
	$('#poibuilding').blur(function() {
		var poiname = jQuery.trim($(this).val()).toLowerCase();

		if (poiname.length > 0) {
			var poi_address_id   = poi_name_address_id[poiname];



			if (poi_address_id != undefined && autocomplete_poi_flag == false) {
				//processModalSubmit();
				$.getJSON('/addresses/get_one/' + poi_address_id + '/return:json', function(result) {
					//autocompleteName = data.name;
					$("#txtaddress1").val(result.Address.address1);
					$("#txtaddress2").val(result.Address.address2);
					$("#txtcity").val(result.Address.city);
					$("#txtpostalcode").val(result.Address.postalcode);
					$("#txtaddress1").attr("disabled", true).addClass("mm_disabled");
					$("#txtaddress2").attr("disabled", true).addClass("mm_disabled");
					$("#txtcity").attr("disabled", true).addClass("mm_disabled");
					$("#txtpostalcode").attr("disabled", true).addClass("mm_disabled");

					$('#sitoes_business_suggestarestaurant :disabled').parent().find('.mm_reqd').css('background-color', '#cccccc');

					//completeModalSubmit();
				});
			}
		}
	});
}

function autocompleteRestaurantNameInit(elementVenue, elementPoi, elementAddress1, elementProvince, elementAddressCity, elementPostalCode, elementRemoveField, elementAddress2) {
	$(elementVenue).autocomplete(businessList, {
		formatItem: function(row, i, max) {
			var displayString = row.businessname;

			displayString = displayString + "<small>";

			if(row.address1 != null)
				displayString = displayString + row.address1;

			if(row.address1 != null && row.city != null)
				displayString = displayString + " ,";

			if(row.city != null)
				displayString = displayString + row.city;

			displayString = displayString + "</small>";

			return displayString;
		},
		formatResult: function(row) {
			return row.businessname;
		},
		width: width_businessname,
		matchContains: true,
		highlight: false,
		formatMatch: function(row, i, max) {
			return row.businessname;
		},
	});

	$(elementVenue).result(function(event, data, formatted) {

		autocomplete_business_flag = true;

		//processModalSubmit()

		autofillPoiResult(data.id);

		//$('#chkAddNewLocation').parent().css("display", "block");
		$('#chkAddNewLocation').removeAttr("disabled");
		$('#chkAddNewLocation').removeAttr('checked');
	//	$('#claimContainer').prependTo("#suggestdish_detail_container");
	});

	$(elementVenue).keyup(function(e) {

		if(e.keyCode != 13 && e.keyCode != 9) {

			if ($(this).val().length == 0 || $(this).val() != resultName) {
				clearPoiResult();

				//$('#chkAddNewLocation').parent().css("display", "none");
				$('#chkAddNewLocation').removeAttr('checked');
				$('#chkAddNewLocation').attr("disabled", "disabled");
				//$('#claimContainer').appendTo("#claimDefaultContainer");

				//$('.mm_disabled').removeClass("mm_disabled");
				$('.hideVenuePhoto').css('display', 'block');

				$('#chkClaim').parent().css('display', 'block');

				autocomplete_business_flag = false;
			}

		}
	});

	/*
	$('#restaurantName').blur(function() {
		var businessname = jQuery.trim($(this).val()).toLowerCase();

		if (businessname.length > 0) {
			var businessId   = business_name_id[businessname];

			if (businessId != undefined && autocomplete_business_flag == false) {

				autofillPoiResult(businessId);

				$('#chkAddNewLocation').removeAttr("disabled");
				$('#chkAddNewLocation').removeAttr('checked');
			}
		}
	});
	*/
}

function autocompleteCity2Init() {
	$('#txtcity').autocomplete(cityList, {
		formatItem: function(row, i, max) {
			return row.city + ": [" + row.province + "]";
		},
		formatResult: function(row) {
		//	$("AddressProvinceId").val(row.province_id);
			return row.city;
		},
		width: width_city,
		matchContains: true,
		highlight: false,
		formatMatch: function(row, i, max) {
			return row.city;
		},
	});
	$('#txtcity').result(function(event, data, formatted) {
		$('#AddressProvinceId').val(data.province_id);
	});

}

function detailLinkSuggestVenue2Init() {
	$(".moreTrigger").click(function() {
		$(".lessTrigger").css("display", "");
		$(".moreTrigger").css("display", "none");

		$(".isHidden").addClass("spesificElement");

		$('.mm_venue_input_spesific_container').toggle('fast');

		setTimeout("resizeModal('#mm_modalv3');", 500);

		return false;
	});

	$(".lessTrigger").click(function() {
		$(".lessTrigger").css("display", "none");
		$(".moreTrigger").css("display", "block");

		//$(".spesificElement").addClass("isHidden");
		//$('.isHidden').toggle('fast');
		$('.mm_venue_input_spesific_container').toggle('fast');
		$(".spesificElement").removeClass("spesificElement");

		setTimeout("resizeModal('#mm_modalv3');", 500);

		return false;
	});
}

function priceSuggestDishInit() {
	$('#basicTrigger').click(function() {

		$('#boxAdvance').css('display', 'none');
		$('#boxBasic').css('display', 'block');
		$('.advancePriceGroup').val("");
		$('.advanceLabelGroup').val(label_price);
		$('.advanceLabelGroup').addClass("gm_Watermark");
	});

	$('#advanceTrigger').click(function() {
		$('#boxBasic').css('display', 'none');
		$('#boxAdvance').css('display', 'block');
		$('.basicPriceGroup').val("");
	});

	$('.removeThisPriceLink').live('click', function() {
		$(this).parent().parent().remove();

		return false;
	});

	$('#priceAdvanceAddMore').click(function() {
		var priceHtml =	'<li class = "clearMargin"><input class="advanceLabelGroup priceLabel mm_textfield_70 alignLeft mm_space_5 gm_Watermark" value = "' + label_price + '"  name="data[Menuprice][label][' + priceIndex + ']" type="text" /><input id = "price' + priceIndex + '" class="advancePriceGroup mm_textfield_100_idr alignLeft mm_space_5" name="data[Menuprice][price][' + priceIndex + ']" type="text" /><span class = "alignLeft mm_paddingtop_3"><a class = "removeThisPriceLink" href = "javascript:void(0)"><img src="/img/trash2.gif"/></a></span><div class="clearFix"></div></li>';
		$(this).before(priceHtml);

		$(".priceLabel").click(function() {

			if($(this).val() == label_price)
			{
				$(this).val("");
				$(this).removeClass('gm_Watermark');
			}
			return false;
		});


		$(".priceLabel").blur(function() {

			if($(this).val() == "") {
				$(this).val(label_price);
				$(this).addClass('gm_Watermark');
			}

			return false;
		});

		$('#price' + priceIndex).rules('add', {'mynumber': "price" + priceIndex});

		priceIndex++;

		return false;
	});

	$(".priceLabel").click(function() {

		if($(this).val() == label_price)
		{
			$(this).val("");
			$(this).removeClass('gm_Watermark');
		}
		return false;
	});


	$(".priceLabel").blur(function() {

		if($(this).val() == "") {
			$(this).val(label_price);
			$(this).addClass('gm_Watermark');
		}

		return false;
	});
}

function checkboxNewLocationInit() {
	$('#chkAddNewLocation').result(function() {
		if ($('#chkAddNewLocation').attr('checked') == true) {
			$('#poibuilding').attr('disabled', false).removeClass("mm_disabled");
			$('#building_address').attr('disabled', false).removeClass("mm_disabled");
			$('#txtaddress1').attr('disabled', false).removeClass("mm_disabled");
			$('#txtaddress2').attr('disabled', false).removeClass("mm_disabled");
			$('#txtcity').attr('disabled', false).removeClass("mm_disabled");
			$('#txtpostalcode').attr('disabled', false).removeClass("mm_disabled");


			$('#poibuilding').val('');
			$('#building_address').val('');
			$('#txtaddress1').val('');
			$('#txtaddress2').val('');
			$('#txtcity').val('');
			$('#txtpostalcode').val('');
		}

		else if($('#chkAddNewLocation').attr('checked') == false)
		{
			var businessname = jQuery.trim($("#restaurantName").val()).toLowerCase();

			if (businessname.length > 0) {
				var businessId   = business_name_id[businessname];

				if (businessId != undefined) {
					autofillPoiResult(businessId);
				}
			}
		}
	});
}

function autofillPoiResult(data, elementVenue, elementPoi, elementAddress1, elementAddress2, elementAddress3, elementParentAddressId, elementProvince,
							elementCity, elementPostalCode, elementRemoveField, elementDescription, elementCuisine, elementCuisineId,
							classVenuetype, elementPhone, elementWeb, elementVenueId, elementUrlTitle, elementSubmitter) {

	//processModalSubmit();
		// disable
		/*
		$('#restaurantDescription').attr('disabled', true).addClass("mm_disabled");
		$('#restaurantCategory').attr('disabled', true);
		$('#restaurantSubcategory').attr('disabled', true);
		$('#poibuilding').attr('disabled', true).addClass("mm_disabled");
		$('#building_address').attr('disabled', true).addClass("mm_disabled");
		$('#txtaddress1').attr('disabled', true).addClass("mm_disabled");
		$('#txtaddress2').attr('disabled', true).addClass("mm_disabled");
		$('#txtcity').attr('disabled', true).addClass("mm_disabled");
		$('#txtpostalcode').attr('disabled', true).addClass("mm_disabled");
		$('#restaurantPhoneNumber').attr('disabled', true).addClass("mm_disabled");
		$('#restaurantUrl').attr('disabled', true).addClass("mm_disabled");
		$('#BusinessLogo').attr('disabled', true).addClass("mm_disabled");
		$('#txtRestaurant').attr('disabled', true).addClass("mm_disabled");
		*/

		var new_container = '<span class="mm_Iconset_14 doUnlock"><a class = "' + elementRemoveField + '" href="javascript:void(0)"><img width="16px" height="16px" src="/img/icon/clear.gif"></a></span>';
		$(elementVenue).after(new_container);

		$(elementDescription).attr('disabled', 'disabled');
		$(elementCuisine).attr('disabled', 'disabled');
		//$('#restaurantSubcategory').attr('disabled', 'disabled');
		$(elementPoi).attr('disabled', 'disabled');
		$(elementAddress3).attr('disabled', 'disabled');
		$(elementAddress1).attr('disabled', 'disabled');
		$(elementAddress2).attr('disabled', 'disabled');
		$(elementCity).attr('disabled', 'disabled');
		$(elementPostalCode).attr('disabled', 'disabled');
		$(elementPhone).attr('disabled', 'disabled');
		$(elementWeb).attr('disabled', 'disabled');
		//$('#BusinessLogo').attr('disabled', 'disabled');
		//$('#txtRestaurant').attr('disabled', 'disabled');
		$(elementSubmitter).attr("disabled", "disabled");
		$(elementVenue).attr("disabled", "disabled");

		var label_class = "isNormal";

		$(elementDescription).siblings("label." + label_class).removeClass("isFocus").addClass("isOff");
		$(elementCuisine).siblings("label." + label_class).removeClass("isFocus").addClass("isOff");
		//$('#restaurantSubcategory').attr('disabled', 'disabled');
		$(elementPoi).siblings("label." + label_class).removeClass("isFocus").addClass("isOff");
		$(elementAddress3).siblings("label." + label_class).removeClass("isFocus").addClass("isOff");
		$(elementAddress1).siblings("label." + label_class).removeClass("isFocus").addClass("isOff");
		$(elementAddress2).siblings("label." + label_class).removeClass("isFocus").addClass("isOff");
		$(elementCity).siblings("label." + label_class).removeClass("isFocus").addClass("isOff");
		$(elementProvince).siblings("label." + label_class).removeClass("isFocus").addClass("isOff");
		$(elementPostalCode).siblings("label." + label_class).removeClass("isFocus").addClass("isOff");
		$(elementPhone).siblings("label." + label_class).removeClass("isFocus").addClass("isOff");
		$(elementWeb).siblings("label." + label_class).removeClass("isFocus").addClass("isOff");
		//$('#BusinessLogo').attr('disabled', 'disabled');
		//$('#txtRestaurant').attr('disabled', 'disabled');
		$(elementVenue).siblings("label." + label_class).removeClass("isFocus").addClass("isOff");
		$("#otherVenueCategories").siblings("label." + label_class).removeClass("isFocus").addClass("isOff");

	$.getJSON('/businesses/get_one/' + data, function(result) {
		$(elementSubmitter).removeAttr("disabled");
		// for multiple action checking
		autocomplete_business_flag = true;

		resultName = result.businessname;

		result.small_logo = '';
		if (result.logo != null) {
			var temp_logo = result.logo.split('.');
			result.small_logo = temp_logo[0] + '_s.' + temp_logo[1];
		}

		$(elementDescription).val(result.description);
		//$('#restaurantSubcategory').val(result.sub_category);
		$(elementPoi).val(result.building_name);
		$(elementAddress3).val(result.building_address);
		$(elementAddress1).val(result.address_1);
		$(elementAddress2).val(result.address_2);
		$(elementCity).val(result.city);
		$(elementProvince).val(result.province);
		$(elementPostalCode).val(result.postal_code);
		$(elementPhone).val(result.phone_number);
		$(elementWeb).val(result.url);
		$(elementVenueId).val(result.id);
		$('#BusinessLogo').val(result.logo);
		//$('#locationNumber').html(result.location_number);
		$(elementVenue).val(result.businessname);
		$(elementCuisine).val(result.cuisine_name);


		var categories = result.sub_category;

		var other_categories = new Array();
		for(var i = 0 ; i < categories.length ; i++) {
			var category = categories[i];

			var found = 0;
			for(var j = 0; j < $(classVenuetype).length ; j++) {
				var temp = $(classVenuetype)[j];
				var value = temp.value;

				if(category.toLowerCase() == value.toLowerCase()) {
					$(temp).attr("checked", "checked");
					found = 1;
					break;
				}
			}
			if (!found)
				other_categories.push(category);
		}
		$(classVenuetype).attr("disabled", "disabled");
		$("#otherVenueCategories").val(other_categories.join(", ")).attr("disabled", "disabled");

		$(elementParentAddressId).val(result.parent_id);
		$(elementUrlTitle).val(result.url_title);
		$(elementCuisineId).val(result.category);
		$(elementVenueId).val(result.id);

		if (result.small_logo != null && result.small_logo != '')
		{
			$('#business_hover_image').attr('src', '/userfiles/businesslogo/' + result.small_logo);
		}
		else if (result.user_photo.length > 0)
		{
			$('#business_hover_image').attr('src', '/userfiles/photo/' + result.user_photo);
		}



		$('#restaurantLogoInputContainer').css('display', 'none');
		//$('.hideVenuePhoto').css('display', 'none');
		//resultData = result;

		// photo
		if (result.small_logo != null || result.user_photo.length > 0) {

				$('#mm_hovered2').attr('src', '/img/icon/clear.gif');
				//$('#mm_hovered2').attr('height', '16px');
				//$('#mm_hovered2').attr('width', '16px');

				//$('#removePhotoBusiness').css('display', 'none');
				$('#msgUpload2').text(msgAfterUploadPhoto);

				$('#mm_hovered2').parent().addClass("isOn");
				sitoes_hoverImage('mm_hovered2', 'business_hover_image');

			} else {

				$('#msgUpload2').css('display', 'none');
			}

/*		//$('.mm_formmsg').css('display', 'none');

		//if (result.owned) {
		//	$('#chkClaim').parent().css('display', 'none');
		//}

		// change required indicator
		//$('#sitoes_business_suggestarestaurant :disabled').parent().find('.mm_reqd').css('background-color', '#cccccc');

		//$('#locationFound').removeClass("isHidden");
		//$('#locationBegin').addClass("isHidden");
		//$('#locationAdding').addClass("isHidden");*/

		completeModalSubmit();

	});
}

function manageVenueLocation()
{
	$("#addNewLoc").click(function() {
		$("#chkAddNewLocation").attr('checked', 'checked');
		$('#locationFound').addClass("isHidden");
		$('#locationAdding').removeClass("isHidden");
		$('#locationBegin').addClass("isHidden");

		$('#poibuilding').attr('disabled', false).removeClass("mm_disabled");
		$('#building_address').attr('disabled', false).removeClass("mm_disabled");
		$('#txtaddress1').attr('disabled', false).removeClass("mm_disabled");
		$('#txtaddress2').attr('disabled', false).removeClass("mm_disabled");
		$('#txtcity').attr('disabled', false).removeClass("mm_disabled");
		$('#txtpostalcode').attr('disabled', false).removeClass("mm_disabled");
		$('#restaurantPhoneNumber').attr('disabled', false).removeClass("mm_disabled")
		$('#restaurantPhoneNumber').addClass("mm_watermark");

		$('#poibuilding').val('');
		$('#building_address').val('');
		$('#txtaddress1').val('');
		$('#txtaddress2').val('');
		$('#txtcity').val('');
		$('#txtpostalcode').val('');
		$('#restaurantPhoneNumber').val(label_phone_number);

		return false;
	});

	$("#cancelNewLoc").click(function() {
		$("#chkAddNewLocation").removeAttr('checked');
		$('#locationFound').removeClass("isHidden");
		$('#locationAdding').addClass("isHidden");
		$('#locationBegin').addClass("isHidden");

			var businessname = jQuery.trim($("#restaurantName").val()).toLowerCase();

			if (businessname.length > 0) {
				var businessId   = business_name_id[businessname];

				if (businessId != undefined) {
					autofillPoiResult(businessId);
				}
			}

		return false;
	});
}

function clearPoiResult(elementPoi, elementAddress1, elementAddress2, elementAddress3, elementParentAddressId, elementProvince,
							elementCity, elementPostalCode, elementDescription, elementCuisine, elementCuisineId,
							elementPhone, elementWeb, elementVenueId, elementUrlTitle) {
	/*
	$('#restaurantDescription').attr('disabled', false);
	$('#restaurantCategory').attr('disabled', false);
	$('#restaurantSubcategory').attr('disabled', false);
	$('#poibuilding').attr('disabled', false);
	$('#building_address').attr('disabled', false);
	$('#txtaddress1').attr('disabled', false);
	$('#txtaddress2').attr('disabled', false);
	$('#txtcity').attr('disabled', false);
	$('#txtpostalcode').attr('disabled', false);
	$('#restaurantPhoneNumber').attr('disabled', false);
	$('#restaurantUrl').attr('disabled', false);
	$('#BusinessLogo').attr('disabled', false);

	$('#restaurantLogoInputContainer').css('display', 'block');

	$('#restaurantDescription').val('').removeClass("mm_disabled");
	$('#restaurantCategory').val('');
	$('#restaurantSubcategory').val('');
	$('#poibuilding').val('').removeClass("mm_disabled");
	$('#building_address').val('').removeClass("mm_disabled");
	$('#txtaddress1').val('').removeClass("mm_disabled");
	$('#txtaddress2').val('').removeClass("mm_disabled");
	$('#txtcity').val('').removeClass("mm_disabled");
	$('#txtpostalcode').val('').removeClass("mm_disabled");
	$('#restaurantPhoneNumber').val(label_phone_number).removeClass("mm_disabled");
	$('#restaurantUrl').val(label_url).removeClass("mm_disabled");
	$('#restaurantId').val('');
	$('#restaurantParentId').val('');
	$('#BusinessLogo').val('');
	$('#restaurantUrlTitle').val('');

	$('#restaurantLogoImage').attr('src', '');

	$('#business_hover_image').attr("src", '');
	$('#mm_hovered2').attr('src', '/img/icon/cam_black.png');
	$('#removePhotoBusiness').css('display', 'none');
	$('#msgUpload2').text('please upload only jpg, png, gif file');

	$('#mm_hovered2').unbind('mouseenter mouseleave');

	$('#locationFound').addClass("isHidden");
	$('#locationBegin').removeClass("isHidden");
	*/
		//console.log("aaa");
		$(elementPoi).removeAttr('disabled').val("");
		$(elementAddress1).removeAttr('disabled').val("");
		$(elementAddress2).removeAttr('disabled').val("");
		$(elementAddress3).removeAttr('disabled').val("");
		$(elementProvince).val("");
		$(elementCity).removeAttr('disabled').val("");
		$(elementPostalCode).removeAttr('disabled').val("");
		$(elementPhone).removeAttr('disabled').val("");
		$(elementWeb).removeAttr('disabled').val("");
		$(elementDescription).removeAttr('disabled').val("");
		$(elementCuisine).removeAttr('disabled').val("");

		$(elementParentAddressId).val("");
		$(elementUrlTitle).val("");
		$(elementVenueId).val("");
		$(elementCuisineId).val("");
		$('#BusinessLogo').val('');
		$('#business_hover_image').attr("src", '');
		$('#mm_hovered2').unbind('mouseenter mouseleave');
		$('#restaurantLogoImage').attr('src', '');

		var label_class = "isNormal";

		$(elementPoi).siblings("label." + label_class).removeClass("isOff");
		$(elementAddress1).siblings("label." + label_class).removeClass("isOff");
		$(elementAddress2).siblings("label." + label_class).removeClass("isOff");
		$(elementAddress3).siblings("label." + label_class).removeClass("isOff");
		$(elementProvince).siblings("label." + label_class).removeClass("isOff");
		$(elementCity).siblings("label." + label_class).removeClass("isOff");
		$(elementPostalCode).siblings("label." + label_class).removeClass("isOff");
		$(elementPhone).siblings("label." + label_class).removeClass("isOff");
		$(elementWeb).siblings("label." + label_class).removeClass("isOff");
		$(elementDescription).siblings("label." + label_class).removeClass("isOff");
		$(elementCuisine).siblings("label." + label_class).removeClass("isOff");
}

function autocompleteAtVenue(elementAtVenue, elementBusinessId, elementJustSubmit, elementDetectNewVenue, elementRemoveField)
{
	//var hasPickResult = false;

// Handle data from ajax request
	 prep_data = function(data){

		   tmp = $.evalJSON(data);
		   parsed_data = [];
		   if(tmp == null)
		   {
				var array = new Array();
				return array;
		   }
		   else
		   {
			   for (i=0; i < tmp.length; i++) {
				 obj = tmp[i];
				 // Other internal autocomplete operations expect
				 // the data to be split into associative arrays of this sort
				 parsed_data[i] = {
					data: obj ,
					value: obj.isbn13,
					result: obj.title
				 };
			   }
			   return parsed_data
			}
	 }



	$(elementAtVenue).autocomplete("/businesses/get_business_list", {
		formatItem: function(row, i, max) {
			var displayString = row.businessname;

			if(row.name == null)
			{
				if(row.address1 != null || row.city != null)
				{
					displayString = displayString + "<br><em>";

					if(row.address1 != null)
						displayString = displayString + row.address1;

					if(row.address1 != null && row.city != null)
						displayString = displayString + ", ";

					if(row.city != null)
						displayString = displayString + row.city;

					displayString = displayString + "</em>";
				}
			}
			else
			{
				if(row.name != null || row.address3 != null || row.city != null)
				{
					displayString = displayString + "<br><em>";

					if(row.name != null)
						displayString = displayString + row.name;

					if(row.name != null && row.address3 != null)
						displayString = displayString + ", ";

					if(row.address3 != null)
						displayString = displayString + row.address3;

					if((row.name != null || row.address3 != null) && row.city != null)
						displayString = displayString + ", ";

					if(row.city != null)
						displayString = displayString + row.city;

					displayString = displayString + "</em>";
				}
			}

			return displayString;
		},
		formatResult: function(row) {
			return row.businessname;
		},
		width: width_at_venue,
		matchContains: true,
		highlight: false,
		formatMatch: function(row, i, max) {
			return row.businessname;
		},
		parse:prep_data
	});


	$(elementAtVenue).result(function(event, data, formatted) {
		$(elementJustSubmit).removeClass("isHidden");
		$(elementDetectNewVenue).addClass("isHidden");
		$(elementAtVenue).val(data.businessname);
		$(elementBusinessId).val(data.id);
		$(elementAtVenue).attr("disabled", "disabled");

		var new_container = '<span class="mm_Iconset_14 doUnlock"><a class = "' + elementRemoveField + '" href="javascript:void(0)"><img width="16px" height="16px" src="/img/icon/clear.gif"></a></span>';
		$(elementAtVenue).after(new_container);

		//hasPickResult = true;
	});

	$(elementAtVenue).keyup(function(e) {
		if(e.keyCode != 13 && e.keyCode != 9) {
			if($(elementDetectNewVenue).hasClass("isHidden"))
			{
				$(elementJustSubmit).addClass("isHidden");
				$(elementDetectNewVenue).removeClass("isHidden");
			}
		}
	});

	/*
	$(elementAtVenue).focus(function() {
		hasPickResult = false;
	});

	$(elementAtVenue).blur(function() {
		if (hasPickResult == true)
		{
			$(elementJustSubmit).removeClass("isHidden");
			$(elementDetectNewVenue).addClass("isHidden");
		}

		else
		{
			$(elementJustSubmit).addClass("isHidden");
			$(elementDetectNewVenue).removeClass("isHidden");
		}
	});
	*/

	$("." + elementRemoveField).live('click', function() {
		var container = $(this);
		container.parent().remove();

		$(elementAtVenue).removeAttr("disabled").val("");
		$(elementBusinessId).val("");
	});

}

function dishStepValidator(elementSubmitter, elementForm, elementTitle, elementVenue, elementPrice, elementDishContainer, elementVenueContainer, elementBack)
{
	$(elementSubmitter).click(function() {

		var isTitleValid = $(elementForm).validate().element(elementTitle);
		var isVenueValid = $(elementForm).validate().element(elementVenue);
		var isPriceValid = $(elementForm).validate().element(elementPrice);


		if(isTitleValid && isVenueValid && (isPriceValid == undefined || isPriceValid == true))
		{
			$(elementDishContainer).addClass("isHidden");
			$(elementVenueContainer).removeClass("isHidden");


			$("#restaurantName").val($("#txt_at_venue").val());
			$("#restaurantName").siblings("label").addClass("isOff");
			$(elementForm).find(".whole_msg").addClass("isHidden");
		}

		else
		{
			$("#added_whole_msg").html("missing required fields");
			$(elementForm).find(".whole_msg").removeClass("isHidden");
		}

		return false;
	});

	$(elementBack).click(function() {
		$(elementDishContainer).removeClass("isHidden");
		$(elementVenueContainer).addClass("isHidden");

		return false;
	});
}

/* ************************************************************************** */

/* TIP */
function suggestTipInit() {
	focusBlurBehaviour("#txt_at_venue", "#sitoes_business_addtip", "isNormal");
	focusBlurBehaviour("#DishName", "#sitoes_business_addtip", "isNormal");
	focusBlurBehaviour("#MenuPrice", "#sitoes_business_addtip", "isNormal");
	focusBlurBehaviour("#MenuIngredient", "#sitoes_business_addtip", "isNormal");
	focusBlurBehaviour("#MenuCuisine", "#sitoes_business_addtip", "isNormal");
	focusBlurBehaviour("#MenuType", "#sitoes_business_addtip", "isNormal");
	focusBlurBehaviour("#ReviewContent", "#sitoes_business_addtip", "isNormal");

//	sitoes_hoverImage('menu_hover_image', 0, -24);

	// check flash version
	if (checkFlashVersion() > 0)
	{
		// uploadify for dish photo
		uploadifyMenuPhotoInit();
	}
	// upload without flash
	else
	{
		var options = {
			containerId : '#menuPhotoContainer',
			inputId     : 'MenuPhotoS',
			inputName   : 'data[Menu][photo][]',
			imageId     : 'menu_hover_image',
			uploadPath  : '/photos/ajax_upload/photo/menu',
			messageId   : 'msgUpload',
			removeLinkId: 'removePhotoMenu',
			hoveredId   : 'mm_hovered'
		};
		ajaxUploadInit(options);
	}

	validationSuggestTipInit();

	autocompleteAtVenue2("#txt_at_venue", "#MenuBusinessId", "#mm_addtip", "#mm_suggestvenue", "removeAtVenue", "removeDish");
	autocompleteDishAtVenue("#DishName", "#MenuId", "#MenuBusinessId", "removeDish");

	$("#backToDishStep").click(function() {
		$("#mm_addtip").removeClass("isHidden");
		$("#mm_suggestvenue").addClass("isHidden");
		return false;
	});
}

function validationSuggestTipInit() {
	// form validation
// START validation for tip suggest
	var validationSettings  = sitoesModalv4ValidationSettings;

	// validation rules
	validationSettings.rules = {
		"data[Menu][venuename]": {
			"requiredId": "MenuBusinessId"
		},
		"data[Menu][title]": "required",
		"data[Menu][Menuprice][price]": {
			'mynumber': "MenuPrice",
		},
		"data[Review][dish_score]": "required"
	};

	// validation submit handler
	validationSettings.submitHandler = function(form) {
		$("#menuPhotoUploader").css("visibility", "hidden");
		processModalSubmit("", ".loadElement");

		$(form).ajaxSubmit({
			success: function(data) {
				url_redir = '/dish/' + data;
				$("#mm_addtip").addClass("isHidden");
				completeModalSubmit("", ".loadElement");
				$("#mm_ratevenue").removeClass("isHidden");
				$.nyroModalSettings ({
					width: $("#mm_ratevenue #mm_Modal_v4").width() + 28,
					height: $("#mm_ratevenue #mm_Modal_v4").height() + 28
				});

				$("#sitoes_rate_venue").attr("action", "/reviews/add/2/" + $("#MenuBusinessId").val());
			}
		});

		return false;
	};

	$('#sitoes_business_addtip').validate(validationSettings);
}

function autocompleteAtVenue2(elementAtVenue, elementBusinessId, elementDivCaller, elementDivVenue, elementRemoveField, elementRemoveFieldDish) {
// Handle data from ajax request
	prep_data = function(data){

		tmp = $.evalJSON(data);
		parsed_data = [];
		if(tmp == null)
		{
			var array = new Array();
			return array;
		}
		else
		{
			for (i=0; i < tmp.length; i++) {
				obj = tmp[i];
				// Other internal autocomplete operations expect
				// the data to be split into associative arrays of this sort
				parsed_data[i] = {
					data: obj ,
					value: obj.isbn13,
					result: obj.title
				};
			}
			return parsed_data;
		}
	}

	$(elementAtVenue).autocomplete("/businesses/get_business_list", {
		formatItem: function(row, i, max) {
			var displayString = row.businessname;

			if(row.name == null)
			{
				if(row.address1 != null || row.city != null)
				{
					displayString = displayString + "<br><em>";

					if(row.address1 != null)
						displayString = displayString + row.address1;

					if(row.address1 != null && row.city != null)
						displayString = displayString + ", ";

					if(row.city != null)
						displayString = displayString + row.city;

					displayString = displayString + "</em>";
				}
			}
			else
			{
				if(row.name != null || row.address3 != null || row.city != null)
				{
					displayString = displayString + "<br><em>";

					if(row.name != null)
						displayString = displayString + row.name;

					if(row.name != null && row.address3 != null)
						displayString = displayString + ", ";

					if(row.address3 != null)
						displayString = displayString + row.address3;

					if((row.name != null || row.address3 != null) && row.city != null)
						displayString = displayString + ", ";

					if(row.city != null)
						displayString = displayString + row.city;

					displayString = displayString + "</em>";
				}
			}

			return displayString;
		},
		formatResult: function(row) {
			return row.businessname;
		},
		width: width_at_venue2,
		matchContains: true,
		highlight: false,
		formatMatch: function(row, i, max) {
			return row.businessname;
		},
		parse:prep_data,
		resultsId: "autoVenue",
		emptyShow: true,
		extraInit: function() {
			// this is extra function for use when autocomplete form is generated
			addVenueToAutocomplete(elementDivCaller, elementDivVenue);
		},
		extraFunctionDisplay: function() {
			// this is extra function for use when autocomplete is displayed
		},
		extraFunctionHide: function() {
			// this is extra function for use when autocomplete is hid
		}
	});

	$(elementAtVenue).result(function(event, data, formatted) {
		$(elementAtVenue).val(data.businessname);
		$(elementBusinessId).val(data.id);
		$(elementAtVenue).attr("disabled", "disabled");

		var new_container = '<span class="mm_Iconset_14 doUnlock"><a class = "' + elementRemoveField + '" href="javascript:void(0)"><img width="16px" height="16px" src="/img/icon/clear.gif"></a></span>';
		$(elementAtVenue).after(new_container);
	});

	$(elementAtVenue).focus(function() {
		if ($(this).val().length >= 2)
			$("#autoVenue").css({"top": ($("#txt_at_venue").offset().top + $("#txt_at_venue").attr("offsetHeight")), "left": ($("#txt_at_venue").offset().left)}).show();
	});

	$(elementAtVenue).blur(function() {
		if ($(this).val() >= 2)
			$("#autoVenue").hide();
	});

	$("." + elementRemoveField).live('click', function() {
		var container = $(this);
		container.parent().remove();

		$(elementAtVenue).removeAttr("disabled").val("");
		$(elementBusinessId).val("");
		$(elementAtVenue).siblings("span.element_error").removeClass("isGood isError");
		$(elementAtVenue).siblings("label.isNormal").removeClass("isOff");

		if ($("." + elementRemoveFieldDish).length) {
			enableMenuDetailTip();
			$("." + elementRemoveFieldDish).click();
		}
	});
}

function autocompleteDishAtVenue(elementDishName, elementMenuId, elementBusinessId, elementRemoveField) {
// Handle data from ajax request
	prep_data = function(data){
		tmp = $.evalJSON(data);

		parsed_data = [];
		if(tmp == null)
		{
			var array = new Array();
			return array;
		}
		else
		{
			for (i=0; i < tmp.length; i++) {
				obj = tmp[i];
				// Other internal autocomplete operations expect
				// the data to be split into associative arrays of this sort
				parsed_data[i] = {
					data: obj ,
					value: obj.id,
					result: obj.title
				};
			}
			return parsed_data;
		}
	}

	$(elementDishName).autocomplete("/businesses/get_menu_list", {
		formatItem: function(row, i, max) {
			return row.title;
		},
		formatResult: function(row) {
			return row.title;
		},
		width: width_at_venue2,
		matchContains: true,
		highlight: false,
		formatMatch: function(row, i, max) {
			return row.title;
		},
		parse:prep_data,
		extraParams: {
			bid: function() {
				return $(elementBusinessId).val();
			}
		}
	});


	$(elementDishName).result(function(event, data, formatted) {
		$(elementDishName).val(data.title);
		$(elementMenuId).val(data.id);
		$(elementDishName).attr("disabled", "disabled");

		var new_container = '<span class="mm_Iconset_14 doUnlock"><a class = "' + elementRemoveField + '" href="javascript:void(0)"><img width="16px" height="16px" src="/img/icon/clear.gif"></a></span>';
		$(elementDishName).after(new_container);

		disableMenuDetailTip();
	});

	$("." + elementRemoveField).live('click', function() {
		var container = $(this);
		container.parent().remove();

		$(elementDishName).removeAttr("disabled").val("");
		$(elementMenuId).val("");
		$(elementDishName).siblings(".element_error").removeClass("isGood isError");

		enableMenuDetailTip();
	});
}

function disableMenuDetailTip () {
	$("#DishHalal").attr("disabled", "disabled").val("");
	$("#DishVegetarian").attr("disabled", "disabled").val("");
	$("#DishSpicy").attr("disabled", "disabled").val("");
	$("#MenuPrice").attr("disabled", "disabled").val("");
	$("#MenuIngredient").attr("disabled", "disabled").val("");
	$("#MenuCuisine").attr("disabled", "disabled").val("");
	$("#MenuType").attr("disabled", "disabled").val("");
}

function enableMenuDetailTip () {
	$("#DishHalal").removeAttr("disabled").val("");
	$("#DishVegetarian").removeAttr("disabled").val("");
	$("#DishSpicy").removeAttr("disabled").val("");
	$("#MenuPrice").removeAttr("disabled").val("");
	$("#MenuIngredient").removeAttr("disabled").val("");
	$("#MenuCuisine").removeAttr("disabled").val("");
	$("#MenuType").removeAttr("disabled").val("");
}

function addVenueToAutocomplete(elementDivCaller, elementDivVenue) {
	if (!$("#AddVenueAuto").length) {
		$("#autoVenue").append('<span class="isGreen isLastRow"><a id="AddVenueAuto" style="cursor: pointer">Add New Business</a></span>');
		$("#AddVenueAuto").live("click", function() {
			$(elementDivCaller).addClass("isHidden");
			$(elementDivVenue).removeClass("isHidden");
			$(".venue_step1").removeClass("isHidden");
			$(".venue_step2").addClass("isHidden");

			$("#restaurantName").val($("#txt_at_venue").val());
			$("#restaurantName").siblings("label").addClass("isOff");
			$("#sitoes_business_addtip").find(".whole_msg").addClass("isHidden");
		});
	}
}

/* VENUE RATE */
function venueRateInit() {
	focusBlurBehaviour("#VenueReviewContent", "#sitoes_rate_venue", "isNormal");

	validationVenueRateInit();

	$("#VenueRateSubmit").click(function() {
		$("#sitoes_rate_venue").submit();
		return false;
	});

	$("#VenueRateClose").click(function() {
		$.nyroModalRemove();
		window.location = url_redir;
		return false;
	});
}

function validationVenueRateInit() {
// START validation for venue rate
	var validationSettings  = sitoesModalv4ValidationSettings;

	// validation rules
	validationSettings.rules = {
		"data[Review][overall_rating]": "required"
	};

	// validation submit handler
	validationSettings.submitHandler = function(form) {

		processModalSubmit("", ".loadElement");

		$(form).ajaxSubmit({
			success: function(data) {
				$.nyroModalRemove();
				window.location = url_redir;
			}
		});

		return false;
	};

	$('#sitoes_rate_venue').validate(validationSettings);
}

/* ************************************************************************** */

/* VENUE */
function suggestVenueInit(formType) {

/*	//if (jQuery.trim($('#restaurantName').val()).length == 0) {
	//	$('#restaurantName').val(labelvenue_title).addClass('mm_watermark');
	//}

	//if (jQuery.trim($('#poibuilding').val()).length == 0) {
	//	$('#poibuilding').val(global_wm_address_building).addClass('mm_watermark');
	//}

	//$('#restaurantName').val(global_wm_venue_title);
	//$('#restaurantPhoneNumber').val(global_wm_address_phone);
	//$('#restaurantUrl').val(global_wm_website);
	//$('#restaurantTags').val(global_wm_venue_tag);

	//focusBlurDefault('#restaurantName', labelvenue_title, 'mm_watermark');
	//focusBlurDefault('#poibuilding', global_wm_address_building, 'mm_watermark');

	//uploadifyBusinessLogo2Init();*/
	// check flash version

	if (checkFlashVersion() > 0)
	{
		// uploadify for venue photo
		uploadifyBusinessLogo2Init();
	}
	// upload without flash
	else
	{
		var options = {
			containerId : '#businessUploadLogoData',
			inputId     : 'businessUploadLogoInput',
			inputName   : 'data[restaurant][logo][]',
			imageId     : 'business_hover_image',
			uploadPath  : '/photos/ajax_upload/photo/business',
			messageId   : 'msgUpload2',
			removeLinkId: 'removePhotoBusiness',
			hoveredId   : 'mm_hovered2'
		};
		ajaxUploadInit(options);
	}


	if(caller == 'tip')
		validationSuggestVenueTipInit("#venueSubmitter", "#poibuilding", "#txtcity", ".venue_step2", "#mm_suggestvenue", "#mm_addtip", "#txt_at_venue", "#MenuBusinessId", "#restaurantName", "removeAtVenue");
	else if(caller != 'dish')
		validationSuggestVenueInit("#venueSubmitter", "#poibuilding", "#txtcity", ".venue_step2");


	//if(formType != 'edit')
		autocompleteRestaurantName2Init("#restaurantName", "#poibuilding", "#txtaddress1", "#txtaddress2", "#building_address", "#restaurantParentId", "#txtProvince",
							"#txtcity", "#txtpostalcode", "remove_this_business_detail", "#txtDescription", "#restaurantCategory", "#restaurantCuisineId",
							".venue_categories", "#restaurantPhoneNumber", "#restaurantUrl", "#restaurantId", "#restaurantUrlTitle", "#restaurantTags", "#formSubmitter");
	//else
	//	autocompleteRestaurantNameEditInit();

	//autocompletePoi2Init();
	autocompleteBuildingNameInit("#poibuilding", "#txtaddress1", "#txtProvince", "#txtcity", "#txtpostalcode", "unlock_txt_poi_venue", "#txtaddress2");

	//console.log("aaa");

	autocompleteCityInit("#txtcity", "#AddressProvinceId" ,"#txtProvince");

//	autocompleteCuisineInit("#restaurantCategory", "#restaurantCuisineId");

	changePhoneNumberInit();

	$('.mynyroModal').nyroModal();

	//detailLinkSuggestVenue2Init();

//	checkboxNewLocationInit();

//	removePhotoBusinessInit();

	//focusBlurDefault('#restaurantPhoneNumber', label_phone_number, 'mm_watermark');
	//focusBlurDefault('#restaurantUrl', label_url, 'mm_watermark');
	//focusBlurDefault('#restaurantTags', global_wm_venue_tag, 'mm_watermark');

	//manageVenueLocation();

	venueStep1Validator(".venueStep1Validator", "#venueSubmitter", "#" + form_name, ".venue_step1", ".venue_step2", "#restaurantName", "#txtaddress1", "#txtcity", ".venue_categories");
}

function validationSuggestVenueInit(elementSubmitter, elementPoi, elementCity, elementStep2) {

	label_phone_number = "dummy";
	label_url = "dummy";

	// START validation for venue suggest
	var validationSettings  = sitoesModalv4ValidationSettings;

	// validation rules
	validationSettings.rules = {
		"data[restaurant][name]": {
			"required": true,
		},
		"data[restaurant][street_address]": "required",
		"data[restaurant][city]": "required",
		"data[restaurant][phone_number]": {
			"numberwithdefault"  : label_phone_number
		},
		"data[restaurant][cuisine]": "required",
		"data[restaurant][website_address]": {
			"urlwithdefault"  : label_url
		}
	};

/*	// validation messages
	//validationSettings.messages = {
	//	'data[Business][url]': {
	//		urlwithdefault: 'Only URL ex. http://goorme.com'
	//	}
	//}*/


	// validation submit handler
	validationSettings.submitHandler = function(form) {
/*			//$('#formSubmitter').attr('disabled', 'disabled');
			//$('.mm_errormessage').css('display', 'none');
			//$('.mm_formmessage').html('processing...');
			//$('.mm_formmessage').css('display', 'block');

			//var val_phone 	= $("#restaurantPhoneNumber").val().toLowerCase();
			//var val_url 	= $("#restaurantUrl").val().toLowerCase();


			//if(label_phone_number.toLowerCase() == val_phone)
			//	$('#restaurantPhoneNumber').val('');
			//if(label_url.toLowerCase() == val_url)
			//	$('#restaurantUrl').val('');

			//if ($('#restaurantTags').length > 0) {
			//	var val_alias 	= $("#restaurantTags").val().toLowerCase();
			//	if(label_venue_tag.toLowerCase() == val_alias)
			//		$('#restaurantTags').val('');
			//}

			//removeWatermarkValue('#restaurantTags', label_venue_tag);
			//removeWatermarkValue('#restaurantPhoneNumber', label_phone_number);
			//removeWatermarkValue('#restaurantUrl', label_url);
			//removeWatermarkValue('#poibuilding', global_wm_address_building);*/

			$(elementCity).removeAttr("disabled");
			$(elementPoi).removeAttr("disabled");
			$(elementStep2).addClass("isHidden");
			$("#businessUploadLogoInputUploader").css("visibility", "hidden");
			processModalSubmit("", ".loadElement");

			$(form).ajaxSubmit({
				success: function(data) {

					var isClaiming = $("#chkClaim").attr('checked') || ($('#ownerClaim').val() == 1);

					if(isClaiming)
					{
						var savemenu = sv_savemenu;
						var objectData = jQuery.parseJSON(data);

						var directTo = '';

						if (objectData.form_type == 'add') {
							directTo = sitoesdomain + '/dashboard/' + objectData.url_title;

						} else {

							if(savemenu == 'y')
								directTo = '/dish/' + objectData.url_title;
							else
								directTo = '/' + objectData.url_title;

						}

						$.nyroModalManual({
							url: '/businesses/claim/' + objectData.business_id,
							endRemove: function() {
								window.location = directTo;
							}
						});
					}

					else
					{
						$.nyroModalRemove();

						if(data != 'none')
						{
							var savemenu = sv_savemenu;
							if(savemenu == 'y')
								window.location = '/dish/' + data;
							else
								window.location = '/' + data;

						}

						else
						{
							completeModalSubmit(elementSubmitter);
							$(elementStep2).removeClass("isHidden");
						}
					}
				}
			});

			return false;
	};



	$('#sitoes_business_suggestarestaurant').validate(validationSettings);

	// form validation
	/*
	$('#sitoes_business_suggestarestaurant').validate({
		errorClass: "mm_input_error",
		errorElement: "div",
		focusInvalid: false,
		highlight: function(element, errorClass, validClass) {
			$(element).addClass(errorClass);
		},
		onfocusout: false,
		onkeyup: false,
		onclick: false,
		showErrors: function(errorMap, errorList) {

			var errorCount = this.numberOfInvalids();
			if (errorCount == 1)
				var errorText = 'error';
			else
				var errorText = 'errors';

			if (errorCount > 0) {
				$('.mm_formmsg').css('display', 'none');
				$('.mm_errormessage').css('color', 'red');
				$('.mm_errormessage').html(errorCount + ' ' + errorText + '.');
				$('.mm_errormessage').css('display', 'block');
			}

			for (var i = 0; i < errorList.length; i++) {

				var elementId = $(errorList[i].element).attr('id');
				var message   = errorList[i].message;

				var errorElement = setErrorMessage(message);

				if (elementId.length) {
					$('#' + elementId).parent().find('.mm_input_error_container').remove();

					//if(elementId == 'restaurantPhoneNumber')
					//	var errorElement = setErrorMessageLower(message);

					$('#' + elementId).after(errorElement);

					$('#' + elementId).parent().addClass("mm_error");
					//$('#' + elementId).parent().removeClass("mm_required");
				}
			}

			this.defaultShowErrors();
		},
		errorPlacement: function(error, element) {
			return true;
		},
		submitHandler: function(form) {

			$('#formSubmitter').attr('disabled', 'disabled');
			$('.mm_errormessage').css('display', 'none');
			$('.mm_formmessage').html('processing...');
			$('.mm_formmessage').css('display', 'block');

			var val_phone 	= $("#restaurantPhoneNumber").val().toLowerCase();
			var val_url 	= $("#restaurantUrl").val().toLowerCase();


			if(label_phone_number.toLowerCase() == val_phone)
				$('#restaurantPhoneNumber').val('');
			if(label_url.toLowerCase() == val_url)
				$('#restaurantUrl').val('');

			if ($('#restaurantTags').length > 0) {
				var val_alias 	= $("#restaurantTags").val().toLowerCase();
				if(label_venue_tag.toLowerCase() == val_alias)
					$('#restaurantTags').val('');
			}

			//removeWatermarkValue('#restaurantTags', label_venue_tag);
			//removeWatermarkValue('#restaurantPhoneNumber', label_phone_number);
			//removeWatermarkValue('#restaurantUrl', label_url);
			//removeWatermarkValue('#poibuilding', global_wm_address_building);

			$(form).ajaxSubmit({
				success: function(data) {

					var isClaiming = $("#chkClaim").attr('checked') || ($('#ownerClaim').val() == 1);

					if(isClaiming)
					{
						var savemenu = sv_savemenu;
						var objectData = jQuery.parseJSON(data);

						var directTo = '';

						if (objectData.form_type == 'add') {
							directTo = sitoesdomain + '/dashboard/' + objectData.url_title;

						} else {

							if(savemenu == 'y')
								directTo = '/dish/' + objectData.url_title;
							else
								directTo = '/' + objectData.url_title;

						}

						$.nyroModalManual({
							url: '/businesses/claim/' + objectData.business_id,
							endRemove: function() {
								window.location = directTo;
							}
						});
					}

					else
					{
						$.nyroModalRemove();

						if(data != 'none')
						{
							var savemenu = sv_savemenu;
							if(savemenu == 'y')
								window.location = '/dish/' + data;
							else
								window.location = '/' + data;

						}

						else
						{
							$('#formSubmitter').removeAttr('disabled');
						}
					}
				}
			});

			return false;
		},
		unhighlight: function(element, errorClass, validClass) {
			$(element).removeClass(errorClass);
		},
		success: function(errorElement) {
			var htmlFor = $(errorElement).attr('htmlfor');
			$('#' + htmlFor).parent().find('.mm_input_error_container').remove();

			if(htmlFor != 'restaurantPhoneNumber' && htmlFor != 'restaurantUrl' && htmlFor != "restaurantTags")
				$('#' + htmlFor).parent().addClass("mm_reqd");
			$('#' + htmlFor).parent().removeClass("mm_error");

		},
		rules: {
			"data[restaurant][name]": {
				"required": true,
				"nodefault": labelvenue_title
			},
			"data[restaurant][street_address]": "required",
			"data[restaurant][city]": "required",
			"data[restaurant][phone_number]": {
				"numberwithdefault"  : label_phone_number
			},
			"data[restaurant][businesstype_id]": "required",
			"data[restaurant][cuisine_id]": "required",
			"data[restaurant][website_address]": {
				"urlwithdefault"  : label_url
			},

		}
	});
	*/
}

function validationSuggestVenueTipInit(elementSubmitter, elementPoi, elementCity, elementStep2, elementDivVenue, elementDivTip, elementAtVenue, elementBusinessId, elementRestaurantName, elementRemoveField) {

	label_phone_number = "dummy";
	label_url = "dummy";

	// START validation for venue suggest
	var validationSettings  = sitoesModalv4ValidationSettings;

	// validation rules
	validationSettings.rules = {
		"data[restaurant][name]": {
			"required": true,
		},
		"data[restaurant][street_address]": "required",
		"data[restaurant][city]": "required",
		"data[restaurant][phone_number]": {
			"numberwithdefault"  : label_phone_number
		},
		"data[restaurant][cuisine]": "required",
		"data[restaurant][website_address]": {
			"urlwithdefault"  : label_url
		},
	};

	// validation submit handler
	validationSettings.submitHandler = function(form) {
		$(elementCity).removeAttr("disabled");
		$(elementPoi).removeAttr("disabled");
		$(elementStep2).addClass("isHidden");

		processModalSubmit("", ".loadElement");

		$(form).ajaxSubmit({
			success: function(data) {
				if(data) {
					$(elementAtVenue).val($(elementRestaurantName).val());
					$(elementBusinessId).val(data);
					$(elementAtVenue).attr("disabled", "disabled");

					var new_container = '<span class="mm_Iconset_14 doUnlock"><a class = "' + elementRemoveField + '" href="javascript:void(0)"><img width="16px" height="16px" src="/img/icon/clear.gif"></a></span>';
					$(elementAtVenue).after(new_container);

					$(elementDivVenue).addClass("isHidden");
					$(elementDivTip).removeClass("isHidden");
				}
				else {
					$.nyroModalRemove();

					$(elementStep2).removeClass("isHidden");
				}
				completeModalSubmit("", ".loadElement");
			}
		});

		return false;
	};

	$('#sitoes_business_suggestarestaurant').validate(validationSettings);
}

function autocompleteRestaurantNameEditInit(businessDetail) {
	$('#restaurantName').autocomplete(businesslist, {
		formatItem: function(row, i, max) {

			var displayString = row.businessname;

			displayString = displayString + "<small>";

			if(row.address1 != null)
				displayString = displayString + row.address1;

			if(row.address1 != null && row.city != null)
				displayString = displayString + " ,";

			if(row.city != null)
				displayString = displayString + row.city;

			displayString = displayString + "</small>";

			return displayString;
		},
		formatResult: function(row) {
			return row.businessname;
		},
		width: width_businessname,
		matchContains: true,
		highlight: false,
		formatMatch: function(row, i, max) {
			return row.businessname;
		},
	});


	$('#restaurantName').result(function(event, data, formatted) {

		autocomplete_business_flag = true;

		$('.mm_errormsg').css('display', 'none');
		$('.mm_formmsg').html('processing...');
		$('.mm_formmsg').css('display', 'block');

		autofillPoiResult(data.id);

		$('#chkAddNewLocation').removeAttr('disabled');
		//$('#chkAddNewLocation').parent().css("display", "block");
		$('#chkAddNewLocation').removeAttr('checked');
		//(data.id);
		if(businessDetail.id != data.id || data.id != '')
			$('#formSubmitter').attr('disabled', 'disabled');
		//alert(businessDetail.id);
		//$('#claimContainer').prependTo("#suggestarestaurant_detail_container");
	});


}

function autocompleteRestaurantName2Init(elementVenue, elementPoi, elementAddress1, elementAddress2, elementAddress3, elementParentAddressId, elementProvince,
							elementCity, elementPostalCode, elementRemoveField, elementDescription, elementCuisine, elementCuisineId,
							classVenuetype, elementPhone, elementWeb, elementVenueId, elementUrlTitle, elementAlias, elementSubmitter) {
	 // Handle data from ajax request
	 prep_data = function(data){

		   tmp = $.evalJSON(data);
		   parsed_data = [];
		   if(tmp == null)
		   {
				var array = new Array();
				return array;
		   }
		   else
		   {
			   for (i=0; i < tmp.length; i++) {
				 obj = tmp[i];
				 // Other internal autocomplete operations expect
				 // the data to be split into associative arrays of this sort
				 parsed_data[i] = {
					data: obj ,
					value: obj.isbn13,
					result: obj.title
				 };
			   }
			   return parsed_data
			}
	 }



	$(elementVenue).autocomplete("/businesses/get_business_list", {
		formatItem: function(row, i, max) {
			/*
			var displayString = row.businessname;

			displayString = displayString + "<small>";

			if(row.address1 != null)
				displayString = displayString + row.address1;

			if(row.address1 != null && row.city != null)
				displayString = displayString + " ,";

			if(row.city != null)
				displayString = displayString + row.city;

			displayString = displayString + "</small>";
			*/
			var displayString = row.businessname;

			if(row.name == null)
			{
				if(row.address1 != null || row.city != null)
				{
					displayString = displayString + "<br><em>";

					if(row.address1 != null)
						displayString = displayString + row.address1;

					if(row.address1 != null && row.city != null)
						displayString = displayString + ", ";

					if(row.city != null)
						displayString = displayString + row.city;

					displayString = displayString + "</em>";
				}
			}
			else
			{
				if(row.name != null || row.address3 != null || row.city != null)
				{
					displayString = displayString + "<br><em>";

					if(row.name != null)
						displayString = displayString + row.name;

					if(row.name != null && row.address3 != null)
						displayString = displayString + ", ";

					if(row.address3 != null)
						displayString = displayString + row.address3;

					if((row.name != null || row.address3 != null) && row.city != null)
						displayString = displayString + ", ";

					if(row.city != null)
						displayString = displayString + row.city;

					displayString = displayString + "</em>";
				}
			}

			return displayString;
		},
		formatResult: function(row) {
			return row.businessname;
		},
		width: width_businessname,
		matchContains: true,
		highlight: false,
		formatMatch: function(row, i, max) {
			return row.businessname;
		},
		parse:prep_data
	});

	$(elementVenue).result(function(event, data, formatted) {
		if(data.id !== null)
		{
			autocomplete_business_flag = true;

			//$('.mm_errormsg').css('display', 'none');
			//$('.mm_formmsg').html('processing...');
			//$('.mm_formmsg').css('display', 'block');

			autofillPoiResult(data.id, elementVenue, elementPoi, elementAddress1, elementAddress2, elementAddress3, elementParentAddressId, elementProvince,
							elementCity, elementPostalCode, elementRemoveField, elementDescription, elementCuisine, elementCuisineId,
							classVenuetype, elementPhone, elementWeb, elementVenueId, elementUrlTitle, elementAlias, elementSubmitter);
			//autofillPoiResult(data.id);

			//$('#chkAddNewLocation').removeAttr('disabled');
			//$('#chkAddNewLocation').parent().css("display", "block");
			//$('#chkAddNewLocation').removeAttr('checked');

			//$('#claimContainer').prependTo("#suggestarestaurant_detail_container");


		}
		else
			return false;
	});

	$("." + elementRemoveField).live('click', function() {
		var container = $(this);
		container.parent().remove();

		$(elementVenue).removeAttr("disabled").val("");
		$(elementVenue).siblings("label").removeClass("isOff");
		$(elementVenue).siblings(".mm_Validation").removeClass("isGood").addClass("isError");

		$(elementPoi).removeAttr('disabled').val("");
		$(elementAddress1).removeAttr('disabled').val("");
		$(elementAddress2).removeAttr('disabled').val("");
		$(elementAddress3).removeAttr('disabled').val("");
		$(elementProvince).val("");
		$(elementCity).removeAttr('disabled').val("");
		$(elementPostalCode).removeAttr('disabled').val("");
		$(elementPhone).removeAttr('disabled').val("");
		$(elementWeb).removeAttr('disabled').val("");
		$(elementDescription).removeAttr('disabled').val("");
		$(elementCuisine).removeAttr('disabled').val("");

		for(var j = 0; j < $(classVenuetype).length ; j++)
		{
			var temp = $(classVenuetype)[j];
			$(temp).removeAttr("checked").removeAttr("disabled");
		}
		$("#otherVenueCategories").removeAttr("disabled").val("");

		$(elementParentAddressId).val("");
		$(elementUrlTitle).val("");
		$(elementVenueId).val("");
		$(elementCuisineId).val("");

		var label_class = "isNormal";

		$(elementPoi).siblings("label." + label_class).removeClass("isOff");
		$(elementAddress1).siblings("label." + label_class).removeClass("isOff");
		$(elementAddress2).siblings("label." + label_class).removeClass("isOff");
		$(elementAddress3).siblings("label." + label_class).removeClass("isOff");
		$(elementProvince).siblings("label." + label_class).removeClass("isOff");
		$(elementCity).siblings("label." + label_class).removeClass("isOff");
		$(elementPostalCode).siblings("label." + label_class).removeClass("isOff");
		$(elementPhone).siblings("label." + label_class).removeClass("isOff");
		$(elementWeb).siblings("label." + label_class).removeClass("isOff");
		$(elementDescription).siblings("label." + label_class).removeClass("isOff");
		$(elementCuisine).siblings("label." + label_class).removeClass("isOff");
		$("#otherVenueCategories").siblings("label." + label_class).removeClass("isOff");

		return false;
	});

	$(elementVenue).keyup(function(e) {

		if(e.keyCode != 13 && e.keyCode != 9) {

			if ($(this).val().length == 0 || $(this).val() != resultName) {
				// disable
				clearPoiResult(elementPoi, elementAddress1, elementAddress2, elementAddress3, elementParentAddressId, elementProvince,
							elementCity, elementPostalCode, elementDescription, elementCuisine, elementCuisineId,
							elementPhone, elementWeb, elementVenueId, elementUrlTitle);
				/*
				$('#restaurantDescription').attr('disabled', false);
				$('#restaurantCategory').attr('disabled', false);
				$('#restaurantSubcategory').attr('disabled', false);
				$('#poibuilding').attr('disabled', false);
				$('#building_address').attr('disabled', false);
				$('#txtaddress1').attr('disabled', false);
				$('#txtaddress2').attr('disabled', false);
				$('#txtcity').attr('disabled', false);
				$('#txtpostalcode').attr('disabled', false);
				$('#restaurantPhoneNumber').attr('disabled', false);
				$('#restaurantUrl').attr('disabled', false);
				$('#BusinessLogo').attr('disabled', false);

				$('#restaurantLogoInputContainer').css('display', 'block');

				$('#restaurantDescription').val('').removeClass("mm_disabled");
				$('#restaurantCategory').val('');
				$('#restaurantSubcategory').val('');
				$('#poibuilding').val('').removeClass("mm_disabled");
				$('#building_address').val('').removeClass("mm_disabled");
				$('#txtaddress1').val('').removeClass("mm_disabled");
				$('#txtaddress2').val('').removeClass("mm_disabled");
				$('#txtcity').val('').removeClass("mm_disabled");
				$('#txtpostalcode').val('').removeClass("mm_disabled");
				$('#restaurantPhoneNumber').val(label_phone_number).removeClass("mm_disabled");
				$('#restaurantUrl').val(label_url).removeClass("mm_disabled");
				$('#restaurantId').val('');
				$('#restaurantParentId').val('');
				$('#BusinessLogo').val('');
				$('#restaurantUrlTitle').val('');

				$('#restaurantLogoImage').attr('src', '');

				$('#chkAddNewLocation').attr('disabled', 'disabled');

				$('#chkAddNewLocation').removeAttr('checked');

				$('#chkClaim').parent().css('display', 'block');

				$('.hideVenuePhoto').css('display', 'block');

				$('#business_hover_image').attr("src", '');
				$('#mm_hovered2').attr('src', '/img/icon/cam_black.png');
				$('#removePhotoBusiness').css('display', 'none');
				$('#msgUpload2').text('please upload only jpg, png, gif file');

				$('#mm_hovered2').unbind('mouseenter mouseleave');


				$('#locationFound').addClass("isHidden");
				$('#locationBegin').removeClass("isHidden");

				autocomplete_business_flag = false;
				*/
			}
		}
	});

	/*
	$('#restaurantName').blur(function() {
		var businessname = jQuery.trim($(this).val()).toLowerCase();

		if (businessname.length > 0) {
			var businessId   = business_name_id[businessname];

			if (businessId != undefined && autocomplete_business_flag == false) {
				autofillPoiResult(businessId);

				$('#chkAddNewLocation').removeAttr("disabled");
				$('#chkAddNewLocation').removeAttr('checked');
			}
		}
	});
	*/
}

function changePhoneNumberInit() {
	$("#restaurantPhoneNumber").change(function() {
		var content = $('#restaurantPhoneNumber').val();

		if (content == "")
			$('#restaurantPhoneNumber').parent().find('.mm_reqd').css('background-color', '#ffffff');
	});
}

function autocompleteCuisineInit(elementCuisine, elementCuisineId) {
	$(elementCuisine).autocomplete(gv_cuisineList, {
		formatItem: function(row, i, max) {
			var displayString = row.name;

			return displayString;
		},
		formatResult: function(row) {
			return row.name;
		},
		width: width_cuisine,
		matchContains: true,
		highlight: false,
		formatMatch: function(row, i, max) {
			return row.name;
		},
	});


	$(elementCuisine).result(function(event, data, formatted) {
		$(elementCuisine).val(data.name);
		$(elementCuisineId).val(data.id);
	});


}

function venueStep1Validator(elementValidator, elementSubmit, elementForm, elementStep1, elementStep2, elementVenue, elementAddress1, elementCity, classCategory)
{
	$(elementValidator).click(function() {

		var isVenueValid = $(elementForm).validate().element(elementVenue);
		var isAddress1Valid = $(elementForm).validate().element(elementAddress1);
		var isCityValid = $(elementForm).validate().element(elementCity);
		var isCategoryValid = false;

		for(var i = 0 ; i < $(classCategory).length ; i++)
		{
			var temp = $(classCategory)[i];

			//console.log(temp);

			var isChecked = $(temp).attr("checked");

			if(isChecked)
			{

				isCategoryValid = true;
				break;

			}
		}
		if(!isCategoryValid)
			if ($("#otherVenueCategories").val())
				isCategoryValid = true;

		if(isVenueValid && isAddress1Valid && isCityValid && isCategoryValid)
		{
			$(elementStep1).addClass("isHidden");
			$(elementStep2).removeClass("isHidden");
			$(elementValidator).addClass("isHidden");
			$(elementSubmit).removeClass("isHidden");

			$(elementForm).find(".whole_msg").addClass("isHidden");
			$("#added_whole_msg").html("");
		}

		else
		{
			$("#added_whole_msg").html("missing required fields");
			$(elementForm).find(".whole_msg").removeClass("isHidden");
		}

		return false;
	});

	$("#backToStep1").click(function() {
		$(elementStep1).removeClass("isHidden");
		$(elementStep2).addClass("isHidden");
		$(elementValidator).removeClass("isHidden");
		$(elementSubmit).addClass("isHidden");
	});
}

/* ************************************************************************** */

/* ARTICLE */
function tinymceInit(textareaElement) {
	$(textareaElement).tinymce({
		// Location of TinyMCE script
		script_url : '/js/tiny_mce/tiny_mce.js',

		relative_urls: false,

		// General options
		theme : "advanced",
		width : "498",
		height: "300",
		plugins : "safari,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,imagemanager",

/*		//setup : function(ed) {
		//	ed.onChange.add(function(ed, l) {
		//		console.debug('Editor contents was modified');
		//		sa_formChange = true;
		//	});
		//},*/

		object_resizing : false,

		// Theme options
		theme_advanced_buttons1 : "bold,|,italic,|,strikethrough,|,underline,|,bullist,|,numlist,|,blockquote,|,justifyleft,|,justifycenter,|,justifyright,|,justifyfull,|,outdent,|,indent,|,link,|,unlink",
		theme_advanced_buttons2 : "formatselect,|,pastetext,|,pasteword,|,removeformat,|,insertimage,|,media,|,charmap,|,undo,|,redo,|,spellchecker,|,fullscreen",
		theme_advanced_buttons3 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : false,
		theme_advanced_blockformats : "p,h2,h3,h4,h5,h6,blockquote",

		// Example content CSS (should be your site CSS)
		//content_css : "/css/sitoes.tinymce.css",

		// inlinepopup skins
		//inlinepopups_skin: "sitoes",

		// Drop lists for link/image/media/template dialogs
		template_external_list_url : "lists/template_list.js",
		external_link_list_url : "lists/link_list.js",
		external_image_list_url : "lists/image_list.js",
		media_external_list_url : "lists/media_list.js",

		spellchecker_rpc_url : "/js/tiny_mce/plugins/spellchecker/rpc.php",

		// Replace values for the template plugin
		template_replace_values : {
			username : "Some User",
			staffid : "991234"
		},

		init_instance_callback : function() {
			$("#nyroModalContent").css("height", "");
		}


	});
}

function keyupBlogPostExcerptInit() {
	// START excerpt container handler

	var cHeight   = 385; //$('#BlogPostContentContainer').height();

	$('#BlogPostExcerptToggleLink').click(function() {
		$('#BlogPostExcerpt').toggle(); //'fast');
		$('#BlogPostExcerptCountContainer').toggle(); //'fast');

		if ($(this).find("a").text() == 'hide') {
			$(this).find("a").text('show');
			$('#BlogPostContentContainer').height(cHeight);
			$('#BlogPostContent_tbl').height(373);
			$('#BlogPostContent_ifr').height(296);

		} else {

			$(this).find("a").text('hide');
			$('#BlogPostContentContainer').height(cHeight - 66);
			$('#BlogPostContent_ifr').height(cHeight - 86 - 57);
			$('#BlogPostContent_tbl').height(cHeight - 87);

		}

		return false;
	});

	textareaMaxCharacterInit('#BlogPostExcerpt', '#BlogPostExcerptCount', gv_BlogPostExcerptCountDefault);

	// END excerpt container handler
}

function blogPostTagInit() {
	// START tag handler
	$('#BlogPostTagAddButton').click(function() {
		var tag = $.trim($('#BlogPostTag').val());
		var tags = tag.split(",");

		for(var i = 0 ; i < tags.length ; i ++)
		{
			var temp = tags[i];
			if (temp.length > 0) {
				ad_addTagItem('#BlogPostTagsContainer', temp);

			}
		}

		$('#BlogPostTag').val('');

		return false;
	});

	$('.BlogPostTagDeleteLink').live('click', function() {
		var rel = $(this).attr('rel');
		$('#BlogPostInternalTag-' + rel).click();

		$(this).parent('span').parent('li').remove();

		return false;
	});

	$('.BlogPostInternalTagClass').change(function() {
		var rel = $(this).attr('rel');
		$('#BlogPostTagDelete-' + rel).parent('span').parent('li').remove();
	});
	// END tag handler
}

function validationSuggestArticleInit() {
	// START validation for blogpost
	var validationSettings = sitoesModalv4ValidationSettings;

	// validation rules
	validationSettings.rules = {
		'data[BlogPost][title]': {
			'required' : true,
			'nodefault': gv_BlogPostTitleDefault
		}
	};

	// validation submit handler
	validationSettings.submitHandler = function(form) {


		tinyMCE.triggerSave();

		ajaxSubmitBlogPostInit();

		return false;
	};

	$('#BlogPostForm').validate(validationSettings);
	// END validation for blogpost
}

function accordionBlogPostInit() {
	$('#BlogPostCategoryTagContainer').accordion({
		autoHeight: true
	});
}

function ajaxSubmitBlogPostInit() {
	$('#BlogPostForm').ajaxSubmit({
		beforeSubmit: function() {
			$('#textFormMessage').addClass('mm_formmessage');
			$('#textFormMessage').removeClass('mm_errormessage');
			$('#publishButton').attr('disabled', 'disabled');
			$('#saveButton').attr('disabled', 'disabled');

			processModalSubmit();
		},
		success: function(data) {
			var word = $("#BlogPostTitle").val().replace(/[^a-zA-Z \d]+/g, "");

			word = urlencode(word);

			setFormOkMessage();

			var out = jQuery.parseJSON(data);
			var mode = $("#BlogPostMode").val();

			$.nyroModalManual({
			  url: "/semantics/suggesttag/" + out.table_id + "/" + out.tablekey_id + "/" + word + "/goorme/" + out.post_to_facebook + "/" + mode,
			  endRemove: function() {
					window.location.reload();
				}
			});

			/*
			if (out.post_to_facebook == 0) {

				$.nyroModalSettings({
					endRemove: function() {

						var reloadTarget = '/article/' + out.url_title;

						if (sa_formCaller == 'dashboard') {
							if(sa_activeBusiness.length == 0) {
								reloadTarget = '/dashboard/index/typewriter';
							} else {
								reloadTarget = '/dashboard/' + sa_activeBusiness + '?tool=typewriter';
							}
						} else if (sa_formCaller == 'admin') {
							reloadTarget = '';
						}

						window.location = reloadTarget;
					}
				});

				$.nyroModalRemove();

			} else if (out.post_to_facebook == 1) {

				$.nyroModalManual({

					url: '/facebook/post/' + out.table_id + '/' + out.tablekey_id,
					endRemove: function() {
						window.location = '/article/' + out.url_title;
					}

				});

			}
			*/
		}
	});
}

function publishDraftBlogPostInit() {
	$('#publishButton').click(function() {
		$('#textFormMessage').addClass('mm_errormessage');
		if ($('#BlogPostForm').validate().form()) {
			$('#BlogPostStatus').val('publish');
			tinyMCE.triggerSave();
			ajaxSubmitBlogPostInit();
		}

		return false;
	});
}

function saveDraftBlogPostInit() {
	$('#saveButton').click(function() {
		$('#textFormMessage').addClass('mm_errormessage');

		if ($('#BlogPostForm').validate().form()) {
			$('#textFormMessage').addClass('mm_formmessage');


			tinyMCE.triggerSave();
			ajaxSubmitBlogPostInit();
		}

		return false;
	});
}

function ad_addTagItem(container, value) {
	var htmlTag = '<li><span class="alignRight"><a class="BlogPostTagDeleteLink" href="javascript:void(0)"><img src="/img/del_1.gif" /></a></span><label>' + value + '</label><input type="hidden" value="' + value + '" name="data[BlogPost][tag][]"><div class="clearFix"></div></li>';

	$(container).append(htmlTag);
}

/* ************************************************************************** */

/* RECIPE */
function recipeSuggestInit(ingredientNum, formCaller, sessionId) {
	$('#submitRecipeButton').attr('disabled', 'disabled');
	//count character limit in ovwerview
	if(fromType == 'add') {
		$('#RecipeExcerptCount').text(gv_RecipeExcerptCount);
	} else if(fromType == 'edit') {
		var excerptCount = $('#RecipeExcerpt').val().length;
		var diff = gv_RecipeExcerptCount - excerptCount;
		$('#RecipeExcerptCount').text(diff);
	}

	var cHeight   = 277;

	$('#recipeExcerptToogleLink').click(function() {

		$('#recipeExcerptContainer').toggle();
		$('#recipeExcerptCountContainer').toggle();

		if ($(this).find("a").text() == 'hide') {
			$(this).find("a").text('show');
			$('#recipeContentContainer').height(cHeight);
			$('#RecipeContent_tbl').height(280);
			$('#RecipeContent_ifr').height(243);
		} else {
			$(this).find("a").text('hide');
			$('#recipeContentContainer').height(cHeight - 77);
			$('#RecipeContent_ifr').height(cHeight - 87 - 24);
			$('#RecipeContent_tbl').height(cHeight - 87);
		}

		return false;
	});

	// check flash version
	if (checkFlashVersion() > 0)
	{
		// uploadify for promotion photo
		recipeUploadify(sessionId);
	}
	// upload without flash
	else
	{
		var options = {
			containerId : gv_recipePhotoContainer,
			inputId     : 'RecipePhoto',
			inputName   : 'data[Recipe][photo]',
			imageId     : 'RecipePhotoImage',
			uploadPath  : '/photos/ajax_upload/recipe',
			messageId   : 'msgUpload',
			removeLinkId: 'RecipePhoto_remove_link',
			hoveredId   : 'mm_hovered'
		};
		ajaxUploadInit(options);
	}

	removeRecipePhoto();

	focusBlurBehaviour("#RecipeTitle", "#" + recipe_form_name, "isNormal");
	focusBlurBehaviour("#RecipeExcerpt", "#" + recipe_form_name, "isNormal");
	focusBlurBehaviourRecipe("#RecipeServing", "#" + recipe_form_name, "isNormal");
	focusBlurBehaviour("#txt_amount_ingredient", "#" + recipe_form_name, "isNormal");
	focusBlurBehaviour("#txt_ingredients", "#" + recipe_form_name, "isNormal");
	focusBlurBehaviour("#txt_note_ingredient", "#" + recipe_form_name, "isNormal");
}

function recipeUploadify(sessionId) {
	$('#RecipePhoto').uploadify({
		'uploader'  : '/swf/uploadify.swf',
		'script'    : '/photos/ajax_upload/recipe',
		'folder'    : '/userfiles/recipe/',
		'buttonImg' : '/img/browse_button.png',
		'width'     : 69,
		'height'    : 28,
		'sizeLimit' : 512000,
		'multi'     : false,
		'auto'		: true,
		'fileDesc'  : 'Images Files',
		'fileExt'   : '*.jpg;*.gif;*.png;*.jpeg',
		'scriptData': {'sid': sessionId},

		onSelect: function(event, queueID, fileObj) {

			modalUploadifyOnSelect(event, queueID, fileObj, gv_recipePhotoContainer);
			$('#msgUpload').html(msgOnProgressUploadPhoto);
			$('.disableOnUploadPhoto').attr("disabled", "disabled");
			return false;
		},
		onError: function(event, queueID, fileObj, errorObj) {

			modalUploadifyOnError(event, queueID, fileObj, errorObj);

			return false;
		},
		onProgress: function(event, queueID, fileObj, data) {

			modalUploadifyOnProgress(event, queueID, fileObj, data, progressPiePrevClass);

			return false;
		},
		onComplete: function(event, queueID, fileObj, response, data) {

			var imageData  = jQuery.parseJSON(response);
			var imageFile  = imageData.original + '.' + imageData.extension;
			var imageThumb = imageData.thumbnail + '.' + imageData.extension;

			var imgPath = '/userfiles/recipe/' + imageThumb;

			var iconAfterUpload = '<span class="mm_Iconset_14 isPhoto isOn"><img id="mm_hovered" src="/img/icon/clear.gif" width="16px" height="16px" /></span>';
			var imgTag          = '<img style="display:none" id="RecipePhotoImage" src="' + imgPath + '" class="mm_dev_image24" />';

			var hiddenTag  = '<input type="hidden" name="data[Recipe][photo]" value="' + imageFile + '" />';

			$(gv_recipePhotoContainer).html(imgTag);
			$(gv_recipePhotoContainer).append(iconAfterUpload);
			$(gv_recipePhotoContainer).append(hiddenTag);

			$(gv_recipePhotoContainer).siblings("label.isPhoto").html(imageData.original_label);

			$('#msgUpload').html(msgAfterUploadPhoto);
			$('.disableOnUploadPhoto').removeAttr("disabled");
			$('#RecipePhoto_remove_link').css('display', 'block');

			sitoes_hoverImage('mm_hovered', 'RecipePhotoImage');

			return false;
		}
	});
	// END uploadifty for recipe photo
}

function removeRecipePhoto() {
	$('#RecipePhoto_remove_link').click(function() {
		var imgPath    = '/img/icon/cam_black.png';

		var imgTag          = '<img id="RecipePhotoImage" src="" class="mm_dev_image24" style="display:none" />';
		var iconAfterUpload = '<img id="mm_hovered" src="' + imgPath + '" width="24px" height="24px" />';

		var hiddenTag  = '<input type="hidden" name="data[Recipe][photo]" value="" />';

		$(gv_recipePhotoContainer).html(imgTag);
		$(gv_recipePhotoContainer).append(iconAfterUpload);
		$(gv_recipePhotoContainer).append(hiddenTag);

		$('#msgUpload').html('please upload only jpg, png, gif file');
		$('#RecipePhoto_remove_link').css('display', 'none');
	});
}

function validationSuggestRecipeInit(fromName, formCaller, ingredientNum) {

	// START validation for recipe suggest
	var validationSettings  = sitoesModalv4ValidationSettings;

	// validation rules
	validationSettings.rules = {
		'data[Recipe][title]': {
			'required' : true
		},
	};

	// validation submit handler
	validationSettings.submitHandler = function(form) {
		//removeWatermarkValue('#PromotionTitle', gv_promotionTitleDefault);
			removeWatermarkValue('#RecipeTitle', gv_recipeTitleDefault);
			removeWatermarkValue('#Reciperecipe_ingredient0Amount', gv_RecipeIngredientAmountDefault);
			removeWatermarkValue('#Reciperecipe_ingredient0Name', gv_RecipeIngredientNameDefault);
			removeWatermarkValue('#Reciperecipe_ingredient0Note', gv_RecipeIngredientNoteDefault);
		tinyMCE.triggerSave();

		$(fromName).ajaxSubmit({
			beforeSubmit: function(formData, jqForm, options) {
				$('#submitRecipeButton').attr('disabled', 'disabled');
				processModalSubmit();
			},
			success: function(responseData) {
				var word = $("#RecipeTitle").val().replace(/[^a-zA-Z \d]+/g, "");

				word = urlencode(word);


/*				//$.nyroModalManual({
				 // url: "/semantics/suggesttag/" + word + "/recipe",
				 // endRemove: function() {
				//		window.location.reload();
				//	}
				//});*/

							var out = jQuery.parseJSON(responseData);

							$.nyroModalManual({
							  url: "/semantics/suggesttag/" + 12 + "/" + out.tablekey_id + "/" + word + "/" + formCaller + "/null/" + fromType,
							  endRemove: function() {
									window.location.reload();
								}
							});

				/*
				setFormOkMessage();
				var recipe_url   = jQuery.parseJSON(responseData);

				$.nyroModalSettings({
					endRemove: function() {

						if (formCaller == 'dashboard') {
							var new_location = '/dashboard/index/recipe';
						} else if (formCaller == 'admin') {
							var new_location = '/admin/recipes/manage';
						} else if (formCaller == 'goorme') {
							var new_location = '/recipe/' + recipe_url;
						}
						window.location = new_location;;
					}
				});
				$.nyroModalRemove();
				*/
			}
		});

		return false;
	};
	//console.log(fromName);
		$(fromName).validate(validationSettings);
	// END validation for recipe
	submitButtonSuggestRecipeInit(fromName, ingredientNum);
}

function ingredientValidate(ingredientNum, error) {

	var errorCount = error;
	for(z=0; z<ingredientNum; z++) {
		var recipeAmount = $('#Reciperecipe_ingredient' + z + 'Amount').attr('value');
		var recipeIngredient = $('#Reciperecipe_ingredient' + z + 'Name').attr('value');
		var recipeNote = $('#Reciperecipe_ingredient' + z + 'Note').attr('value');

		if (recipeAmount == gv_RecipeIngredientAmountDefault)
			recipeAmount = '';
		if (recipeIngredient == gv_RecipeIngredientNameDefault)
			recipeIngredient = ''
		if (recipeNote == gv_RecipeIngredientNoteDefault)
			recipeNote = ''

		if((recipeAmount == '' && recipeIngredient !='') || recipeIngredient == ''  && recipeAmount !='' || recipeIngredient == ''  && recipeNote !='' ) {

			$('#Reciperecipe_ingredient' + z + 'Name').parent('li').addClass('mm_error');
			$('#Reciperecipe_ingredient' + z + 'Name').addClass('mm_input_error');

				//$('#Reciperecipe_ingredient' + z + 'Amount').parent('li').addClass('mm_error');
				//$('#Reciperecipe_ingredient' + z + 'Amount').addClass('mm_input_error');

			var errorMessage = setErrorMessage('Amount and Ingredient are required fields');
			$('#Reciperecipe_ingredient' + z + 'Name').after(errorMessage);

			errorCount++;

		} else 	if(recipeAmount == '' && recipeNote =='' && recipeIngredient == '') {
			$('#Reciperecipe_ingredient' + z + 'Name').parent('li').removeClass('mm_error');
			$('#Reciperecipe_ingredient' + z + 'Name').removeClass('mm_input_error');
		}
	}

	if (errorCount > 1)
			var errorText = 'errors';
		else
			var errorText = 'error';

	if (errorCount > 0) {
		$('.mm_formmessage').css('display', 'none');
		$('.mm_errormessage').html(errorCount + ' ' + errorText + '.');
		$('.mm_errormessage').css('display', 'block');
		return false;

		}
	else {
		$('#ingredientRow').children('li').removeClass('mm_error');
		$('.mm_errormessage').css('display', 'none');
		return true;
	}
}

function submitButtonSuggestRecipeInit(fromName, ingredientNum) {
	var i = ingredientNum;
	$('#ingredientAddAnother').click(function() {
		var ingredientHtml = '<li><input type="text" id="Reciperecipe_ingredient'+ i + 'Amount" class="mm_textfield_80 mm_space_5" name="data[Recipe][recipe_ingredient]['+ i +'][amount]"><input type="text" id="Reciperecipe_ingredient'+ i +'Name" class="mm_textfield_130 mm_space_5" name="data[Recipe][recipe_ingredient]['+ i +'][name]"><input type="text" id="Reciperecipe_ingredient'+ i +'Note" class="mm_textfield_210" name="data[Recipe][recipe_ingredient]['+ i +'][note]"><div class="clearFix"></div></li>';
		$('#ingredientRow').append(ingredientHtml);
		i++;
	});

	$('#ingredientAdd5Another').click(function() {
		for(k=0; k<5; k++) {
			var ingredientHtml = '<li><input type="text" id="Reciperecipe_ingredient'+ i + 'Amount" class="mm_textfield_80 mm_space_5" name="data[Recipe][recipe_ingredient]['+ i +'][amount]"><input type="text" id="Reciperecipe_ingredient'+ i +'Name" class="mm_textfield_130 mm_space_5" name="data[Recipe][recipe_ingredient]['+ i +'][name]"><input type="text" id="Reciperecipe_ingredient'+ i +'Note" class="mm_textfield_210" name="data[Recipe][recipe_ingredient]['+ i +'][note]"><div class="clearFix"></div></li>';
			$('#ingredientRow').append(ingredientHtml);
			i++;
		}

	});

	$('#ingredientAdd10Another').click(function() {
		for(k=0; k<10; k++) {
			var ingredientHtml = '<li><input type="text" id="Reciperecipe_ingredient'+ i + 'Amount" class="mm_textfield_80 mm_space_5" name="data[Recipe][recipe_ingredient]['+ i +'][amount]"><input type="text" id="Reciperecipe_ingredient'+ i +'Name" class="mm_textfield_130 mm_space_5" name="data[Recipe][recipe_ingredient]['+ i +'][name]"><input type="text" id="Reciperecipe_ingredient'+ i +'Note" class="mm_textfield_210" name="data[Recipe][recipe_ingredient]['+ i +'][note]"><div class="clearFix"></div></li>';
			$('#ingredientRow').append(ingredientHtml);
			i++;
		}

	});

	var step1_Ingredient = false;
	var step1_Ok = false;
	$('#nextButton').click(function() {

		step1_Ok = $(fromName).validate().form();
		if(step1_Ok == false)
			var error = 1;
		else
			var error = 0;
		step1_Ingredient = ingredientValidate(i, error);
		//alert(error);
		if (step1_Ok && step1_Ingredient) {
			processModalSubmit();

			sr_toggleForm();
			$('#submitRecipeButton').removeAttr('disabled');

			}

		return false;
	});

	$('#backButton').click(function() {

		sr_toggleForm();
		$('#submitRecipeButton').attr('disabled', 'disabled');
		return false;
	});
}

function sr_toggleForm() {

	$('.add_recipe_step1').toggle();
	$('.add_recipe_step2').toggle();

	setFormOkMessage();
}

// START tag handler
function recipeTagInit() {

	$('#recipeCategoryTagContainer').accordion({
		autoHeight: true
	});

	$('#RecipeTagAddButton').click(function() {

		var tag = $.trim($('#RecipeTag').val());
		var tags = tag.split(",");
		for(var i = 0 ; i < tags.length ; i ++)
		{

			var temp = tags[i];
			if (temp.length > 0) {
				addRecipeTagItem('#RecipeTagsContainer', temp);
			}
		}

		$('#RecipeTag').val('');

		return false;
	});

	$('.RecipeTagDeleteLink').live('click', function() {
		var rel = $(this).attr('rel');
		$('#RecipeInternalTagClass-' + rel).click();

		$(this).parent('span').parent('li').remove();

		return false;
	});

	$('.RecipeInternalTagClass').change(function() {
		var rel = $(this).attr('rel');
		$('#RecipeTagDelete-' + rel).parent('span').parent('li').remove();
	});
	// END tag handler
}

function addRecipeTagItem(container, value) {
		var htmlTag = '<li><span class="alignLeft mm_space_5"><a class="RecipeTagDeleteLink" href="javascript:void(0)"><img src="/img/del_1.gif" /></a></span><label>' + value + '</label><input type="hidden" value="' + value + '" name="data[Recipe][tag][]"><div class="clearFix"></div></li>';
		$(container).append(htmlTag);
}

function recipeTinyMceInit(textareaElement) {

	$(textareaElement).tinymce({
		// Location of TinyMCE script
		script_url : '/js/tiny_mce/tiny_mce.js',

		relative_urls: false,

		// General options
		theme : "advanced",
		width : "477",
		height: "294",

		plugins : "safari,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,imagemanager",

		object_resizing : false,

		// Theme options
		theme_advanced_buttons1 : "bold,|,italic,|,bullist,|,numlist,|,insertimage,|,link,|,unlink",
		theme_advanced_buttons2 : "",
		theme_advanced_buttons3 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : false,
		theme_advanced_blockformats : "p,h2,h3,h4,h5,h6,blockquote",

		// Example content CSS (should be your site CSS)
		//content_css : "/css/sitoes.tinymce.css",

		// Drop lists for link/image/media/template dialogs
		template_external_list_url : "lists/template_list.js",
		external_link_list_url : "lists/link_list.js",
		external_image_list_url : "lists/image_list.js",
		media_external_list_url : "lists/media_list.js",

		spellchecker_rpc_url : "/js/tiny_mce/plugins/spellchecker/rpc.php",

		// Replace values for the template plugin
		template_replace_values : {
			username : "Some User",
			staffid : "991234"
		}
	});
}
/* ************************************************************************** */

/* ***** CALENDAR **** */
function calendarInit() {

	if (checkFlashVersion() > 0)
	{
		calendarUploadifyInit();
	}
	// upload without flash
	else
	{
		var options = {
			containerId : gv_calendarPhotoContainer,
			inputId     : 'CalendarPhoto',
			inputName   : 'data[Calendar][photo]',
			imageId     : 'CalendarPhotoImage',
			uploadPath  : '/photos/ajax_upload/calendar',
			messageId   : 'msgUpload',
			removeLinkId: 'CalendarPhoto_remove_link',
			hoveredId   : 'mm_hovered'
		};
		ajaxUploadInit(options);
	}

	removeCalendarPhoto();
}

function calendarUploadifyInit() {
	$('#CalendarPhoto').uploadify({
			'uploader'  : '/swf/uploadify.swf',
			'script'    : '/photos/ajax_upload/calendar',
			'folder'    : '/userfiles/calendar/',
			'buttonImg' : '/img/browse_button.png',
			'width'     : 69,
			'height'    : 28,
			'sizeLimit' : 512000,
			'multi'     : false,
			'auto'		: true,
			'fileDesc'  : 'Images Files',
			'fileExt'   : '*.jpg;*.gif;*.png;*.jpeg',
			//'scriptData': {'sid': '<?php echo session_id(); ?>'},

			onSelect: function(event, queueID, fileObj) {

				modalUploadifyOnSelect(event, queueID, fileObj, gv_calendarPhotoContainer);

				return false;
			},
			onError: function(event, queueID, fileObj, errorObj) {

				modalUploadifyOnError(event, queueID, fileObj, errorObj);

				return false;
			},
			onProgress: function(event, queueID, fileObj, data) {

				modalUploadifyOnProgress(event, queueID, fileObj, data, progressPiePrevClass);

				$('#msgUpload').html(msgOnProgressUploadPhoto);

				return false;
			},
			onComplete: function(event, queueID, fileObj, response, data) {

				var imageData  = jQuery.parseJSON(response);
				var imageFile  = imageData.original + '.' + imageData.extension;
				var imageThumb = imageData.thumbnail + '.' + imageData.extension;

				var imgPath = '/userfiles/calendar/' + imageThumb;

				var iconAfterUpload = '<img id="mm_hovered" src="/img/icon/cam_green.png" width="24px" height="24px" />';
				var imgTag          = '<img style="display:none" id="CalendarPhotoImage" src="' + imgPath + '" class="mm_dev_image24" />';

				var hiddenTag  = '<input type="hidden" name="data[Calendar][photo]" value="' + imageFile + '" />';

				$(gv_calendarPhotoContainer).html(imgTag);
				$(gv_calendarPhotoContainer).append(iconAfterUpload);
				$(gv_calendarPhotoContainer).append(hiddenTag);

				$('#msgUpload').html(msgAfterUploadPhoto);
				$('#CalendarPhoto_remove_link').css('display', 'block');

				sitoes_hoverImage('mm_hovered', 'CalendarPhotoImage');

				return false;
			}
		});
}

function removeCalendarPhoto() {
	$('#CalendarPhoto_remove_link').click(function() {
		var imgPath    = '/img/icon/cam_black.png';

		var imgTag          = '<img id="CalendarPhotoImage" src="" class="mm_dev_image24" style="display:none" />';
		var iconAfterUpload = '<img id="mm_hovered" src="' + imgPath + '" width="24px" height="24px" />';

		var hiddenTag  = '<input type="hidden" name="data[Calendar][photo]" value="" />';

		$(gv_calendarPhotoContainer).html(imgTag);
		$(gv_calendarPhotoContainer).append(iconAfterUpload);
		$(gv_calendarPhotoContainer).append(hiddenTag);

		$('#msgUpload').html('please upload only jpg, png, gif file');
		$('#CalendarPhoto_remove_link').css('display', 'none');
	});
}

/* ***************************************************************************************** */

/* GENERAL */
function setFormProcessingMessage(loading_element) {

	if(loading_element == "" || loading_element == undefined)
		loading_element = "#mm_Body";
	$(loading_element).parent().attr('id', 'mm_Progress');
	$(".whole_msg").addClass("isHidden");
	//$('.mm_errormessage').css('display', 'none');
	//$('.mm_formmessage').html('processing...');
	//$('.mm_formmessage').css('display', 'block');
}

function textareaMaxCharacterInit(textElement, countElement, maxChar) {
	$(textElement).keyup(function() {

		var text  = $(this).val();
		var chars = text.length;
		var limit = parseInt(maxChar);

		var diff = maxChar - chars;

		if(diff < 0) {
			var new_text = text.substr(0, limit);
			$(this).val(new_text);
		}

		if (diff > 0) {
			$(countElement).text(diff);
		} else {
			$(countElement).text(0);
		}
	});
}

function ajaxUploadInit(options)
{
	var containerId  = options.containerId;
	var target       = options.uploadPath;
	var inputId      = options.inputId;
	var inputName    = options.inputName;
	var imageId      = options.imageId;
	var removeLinkId = options.removeLinkId;
	var messageId    = options.messageId;
	var hoveredId    = options.hoveredId;

	var img = "<img src='/img/browse_button.png' id='"+ inputId +"'>";
	$('#' + inputId).replaceWith(img);
	new AjaxUpload(
		inputId,
		{
			action: target,
			name: 'Filedata',
			onSubmit: function(file, extension)
			{
				$('#' + messageId).text(msgOnProgressUploadPhoto);
				$('.disableOnUploadPhoto').attr("disabled", "disabled");
				$(containerId).html('<img src="/img/ajaxload.gif">');
			},
			onComplete: function(file, response)
			{
				var imageData  = jQuery.parseJSON(response);
				var imageFile  = imageData.original + '.' + imageData.extension;
				var imageThumb = imageData.thumbnail + '.' + imageData.extension;

				var imgPath = imageData.url_path + imageThumb;

				var iconAfterUpload = '<span class="mm_Iconset_14 isPhoto isOn"><img id="' + hoveredId + '" src="/img/icon/clear.gif" width="16px" height="16px" /></span>';
				var imgTag          = '<img style="display:none" id="' + imageId + '" src="' + imgPath + '" class="mm_dev_image24" />';
				var imgDisplayed    = '<img id="displayed_img" src="' + imgPath + '" width="44px" height="44px" />';

				var hiddenTag  = '<input type="hidden" name="' + inputName + '" value="' + imageFile + '" />';

				$(containerId).html(imgTag);
				$(containerId).append(iconAfterUpload);
				$(containerId).append(hiddenTag);

				$("#displayed_img").html(imgDisplayed);

				$('#' + messageId).text(msgAfterUploadPhoto);
				$('.disableOnUploadPhoto').removeAttr("disabled");
				$('#' + removeLinkId).css('display', 'block');

				sitoes_hoverImage(hoveredId, imageId);
			}
		}
	);
}
/* ************************************************************************** */


/* POI */

function poiInit() {
	validationPoiInit();
	autocompleteCity2Init();
	autocompletePoi2Init();
}


function validationPoiInit() {
	var poi_url_title = $('#poiurltitle').val();
	$('#frmEditPoi').validate({
		errorClass: "mm_input_error",
		errorElement: "div",
		focusInvalid: false,
		highlight: function(element, errorClass, validClass) {
			$(element).addClass(errorClass);
		},
		onfocusout: false,
		onkeyup: false,
		onclick: false,
		showErrors: function(errorMap, errorList) {

			var errorCount = this.numberOfInvalids();
			if (errorCount == 1)
				var errorText = 'error';
			else
				var errorText = 'errors';

			if (errorCount > 0) {
				$('.mm_formmsg').css('display', 'none');
				$('.mm_errormessage').css('color', 'red');
				$('.mm_errormessage').html(errorCount + ' ' + errorText + '.');
				$('.mm_errormessage').css('display', 'block');
			}

			for (var i = 0; i < errorList.length; i++) {

				var elementId = $(errorList[i].element).attr('id');
				var message   = errorList[i].message;

				var errorElement = setErrorMessage(message);

				if (elementId.length) {
					$('#' + elementId).parent().find('.mm_input_error_container').remove();

					$('#' + elementId).after(errorElement);
					$('#' + elementId).parent().addClass("mm_error");
				}
			}

			this.defaultShowErrors();
		},
		errorPlacement: function(error, element) {
			return true;
		},
		submitHandler: function(form) {
			$("#mm_general_submit_button").attr('disabled', 'disabled');
			$('.mm_errormessage').css('display', 'none');
			$('.mm_formmessage').html('checking. please wait ...');
			$('.mm_formmessage').css('display', 'block');

			$(form).ajaxSubmit({
				success: function(data) {
					window.location.reload();
					$.nyroModalRemove();

				}
			});
		},
		unhighlight: function(element, errorClass, validClass) {
			$(element).removeClass(errorClass);
		},
		success: function(errorElement) {
			var htmlFor = $(errorElement).attr('htmlfor');
			$('#' + htmlFor).parent().find('.mm_input_error_container').remove();
				$('#' + htmlFor).parent().removeClass("mm_error");
		},
		rules: {
			"data[Address][building_name]": {
				"required": true,
				"nodefault": label_building_name
			},
			"data[Address][address1]": "required",
			"data[Address][city]": "required",
			'data[Poi][url_title]': {
					'remote'       : '/businesses/ajax_check/url_title/' + poi_url_title
			},
		},
		messages : {
				'data[Poi][url_title]': {
					'remote': 'The url is taken.'
				}
		}
	});

}
/* ************************************************************************** */

/* ************************************************************************** */
/* EDIT ADDRESS */

function editAddressInit() {
	validationEditAddressInit();
}

function validationEditAddressInit() {
	$('#address_profile_location_edit_form').validate({
		errorClass: "mm_input_error",
		errorElement: "div",
		focusInvalid: false,
		highlight: function(element, errorClass, validClass) {
			$(element).addClass(errorClass);
		},
		onfocusout: false,
		onkeyup: false,
		onclick: false,
		showErrors: function(errorMap, errorList) {

			var errorCount = this.numberOfInvalids();
			if (errorCount == 1)
				var errorText = 'error';
			else
				var errorText = 'errors';

			if (errorCount > 0) {
				$('.mm_formmsg').css('display', 'none');
				$('.mm_errormessage').css('color', 'red');
				$('.mm_errormessage').html(errorCount + ' ' + errorText + '.');
				$('.mm_errormessage').css('display', 'block');
			}

			for (var i = 0; i < errorList.length; i++) {

				var elementId = $(errorList[i].element).attr('id');
				var message   = errorList[i].message;

				var errorElement = setErrorMessage(message);

				if (elementId.length) {
					$('#' + elementId).parent().find('.mm_input_error_container').remove();

					$('#' + elementId).after(errorElement);
					$('#' + elementId).parent().addClass("mm_error");
				}
			}

			this.defaultShowErrors();
		},
		errorPlacement: function(error, element) {
			return true;
		},
		submitHandler: function(form) {
			$("#mm_general_submit_button").attr('disabled', 'disabled');
			$('.mm_errormessage').css('display', 'none');
			$('.mm_formmessage').html('checking. please wait ...');
			$('.mm_formmessage').css('display', 'block');

			$(form).ajaxSubmit({
				success: function(data) {
					location.reload();
					//$.nyroModalRemove();
				}
			});
		},
		unhighlight: function(element, errorClass, validClass) {
			$(element).removeClass(errorClass);
		},
		success: function(errorElement) {
			var htmlFor = $(errorElement).attr('htmlfor');
			$('#' + htmlFor).parent().find('.mm_input_error_container').remove();
				$('#' + htmlFor).parent().removeClass("mm_error");
		},
		rules: {
			"data[Address][address1]": "required",
			"data[Address][city]": "required",
		}
	});
}

/* ************************************************************************** */

function autocompleteBuildingNameInit(elementCity, elementAddress1, elementProvince, elementAddressCity, elementPostalCode, elementRemoveField, elementAddress2) {

	if(elementAddress2 == undefined || elementAddress2 == "")
		elementAddress2 = "#dummy";

	prep_data = function(data){

		   tmp = $.evalJSON(data);
		   parsed_data = [];
		   if(tmp == null)
		   {
				var array = new Array();
				return array;
		   }
		   else
		   {
			   for (i=0; i < tmp.length; i++) {
				 obj = tmp[i];
				 // Other internal autocomplete operations expect
				 // the data to be split into associative arrays of this sort
				 parsed_data[i] = {
					data: obj ,
					value: obj.isbn13,
					result: obj.title
				 };
			   }
			   return parsed_data
			}
	 }

	$(elementCity).autocomplete("/pois/get_poi_list", {

			formatItem: function(row, i, max) {
			/*
			var displayString = row.name;

			displayString = displayString + "<small>";

			if(row.address1 != null)
				displayString = displayString + row.address1;

			if(row.address1 != null && row.city != null)
				displayString = displayString + " ,";

			if(row.city != null)
				displayString = displayString + row.city;

			displayString = displayString + "</small>";
			*/

			var displayString = row.name;

			if(row.city != null)
				displayString = displayString + "<br><em>" + row.city + "</em>";

			return displayString;
			},
			width: width_buildingname2,
			formatResult: function(row) {
				return row.name;
			},
			matchContains: true,
			highlight: false,
			formatMatch: function(row, i, max) {
				return row.name;
			},
			parse:prep_data
	});

	$(elementCity).result(function(event, data, formatted) {
		var new_container = '<span class="mm_Iconset_14 doUnlock"><a class = "' + elementRemoveField + '" href="javascript:void(0)"><img width="16px" height="16px" src="/img/icon/clear.gif"></a></span>';
		$(elementCity).after(new_container);
		$(elementCity).attr("disabled", "disabled").val(data.name);

		//processModalSubmit();
		$(elementAddress1).attr('disabled', 'disabled');
		$(elementAddress2).attr('disabled', 'disabled');
		$(elementAddressCity).attr('disabled', 'disabled');
		$(elementPostalCode).attr('disabled', 'disabled');

		var label_class = "isNormal";
		$(elementAddress1).siblings("label." + label_class).removeClass("isFocus").addClass("isOff");
		$(elementAddress2).siblings("label." + label_class).removeClass("isFocus").addClass("isOff");
		$(elementProvince).siblings("label." + label_class).removeClass("isFocus").addClass("isOff");
		$(elementAddressCity).siblings("label." + label_class).removeClass("isFocus").addClass("isOff");
		$(elementPostalCode).siblings("label." + label_class).removeClass("isFocus").addClass("isOff");

		$.getJSON('/addresses/get_one/' + data.address_id + '/return:json', function(result) {

			//autocompleteName = data.buildingname;
			$(elementAddress1).val(result.Address.address1);
			$(elementAddress2).val(result.Address.address2);
			$(elementProvince).val(result.Province.provincename);
			$(elementAddressCity).val(result.Address.city);
			$(elementPostalCode).val(result.Address.postalcode);

			//console.log($(elementAddress1).val());
			//console.log($(elementProvince).val());
			//console.log($(elementAddressCity).val());
		//	completeModalSubmit();
		});

	});

	//console.log(elementAddress2);

	$("." + elementRemoveField).live('click', function() {
		var container = $(this);
		container.parent().remove();

		$(elementCity).removeAttr("disabled").val("");
		$(elementCity).siblings("label").removeClass("isOff");
		//$(elementCity).siblings("label").addClass("isFocus");
		$(elementCity).siblings(".mm_Validation").removeClass("isGood");

		$(elementAddress1).removeAttr('disabled').val("");
		//if(elementAddress2 != "dummy")
		if($(elementAddress2).length > 0)
		{
		//	console.log("aaa");
			$(elementAddress2).removeAttr('disabled').val("");
		}

		//	console.log("bbb");
		$(elementAddressCity).removeAttr('disabled').val("");
		$(elementPostalCode).removeAttr('disabled').val("");
		$(elementProvince).val("");

		var label_class = "isNormal";
		$(elementAddress1).siblings("label." + label_class).removeClass("isOff");
		if($(elementAddress2).length > 0)
		{
		//	console.log("aaa");
			$(elementAddress2).siblings("label." + label_class).removeClass("isOff");
		}

		//	console.log("bbb");
		$(elementProvince).siblings("label." + label_class).removeClass("isOff");
		$(elementAddressCity).siblings("label." + label_class).removeClass("isOff");
		$(elementPostalCode).siblings("label." + label_class).removeClass("isOff");

		return false;
	});
	// END autocomplete for city

}
