$(document).ready(function() {
    //$('#bookOnline').BookOnline();
    $('#bookOnline .row1').SelectDate();
    
    $('#newsletter').newsletterSignup();
    $('#contact_form').contactForm();
    $('#banners .banner').banners();
    $('#tour .banner').banners();
    $('#galleryContainer').theGallery();
    
    $('#content, #banners').hcontrol();
    $('#LSide, #Middle').hcontrol();
    
    
    $('#content IMG[vspace]').each(function() {
        var val = parseInt($(this).attr('vspace'));
        $(this).css({ marginTop:val, marginBottom:val });
    });
    
    $('#content IMG[hspace]').each(function() {
        var val = parseInt($(this).attr('hspace'));
        $(this).css({ marginRight:val, marginLeft:val });
    });
    
    $('#contact_form P').each(function() {
        if ($(this).html() == '') $(this).remove();
    });
});






jQuery.fn.banners = function(){
    return this.each(function(){
        var title = $('DT', this);
        var image = $('.image', this);
        var link = $('.link A', this).attr('href');
        var target = $('.link A', this).attr('target') || '_self';
        var link_title = $('.link A', this).attr('title');
        $(this).attr('title', link_title)
            .hover(
                function(){
                    $(this).addClass('hover');
                    image.css({opacity:.8});
                    title.css({opacity:.8});
                }, function() {
                    $(this).removeClass('hover');
                    image.css({opacity:1});
                    title.css({opacity:1});
                }
            )
            .click(function(){
                if (target == '_blank') {
                    window.open(link, '_blank');
                } else window.document.location.href = link;
                return false;            
            });
    })    
}

jQuery.fn.hcontrol = function() {
    jQuery.fn.getHeight = function(){
        var tM = parseInt($(this).css('marginTop'));
        var bM = parseInt($(this).css('marginBottom'));
        var tP = parseInt($(this).css('paddingTop'));
        var bP = parseInt($(this).css('paddingBottom'));
        var H = parseInt(this.height())+tM+bM+tP+bP;
        //console.log('total:' + this.height() + '\n' +'tM: ' + tM + '\n' + 'bM: ' + bM + '\n' + 'tP: ' + tP + '\n' + 'bP: ' + bP + '\n' + 'Height: ' + H);
        return H;
    }
    jQuery.fn.setHeight = function(newH){
        var tM = parseInt($(this).css('marginTop'));
        var bM = parseInt($(this).css('marginBottom'));
        var tP = parseInt($(this).css('paddingTop'));
        var bP = parseInt($(this).css('paddingBottom'));
        var H = newH-tM-bM-tP-bP;
        //console.log(this.attr('id') + ':\n' + 'given: '+ newH + '\n' + 'was: '+ this.height() + '\n' +'tM: ' + tM + '\n' + 'bM: ' + bM + '\n' + 'tP: ' + tP + '\n' + 'bP: ' + bP + '\n' + 'Height: ' + H);
        $(this).css('minHeight', H);        
        //return this.height(H);
    }
    
    var stack = $.makeArray(this);
    var bufH = $(stack[0]).getHeight();
    for (i = 1; i < stack.length;i++) {
        var H = $(stack[i]).getHeight();
        if (H > bufH) for (j=0; j < i; j++) $(stack[j]).setHeight(H);
        else $(stack[i]).setHeight(bufH);
    }
    
    return true;
}

