var tmpProductRegionId = null;
var tmpProductCityId = null;
var tmpImageAcceptanceValid = false;

function Bootstrap()
{
	SetupFormAcceptance();
	SetupYourLocationEvents();
	SetupAccomLocationEvents();
	SetupBestPartEvents();
	SetupLiveResortSearch();
	SetupFieldGroupValidation();
	SetupReviewRating();
	SetupSearchEvents();
	SetupExternalLinks();
}

function SetupExternalLinks()
{
	 $("a[rel=external]").click(
			 function()
			 {
				 window.open(this.href);
				 return false;
			 }
	 )
}

function LaunchDialogWithMessage(message, showButtons)
{
	var dialogOptions = {
				autoOpen: 	true,
				modal:		true,
				title: 		'Warning',
				width: 		600
			};

	if(showButtons)
	{
		$.extend(
				true, 
				dialogOptions,
				{buttons: {
					"Continue": function() { 
					$("#dialog").dialog("destroy"); 
				} 
			}}
		);
	}
	 
	$('#dialog').dialog(dialogOptions);
	$("div#dialog_content").html(message);
}

function SetupFormAcceptance()
{
	if( $("input.submit-button").length > 0 )
	{
		$("input.submit-button").click(
				function()
				{
					if($("input#terms_acceptance").attr('checked') == false)
					{
						LaunchDialogWithMessage('You must agree to our terms and conditions.', true);
						this.checked = false;
						return false;
						
					}
					else if( $("input#reviewer_photo").val().length > 0 || $("input#product_photo").val().length > 0 )
					{
						LaunchDialogWithMessage('<p>Please wait whilst your photo\'s are uploaded. This may take sometime.</p><p style="text-align:center;"><img src="/images/uploading-timer.gif" /></p>', false);
						//return false;
					}
				});
	}

}

function SetReviewRating(rating)
{
	$("input#product_rating").val(rating);
}

function SetupReviewRating()
{
	var el = $("div.rating-choice-box img");
	el.hover(
			function()
			{
				var ce = this;
				var coldPth = '/images/rating-cold.png';
				var hotPth = '/images/rating-hot.png';
				var turnCold = false;
				
				$(this).parent().find("img").each(
					function(i)
					{
						if(turnCold)
						{
							$(this).attr('src', coldPth)
						}
						else
						{
							SetReviewRating(i+1);
							$(this).attr('src', hotPth);
						}
						
						if(ce == this) { turnCold = true; }
					}
				);				
			}
	);	
}

function LimitOptionChoiceCount(message, containerSelector, maxOptions)
{
	$(containerSelector + " input").click(
			function()
			{

				if($(containerSelector + " input:checked").length <= maxOptions)
				{
					return true;
				}
				else
				{
					LaunchDialogWithMessage(message, true)
					this.checked = false;
					return false;
				}
			}
	)

}

function SetupFieldGroupValidation()
{
	LimitOptionChoiceCount('You may only choose up to 5 things that made your break fantastic', 'div#best-part-options'     , 5);
	LimitOptionChoiceCount('You may only choose up to 3 recommendations for other reviewers', 'div#recommendation-options', 3);
}

