﻿$(document).ready(function(){
    if ($('#flickr').length) {
        var flickrNext = $('#flickr-more');
        var flickrUserId = flickrNext.attr('href').replace('#', '');
        flickr.init(flickrUserId, $('#flickr'), flickrNext);
    }
    
    if ($('#useful-links').length) {
        var url = $('#useful-links p').text();
        $('#useful-links p').text(' ');
        $.ajax({
    		type: "GET",
    		url: url,
    		dataType: "xml",
    		success: function(xml) {
    			$(xml).find('link').each(function(){
    				var id = $(this).attr('id');
    				var title = $(this).find('title').text();
    				var url = $(this).find('url').text();
    				//$('<div class="items" id="link_'+id+'"></div>').html('<a href="'+url+'">'+title+'</a>').appendTo('#useful-links');
    				$('<a href="'+url+'">'+title+'</a><br/>').appendTo('#useful-links p');
    				$(this).find('desc').each(function(){
    					//var brief = $(this).find('brief').text();
    					//var long = $(this).find('long').text();
    					//$('<div class="brief"></div>').html(brief).appendTo('#link_'+id);
    					//$('<div class="long"></div>').html(long).appendTo('#link_'+id);
    				});
    			});
    		}
    	});
    }
    
    // small window siblings dropdown fix
//    $('body').width(Math.max($('body').width(), 1110));
    // target="_blank" support for links
    $('a.blank').attr('target', '_blank');
    // Add first and last classes to appropriate li
    $('li:first-child').addClass('first');
    $('li:last-child').addClass('last');
    // Add odd and even to table rows
    $('table').each(function(){
        $(this).find('tr:odd').addClass('odd');
        $(this).find('tr:even').addClass('even');
    });
    // Process subsites listing
    $('#subsites-list .item').bind('click', function(){
        location.href = $(this).find('a').attr('href');
    });
    $('#subsites-list .item').hover(function(){
        $(this).addClass('hover');
    }, function(){
        $(this).removeClass('hover');
    });
    // Add dropdowns handler
    $('.dropdown.hover').hover(function(){
        $(this).addClass('active');
        $(this).find('.dropdown-content').show();
    }, function(){
        $(this).removeClass('active');
        $(this).find('.dropdown-content').hide();
    });
    $('.dropdown.click .dropdown-title').click(function(){
        $(this).parents('.dropdown').toggleClass('active');
        $(this).parents('.dropdown').find('.dropdown-content').toggle();
    });
    $('.dropdown.click .close').click(function(){
        $(this).parents('.dropdown').removeClass('active');
        $(this).parents('.dropdown-content').hide();
    });
    // Preload hover images for dropdowns
    $('.dropdown').addClass('active');
    $('.dropdown-content').show(1, function(){
        $('.dropdown-content').hide();
        $('.dropdown').removeClass('active');
    });
    // Add hovers for language switch
    $('#language ul li').hover(function(){
        $(this).addClass('hover');
    }, function(){
        $(this).removeClass('hover');
    });
    // Add click event to li of language switch
    $('#language ul li').bind('click', function(){
        location.href = $(this).find('a').attr('href');
    });
    // Add outbound links tracking
    $('a.outbound').click(function(){
        recordOutboundLink(this, 'Outbound Links', $(this).attr('href'));
        return false;
    });
    // Add captions to images inside content
    //    $('#content .main-column p img[alt]').each(function(){
    //        $(this).load(function(){
    //            var caption = $('<span class="caption">'+$(this).attr('alt')+'</span>').width($(this).width()).addClass($(this).attr('class'));
    //            $(this).after(caption);
    //        });
    //    });
    // Add miscellaneous last classes
    $('.employee').last().addClass('last');
    $('.sidebar-column .item').last().addClass('last');
    // Turn on scrollable
    $('.container').scrollable({
        size: 3
    });
    // Add classes to inputs
    $(':input').each(function(){
        $(this).addClass($(this).attr('type'));
    });
    // Add validator to form
    $('#contact-form').validate({
        highlight: function(element){
            $(element).addClass('error');
            $('#error').show();
        },
        unhighlight: function(element){
            $(element).removeClass('error');
            if ($('#contact-form :input.error').length == 0) $('#error').hide();
        },
        errorPlacement: function(){},
        submitHandler: function(form) {
            $(form).ajaxSubmit({
                success: function(responseValue) {
                    $(form).find('.result').html(responseValue).show();
                    $(form).find('.submit').hide();
                }
            });
        }
    });
    $('#comment-form').validate({
        highlight: function(element){
            $(element).addClass('error');
            $('#error').show();
        },
        unhighlight: function(element){
            $(element).removeClass('error');
            if ($('#comment-form :input.error').length == 0) $('#error').hide();
        },
        errorPlacement: function(){},
        submitHandler: function(form) {
            $(form).ajaxSubmit({
                success: function(responseValue) {
                    $(form).find('.result').html(responseValue).show();
                    $(form).find('.submit').hide();
                }
            });
        }
    });
    $('#signup-form').validate({
        highlight: function(element){
            $(element).addClass('error');
        },
        unhighlight: function(element){
            $(element).removeClass('error');
        },
        errorPlacement: function(){},
        submitHandler: function(form) {
            $(form).ajaxSubmit({
                success: function(responseValue) {
                    $(form).children().hide();
                    if (/.*ERROR.*/.test(responseValue)) {
                        $(form).find('.error-message').show();
                    } else {
                        $(form).find('.success-message').show();
                    }
                }
            });
        }
    });
    $('form .submit').click(function(){
        $(this).parents('form').submit();
        return false;
    });
    // Wrap mainpart block to create shadow
    $('.mainpart-block').wrap('<div class="mainpart-block-wrapper">');
    // Banner
    $("#slides-container .slide").first().show();
    var slideShow = new SlideShow($("#slides-container .slide"), [], 'slideShow');
    // Enumerate slide-controls
    $('#slide-controls-container .control').each(function(index){
        $(this).addClass('index-'+ (index * 1 + 1));
    });
    // Accordion
    var active = false;
    $('#tours-menu>h3').each(function(index){
        $(this).addClass('index-'+ (index * 1 + 1));
        if ($(this).hasClass('current')) {
            active = index;
        }
    });
    $('#tours-menu').children('div').each(function(index){
        $(this).addClass('index-'+ (index * 1 + 1));
    });
    $('#tours-menu').accordion({
        collapsible: true,
        active: active
    });
    // Prepare tabs implemenation
//    $('#tours-menu').children('div').each(function(parentIndex){
//        $(this).find('ul li a').each(function(index){
//            $(this).attr('href', '#tab-a-'+parentIndex+'-'+index);
//        });
//        $(this).find('div.weekday-content').each(function(index){
//            $(this).attr('id', 'tab-a-'+parentIndex+'-'+index);
//        });
//        $(this).tabs();
//    });
    // Tabs for tour page
//    $('.tourdata .schedule').each(function(parentIndex){
//        $(this).find('.schedule-days ul li a').each(function(index){
//            $(this).attr('href', '#tab-s-'+parentIndex+'-'+index);
//        });
//        $(this).find('.weekday-content').each(function(index){
//            $(this).attr('id', 'tab-s-'+parentIndex+'-'+index);
//        });
//        $(this).tabs();
//    });
    // Lightbox
    $('#gallery a').lightBox({
        imageLoading:			'/public/assets/lightbox-ico-loading.gif',		// (string) Path and the name of the loading icon
        imageBtnPrev:			'/public/assets/lightbox-btn-prev.gif',			// (string) Path and the name of the prev button image
        imageBtnNext:			'/public/assets/lightbox-btn-next.gif',			// (string) Path and the name of the next button image
        imageBtnClose:			'/public/assets/lightbox-btn-close.gif',		// (string) Path and the name of the close btn
        imageBlank:			'/public/assets/lightbox-blank.gif'
    });
    // Add removing of hints on focus for signup form
    $('#signup-form :input').each(function(){
        var backup = $(this).attr('value');
        $(this).focus(function(){
            if ($(this).attr('value') == backup) {
                $(this).attr('value', '');
            }
        }).focusout(function(){
            if ($(this).attr('value') == '') {
                $(this).attr('value', backup);
            }
        });
    });
    // Add first/last to guides list
    $('.guide').first().addClass('first');
    $('.guide').last().addClass('last');
    // Weather
    $.ajax({
        url: '/weather.php?a='+$('#weather').html(),
        method: 'get',
        success: function(data){
            applyCurrent(data);
        }
    });

    // Init support of youtube lightbox
    $('a.video').fancybox({
        autosize: false,
        width:640,
        height:360
    });
    $('a.galll').fancybox({
        autosize: false,
        width:760,
        height:383
    });

    // Hide nextPage link if it's not needed
    if ($('#booking .item').length <= 3) {
        $('.nextPage').hide();
    }
});


