// Constants
var INFO_PANEL_OPACITY = 0.70;
var TIP_THUMB_FADE_SPEED = 100; 
var BOOKING_ANIM_SPEED = 200;
var START_FEATURE_ANIM_SPEED = 200;

var run_start_slideshow = 1;

var lang;

// Keep track of the start page featured tip content.
var start_featured_tips = Array();

var start_inited = false;

// React to a change to the start page slideshow - update the title and date text.
function onStartAfter(curr, next, opts) {
    if (start_inited) {
    	$('div#start_feature_main_info').animate({top: 0}, START_FEATURE_ANIM_SPEED);
    } else {
    	start_inited = true;
    }
    var index = opts.currSlide;
    $('div#start_feature_main_title > a').html(start_featured_tips[index][0]);
    $('div#start_feature_main_title > a').attr("href", start_featured_tips[index][1])
    $('div#start_feature_main > a').attr("href", start_featured_tips[index][1])
    $('div#start_feature_main_date').text(start_featured_tips[index][2]);
    $('div#start_feature_main_dest').text(start_featured_tips[index][3]);
}

function onStartBefore(curr, next, opts) {
	if (start_inited) {
		$('div#start_feature_main_info').animate({top: 77}, 0);
	}
}

// Get IE6 PNG24 transparency working.
function transpPNGie6 () {
	$('img.transp_png').supersleight({shim: '/static/img/transp.gif'});
}

//Show and hide tip thumbs and their backgrounds when hovered.
function initTipHover() {

	$('div.tip_thumb').hover(
			function(){
				$('div.tip_thumb_hover', this).fadeIn(TIP_THUMB_FADE_SPEED);
				$('div.tip_thumb_hover_bg', this).fadeIn(TIP_THUMB_FADE_SPEED);
			},
			function(){
				$('div.tip_thumb_hover', this).fadeOut(TIP_THUMB_FADE_SPEED);
				$('div.tip_thumb_hover_bg', this).fadeOut(TIP_THUMB_FADE_SPEED);
			} 
		);
}

function init_dialog(div, p_width, p_title) {
	
	div.dialog({
		width: p_width,
		autoOpen: false,
		resizable: false,
		draggable: true,
		modal: true,
		closeText: "",
		stack: false,
		title: p_title
	});
}

function setup_share_links(container, url) {
	url = encodeURIComponent(url);
	var title = encodeURIComponent('redguide');
	container.find('a.share_twitter').attr(
		"href", "http://twitter.com/?status=redguide+" + url);
	container.find('a.share_facebook').attr(
		"href", "http://www.facebook.com/share.php?u=" + url);
	container.find('a.share_digg').attr(
		"href", "http://digg.com/submit?url=" + url + "&title=" + title);
	container.find('a.share_stumbleupon').attr(
		"href", "http://www.stumbleupon.com/submit?url=" + url + "&title=" + title);
	container.find('a.share_delicious').attr(
		"href", "http://www.delicious.com/save?v=5&noui&url=" + url + "&title=" + title);
	container.find('a.share_myspace').attr(
		"href", "http://www.myspace.com/Modules/PostTo/Pages/?u=" + url + "&t=" + title);
	container.find('a.share_reddit').attr(
		"href", "http://reddit.com/submit?url=" + url + "&title=" + title);
	container.find('a.share_linkedin').attr(
		"href", "http://www.linkedin.com/shareArticle?mini=true&url=" + url + "&title=" + title);
}

