$(document).ready(function(){
    // header panels
    
    $('#header-panels').children().each(function(){
        $(this).hide();         // hide the panels on start
    });

    $('#top-nav a, h4.close-panels a').bind('click', function() {
        // show selected panel, hide others
        var panel_id = $(this).attr('href').split('#');
            panel_id = panel_id[1];
            
            $('#header-panels').children().each(function(){
                if( this.id == panel_id && $(this).css('display') == 'none') {
                    $(this).slideDown();
                } else {
                    $(this).slideUp();
                }
            });
            
        return false;
    });
    
    $('a.contact-us').click(function(){
        $('ul#top-nav a[href="#contact"]').click();
        $('html, body').animate({scrollTop:0}, 'slow');
        return false;
    });
    
    // search
    $('#top-nav .header-search').bind('focus', function(){
        if( $(this).val() == 'Search Wines...' )
            $(this).val('');
    });

    $('#top-nav .header-search').bind('blur', function(){
        if( $(this).val() == '' )
            $(this).val('Search Wines...');
    });
    
    $('#search-wine').focus(function(){
        if( $(this).val() == 'Search...' )
            $(this).val('');
    });

    $('#search-wine').blur(function(){
        if( $(this).val() == '' )
            $(this).val('Search...');
    });

    if( $('#search-wine').val() == '' )
        $('#search-wine').val('Search...');

    if( $('#nav li.sub-menu a').length < 1 )
        $('#nav li.sub-menu').css({ borderColor : '#dde4c5'});

    /* contact form */
    $('#contact-form').submit(function(){
        var valid_form = true;

        // check name
        if( jQuery.trim($('#contact-form input[name="name"]').val()) == '' ) {
            valid_form = false;
            WofG._show_error($('#contact-form input[name="name"]'));
        } else
            WofG._hide_error($('#contact-form input[name="name"]'));

        // check email
        if( jQuery.trim($('#contact-form input[name="email"]').val()) == '' || !WofG._valid_email($('#contact-form input[name="email"]').val()) ) {
            valid_form = false;
            WofG._show_error($('#contact-form input[name="email"]'));
        } else
            WofG._hide_error($('#contact-form input[name="email"]'));

        // check message
        if( jQuery.trim($('#contact-form textarea[name="message"]').val()) == '' ) {
            valid_form = false;
            WofG._show_error($('#contact-form textarea[name="message"]'));
        } else
            WofG._hide_error($('#contact-form textarea[name="message"]'));
        
        if( valid_form ) {
            $('#contact-form input.button').replaceWith('<div class="sending-form">Sending form</div>');

            var our_form = $(this);
            var url = '/contact_us';
            var post = $(this).serialize();

            $.post(url, post, function(data) {
                if( typeof(data.success) != 'undefined' && data.success ) {
                    // contacted us
                    our_form.parent().find('h4').text(data.title);
                    our_form.replaceWith('<strong>' + data.message + '</strong>');
                } else {
                    // some error                    
                    our_form.parent().find('h4').text('Sorry an error has occurred');
                    if (data.message) {
                      our_form.replaceWith('<strong>' + data.message + '</strong>');
                    } else {
                      our_form.replaceWith('<strong>We were unable to send the email.<br /><br />Please try again later.</strong>');
                    }
                }
            }, 'json');
        }
        return false;
    }); /* contact us end */

    /* subscribe form */
    $('#subscribe-form').submit(function(){
        var valid_form = true;

        // check name
        if( jQuery.trim($('#subscribe-form input[name="name"]').val()) == '' ) {
            valid_form = false;
            WofG._show_error($('#subscribe-form input[name="name"]'));
        } else
            WofG._hide_error($('#subscribe-form input[name="name"]'));

        // check email
        if( jQuery.trim($('#subscribe-form input[name="email"]').val()) == '' || !WofG._valid_email($('#subscribe-form input[name="email"]').val()) ) {
            valid_form = false;
            WofG._show_error($('#subscribe-form input[name="email"]'));
        } else
            WofG._hide_error($('#subscribe-form input[name="email"]'));
        
        if( valid_form ) {

            $('#subscribe-form input.button').replaceWith('<div class="sending-form">Sending form</div>');

            var our_form = $(this);
            var url = '/subscribe';
            var post = $(this).serialize();

            $.post(url, post, function(data) {
                if( typeof(data.success) != 'undefined' && data.success ) {
                    // contacted us
                    our_form.parent().find('h4').text(data.title);
                    our_form.replaceWith('<strong>' + data.message + '</strong>');
                } else {
                    // some error                    
                    our_form.parent().find('h4').text('Sorry an error has occurred');
                    if (data.message) {
                      our_form.replaceWith('<strong>' + data.message + '</strong>');
                    } else {
                      our_form.replaceWith('<strong>We were unable to subscribe you.<br /><br />Please try again later.</strong>');
                    }
                }
            }, 'json');
        }
        return false;
    }); /* subscribe end */
    
    /* competition-form */
    
    $('#show-more-competition').click(function(){
        $(this).slideUp();
        $('#competition-form').slideDown();
        
        $('#competition-title a').fadeIn();
        
        return false;
    });
    
    $('#competition-title a').click(function(){
        $(this).fadeOut();
        $('#competition-form').slideUp();
        
        $('#show-more-competition').slideDown();
        return false;
    });

    $('#competition-form form').submit(function(){
        var valid_form = true;
        // check name
        if( jQuery.trim($('#competition-form input[name="name"]').val()) == '' ) {
            valid_form = false;
            WofG._show_error($('#competition-form input[name="name"]'));
        } else
            WofG._hide_error($('#competition-form input[name="name"]'));

        // check email
        if( jQuery.trim($('#competition-form input[name="email"]').val()) == '' || !WofG._valid_email($('#competition-form input[name="email"]').val()) ) {
            valid_form = false;
            WofG._show_error($('#competition-form input[name="email"]'));
        } else
            WofG._hide_error($('#competition-form input[name="email"]'));
        
        if( $('#competition-form input[name="answer"]:checked').length < 1 ) {
            valid_form = false;
            WofG._show_error($('#competition-form input[name="answer"]'));
        }
        
        // check terms are accepted
        if( $('#competition-form input[name="accept"]:checked').length < 1 ) {
            valid_form = false;
            WofG._show_error($('#competition-form input[name="accept"]'));
        } else
            WofG._hide_error($('#competition-form input[name="accept"]'));
        
      
        if( valid_form ) {
            var our_form = $(this);
            
            $('#competition-form form input.submit').replaceWith('<div class="sending-form">Sending form</div>');

            var url = '/competition';
            var post = $(this).serialize();

            $.post(url, post, function(data) {
                if( typeof(data.success) != 'undefined' && data.success ) {
                    // contacted us
                    setTimeout(function(){$('#competition-result').html('<strong>Thank you for participating</strong>');}, 1000);
                } else {
                    // some error
                    setTimeout(function(){$('#competition-result').html('<strong>Sorry and error occurred, please try again later.</strong>');}, 1000);
                }
            }, 'json');
        }
        return false;
    });
    /* competition-form end */
    // header panels end
    
    
    /* advanced filter */
    $('#advanced-filter').bind('click', function(){
        if( $('#search-options').css('display') == 'none' ) {
            $('#search-options').slideDown();
            $('#advanced-search-hidden').val('true');
            $(this).addClass('selected').text('Minimize');
        } else {
            $('#search-options').slideUp();
            $('#advanced-search-hidden').val('false');
            $(this).removeClass('selected').text('Advanced Filter');
        }
        
        return false;
    });
    

    var version = jQuery.browser.version.split('.');
        version = parseInt(version[0]);

        var event = 'change';
        
        $('#search-options label').find(':checkbox').each(function(){
            $(this).css({ opacity : '0' }); // hide the checkbox
            $(this).parent().addClass('check-box');
    
             if( $(this).attr('checked') ) $(this).parent().addClass('checked-box');
             
             $(this).bind(event, function(){
                if( $(this).attr('checked') )
                    $(this).parent().addClass('checked-box');
                else
                    $(this).parent().removeClass('checked-box');
             });
        });
    
        $('#search-options label').find(':radio').each(function(){
            $(this).css({ opacity : '0' }); // hide the checkbox
            $(this).parent().addClass('check-box');
            var event = 'change';

            if( $(this).attr('checked') ) $(this).parent().addClass('checked-box');

            $(this).bind(event, function(){
                $('input[name="alcohol-level"]').each( function(){
                    $(this).parent().removeClass('checked-box');
    
                    if( $(this).val() == $('input[name="alcohol-level"]:checked').val() )
                        $(this).parent().addClass('checked-box');
                });
    
             });
        });

        $('#competition-form').find(':radio').each(function(){
            $(this).css({ opacity : '0' }); // hide the checkbox
            $(this).parent().addClass('check-box');
            var event = 'change';

            if( $(this).attr('checked') ) $(this).parent().addClass('checked-box');

            $(this).bind(event, function(){

                $('#competition-form input[name="' + $(this).attr('name') + '"]').each( function(){
                    $(this).parent().removeClass('checked-box');
    
                    if( $(this).val() == $('#competition-form input[name="' + $(this).attr('name') + '"]:checked').val() )
                        $(this).parent().addClass('checked-box');
                });
    
             });
        });
    /* advanced filter end */
    
    /* reset filter */
    $('#reset-search-options').bind('click', function(){
        $('#search-options input[type="checkbox"], #search-options input[type="radio"]').removeAttr('checked').removeAttr('disabled').parent().removeClass('disabled-box').removeClass('checked-box');
        $('input#all-alcohol-radio').attr('checked', true).parent().addClass('checked-box');
        return false;
    });

    /* food quotes pagi */
    
    if( $('#quote-food-ideas').length > 0 && $('.quote-food-pag .pagination').length > 0 ) {
        $('#quote-food-scroller').css({ width : $('#quote-food-ideas .widgt-item').length * ($('#quote-food-ideas').width() + 30) + 'px' });
    }

    $('#quote-food-ideas .widgt-item').each(function(index){
        $(this).attr({'id' : 'quote-food-item-' + (index + 1)});
    })
    
    $('.quote-food-pag .pagination a').click( function(){
        var page = 1;

        if( $(this).text() == 'previous' ) {
            var page_id = parseInt($('.quote-food-pag .pagination a.selected:not(.prev)').text());
            page = page_id > 1 ? page_id - 1 : 1;
    
        } else if( $(this).text() == 'next' ) {
            var page_id = parseInt($('.quote-food-pag .pagination a.selected:not(.prev)').text());
            page = page_id >= $('#quote-food-ideas .widgt-item').length ? $('#quote-food-ideas .widgt-item').length : page_id + 1;
        } else {
            page = $(this).text();
        }

        var move_to = $('#quote-food-ideas #quote-food-item-' + page).parent().offset().left - $('#quote-food-ideas #quote-food-item-' + page ).offset().left;
        $('#quote-food-ideas #quote-food-item-' + page).parent().animate({'marginLeft': move_to + 'px'});
        
        $('.quote-food-pag .pagination a').removeClass('selected');
        
        if( page == 1 ) $('.quote-food-pag .pagination a.prev').addClass('selected');
        
        if( page == $('#quote-food-ideas .widgt-item').length ) $('.quote-food-pag .pagination a.next').addClass('selected');
        
        $('.quote-food-pag .pagination a').each(function(){
            if( $(this).text() == page )
                $(this).addClass('selected');
        });

        return false;
    });

    /* food quotes pagi end */


    /* food ideas pagi */
    
    if( $('#food-ideas').length > 0 && $('#food-ideas-pagination').length > 0 ) {
        $('#food-ideas').wrapInner('<div style="width : ' + ( $('#food-ideas .item').length * ($('#food-ideas').width() + 30) ) + 'px"></div>')
        $('#food-ideas .item').css({ float : 'left'})
    }

    $('#food-ideas .item').each(function(index){
        $(this).attr({'id' : 'food-item-' + (index + 1)});
    })
    
    $('#food-ideas-pagination a').click( function(){
        var page = 1;

        if( $(this).text() == 'previous' ) {
            var page_id = parseInt($('#food-ideas-pagination a.selected:not(.prev)').text());
            page = page_id > 1 ? page_id - 1 : 1;
    
        } else if( $(this).text() == 'next' ) {
            var page_id = parseInt($('#food-ideas-pagination a.selected:not(.prev)').text());
            page = page_id >= $('#food-ideas .item').length ? $('#food-ideas .item').length : page_id + 1;
        } else {
            page = $(this).text();
        }

        var move_to = $('#food-ideas #food-item-' + page).parent().offset().left - $('#food-ideas #food-item-' + page ).offset().left;
        $('#food-ideas #food-item-' + page).parent().animate({'marginLeft': move_to + 'px'});
        
        $('#food-ideas-pagination a').removeClass('selected');
        
        if( page == 1 ) $('#food-ideas-pagination a.prev').addClass('selected');
        
        if( page == $('#food-ideas .item').length ) $('#food-ideas-pagination a.next').addClass('selected');
        
        $('#food-ideas-pagination a').each(function(){
            if( $(this).text() == page )
                $(this).addClass('selected');
        });

        return false;
    });

    /* food ideas pagi end */

    WofG._featured_wine();

    /* food ideas pagi end */
    
    /* embed home flash */
    var params = {
                wmode           : 'opaque',
                bgcolor         : '#fff'
            };

    swfobject.embedSWF("/swf/wofg_map.swf", 'flash-movie', 768, 326, "8","expressInstall.swf", {}, params);


    var flash_version = swfobject.getFlashPlayerVersion();

    if( flash_version['major'] > 0 ) {
        $('.region-menu ul li a').click(function(){
            var region = WofG._remove_accents($(this).text().toLowerCase().replace(' ', '_').replace('-', '_'));
            $('#flash-map object')[0].go_pos(region);
            $('.sub-menu ul').css({ display : 'none'});
            setTimeout(function(){$('.sub-menu ul').css({ display : ''})}, 200);
            return false;
        });
    
        $('.region-menu ul li a').mouseover(function(){
            var region = WofG._remove_accents($(this).text().toLowerCase().replace(' ', '_').replace('-', '_'));
            $('#flash-map object')[0].show_pos(region);
        });
    }


    /* text over large list */
    $('.large-list, .small-list').hover(
        function(){
            $(this).find('.text, .background').animate({ height : '55px', marginTop : '-59px'}, 250);
        },
        function() {
            $(this).find('.text, .background').animate({ height : '35px', marginTop : '-39px'}, 250);
        }
    );

    $('#sidebar #news-feed-box').lb_feed({feeds : [
             { url : 'http://twitter.com/statuses/user_timeline/21185175.rss'}, {url : 'http://search.twitter.com/search.rss?q=@WinesofGermany' }
            ]
   });
   
   $('a.panel-opener').click(function(){
        // show selected panel, hide others
        var panel_id = $(this).attr('href').split('#');
            panel_id = panel_id[1];
            
            $('#header-panels').children().each(function(){
                if( this.id == panel_id && $(this).css('display') == 'none') {
                    $(this).slideDown();
                    $('html, body').animate({scrollTop:0}, 'slow');
                } else {
                    $(this).slideUp();
                }
            });
            
        return false;
   })
   
    var version = jQuery.browser.version.split('.');
        version = parseInt(version[0]);

    if( jQuery.browser.msie && version < 7 ) {

        $('#nav li.sub-menu').hover(
            function(){
                $(this).find('ul').css({ display : 'block', position : 'absolute', zIndex : 999 });
            },
            function() {
                $(this).find('ul').css({ display : 'none' });
            }
        );
    }
    
    /* links */
    $('#wofg-links').load('/links.xml');
});


