var Aperol = (new function() {

    var current_image_display = 0; //track which image is in viewer
    var current_event_id = 0;
    var unique_flash_ident = 0;

    $(function() {    
    
        var recipe_dropdown_bg = new Image();
        recipe_dropdown_bg.src = "../images/aperol-recipes-active.png";
        var events_dropdown_bg = new Image();
        events_dropdown_bg.src = "../images/upcoming-events-active.png";
        var past_events = new Image();
        past_events.src = "../images/past-events-link.png";
        var upcoming_events = new Image();
        upcoming_events.src = "../images/upcoming-events-link.png";
        var aperol_recipes = new Image();
        aperol_recipes.src = "../images/aperol-recipes-link.png";
        var shared_recipes = new Image();
        shared_recipes.src = "../images/shared-recipes-link.png";
        
        preload_image_gallery();
        
        $('ul.nav li a.dropdown').parent().hover( function() {
            $('a.dropdown', this).addClass('active');
            $('ul', this).show();
        },
        function() {
            $('a.dropdown', this).removeClass('active');
            $('ul', this).hide();
        });
        
        if ($('#stamps-list').length) {
            $('<object width="600" height="600" id="recipe-flashcard-'+unique_flash_ident+'"><param name="quality" value="high" /><param name="wmode" value="transparent" /><param name="movie" value="/uploads/aperol-recipe/flash/'+$('#stamps-list ul li.active').attr('swf')+'"><embed src="/uploads/aperol-recipe/flash/'+$('#stamps-list ul li.active').attr('swf')+'" width="600" height="600" wmode="transparent"></embed></object>').insertBefore('#recipe #upload-recipe');
            //if (navigator.userAgent.indexOf('MSIE') ==-1) {
                $('#stamps-list').jScrollPane({showArrows: true, scrollbarWidth: 18, dragMinHeight: 68, dragMaxHeight: 68, topCapHeight: 15, bottomCapHeight: 15, reinitialiseOnImageLoad: false});
            //}
            $('#stamps-list li').click( function() {
                window.location = "/aperol-recipes?id="+$(this).attr('rel');
            });
        }
        
        if ($('#recipes-list').length) {
            $('#recipes-list').jScrollPane({showArrows: true, scrollbarWidth: 18, dragMinHeight: 68, dragMaxHeight: 68, topCapHeight: 15, bottomCapHeight: 15, reinitialiseOnImageLoad: true});
        }
        
        if ($('#event-postcards').length) {
            $('#event-postcards').jScrollPane({showArrows: true, scrollbarWidth: 18, dragMinHeight: 68, dragMaxHeight: 68, topCapHeight: 15, bottomCapHeight: 15, reinitialiseOnImageLoad: true});
            load_new_gallery($('#event-postcards ul li:first').attr('event'));
            $('#event-postcards ul li').click( function() {
                load_new_gallery($(this).attr('event'));
            });
        }
        
        if ($('#files').length) {
            $('#files').jScrollPane({showArrows: true, scrollbarWidth: 18, dragMinHeight: 68, dragMaxHeight: 68, topCapHeight: 15, bottomCapHeight: 15, reinitialiseOnImageLoad: true});
        }

        if ($('#locator-search').length) {
            $('#locator-search form').submit( function() {
                var submit = $('#locator-search form input[type=submit]');
                submit.attr('disabled', true);
                $('#locator-results').html('<div class="messages"><p>Searching...<br /><img src="../images/locator-searching.gif" /></p></div>');
                var values = $(this).serialize();
                $('#locator-results').load('/locator/search?'+values, function() {
                    submit.removeAttr('disabled');
                    $('#locator-results').css({'position': 'relative', 'top': '0px', 'left': '0px'});
                    $('#locator-results').jScrollPane({showArrows: true, scrollbarWidth: 18, dragMinHeight: 68, dragMaxHeight: 68, topCapHeight: 15, bottomCapHeight: 15});
                });
                return false;
            });
        }
        
        $('#calculate-drinks').click( function(e){
            e.preventDefault();
            var submit = true;
            var parent = $(this).parents('form');
            $('input', parent).not($(this)).each( function() {
                if ($(this).val() == "" || !checkNumberic($(this).val())) {
                    submit = false;
                    $(this).parent().prev('td').addClass('error');
                }
                else {
                    $(this).parent().prev('td').removeClass('error');
                }
            });
            $('select', parent).not($(this)).each( function() {
                if ($(this).val() == "") {
                    submit = false;
                    $(this).parent().prev('td').addClass('error');
                }
                else {
                    $(this).parent().prev('td').removeClass('error');
                }
            });
            if (submit) {
                $('#drink-calculation').load('/calculator/calculate?'+$('form[name="drink-calculator"]').serialize(), function() {
                    $('div.ingredient-list').jScrollPane({showArrows: true, scrollbarWidth: 18, dragMinHeight: 68, dragMaxHeight: 68, topCapHeight: 15, bottomCapHeight: 15, reinitialiseOnImageLoad: true});
                });
                /*
$('#drink-calculation').load('/calculator/calculate?'+$('form[name="drink-calculator"]').serialize(), function() {
                    sIFR.replaceElement(named({sSelector:"h3.title", sFlashSrc:"../flash/noteclt.swf", sColor:"#000000", sLinkColor:"#000000", sWmode:"transparent"}));
                });
*/
            }
        });
        
    });
    
    // Check to see if values are numberic
    var checkNumberic = function(value) {
        var anum = /(^\d+$)|(^\d+\.\d+$)/;
        if (anum.test(value)) {
            return true;
        }
        return false;
    }

    // Handle past event gallery slider    
    var enable_gallery_slider = function() {
      $('#image-slider').each( function() {
        var li_margin = parseInt($('ul li', this).css('margin-left').replace('px','')) + parseInt($('ul li', $(this)).css('margin-right').replace('px',''));
        var li_total_width = li_margin + $('ul li', this).width();
        var window_size = $(this).width();
        $('ul', this).css('position','relative');
        // Calculate width of ul
        var viewport_width = 0;
        $('ul li', this).not('.current').each( function(){
            viewport_width += $(this).width() + li_margin;
        });
        viewport_width += $('ul li.current').width();
        $('ul', this).css('width', viewport_width + 'px');
        $('#gallery img.forward').not('.disabled').click( function() {
            $('#image-slider ul').css('left',parseInt($('#image-slider ul').css('left'))-window_size+'px');
            update_scrolls();
        });
        $('#gallery img.back').not('.disabled').click( function() {
            $('#image-slider ul').css('left',parseInt($('#image-slider ul').css('left'))+window_size+'px');
            update_scrolls();
        });
        $('ul li img', this).click( function() {
            var active_parent = $('#image-slider ul li.current');
            active_parent.toggleClass('current');
            active_parent.find('img').attr('src',active_parent.attr('carousel-size'));
            var this_parent = $(this).parent('li');
            this_parent.toggleClass('current');
            $(this).attr('src',this_parent.attr('current-size'));
            $('img.viewer').attr('src',this_parent.attr('viewer-size'));
        });
        update_scrolls();
      });
    }
    
    // Handle enable/disable of scrolls
    var update_scrolls = function() {
        var pages = Math.ceil($('#image-slider ul').width() / $('#image-slider').width());
        var max = $('#image-slider').width() * (pages - 1);
        if ($('#image-slider ul').width() <= $('#image-slider').width()) {
            $('#gallery img.forward').addClass('disabled');
            $('#gallery img.back').addClass('disabled');
        }
        else if (parseInt($('#image-slider ul').css('left')) <= (max * -1)) {
            $('#gallery img.forward').addClass('disabled');
        }
        else if (parseInt($('#image-slider ul').css('left')) == 0) {
            $('#gallery img.back').addClass('disabled');
        }
        else {
            $('#gallery img.forward').removeClass('disabled');
            $('#gallery img.back').removeClass('disabled');
        }
    }
    
    // Load the new gallery
    var load_new_gallery = function(event_id) {
        $('#gallery').load('/past-events/event-information?id='+event_id, function(){
            current_event_id = event_id;
            $('#event-postcards ul li.active').toggleClass('active');
            $('#event-postcards ul li[event="'+event_id+'"]').toggleClass('active');
            enable_gallery_slider();
            preload_image_gallery();
            var status = $('#status');
            var button = $('#file_upload');
            new AjaxUpload(button, {
        		action: '/upload-image',
        		name: 'image',
        		data: {
                    event_id : current_event_id
                },
                onSubmit: function(file, ext){  
                    if (! (ext && /^(jpg|jpeg|gif)$/.test(ext))){  
                        // check for valid file extension  
                        alert("We're sorry, there was a problem uploading your image.  Please make sure it is 1mb or less in size, and that it's in JPG or GIF format.");  
                        return false;  
                    }  
                    status.text('Uploading...');
                    button.hide();
                },
        		onComplete : function(file, response){
        			status.text('');
        			alert(response);
        			button.show();
        		}	
        	});
        });
    }
    
    // Preload all images in the photo gallery
    var preload_image_gallery = function() {
        var images = new Array();
        var counter = 0;
        $('#image-slider ul.image-nav li').each( function() {
            images[counter] = new Image();
            images[counter].src = $(this).attr('viewer-size');
        });
    }

    return this;
    
}());