function SetupLiveResortSearch()
{
	
	if($('input.live-search').length > 0)
	{
		var opts = { 
						minChars:1, 
						autoFill: true, 
						max: 5,
						parse: function(data) {
							return $.map(eval(data), function(row) {
								return {
									data: row,
									value: row.product_id,
									result: row.product_name
								}
							});
						},
						formatItem: function(item) {
							var str = "<p>" + item.product_name + ": " + item.product_type_name + "</p>";
							str += '<p class=\"small\">';
							
							if(item.product_city_name != null)
							{
								str += item.product_city_name + ', ';
							}
							else if(item.product_city_name == null && item.product_region_name != null)
							{
								str += item.product_custom_location + ', ';
							}
							
							if(item.product_region_name != null)
							{
								str += item.product_region_name + ', ';
							}
							else
							{
								str += item.product_custom_location + ', ';
							}							
							
							str += item.product_country_name + '</p>'; 
							
							
							return str;
						}						
					}
		
		
		$('input.live-search').autocomplete(
				'/services/livesearch/',opts).result(
						function(e, item)
						{
							if($("select#search-country-id").length >= 1)
							{
								location.href = '/trip-elated/review/' + item.latest_review_id;
							}
							else
							{
								$("input#product_id").val(item.product_id);
								$("input#product_name").val(item.product_name);
								$("input#product_website").val(item.product_website);
								$("select#product_type_id").val(item.product_type_id).change();
								//alert(item.product_custom_location)
								if(item.product_custom_location != null)
								{
									$("input#product_custom_location").val(item.product_custom_location);
									$("input#product_custom_location").attr('readonly', 'true');
								}
								else
								{
									$("input#product_custom_location").removeAttr('readonly');
								}
								//need to set these as no way of chaining events.
								tmpProductCityId = item.product_city_id;
								tmpProductRegionId = item.product_region_id;
								
								$("select#product_country_id").val(item.product_country_id);
								$("select#product_country_id").change();								
							}
						}
						
				);
	}
}

function PositionHighlight()
{
	if($("a.spl_lnk1").length)
	{
		var refElementPosition = $("a.spl_lnk1").position();
		var highlightElement = $("img#whats-new-highlight");
		var horizPad = 10;
		var vertPad = 24;		
		var availWidth = refElementPosition.left - (horizPad * 2) ;
	
		if(availWidth >= highlightElement.width())
		{
			highlightElement.css('left', parseInt(refElementPosition.left - horizPad) - highlightElement.width() + 'px');
			highlightElement.css('top', parseInt(refElementPosition.top + vertPad) + 'px');
			highlightElement.fadeIn();
		}
		else
		{
			highlightElement.fadeOut();
		}
	}
}

$(window).resize(
		function()
		{
			PositionHighlight();
		}
);

function SetupBestPartEvents()
{
	if($('select#reviewer_option_id').length > 0)
	{
		$('select#reviewer_option_id').change(
				function()
				{
					var id = this.options[this.selectedIndex].value;
					$('div.field-group ul li:hidden').show();
					if(id != null || id != '')
					{
						$('input#bestpart_' + id).removeAttr('checked');
						$('input#bestpart_' + id).parent().hide();
					}
				}
		);
	}
}

function SetupYourLocationEvents()
{
	if($('select#reviewer_country_id').length > 0)
	{
		$('select#reviewer_country_id').change(
				function()
				{
					$("select#reviewer_city_id option:gt(0), select#reviewer_region_id option:gt(1)").remove();
					PopulateRegionListWithDataFromCountry('reviewer_region_id',this.options[this.selectedIndex].value);
				}
		);
	}

	if($('select#reviewer_region_id').length > 0)
	{
		$('select#reviewer_region_id').change(
				function(data)
				{
					var val = this.options[this.selectedIndex].value;
					
					if(val == 'CUSTOM')
					{
						ResetProductLocationFields(3, 'reviewer');
					}
					else
					{
						PopulateCitiesListWithDataFromRegion('reviewer_city_id', this.options[this.selectedIndex].value);
					}
				}
		);
	}	
}

function SetupAccomLocationEvents()
{
	if($('select#product_country_id').length > 0)
	{
		$('select#product_country_id').change(
				function(data)
				{
					$("select#product_city_id option:gt(0), select#product_region_id option:gt(1)").remove();
					PopulateRegionListWithDataFromCountry('product_region_id',this.options[this.selectedIndex].value);
				}
		);
	}

	if($('select#product_region_id').length > 0)
	{
		$('select#product_region_id').change(
				function()
				{
					var val = this.options[this.selectedIndex].value;
					
					if(val == 'CUSTOM')
					{
						ResetProductLocationFields(3, 'product');
					}
					else
					{
						PopulateCitiesListWithDataFromRegion('product_city_id',val);
					}
				}
		);
	}	
	
	if($("select#product_city_id").length > 0)
	{
		$("select#product_city_id").change(
				function()
				{
					$("input#product_custom_location").val('');
				}
		)
	}
}