/* Banner slideshow with controls */
function SlideShow(slides, controls, varName) {
    /* Slides container */
    this.slides = slides;
    /* Controls container */
    this.controls = controls;
    /* Active slide number container */
    this.active_slide = 0;
    /* Interval handler */
    this.interval = null;
    /* Variable of the slideshow */
    this.varName = varName;

    /* Changes active slide to new_slide. new_slide is INT */
    this.changeSlide = function(new_slide) {
        if (this.active_slide == new_slide) return false;

        $(this.controls[this.active_slide]).removeClass('active');
        $(this.slides[this.active_slide]).fadeOut(500);
        this.active_slide = new_slide;
        $(this.controls[this.active_slide]).addClass('active');
        $(this.slides[this.active_slide]).fadeIn(500);
        return true;
    }

    /* Change to next */
    this.changeToNext = function() {

    }

    /* Timed executioner */
    this.runTimer = function() {
        //        return false;
        if (this.slides.length < 2) return false;
        var self = this;
        this.interval = setInterval(function(){
            var next_slide = self.active_slide + 1;
            if (next_slide == self.slides.length) next_slide = 0;
            self.changeSlide(next_slide);
        }, 14000);
        return true;
    }

    /* Map slides to controls */
    this.mapSlides = function() {
        var self = this;
        $.each(this.controls, function(index, control){
            $(control).hover(function(){
                self.changeSlide(index);
                clearInterval(self.interval);
            }, function(){
                self.runTimer();
            });
        });
    }

    /* Apply height of image to slides container */
    this.applyHeight = function() {
        var maxHeight = 0;
        this.slides.each(function(slide){
            if(slide.getHeight() > maxHeight) maxHeight = slide.getHeight();
        });
        this.slides.first().up().setStyle({
            height: maxHeight+'px'
        });
    }


    /* Initialize */
    this.mapSlides();
    //    this.applyHeight();
    this.runTimer();
    $(this.controls[this.active_slide]).addClass('active');
}

