﻿
	$j(document).ready(function() {
		$j("a._blank").attr('target', '_blank');
		$j("img.absmiddle").attr('align', 'absmiddle');
		
		activateMap();
		activateSearchForm();
		activatePngFix();		
	});
	
	// -- Index --
		
	function activateIndexPage() {
		activateGallery();
		activateGarousel();
	}
	
	function activateGallery() {
		var $links = $j('.photo_link a');
		$links.bind('click', function(){			
			clearInterval(interval);
			$this = $j(this);
			$j('.vis').removeClass('vis');
			$j('img', $this).addClass('vis');						
			$j('.mainimg').fadeOut(function(){
				$j(this).remove();
			});
			
			var $a = $j('<a />').attr('href', $this.attr('rel')).addClass('mainimg').hide();
			var $img = $j('<img />').attr('src', $this.attr('href'));			
			$img.preload({
				'onFinish':function(){
					$a.prepend($img);
					$j('.photo').prepend($a);
					$a.fadeIn();
				}
			});
			
			activateAutoPlayGallery();			
			return false;
		});
		
		activateAutoPlayGallery();
	}
	
	var interval;	
	function activateAutoPlayGallery() {		
		interval = setInterval(function(){
			var $next = $j('.vis').parent().next();
			if($next && $next.is('a')) {
				$next.click();
			} else {
				$j('.photo_link a:first').click();
			}
		}, 5000);
	}
	
	function activateGarousel() {
		$object_carousel = $j('.carousel');
		$object_carousel.each(function(){
			$curr_carousel = $j(this);
			$curr_carousel.jcarousel({
				initCallback: function(carousel){ 
					$object_carousel.css({'visibility':'visible'}); 

					var $carusel_prev	= jQuery('.arrow_left');
					var $carusel_next	= jQuery('.arrow_right');				
					$carusel_prev.bind('click', function() {
						carousel.prev();
						return false;
					});					
					$carusel_next.bind('click', function() {
						carousel.next();
						return false;
					})
				},				
				animation: "slow",
				scroll: 2//,
				//buttonNextHTML: null,
				//buttonPrevHTML: null
			});		
		});
	}
	
	// -- Map --
	
	function activateMap() {
		var coordinates = new Array();
		coordinates['africa'] = -125;
		coordinates['asia'] = -250;
		coordinates['s_america'] = -375;
		coordinates['n_america'] = -500;
		coordinates['australia'] = -625;
		coordinates['europe'] = -750;		
		
		$j("#Map area").hover(function() {
			$j(".map_bg").css('background-position', '1px '+coordinates[$j(this).attr('id')]+'px'); 	
		}, function() {
			$j(".map_bg").css('background-position', 'left top');
		});
	}
		
	// -- Search --
	
	function activateSearchForm() {
		var $select_country = $j('#select_country');
		var $first_option = $j('#select_country option:first');		
		$j('#select_region').bind('change', function(){												
			var value = $j(this).val();
			if (value==0) {
				$select_country.empty().append($first_option);
				return;
			}						
			$j.ajax({ // $j.getJSON( 
	            url: "/search/getCountryJSON",
	            dataType: 'json',
	            timeout: 3000,
	            error: function(){ 
	                ajaxError();
	            }, 
	            success: function(json) {
					if (json.error) {
						alert(json.error);
						return;
					}															
					var $option = $j('<option />').attr('value', '').text('Countries not found');
					if( json.length>0 ){
						$select_country.empty().append($first_option);
						for (var i = 0; i < json.length; i++){
							$option = $j('<option />').val(json[i].id).text(json[i].country);
							$select_country.append($option);
						}									
					} else {
						$select_country.empty().append($option);
					}
				},
	            complete: function(){
	            }, 
	            // Parametrs
	            data: { regionID:value }
	        });			
		});
	}
		
	// -- Tours --
	
	function activateTours() {
		
		var $menu_links = $j('#center .menu a');
		var $tabContainers = $j('div#tab_container > div.fragment');
		
		$tabContainers.hide().filter(':first').show();
		$menu_links.bind('click', function () {
			if($j(this).hasClass('vis')) {				
				return;
			}
									
			var hash = this.hash;
			// Сначала присвеиваем хеш ( что бы избежать скачка по якорю )
			window.location.hash = hash;	
			$tabContainers.hide();
			$tabContainers.filter(hash).show();		
			$menu_links.removeClass('vis');
			$j(this).addClass('vis');						
			return false;
		})//.filter(':first').mouseover();*/
				
		if(window.location.hash) {			
			$j('a[href='+window.location.hash+']').click();
		}
						
		$j('.book_now').bind('click', function(){
			$j('#price_form').submit();
		});
	}
		
	function activateSentInvite() {
		var $inviteFormDiv = $j('#inviteFormDiv');
		var $inviteForm = $j('#inviteForm');		
		var $inviteResponseDiv = $j('#inviteResponseDiv');
		var $inviteSentMore = $j('#inviteSentMore');
		var $errorContainer = $j('div.errorContainer');
		
		$inviteForm.validate({
			onkeyup : false,
			//errorContainer : $errorContainer,
			//errorLabelContainer : $j("ol", $errorContainer),
			//wrapper : 'li',
			//errorPlacement : function(error, element) {
			//},
			rules : {
				//dateStart : "required",
				//dateEnd : "required"
			},
			messages : {
				//dateStart : "Please enter Date Start",
				//dateEnd : "Please enter Date End"
			},
			submitHandler: function(form) {				
				var request = $inviteForm.serialize();
				$inviteFormDiv.fadeOut();
				addAjaxIndicator($inviteResponseDiv);
				$inviteResponseDiv.fadeIn();
				
				$j.ajax({
		            url: "/tours/sent-invite",
		            type: 'post',
		            dataType: 'json',
		            timeout: 3000,
		            error: function(){ 
		                ajaxError();
		                $inviteFormDiv.fadeIn();
		            }, 
		            success: function(json) {
		            	var json = checkResponse(json);						
						if (json.error) {
							slideFlashMessanger(json.error);
							alert(json.error);
							$inviteResponseDiv.fadeOut(function(){
								$inviteFormDiv.fadeIn();
							});							
							return;
						}

						$inviteResponseDiv.empty();
						for (var i in json) {
							if (json[i].status == true) {
								$inviteResponseDiv.append('<p class="sent_status sent_ok">' + json[i].email + ' - Sent</p>');								
							} else {
								$inviteResponseDiv.append('<p class="sent_status sent_error">' + json[i].email + ' - Error</p>');
							}		
						}
						
						var $inviteSentMore = $j('<a href="javascript:void(0)" id="inviteSentMore">Sent more</a>');
						$inviteSentMore.bind('click', function(){
							$inviteResponseDiv.fadeOut(function(){
								$inviteResponseDiv.empty();
								$inviteFormDiv.fadeIn();
								//$inviteForm.reset();
							});							
						});
						$inviteResponseDiv.append($inviteSentMore);
		            	return false;			
					},
		            complete: function(){
		            }, 
		            // Parametrs
		            data: { 'request' : request }
		        });			
				return false;
			}
		});
	}
	
	// -- Gallery --
	
	function activateFancyGallery(){
		$j("a.gallery_thumbs").fancybox({
			'zoomOpacity'			: true,
			//'overlayShow'			: false,
			'zoomSpeedIn'			: 500,
			'zoomSpeedOut'			: 500,
			'overlayColor'			: '#000',
			'hideOnContentClick'	: false
        });
	}
	
	// -- Orders --
	
	function activateOrders() {
		$j('#number_of_people').bind('change', function(){
			if ($j(this).val()==2) {
				$j('#second_participant').slideDown();						
			} else {
				$j('#second_participant').hide();
			}
		});
		// При отправке формы с ошибками(без javascript) нужно вывести доп форму, если нужно
		$j('#number_of_people').change();
	}
	
	// -- Png fix --
	
	function activatePngFix() {
		// $j(".transparent, #footer").pngFix();
	}
			
	// -- Addithional --
	
	function slideFlashMessanger(message) {
		jQuery('#messages').hide();
		
		if(message) {
			jQuery('#messages ul li:first').html(message);
		}
		
		jQuery('#messages').slideDown();
	     setTimeout(function(){
	        jQuery('#messages').slideUp();
	    }, 3200);
	}
	
	function addAjaxIndicator(obj) {
		$j(obj).html('<img src="/images/ajax_load.gif" class="ajax_load" />');
	}
	
	function activateCalendar() {	
		// Календарь
		$j(".calendar-input").datepicker( {
			mandatory : true,
			yearRange : '1920:2020',
			dateFormat : $j.datepicker.ATOM // 'dd/mm/yy'
		}).attr("readonly", "readonly");
	
		$j(".calendar-image").bind('click', function() {
			$j(this).prev().focus();
		}).css("cursor", "pointer");
	}
			
	function ajaxError(){
		// alert("Ошибка при передаче данных! Попробуйте снова");
	}
	
	function reloadPage(){
		window.location.reload();
		return;
	}
	
	function checkResponse(json) {	
		if (typeof (json) == 'undefined') {
			// alert("Ошибка при передаче данных! Попробуйте снова");
			return false;
		}
			
		// var json = eval("(" + responseText + ")");	
		if (typeof (json) != 'object' && typeof (json) != 'array') {
			// alert("Ошибка при передаче данных! Попробуйте снова");
			return false;
		}
	
		return json;
	}
			
	function var_dump(obj) {
		  var result = null;
		  for (var i in obj)
		  result += 'object' + '.' + i + ' = ' + obj[i] + '\n';
		  return result;
	}
	 
	function activateblock(){
		$j.blockUI({ css: { 
            border: 'none', 
            padding: '15px', 
            backgroundColor: '#000', 
            '-webkit-border-radius': '10px', 
            '-moz-border-radius': '10px', 
            opacity: '.5', 
            color: '#fff'				
        }, overlayCSS:{'z-index': 1007} }); 
	}
	
	function deactivateblock(){
		$j.unblockUI();
	}
	
	function you_are_sure(str){
		return confirm(str);
	}