function show_print_calculator() {
    window.open('/calculator/calculate?print=true&'+$('form[name="drink-calculator"]').serialize(), 'PrintRecipe', 'height=600,width=520,menubar=no,toolbar=yes,location=no,resizable=yes,scrollbars=no,status=no');
}

function email_calculator_drink() {
    window.open('/send-email?type=calculator&'+$('form[name="drink-calculator"]').serialize(), 'SubmitDrinkRecipe', 'height=440,width=540,menubar=no,toolbar=no,location=no,resizable=yes,scrollbars=no,status=no');
}

function open_more_info(id) {
    window.open('/upcoming-events/event-details?id='+id, '', 'height=300,width=450,menubar=no,toolbar=no,location=no,resizable=yes,scrollbars=yes,status=no');
}

function open_recipe_print() {
    id = gup('id');
    if (!id) {
        id = 1;
    }
    window.open('/print-recipe?type=aperol_recipe&id='+id, '', 'height=700,width=650,menubar=no,toolbar=yes,location=no,resizable=yes,scrollbars=yes,status=no');
}

function open_recipe_email() {
    id = gup('id');
    if (!id) {
        id = 1;
    }
    window.open('/send-email?type=aperol_recipe&id='+id, '', 'height=440,width=540,menubar=no,toolbar=no,location=no,resizable=yes,scrollbars=no,status=no');
}

function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}