// XO Private - main JavaScript functions

if(document.getElementById && document.getElementsByTagName) {
  document.write('<link rel="stylesheet" type="text/css" href="/stylesheets/js.css" media="screen" />');
}


/* Tracing function for jsTrace() - http://www.easy-designs.net/code/jsTrace/ */
function trace( msg ){
  if( typeof( jsTrace ) != 'undefined' ){
    jsTrace.send( msg );
  }
}

// Cancel default action
function stopEvent(e) {
  if (window.event) {
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  
  if (e && e.stopPropagation && e.preventDefault) {
    e.stopPropagation();
    e.preventDefault();
  }
}

// Image Preview
var ImagePreview = Tips.extend({
    start: function(el){
		this.wrapper.setHTML('<img src="/images/bg/loading.gif" />');
		
		var wrapper = this.wrapper;
		var src = el.src.replace(/-r1.jpg|-r2.jpg|-r3.jpg/, '-l.jpg'); 
		
		var image = new Image();
        image.src  = src;
		
		function showImage()  {
		   wrapper.setHTML('<img class="preview" src="' + image.src + '" />');
		}
		
		if (image.complete) {
		   showImage();
		} else {
		   image.onload = showImage;
		} 

        $clear(this.timer);
		this.timer = this.show.delay(this.options.showDelay, this);
	}
});

function initImagePreview() {
 var myTips = new ImagePreview($$('.thumb'));
}

// Resolution depended design
function checkSize() {

    if (!document.getElement) { 
        return;
    }

    var body = document.getElement('BODY');
	var w;
	
	// all except Explorer
    if (self.innerHeight) {
        w = self.innerWidth;
    
    // Explorer 6 Strict Mode
    } else if (document.documentElement && document.documentElement.clientHeight) {
        w = document.documentElement.clientWidth;
    
    // other Explorers
    } else if (document.body) {
        w = document.body.clientWidth;
    }

    // Change layout depending on browser window size
    if (w < 995) {
		body.addClass('narrow-layout'); 
    } else {
	    body.removeClass('narrow-layout'); 
	}
}

function initEmptyFields() {
	emptyField('search-txt');
	emptyField('search-txt2');
	emptyField('email');
	emptyField('search-term');
}

function emptyField(field) {
	if (!$(field)) { 
        return;
    }

    $(field).onfocus = function() {
        if (field != "search-txt" && field != "search-txt2" && field != "search-term") {
          $(field).value = "";
        } else if ($(field).value == "Enter your search keyword(s)") {
          $(field).value = "";
        }
    }
	
	if (field == "search-txt") {
		$("search").onsubmit = function(e) 
		{
			if ($(field).value == "Enter your search keyword(s)") {
				alert("Search Error\nPlease enter the search term before clicking on the Search button!");
				stopEvent(e);
			}
		}
	}	
	if (field == "search-txt2") {	
		$("search2").onsubmit = function(e) 
		{
			if ($(field).value == "Enter your search keyword(s)") {
				alert("Search Error\nPlease enter the search term before clicking on the Search button!");
				stopEvent(e);
			}
		}
	}
}

function getAreaName(url) {
	var arr = url.split("/");
    var href = arr.pop();
        
	if (href == "") {
	  href = arr.pop();
    }
		
    return href.split("#").pop();
}

function initMap() {

    if (!$('map')) {
		return;
	}
	
	var areas = $$('AREA');
	var map = $('map');
	var map_alt = map.getProperty('alt');
	var src = map.src;
	var map_area = $('map-area');

    areas.each(function(el, i) {

      var area_name = getAreaName(areas[i].href);
	  
	  // Preload images
	  var over_image = new Image();
	  over_image.src = '/images/maps/over/' + area_name + '.gif)';
	  
	  areas[i].onmouseover = function() {
		
		var href = getAreaName(this.href);
		
        if (href == 'russian-federation' && map_alt == 'Far East') {
		   var image_src = '/images/maps/over/russian-federation-far-east.gif';
		} else {
		   var image_src = '/images/maps/over/' + href + '.gif';
		}

		map.src = image_src;
      };
	  
	  areas[i].onmouseout = function() {
		map.src = src;
      };
	  
	  areas[i].onclick = function() {
 	    location.href = this.href;
		initProfiles();
      };
    });
}

function removeLoadingMap() {
	
	if (!$('map-area')) {
		return;
	}
	
    var map_area = $('map-area');
	map_area.removeClass('loading-map');
}

// Hover effect on random profile links
function initRandoms() {
	var random_images = $$('.random_image');
	var random_links = $$('.random_link');
	
	random_images.each(function(el, i) {
       random_images[i].onmouseover = function() {
		   random_links[i].addClass('hover');
	   };

	   random_images[i].onmouseout = function() {
           random_links[i].removeClass('hover');
	   };
    });
}

// Hover effect profile card images
function initProfileCards() {
	var profile_cards = $$('.profile-card');
	
	profile_cards.each(function(el, i) {
       profile_cards[i].onmouseover = function() {
		   profile_cards[i].getElements('a').addClass('hover');
	   };
	   
	   profile_cards[i].onmouseout = function() {
		   profile_cards[i].getElements('a').removeClass('hover');
	   };
    });
}


// Opening / closing profiles in list
function initProfiles() {
	var profiles_links = $$('.profiles-link');
	var profiles_wrappers = $$('.profiles-wrapper');
	
	var path = location.href;
    var path_parts = path.split("#");
	
	profiles_links.each(function(el, i) {
	   
       if(profiles_links[i].getProperty('id') == path_parts[1] && path_parts[1] != undefined) {
		   closeAllProfiles(profiles_wrappers, i);
		   loadProfilesImages(profiles_wrappers[i]);
           profiles_wrappers[i].toggleClass('display');
		   profiles_wrappers[i].getParent().toggleClass('displayed');
       }
								 
       profiles_links[i].onclick = function(e) {
		   closeAllProfiles(profiles_wrappers, i);
		   loadProfilesImages(profiles_wrappers[i]);
		   profiles_wrappers[i].toggleClass('display');
		   profiles_wrappers[i].getParent().toggleClass('displayed');
		   stopEvent(e);
	   };
    });
}

function loadProfilesImages(profile_wrapper) {
	var images = $ES('img', profile_wrapper);

	images.each(function(el, i) {
        var a = images[i].getParent();
		var area = getAreaName(a.href);
		images[i].src = images[i].src.replace(/load-small.gif/, area + '-r1.jpg');
    }); 
}

function closeAllProfiles(elements, current) {
	for (var i = 0; i < elements.length; i++ ) {
		if (i != current) {
		   elements[i].removeClass('display');
		   elements[i].getParent().removeClass('displayed');
		}
	}
}

function initSentToFriend()
{
	if (!$('send-to-friend')) {
		return;
	}
	
	var send_form = $('send-to-friend');
    var send_link = $('send-to-friend-link');
	var close_link = $('close-send-to-friend');

    var from_name  = $("your-name");
    var from_email = $("your-email");
    var to_name = $("friend-name");
    var to_email = $("friend-email");

    send_link.onclick = function(e) {
		send_form.toggleClass('showed');
		send_form.setStyle('left', this.getLeft() + 'px');
		
		var top = this.getTop() + 35;
		
		send_form.setStyle('top', top + 'px');
		$E('body').appendChild(send_form);

		stopEvent(e);
    };
	
	send_form.onsubmit = function(e) {
        
        var validated = true;
       
        if (!checkFill(from_name)) {
            validated = false;    
        }
        
        if (!checkFill(from_email)) {
            validated = false;    
        } else {
            if (!checkEmail(from_email)) {
                validated = false;
            }
        }
        
        if (!checkFill(to_name)) {
            validated = false;
        }
        
        if (!checkFill(to_email)) {
            validated = false;
        } else {
            if (!checkEmail(to_email)) {
                validated = false;
            }
        }
        
        if (validated) {
			this.send();
            alert('The postcard from ' + from_name.value + ' <' + from_email.value + '> will be sent to\n ' + to_name.value + ' <' + to_email.value + '>. Thank you.');
			send_form.removeClass('showed');
            return false;
        } else {
            return false;
        }
        
    }
	
	close_link.onclick = function(e) {
		send_form.removeClass('showed');
		stopEvent(e);
	}
	
	from_name.onchange = function() {
        checkFill(this);
    }
    
    from_email.onchange = function() {
        if(checkFill(this)) {
            checkEmail(this);
        }
    }
    
    to_name.onchange = function() {
        checkFill(this);
    }
    
    to_email.onchange = function() {
        if(checkFill(this)) {
            checkEmail(this);
        }
    }
}

// Check if field is not empty
function checkFill(input) {
    
    // Append error if field is empty
    if (input.value == '') {
        removeError(input);
        appendError(input, 'Field cannot be empty')
        return false;
        
    // Remove error if field filled
    } else {
        removeError(input);
        return true;
    }
}

function checkEmail(input) {
    
    var pattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.([a-zA-Z]{2,4})$/;
    
    // Append error if email is not in correct format   
    if (pattern.exec(input.value) == null) {
        removeError(input);
        appendError(input, 'Email is not in correct format')
        return false;
    // Remove error if     
    } else {
        removeError(input);
        return true;    
    }
}

/**
 * Append error message to table cell with input
 * @param object t input element
 * @param string err_mess error message
 */  
function appendError(t, err_mess) {
    
    // Get table cell in which is input element
    while (t.nodeName.toLowerCase() != 'td') {
        var t = t.parentNode;
    }
    
    // Check if there are any errors elements already appended to table cell
    var spans = t.getElementsByTagName('span');
    if (spans.length > 0) {
        return;
    }
    
    // Create new error element
    var span = document.createElement('span');        
    span.innerHTML = err_mess;
    t.appendChild(span);
}

/**
 * Remove all error elements from table cell
 * @param object t input element
 */  
function removeError(t) {
    
    // Get table cell in which is input element
    while (t.nodeName.toLowerCase() != 'td') {
        var t = t.parentNode;
    }
    
    // Get all SPANs
    var span = t.getElementsByTagName('span');
   
    for(var i = 0; i < span.length; i++) {
        t.removeChild(span[i]);    
    }
}


// Random profiles
function initRandomProfiles() {
	
	if (!$('random-profiles-link')) {
		return;
	}
	
	var random_profiles_link = $('random-profiles-link');
	var path = location.pathname.split('/');
	
	random_profiles_link.onclick = function(e) {
	  var p2='';
	  var p3='';

	  if (path[2]) p2='/' + path[2];
	  if (path[3]) p3='/' + path[3];
	  // neslo by tam dat rovnou path od 1. / dal ? (muki)
	  var myAjax = new Ajax('/random-profiles/' + path[1] + p2 + p3, {update: 'random-profiles'}).request();
	  stopEvent(e);
	}
}

function initPrint() {
  
  var print_links = $$('a.print');
  
  print_links.each(function(el, i) {
    print_links[i].onclick = function(e) {
	  if (confirm('Page will be formatted for print and printed')) {
        window.print();
      }	
	  stopEvent(e);
	}
  });
}

function initDisableSubmit() {
  
  var submits = $$('input.submit');
  
  submits.each(function(el, i) {
    submits[i].onclick = function(e) {
	  this.src = this.src.replace(/.gif/, '_d.gif'); 
      this.disabled = true;
	  
	  var element = this;
	  
	  while (element.nodeName.toLowerCase() != 'form') {
        var element = element.getParent();
      }
      
	  element.submit();
	}
  });
}

// Slideshow
var XOSlideshow = Slideshow.extend({
	
	loaded: function() {
		
		if (this.ul) {
			anchors = $ES('a[name]', this.ul);
			anchors.each(function(a, i) {
				if (i == this.curr[0]) { a.addClass(this.props.classes[2]); }
				else { a.removeClass(this.props.classes[2]); }
			}, this);
		}

		this.direction = 'left';
		this.curr[0] = (this.curr[0] == this.props.images.length - 1) ? 0 : this.curr[0] + 1;
		this.curr[1]++;
		this.timer[0] = (new Date).getTime() + this.props.duration[1] + ((this.props.type.test(/fade|push|wipe/)) ? this.props.duration[0] : 0);
		this.timer[1] = (new Date).getTime() + this.props.duration[0];

		this.loader = new Image();
		this.loader.src = this.props.hu + this.props.images[this.curr[0]].trim();
		
		if (this.curr[1] != this.loopsNum) {
		  this.preload();
		}
	}
});

function initSlideshow() {
	
  if (!$('slideshow')) {
		return;
  }
	
  myShow = new XOSlideshow('slideshow', {hu: 'images/slideshows/', duration: [2500, 6000], images: slideshow_images, captions: slideshow_captions});
  myShow.loopsNum = Math.floor(Math.random() * 10) + 10;
}

function initBookSlideshow() {

  if (!$('book-slideshow')) {
		return;
  }
	
  myShow = new Slideshow('book-slideshow', {hu: '/images/book/the-private-collection/', duration: [2500, 6000], images: ['a-jia-hotel.jpg','boulders-safari-camp.jpg','buddha-bar-hotel-prague.jpg','capella-singapore.jpg','cuixmala.jpg','estancia-vik-jose-ignacio.jpg','inkaterra-la-casona.jpg','lesic-dimitri-palace.jpg','loisaba-star-beds.jpg','ms-prince-de-neufchatel.jpg','alila-villas-hadahaa.jpg','villa-aquamare.jpg','villa-babar.jpg']});
}

var XO = {

    /**
     * Insert overlay
     */         
    insertOverlay: function () {
        var overlay = new Element('div');
        overlay.id = 'overlay';
        overlay.setStyle('height', window.getScrollHeight() + 'px');
        overlay.setOpacity(0);
        $E('body').appendChild(overlay);
        
        var overlay_inner = new Element('div');
        overlay_inner.id = 'overlay-inner';
        overlay_inner.setStyle('height', window.getScrollHeight() + 'px');
        $E('body').appendChild(overlay_inner);
    },
    
    /**
     * Hide overlay
     */         
    hideOverlay: function () {
        var fade = $('overlay').effect('opacity', {duration: 300, transition: Fx.Transitions.linear});
        fade.start(1.0, 0).addEvent('onComplete', function() {
            $('overlay').remove();
            $('overlay-inner').remove();
        });
    }
}

/**
 * XO Google map
 */ 
XO.Location = {
    
    init: function () {
        if (!$('location')) {
            return;
        }
       
        $$('#location p a').each(function (el, i) {
            el.onclick = function (e) {
                XO.insertOverlay();
                var top = window.getScrollTop() + 10;
                var fade_overlay = $('overlay').effect('opacity', {duration: 600});
                var height = window.getHeight() - 30;
                fade_overlay.start(0, 0.8).addEvent('onComplete', function() {
                    
                    $('overlay-inner').setHTML('<div id="map-wrapper"><div id="map" style="width: 90%; height: 90%"></div><ul class="nav"><li class="close"><a href="#" title="Close map" id="map-close"><img src="/images/buttons/gallery-close.gif" alt="Close" width="18" height="18" /></a></li></ul></div>');
                    $('map-wrapper').setStyle('top', top + 'px');
                    $('map-wrapper').setStyle('height', height + 'px');
                    $('map').setStyle('height', 90 + '%');
                    // XO.Location.fadeInMap();
                    XO.Location.initMap();
                    XO.Location.closeMap(); 
                });
                stopEvent(e);
            }
        });          
    },
    
    /**
     * Fade in map
     */         
    fadeInMap: function (i) {
        $('map').setStyle('opacity', 0);
        var fade = $('map').effect('opacity', {duration: 500});
        fade.start(0, 1.0);
    },    
    
    closeMap: function () {
        $('map-close').onclick = function (e) {
            var fade = $('map').effect('opacity', {duration: 300, transition: Fx.Transitions.linear});
            fade.start(1.0, 0).addEvent('onComplete', function() {
                $('map-wrapper').remove();
                XO.hideOverlay();
            });            
            stopEvent(e);
        }
    },
    
    initMap: function () {
        if (GBrowserIsCompatible()) {
            var clat = $('clat').innerHTML;
            var clng = $('clng').innerHTML;
            var lat = $('lat').innerHTML;
            var lng = $('lng').innerHTML;
            var zoom = $('zoom').innerHTML;
            if (!zoom) {
                zoom = 17;     
            }
            map = new GMap2(document.getElementById("map"));
            map.setCenter(new GLatLng(clat, clng), zoom * 1);
            
            //Add controls to the map
            map.addControl(new GScaleControl());
            map.addControl(new GLargeMapControl());
            map.addControl(new GMapTypeControl());
            
            centerBeforeMove = map.getCenter();
		    GEvent.addListener(map, "moveend", moveEnd);
		    GEvent.addListener(map, "zoomend", zoomEnd);
		    doSearch();
        }
    }
}

/**
 * XO Private Lightbox Style Gallery
 */ 
XO.Gallery = {
    
    images: Array,
    current: 1,
    
    init: function () {
        if (!$('photos')) {
            return;
        }
        
        $$('#photos li a').each(function (el, i) {
            el.onclick = function (e) {
                XO.Gallery.images = $$('#photos li a');
                XO.Gallery.current = i;
                XO.insertOverlay();
                var top = window.getScrollTop() + 50;
                var fade_overlay = $('overlay').effect('opacity', {duration: 600});
                fade_overlay.start(0, 0.8).addEvent('onComplete', function() {
                    $('overlay-inner').setHTML('<div id="gallery"><div class="photo"> <img src="' + XO.Gallery.images[XO.Gallery.current].href + '" alt="Gallery image" id="gallery-image" /> </div><ul class="nav"> <li class="prev"><a href="#" title="Previous image" id="gallery-prev"><img src="/images/buttons/gallery-prev.gif" alt="Previous" width="18" height="18" /></a></li> <li class="next"><a href="#" title="Next image" id="gallery-next"><img src="/images/buttons/gallery-next.gif" alt="Next" width="18" height="18" /></a></li><li class="close"><a href="#" title="Close gallery" id="gallery-close"><img src="/images/buttons/gallery-close.gif" alt="Close" width="18" height="18" /></a></li> </ul></div>');
                    $('gallery').setStyle('top', top + 'px');
                    XO.Gallery.fadeInImage(i);
                    // Previous, Next and Close link handlers
                    XO.Gallery.previousImage();
                    XO.Gallery.nextImage();
                    XO.Gallery.closeGallery(); 
                    if (XO.Gallery.current === 0) {
                        $('gallery-prev').addClass('hide');
                    }
                    
                    if (XO.Gallery.current === XO.Gallery.images.length - 1) {
                        $('gallery-next').addClass('hide');
                    }                
                });
                stopEvent(e);
            }
        });
    },
    
    /**
     * Fade in image
     */         
    fadeInImage: function (i) {
        $('gallery-image').src = XO.Gallery.images[i].href;
        $('gallery-image').setStyle('opacity', 0);
        var fade = $('gallery-image').effect('opacity', {duration: 500});
        fade.start(0, 1.0);
    },
    
    /**
     * Fade out image
     */         
    fadeOutImage: function () {
        var fade = $('gallery-image').effect('opacity', {duration: 300});
        fade.start(1.0, 0);
    },    
    
    
    /**
     * Display image
     */          
    displayImage: function (i) {
        // fade in current image
        $('gallery-image').src = XO.Gallery.images[i].href;
    },
    
    previousImage: function () {
    
        $('gallery-prev').onclick = function (e) {
            
            XO.Gallery.current = XO.Gallery.current - 1
            var prev = XO.Gallery.current - 1;
            
            // If there is no other image before this one don't display previous link
            if (XO.Gallery.images[prev] === undefined) {
                $('gallery-prev').addClass('hide');
            }
            
            $('gallery-next').removeClass('hide');
            
            // Display prev
            XO.Gallery.displayImage(XO.Gallery.current);
            stopEvent(e);
        }
    },

    nextImage: function () {
        $('gallery-next').onclick = function (e) {
            
            XO.Gallery.current = XO.Gallery.current + 1
            var next = XO.Gallery.current + 1;

            // If there is no other image after this one don't display next link
            if (XO.Gallery.images[next] === undefined) {
                $('gallery-next').addClass('hide');
                
            } 
            $('gallery-prev').removeClass('hide');
            
            // Display next image           
            XO.Gallery.displayImage(XO.Gallery.current);
            stopEvent(e);
        }
    },
    
    closeGallery: function () {
        $('gallery-close').onclick = function (e) {
            var fade = $('gallery-image').effect('opacity', {duration: 300, transition: Fx.Transitions.linear});
            fade.start(1.0, 0).addEvent('onComplete', function() {
                $('gallery').remove();
                XO.hideOverlay();
            });            
            stopEvent(e);
        }
    }
}

/**
 * XO Private Tabs navigation
 */ 
XO.Tabs = {
    
    /**
     * Init function
     */         
    init: function () {
        if (!$('tabs')) {
            return;
        }
        XO.Tabs.switchOnClick();
        XO.Tabs.switchFromUrl();
    },

    /**
     * Switch tabs on click
     */         
    switchOnClick: function () {
        $$('#tabs-nav a').each(function (el, i) {
            el.onclick = function (e) {
        	    if (id = XO.Tabs.getId(el.getProperty('href'))) {
                    location.hash = id;
                    XO.Tabs.switchTabs(id);
                }        	    
        	    stopEvent(e);
        	}
        });    
    },

    /**
     * Switch tabs if an on page anchor in URL is defined (eg. /kulm-hotel/#description)
     */         
    switchFromUrl: function () {
        if (id = XO.Tabs.getId(location.href)) {
            XO.Tabs.switchTabs(id);
        }
    },
    
    /**
     * Get id from url
     */         
    getId: function (link) {
        var url_parts = link.split('#');
        if (url_parts[1]) {
            return url_parts[1];
        } else {
            return false;
        }
    },

    /**
     * Switching tabs functionality
     */         
    switchTabs: function (id) {
        // Deselect all tabs links, then select current
        $$('#tabs-nav li').removeClass('selected');
	    // $('tabs-nav').getElements('a[href=#' + id + ']').getParent().addClass('selected');
	     
	    $$('#tabs-nav a').each(function (el, i) {
	        var link_id = XO.Tabs.getId(el.href);
	        if (link_id === id) {
                el.getParent().addClass('selected');
                return;
            }
	    }); 
	    
	    // Hide all tabs, then display selected
        $$('#tabs .tab').removeClass('displayed-tab');
	    $(id).addClass('displayed-tab');
    }
}

window.addEvent('load', checkSize);
window.addEvent('resize', checkSize);
window.addEvent('load', initEmptyFields);
window.addEvent('load', initImagePreview);
window.addEvent('load', initMap);
window.addEvent('load', initRandoms);
window.addEvent('load', initProfiles);
window.addEvent('load', initProfileCards);
window.addEvent('load', initSentToFriend);
window.addEvent('load', initRandomProfiles);
window.addEvent('load', initPrint);
window.addEvent('load', initSlideshow);
window.addEvent('load', initBookSlideshow);
window.addEvent('load', removeLoadingMap);
window.addEvent('load', XO.Gallery.init);
window.addEvent('load', XO.Tabs.init);
window.addEvent('load', XO.Location.init);

// window.addEvent('load', initDisableSubmit);