jQuery.fn.newsletterSignup = function(){
    //console.log(typeof(this));
    //console.log(this.length);
    if ((typeof(this) != 'undefined')&&(this.length == 1)) {
        var form = $('FORM', this); // Newsletter form
        var body = $('DD', this); // Newsletter body
        var submit = $('.submit', this); // Newsletter Submit block
        var iSubmit = $('INPUT', submit); // Newsletter Submit field
        
        var ar = 'ar'; // ar ~ Ajax Receiver page
        var ar_act = 'newsletter'; // ar_act ~ Ajax Receiver's action name
        var anewID = 'new_newsletter'; // ID for link that making anew newsletter
        var fnName = 'yourname'; // fn ~ Field Name
        var fnMail = 'youremail'; // fn ~ Field Name
        
        var lMail = $('LABEL[for='+fnMail+']', this); // l ~ Label
        var iMail = $('#'+fnMail, this); // i ~ Input
        var tMail = lMail.text(); // t ~ title/text
        lMail.hide();
        iMail.val(tMail)
            .live('focusin', function(){ if ($(this).val() == tMail){ $(this).val(''); }})
            .live('focusout', function(){ if ($(this).val() == ''){ $(this).val(tMail); }});
        
        var ar_opt = { //ajax receiver options 
            target:     form.attr('id'),
            url:        ar,
            type:       'post',
            dataType:   'json',
            data:       { action:ar_act },
            beforeSubmit: function(formData, jqForm, options) {
                //form = $("FORM", this.target);
                // checking 'email' field
                var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
                if (!filter.test(iMail.val())) {
                    alert('Please, Enter the valid e-mail address.');
                    iMail.focus();
                    return false;
                }
                //var queryString = $.param(formData); 
                //alert('About to submit: \n\n' + queryString); 
                submit.addClass('loading');
                return true; 
            },
            success: function(json, statusText, xhr, $form) { 
                //console.log(json);
                if (json['status']) var tpl = '<b>{text}</b><p>{post}</p><a href="#anew" id="'+anewID+'" title="Subscribe another email">Back to the form</a>';
                else var tpl = '<b>Error</b><p>Something is wrong</p><a href="#anew" id="new_newsletter" title="Subscribe another email">Back to the form</a>';
                var res = tpl.supplant(json);
                body.hide().html(res).fadeIn('slow');
                submit.removeClass('loading');
            }
        }
        
        iSubmit.live('click', function(){ 
            form.ajaxSubmit(ar_opt);
            return false;
        });
        
        var anew = form.clone();
        $('#'+anewID, this).live('click', function() {
            body.hide().html(anew).fadeIn('slow');
            return false;        
        });
        
    }
}

jQuery.fn.contactForm = function(){
    if ((typeof(this) != 'undefined')&&(this.length == 1)) {
        var form = $(this); // Contact form
        var submit = $('INPUT[name=submit]', form); // Newsletter Submit field
        
        var ar = 'ar'; // ar ~ Ajax Receiver page
        var ar_act = 'contact'; // ar_act ~ Ajax Receiver's action name
        var anewID = 'new_form'; // ID for link that making anew form
        
        var ar_opt = { //ajax receiver options 
            target:     form.attr('id'),
            url:        ar,
            type:       'post',
            dataType:   'json',
            data:       { action:ar_act },
            beforeSubmit: function(formData, jqForm, options) {
                var fName = $('INPUT[name=name]', form);
                if (fName.val() == '') {
                    alert('Please, Enter your name.');
                    fName.focus();
                    return false;
                }
                
                var fMail = $('INPUT[name=email_address]', form);
                var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
                if (!filter.test(fMail.val())) {
                    alert('Please, Enter the valid e-mail address.');
                    fMail.focus();
                    return false;
                }
                
                submit.addClass('loading');
                return true; 
            },
            success: function(json, statusText, xhr, $form) { 
                //console.log(json);
                if (json['status']) var tpl = '<p><b>{text}</b></p><p>{post}</p><p><a title="Return back" id="'+anewID+'" href="#anew">Back to the form</a></p>';
                else var tpl = '<b>Error</b><p>Something is wrong</p>';
                var res = tpl.supplant(json);
                form.html(res).fadeIn('slow');
                submit.removeClass('loading');
            }
        }
        
        submit.live('click', function(){ 
            form.ajaxSubmit(ar_opt);
            return false;
        });
        
        var anew = form.clone();
        $('#'+anewID).live('click', function() {
            form.hide().html(anew.html()).fadeIn('slow');
            return false;        
        });
    }
}