// Path to images
var img_path = '/public/assets/weather/google/';
/**
 * Add current conditions data to page
 */
function applyCurrent(xmlDoc) {
    var xml_data = xmlDoc.getElementsByTagName('current_conditions')[0];

    // Create icon
    if (xml_data.childNodes[4].getAttribute('data') != '') {
        var src = img_path + xml_data.childNodes[4].getAttribute('data').replace('/ig/images/weather/', '').replace('.gif', '.png');
    } else {
        var src = img_path + xmlDoc.getElementsByTagName('forecast_conditions')[0].childNodes[3].getAttribute('data').replace('/ig/images/weather/', '').replace('.gif', '.png');
    }
//    var code = $('<img src="' + src + '"><span>' + xml_data.childNodes[2].getAttribute('data') + '=°C</span>');

    $('#weather').html('<img src="' + src + '"><span>' + xml_data.childNodes[2].getAttribute('data') + '°C</span>');
}



// Checks the browser and adds classes to the body to reflect it.

$(document).ready(function(){

    var userAgent = navigator.userAgent.toLowerCase();
    $.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase());

    // Is this a version of IE?
    if($.browser.msie){
        $('body').addClass('browserIE');

        // Add the version number
        $('body').addClass('browserIE' + $.browser.version.substring(0,1));
    }


    // Is this a version of Chrome?
    if($.browser.chrome){

        $('body').addClass('browserChrome');

        //Add the version number
        userAgent = userAgent.substring(userAgent.indexOf('chrome/') +7);
        userAgent = userAgent.substring(0,1);
        $('body').addClass('browserChrome' + userAgent);

        // If it is chrome then jQuery thinks it's safari so we have to tell it it isn't
        $.browser.safari = false;
    }

    // Is this a version of Safari?
    if($.browser.safari){
        $('body').addClass('browserSafari');

        // Add the version number
        userAgent = userAgent.substring(userAgent.indexOf('version/') +8);
        userAgent = userAgent.substring(0,1);
        $('body').addClass('browserSafari' + userAgent);
    }

    // Is this a version of Mozilla?
    if($.browser.mozilla){

        //Is it Firefox?
        if(navigator.userAgent.toLowerCase().indexOf('firefox') != -1){
            $('body').addClass('browserFirefox');

            // Add the version number
            userAgent = userAgent.substring(userAgent.indexOf('firefox/') +8);
            userAgent = userAgent.substring(0,1);
            $('body').addClass('browserFirefox' + userAgent);
        }
        // If not then it must be another Mozilla
        else{
            $('body').addClass('browserMozilla');
        }
    }

    // Is this a version of Opera?
    if($.browser.opera){
        $('body').addClass('browserOpera');
    }


});

function isMobileDevice(){
    var a = navigator.userAgent||navigator.vendor||window.opera;
    if(/android.+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od|ad)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(a)
        ||
        /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))
        ){
        return true;
    } else {
        return false;
    }
}