function SetupSearchEvents()
{
	if($('form#searchForm').length > 0)
	{
		
		$('form#searchForm select').change(
				function(data)
				{
					$("form#searchForm").submit();
				}
		);
	}
}


function CreateElementWithValText(elType,value,text)
{
	var opt = $(document.createElement(elType));
	opt.val(value);
	opt.text(text);
	opt.val(value);
	return opt;
}

function PopulateRegionListWithDataFromCountry(listId, refId)
{
	PopulateLocationList("/services/locations/get_regions_by_country/" + refId, listId, null, null);
}

function PopulateCitiesListWithDataFromRegion(listId, refId)
{
	PopulateLocationList("/services/locations/get_cities_by_region/" + refId, listId, 'Not Applicable', '0');
}

function ResetProductLocationFields(state, pf)
{
	switch(state)
	{
		case 1:
			$('select#' + pf + '_region_id').parent().slideUp();
			$('select#' + pf + '_region_id').val('');
			$('select#' + pf + '_city_id').parent().slideUp();
			$('select#' + pf + '_city_id').val('');
			$('div#' + pf + '-custom-location-box:hidden').slideDown();
			break;
		case 2:
			$('select#' + pf + '_region_id:hidden').parent().slideDown();
			$('select#' + pf + '_city_id:hidden').parent().slideDown();
			$('div#' + pf + '-custom-location-box').slideUp();
			$('div#' + pf + '-custom-location-box').val('');
			break;
		case 3:
			$('select#' + pf + '_city_id').parent().slideUp();
			$('div#' + pf + '-custom-location-box:hidden').slideDown();
			break;
		case 4:
			$('select#' + pf + '_city_id:hidden').parent().slideDown();
			$('div#' + pf + '-custom-location-box').slideUp();		
			$('div#' + pf + '-custom-location-box').val('');
			break;
			
	}

}

function PopulateLocationList(jsonURL, listId, blankText, blankValue)
{
	var selector = "select#" + listId;
	var el = $(selector);
	$(selector + " option").remove();
	
	el.append(CreateElementWithValText("option", "", "Please wait..."));
	
	$.getJSON(jsonURL, 
			function(data,textStatus)
			{
				
				if(textStatus == "success");
				{
					ePrefix = listId.match('^(.*?)_')[1] 
					
					$(selector + " option").remove();

					if(blankText != null && data.length == 0)
					{
						el.append(CreateElementWithValText("option", blankValue, blankText));
					}
					else
					{
						el.append(CreateElementWithValText("option", "", "Please select..."));
					}
					
					if(listId == (ePrefix + '_region_id') && data.length == 0)
					{
						ResetProductLocationFields(1, ePrefix);
					}
					else if(listId == (ePrefix + '_region_id') && data.length > 0)
					{
						el.append(CreateElementWithValText("option", 'CUSTOM', 'Add Your Own Location'));
						el.append(CreateElementWithValText("option", '', '--------------------'));
						ResetProductLocationFields(2, ePrefix);
					}

					if(listId == (ePrefix + '_city_id') && data.length == 0)
					{
						ResetProductLocationFields(3,ePrefix);
					}
					else if(listId == (ePrefix + '_city_id') && data.length > 0)
					{
						ResetProductLocationFields(4, ePrefix);
					}

					$.each(data, function(i,item)
										{
											el.append(CreateElementWithValText("option", item.id, item.name));
										}
					);

					// we need to use the temporary variables set by the live query search box, 
					// to automatically query and set the related drop downs.
					// the temp variables are then null'd to prevent other event interference.
					if(tmpProductRegionId == null && tmpProductCityId != null)
					{
						$("select#product_city_id").val(tmpProductCityId);
						$("select#product_city_id").change();
						tmpProductCityId = null;
					}

					if(tmpProductRegionId != null)
					{
						$("select#product_region_id").val(tmpProductRegionId);
						$("select#product_region_id").change();
						tmpProductRegionId = null;
					}
				}
			}
	);
}


$(function(){ Bootstrap(); });