jQuery.fn.SelectDate = function(){
    var jq = {
        D: $('#book_day', this),
        M: $('#book_month', this),
        Y: $('#book_year', this)
    }
    // Create html of options for select the Day
    var d_select = function(n, active) {
        var html = '';
        for (i=1;i<=n;i++) {
            html += '<option value="'+i+'"'+(i==active?' selected="selected"':'')+'>'+i+'</option>';
        }
        return html;        
    }
    // Determine whether a given year is a leap year.
    var isLeapYear = function(year) {
        if (year % 100 == 0) {
            return (year % 400 == 0);
        }
        return (year % 4 == 0);
    }
    // Selects control about options quantity
    var sControl = function(){
        var M = parseInt($(':selected', jq.M).val());
        var D = parseInt($(':selected', jq.D).val());
        var Y = parseInt($(':selected', jq.Y).val());
        switch (M) {
            case 2: {
                if (isLeapYear(Y)) jq.D.html(d_select(29, D));
                else jq.D.html(d_select(28, D));
            } break;
            case 4: case 6: case 9: case 11: {
                jq.D.html(d_select(30, D));
            } break;
            default: 
                jq.D.html(d_select(31, D));
        }
    }
    sControl();
    jq.M.live('change', function(){ sControl() });
    jq.Y.live('change', function(){ sControl() });
}

jQuery.fn.BookOnline = function(){
    if ((typeof(this) != 'undefined')&&(this.length == 1)) {
        var form = $('FORM', this); // Newsletter form
        var body = $('DD', this); // Newsletter body
        var submit = $('.submit', this); // Newsletter Submit block
        var iSubmit = $('INPUT', submit); // Newsletter Submit field
        
        var ar = 'ar'; // ar ~ Ajax Receiver page
        var ar_act = 'book'; // ar_act ~ Ajax Receiver's action name
        
        
        var ar_opt = { //ajax receiver options 
            target:     form.attr('id'),
            url:        ar,
            type:       'post',
            dataType:   'json',
            data:       { action:ar_act },
            beforeSubmit: function(formData, jqForm, options) {
                 
                submit.addClass('loading');
                return true; 
            },
            success: function(json, statusText, xhr, $form) { 
                //console.log(json);
                if (json['status']) var tpl = '<b>{text}</b><p>{post}</p>';
                else var tpl = '<b>Error</b><p>Something is wrong</p>';
                var res = tpl.supplant(json);
                body.hide().html(res).fadeIn('slow');
                submit.removeClass('loading');
            }
        }
        
        iSubmit.live('click', function(){ 
            //form.ajaxSubmit(ar_opt);
            window.document.location.href = 'book-online';
            return false;
        });
    } 
}