var WofG = function() {
    return {

        _show_error : function(trigger, message) {
            trigger.parent().addClass('error').removeClass('valid');
        },

        _hide_error : function(trigger) {
            trigger.parent().addClass('valid').removeClass('error');
        },

        _valid_email : function (strEmail){
            validRegExp = /^[^@]+@[^@]+.[a-z]{2,}$/i;
        
            if (strEmail.search(validRegExp) == -1)  {
                return false;
            } else
                return true; 
        },

        _remove_accents : function(s) {
            var diacritics =[
            /[\300-\306]/g, /[\340-\346]/g, // A, a
            /[\310-\313]/g, /[\350-\353]/g, // E, e
            /[\314-\317]/g, /[\354-\357]/g, // I, i
            /[\322-\330]/g, /[\362-\370]/g, // O, o
            /[\331-\334]/g, /[\371-\374]/g,  // U, u
            /[\321]/g, /[\361]/g, // N, n
            /[\307]/g, /[\347]/g, // C, c
            ];
            
            var chars = ['A','a','E','e','I','i','O','o','U','u','N','n','C','c'];

            for (var i = 0; i < diacritics.length; i++)
                s = s.replace(diacritics[i],chars[i]);

            return s;
        },
        _region_recommended : function(id) {
            // load recommendations for a region
            $('#featured-wines-to-load').css({ height : $('#featured-wines-to-load').height() + 'px'});
            
            var url = '/';

            if( id != 'all_regions' )
                url = '/regions/' + id;

            if( $('#hoccus-poccus-invisible').length < 1 ) {
                $('body').append('<div id="hoccus-poccus-invisible"></div>');
            }
            
            $('#hoccus-poccus-invisible').load(url + ' #featured-wines-to-load',
                                                    function() {
                                                        if( $('#hoccus-poccus-invisible .item').length > 0 ) {
                                                            $('#featured-wines-to-load').fadeOut(500, function(){
                                                                $(this).html($('#hoccus-poccus-invisible').html());
                                                                $('#hoccus-poccus-invisible').remove();
                                                                $('#featured-wines-to-load').fadeIn(500, function(){ WofG._featured_wine(); });
                                                            })
                                                        } else
                                                            $('#hoccus-poccus-invisible').remove();
                                                    });
        },
        _featured_wine : function() {
            /* featured wine pagi */            
            if( $('#featured-wine').length > 0 && $('#featured-wine-pagination').length > 0 ) {
                $('#featured-wine').wrapInner('<div style="width : ' + ( $('#featured-wine .item').length * ($('#featured-wine').width() + 30) ) + 'px"></div>')
                $('#featured-wine .item').css({ float : 'left'})
            }
        
            $('#featured-wine .item').each(function(index){
                $(this).attr({'id' : 'featured-item-' + (index + 1)});
            })
            
            $('#featured-wine-pagination .pagination a').click( function(){
                var page = 1;
        
                if( $(this).text() == 'previous' ) {
                    var page_id = parseInt($('#featured-wine-pagination .pagination a.selected:not(.prev)').text());
                    page = page_id > 1 ? page_id - 1 : 1;
            
                } else if( $(this).text() == 'next' ) {
                    var page_id = parseInt($('#featured-wine-pagination .pagination a.selected:not(.prev)').text());
                    page = page_id >= ($('#featured-wine .item').length / 2 ) ? ($('#featured-wine .item').length / 2 ) : page_id + 1;
                } else {
                    page = $(this).text();
                }
                
                page = Math.round(page*Math.pow(10,0))/Math.pow(10,0);
        
                var move_to = - (page-1) * ( $('#featured-wine .item').width() * 2);
        
                $('#featured-wine #featured-item-' + page).parent().animate({'marginLeft': move_to + 'px'});
                
                $('#featured-wine-pagination a').removeClass('selected');
                
                if( page == 1 ) $('#featured-wine-pagination .pagination a.prev').addClass('selected');
                
                if( page == ($('#featured-wine .item').length / 2 ) ) $('#featured-wine-pagination a.next').addClass('selected');
                
                $('#featured-wine-pagination a').each( function(){
                    if( $(this).text() == page )
                        $(this).addClass('selected');
                });
        
                return false;
            });
        }
    }
}();

$(document).ready(function(){
   $('a[rel="modal"]').nyroModal();
});