// All jQuery functions.
jQuery(function() {
	
	// focus first input element of content_standard
	$('#content_standard').find(':input:visible:enabled:first:not("#id_note")').focus();
	
	// Set opacity of info panels.
	$('div.info_panel_bg').css('opacity', INFO_PANEL_OPACITY);
	
	// Get IE6 PNG24 transparency working.
	transpPNGie6();
	
	// Hide the start menu arrows if navigating away (to avoid problems with back button.)
	$(window).unload(function() {
		$('img.start_menu_arrow').hide();}
	);
	
	// Show and hide the start menu arrows.
	$('a.start_menu_item').hover(
		function(){
			$(this).prev().show();
		},
		function(){
			$(this).prev().hide();
		} 
	);
	
	initTipHover()
	
	$('div#share_off').hover(
		function() {
			$('div#share_off').hide();
			$('div#share_on').css('height', '35px');
	});

	$('div#share_on').hover(
		null, function() {
			$('div#share_on').css('height', '0px');
			$('div#share_off').show();
		}
	);
	
	$('a.share_anchor').live('click', function() {
		
		url = $(this).attr("href");
		url_parsed = url.substring(url.indexOf('#') + 1);
		setup_share_links($('div#sharing_dialog'), url_parsed);
		
		link_offset = $(this).offset();
		link_offset_x = link_offset.left
		link_offset_y = link_offset.top
		var sharing_dialog = $('div#sharing_dialog');
		dialog_shift_x = 40;
		dialog_shift_y = 15;
		sharing_dialog.show();
		sharing_dialog.offset({left: link_offset_x - dialog_shift_x, top: link_offset_y - dialog_shift_y});
		return false;
	})
	
	$('div#sharing_dialog').hover(
		null, function() {
			$(this).hide();
		}
	);
	
	$('#id_search-query').titleAsLabel();
	
	$('a#search_check_all').click(function() {
		$('div#search_filter input').each(function() {
			$(this).attr('checked', true);
		})
	});
	
	$('a#search_uncheck_all').click(function() {
		$('div#search_filter input').each(function() {
			$(this).attr('checked', false);
		})
	});

	$("select#language_select").change(function() {
		$(this).parent('form').submit();
	});
	
	var bookingOpen = false;
	
	$("div.booking_city_cont, a.booking_drop_arrow").click(function() {
		if (!bookingOpen) {
			$('div#booking-form').css("overflow", 'visible');
			$('div#booking-form').animate({height: '285px'}, BOOKING_ANIM_SPEED);
			$('div#booking-form').css("border-color", '#EEEEEE');
			bookingOpen = true;
		}
	});
	
	function closeBooking() {
		if (bookingOpen) {
			$('div#booking-form').css("overflow", 'hidden');
			$('div#booking-form').animate({height: '40px'}, BOOKING_ANIM_SPEED);
			$('div#booking-form').css("border-color", 'white');
			bookingOpen = false;
		}
	}
	
	/* close the booking form if we click the close link. */
	$('a#booking_close').click(function() {
		closeBooking();
	});
	
	/* close the booking form if we click outside the booking layer. */
	$('div#booking-form').bind("clickoutside", function(event){
		
		/*closeBooking();*/
	});
	
	$('h1.flip').hover(
		function() {
			$(this).css('background-color','white');
			$(this).find('a').css('color','black');
		}, 
		function() {
			$(this).css('background-color','black');
			$(this).find('a').css('color','white');
		}
	);
	
	$('div.drop_down_header').hover(
		function() {
			$(this).parent('div.drop_down').css('height', 'auto');}
	);
	
	$('div.drop_down').hover(
		function() {}, function() {
			var height = $(this).attr('id').indexOf('dest') != -1 ? "20px" : "30px";
			$(this).css('height', height);
		}
	);
	
	$('div.dest_main_header').hover(
		function() {
			$('div#dest_main_content').show();
	});
	
	$('div#dest_main_content').hover(
		function() {}, 
		function() {
			$(this).hide();}
	);
	
	var map_holder = $('div#dest_map');
	
	map_holder.bind('mapinitialized', function (event, map) {
		var mainControl = new GLargeMapControl3D();
		var posMainControl = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,40));
		map.addControl(mainControl, posMainControl);
		
		var posMapTypes = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,10));
		var typeControl = new GMapTypeControl();
		map.removeControl(typeControl);
		map.addControl(typeControl, posMapTypes);
		map.addMapType(G_HYBRID_MAP);
		map.addMapType(G_SATELLITE_MAP);
		map.addMapType(G_PHYSICAL_MAP);
	});
	if (map_holder.length) {
		var mapLat = $('input#map_lat').val()
		var mapLng = $('input#map_lng').val()
		var icon = null;
		var category = $('#map_icon_category').val();
		var tip_type = $('#map_icon_type').val();
		var mapZoom = parseInt($('input#map_zoom').val());
		map_holder.createMap({ 'lat': 43.6, 'lng': 3.8, 'zoom': 10 }, { 'defaultUi': false });

		if (category && tip_type) {
			icon = markerStore[tip_type + '/' + category];
		}
		var markerParams = {"lat": mapLat, "lng": mapLng, zoom: mapZoom, 
							icon:icon};

		map_holder.addMarker(
				markerParams, {"draggable": false}
		);

	}
	
	$('div.dest_map_hideable').hide();
	
	// access translatable text for the map show/hide button 
	var text_map = {
		"show": $('input#text_show_map').val(), 
		"hide": $('input#text_hide_map').val()
	};
	
	$('a#dest_feature_show_map_link').toggle(
		function() {
			$('div.dest_map_hideable').fadeIn();
			$('a#dest_feature_show_map_link').text(text_map.hide);
			$('img#dest_copyright_img').hide();
		}, 
		function() {
			$('a#dest_feature_show_map_link').text(text_map.show);
			$('div.dest_map_hideable').fadeOut();
			$('img#dest_copyright_img').show();
		}
	);
	
	$('td.dest_sub_menu').hover(
		function() {
			$(this).css('background-color','#E2E2E2');
		}, 
		function() {
			$(this).css('background-color','#F2F2F2');
		}
	);
	
	// Set up the start page slideshow.
	if (run_start_slideshow) {
		var start_feature_slideshow_div = $('div#start_feature_slideshow');
		
		start_feature_slideshow_div.cycle({
			pause: 1,
			delay: 0000,
			timeout: 6000,
			speed: 2000,
			before: onStartBefore,
			after: onStartAfter})
			
		// Stop slideshow on mouseover, resume on mouseout.
		$('div#start_feature_main').hover(
				function() {
					start_feature_slideshow_div.cycle('pause')
				},
				function() {
					start_feature_slideshow_div.cycle('resume')
				})
	}
	
	init_dialog($("#login_dialog"), "324px", "Login");
	$('#login_dialog').dialog({ 
		open: function (event, ui) {
					if (typeof(track) !== "undefined" && $.isFunction(track)) {
						track("Login", "Registration");
					}
				}
	});
	
	init_dialog($("#signup_dialog"), "600px", "Signup");
	$('#signup_dialog').dialog({ 
		open: function (event, ui) {
					if (typeof(track) !== "undefined" && $.isFunction(track)) {
						track("Registration", "Registration");
					}
				}
	});
	
	init_dialog($("#pwd_request_dialog"), "324px", "Password Request");
	
	// dialog submit button with close action.
	$('div.dialog input.close').click(function() {
		window.location = '.';
	});
	
	/* 
	 * This section handles clearing and restoring the 'title' field default text
	 * in the 'tip add' form on the profile page.
	 */
	
	var profile_tipadd_title_field = $('table.form_profile_tipadd input#id_title_short');
	var profile_tipadd_title_introtext = $('table.form_profile_tipadd input#title_intro');
	
	profile_tipadd_title_field.val(profile_tipadd_title_introtext.val());
	
	profile_tipadd_title_field.blur(function() {
		if (profile_tipadd_title_field.val() ==	'') {
			profile_tipadd_title_field.val(profile_tipadd_title_introtext.val());
		}
	});
			
	function profile_tipadd_check_clear() {
		if (profile_tipadd_title_field.val() ==	profile_tipadd_title_introtext.val()) {
			profile_tipadd_title_field.val('');
		}
	}
	
	profile_tipadd_title_field.click(function() {
		profile_tipadd_check_clear();
	});
	
	$('form#form_profile_addtip').submit(function() {
		profile_tipadd_check_clear();
		// if hashtag is present it isn't possible to reopen the dialog in certain browsers
		// so it's necessary to handle this situation
		if (location.href.indexOf("#") != -1) {
			// for mozilla
			location.assign(location.href.substr(0,location.href.indexOf("#")));
			// for chrome
			$(this).attr('action', location.href.substr(0,location.href.indexOf("#")));
		}
	});
	
	/* tip updated, update tip count. */
	
	$(document).bind('tip_updated', function () {
		$('#tab_tips_count').update();
	});
	
	var openDialog = function(dialog_id) {
		if ($(dialog_id).dialog('isOpen')) {
			return false;
		}
		
		// close all dialogs
		$('.ui-dialog-content').each(function () {
			var dialog = $(this);
			if (dialog.dialog('isOpen')) {
				dialog.dialog('close');
			}
		});
		
		// open dialog and focus first form element
		$(dialog_id).dialog('open').find(':input:visible:enabled:first').focus();
		
		return true;
	};

	// expects a structure like
	// <div id="some_id_2">
	//	...
	//		<div class="ajaxify"><a href="...
	//		<div class="ajaxify"><area href="...
	//	...
	// </div>
	$('.ajaxify').live('click', function () {
		var source = $(this);
		var button = $('[href]', source);
		if (!button.length && source.is('[href]')) {
			button = source;
		}
		var href = button.attr('href');
		
		$.ajax({ url: href,
				 cache: false,
				 success: function (data, textStatus, XMLHttpRequest) {
					source.update(transpPNGie6);
					source.trigger('tip_updated');
				 },
				 error: function(XMLHttpRequest, textStatus, errorThrown) {
					if (XMLHttpRequest.status === 403) {
						// updating login form from error response
						var data = $(XMLHttpRequest.responseText);
						$('#login_dialog form.login').empty()
							.append(data.find('form.login:eq(0)').contents());
						openDialog('#login_dialog');
					} else {
						window.location = href;
					}
				 }
				});
		return false;
	});
	
	// special handling for login form
	$('#login_dialog').load('/ form.login', function () {
		var proposed_username = '';
		var re_username = /[\?,&]username=([^&]*)/g;
		var re_result = re_username.exec(location.search)
		if (re_result && re_result.length > 1) {
			proposed_username = decodeURI(re_result[1]);
		}

		$('#login_dialog #id_login-username').val(proposed_username);
		$('#login_dialog form.login').bind('submit', function () {
			var form = $(this);
			var next = $('[name=next]', form).val();
			$.ajax({type: 'POST',
					url: form.attr('action'),
					data: form.serialize(),
					cache: false,
					success: function (data, textStatus, XMLHttpRequest) {
					
						/* close all dialogs */
						openDialog('');
						
						if (XMLHttpRequest.status === 205) {
							window.location.reload(true);
						} else if (XMLHttpRequest.status === 202 && next) {
							$.ajax({ url: next,
									 success: function () {
										location.hash = '';
										window.location.reload(true);
									 },
									 error: function () {
										window.location = next;
									 }
									});
						} else {
							window.location = next || '/accounts/profile/';
						}
						
						// hide login_dialog per default, if successfully logged in
					},
					error: function (XMLHttpRequest, textStatus, errorThrown) {
						var data = $(XMLHttpRequest.responseText);
						var contents = data.find('form.login:eq(0)').contents();
						if (contents.length) {
							form.empty()
								.append(contents);
						} else {
							window.location.reload(true);
						}
					}});
			return false;
		});
	});
	
	$(window).bind('hashchange load', function () {
		if ( location.hash ) {
			
			var dialog_id = location.hash + "_dialog";
			return openDialog(dialog_id);
		}
	});

	$('.ui-dialog-content').bind('dialogclose', function () {
		location.hash = '';
		$(this).update();
	});
	
	$('a, area').live('click', function () {
		var href = $(this).attr('href') + "_dialog";
		if (href.length > 0 && href[0] === '#') {
			return openDialog(href);
		}
		return true;
	});
	
	$('input.submit, input.submit_note').live('mouseover mouseout', function(event) {
		  if (event.type == 'mouseover') {
			  $(this).css('color', $(this).hasClass('submit_profile_addtip') ? 'white' : '#B40000');
		  } else {
			  $(this).css('color', $(this).hasClass('submit_profile_addtip') ? '#640000' : '#7A7A7A');
		  }
	});
	
	$('a#dest_copyright').toggle(
		function() {
			$('div#dest_copyright_text').fadeIn(TIP_THUMB_FADE_SPEED);
			$('div#dest_copyright_bg').fadeIn(TIP_THUMB_FADE_SPEED);
		}, function() {
			$('div#dest_copyright_text').fadeOut(TIP_THUMB_FADE_SPEED);
			$('div#dest_copyright_bg').fadeOut(TIP_THUMB_FADE_SPEED);
		}
	);
	
	var note_editing = false;
	
	$('div#profile_note_cont textarea').hover(
		function() {
			$(this).css('background-color', '#F7F7F7');
		}, 
		function() {
			if (!note_editing) {
				$(this).css('background-color', 'white');
			}
		}
	); 

	$('div#profile_note_cont textarea').click(
		function() {
			note_editing = true;
		}
	); 
	
	$('div#profile_note_cont textarea').bind("clickoutside", 
		function(event) {
			note_editing = false;
			$(this).css('background-color', 'white');
	});
	
	$('a.select_cover').click(function() {
		$(this).hide();
		$(this).parent().next().show();
		$(this).closest('div.select').css('z-index', '100');
	});
	
	$('a.drop_arrow').click(function() {
		$(this).parent().prev().show();
		$(this).closest('div.select').css('z-index', '100');
	});

	$('div.select').bind("clickoutside", function(event){
		$(this).find('a.select_cover').show();
		$(this).find('div.select_vals').hide();
		$(this).css('z-index', '0');
	});

	$('[class^=drop_val_]').click(function() {
		drop_val = $(this).attr('class');
		val =  drop_val.substring(drop_val.indexOf('drop_val_') + 9, drop_val.indexOf(' '));
		select = $(this).closest('div.select') 
		select.find('div.drop_cont span').text($(this).find('span').text());
		select.find('input').val(val);
		select.find('a.select_cover').show();
		select.find('div.select_vals').hide();
		select.css('z-index', '0');
	});
	
	$('[id^=lang_val_]').click(function() {
		lang_val = $(this).attr('id');
		lang =  lang_val.substring(lang_val.indexOf('lang_val_') + 9);
		$('input#language_select').val(lang);
		$(this).closest('form').submit();
	});
	
	$('a#pg_delete').click(function() {
		$(this).parent().hide();
		$('a#pg_delete_cancel').parent().show();
	})

	$('a#pg_delete_cancel').click(function() {
		$(this).parent().hide();
		$('a#pg_delete').parent().show();
	})
	
    var lang_datepicker = (lang == 'de' ? 'de' : '');
	
	$("input#departure_day, input#arrival_day").datepicker($.extend($.datepicker.regional[lang_datepicker], {
        'dateFormat': 'dd/mm/yy',
        'defaultDate': null,
        'changeMonth': true,
        'changeYear': true,
        'maxDate': '+1Y', 
        'minDate': '0Y',
        'showMonthAfterYear': false
    }));

});