jQuery.fn.theGallery = function(){
        
    var arr = {
        Next: '<div class="arr prev"><a href="#prev"><span>Previous Image</span></a></div>',
        Prev: '<div class="arr next"><a href="#next"><span>Next Image</span></a></div>'
    }
    var gal = {
        P       : $(this),                          // Preview List of images
        F       : $('#collague .src'),              // Fullsize image place
        S       : '',                               // Screen Block
        setS    : function(obj) { this.S = $(obj) },
        c       : [],                               // array from all cells
        Next    : '',                               // previous image button
        setNext : function(obj) { this.Next = obj },
        Prev    : '',                               // next image button
        setPrev : function(obj) { this.Prev = obj }
    }
    var cF = gal.F.clone();
    gal.F.css({ position:'relative' });
    
    gal.P
        .wrapInner('<div class="shell"><div class="screen"></div></div>')
        .append(arr.Prev)
        .prepend(arr.Next)
        .prepend('<div id="preloader" style="position:absolute; overflow:hidden; width:0px; height:0px; left:-12px; top:300px;"></div>');
    
    gal.setPrev($('.arr.prev', this));
    gal.setNext($('.arr.next', this));
    gal.setS($('.screen', gal.P));
    
    var img = function(obj, n) {
        $(obj).attr('n', n); //add number to the Image Link
        this.jq = $(obj);
        this.n = n;
        this.id = 'img_'+n;
        this.src = $(obj).attr('href');
        this.w = parseInt($('IMG', obj).width()) + 10; // small image width | 10 ~ MarginRight parent of obj
        this.Fw = ''; // Fullsize image width
        this.set_Fw = function(val) { // Set the Fullsize image width
            if (val < 50) val = 633; // default width
            this.Fw = val;
        }; 
        this.h = $('IMG', obj).height(); // small image height
        this.Fh = ''; // Fullsize image height
        this.set_Fh = function(val) { // Set the Fullsize image height
            if (val < 50) val = 350; // default height
            this.Fh = val;
        };
        this.show = function() {
            $('.galleryItem A', gal.P).attr('active', 'no').parent().removeClass('active');
            this.jq.attr('active', 'yes').parent().addClass('active');
            $('*', gal.F).css({ zIndex:100 }).attr('delete', 'yes');
            var image = $('<img id="'+this.id+'" src="'+this.src+'" alt="image" />');
            // Get Image width'n'height            
            image.prependTo('#preloader');
            //this.set_Fw($('#'+this.id).width());
            this.set_Fw(633);
            //this.set_Fh($('#'+this.id).height());
            this.set_Fh(350);
            $('#'+this.id).remove();
            // --
            image.css({ position:'absolute', zIndex:101, left:0, top:0 }).hide().prependTo(gal.F).fadeIn(500, function(){ $('*[delete=yes]', gal.F).remove() });
            //gal.F.css({ marginLeft:'auto', marginRight:'auto' }).animate({ width:this.Fw, height:this.Fh }, 500);
            gal.F.animate({ width:this.Fw, height:this.Fh }, 500);
            //console.log(this.n);
        }
    }
    
    $('.galleryItem A', gal.P).each(function(i){
        i = i + 1;
        var c = new img(this, i);
        gal.c[i] = c;
    }).click(function(){
        var n = $(this).attr('n');
        gal.c[n].show();
        return false;
    }).hover(function(){
        $('IMG', this).css({ opacity:.7 });
        $(this).siblings(".border").find('.c').css({ backgroundColor:'#DDDBC6' });
    }, function() {
        $('IMG', this).css({ opacity:1 });
        $(this).siblings(".border").find('.c').css({ backgroundColor:'transparent' });
    });
    
    $('.galleryItem:first A', gal.P).trigger('click');
    
        
    
    $('.arr', gal.P).live('click', function() {
        var c = gal.c.length-1;
        var active = parseInt($('.galleryItem A[active=yes]', gal.P).attr('n')) || 0;
        if (active == 0) active = 1;
        
        var prev = ((active-1)<1?c:active-1); 
        var next = ((active+1)>c?1:active+1); 
        var pos = parseInt(gal.S.css('left'));
        
        switch (xslice($('A', this).attr('href'), '#')) {
            case 'prev':
                if (active == 1) {
                    for (j=1;j<c-1;j++) pos = pos-gal.c[j].w;
                    gal.S.animate({ left:pos }, 500);
                } else if (active == 2) gal.S.animate({ left:0 }, 500);
                else gal.S.animate({ left:pos+gal.c[active].w }, 500);
                gal.c[prev].show(); 
            break;
            case 'next':
                if (active == c) gal.S.animate({ left:0 }, 500);
                else gal.S.animate({ left:pos-gal.c[active].w }, 500);
                gal.c[next].show();
            break;
        }
        
        return false;
    });
}

function xslice(s, sep) {
    while (s.substring(0,1) != sep) s = s.substring(1, s.length);
    return s.substring(1, s.length);
}



